]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
Cargo fmt
[rust.git] / src / bin / rustfmt.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![cfg(not(test))]
12
13
14 extern crate env_logger;
15 extern crate getopts;
16 extern crate rustfmt_nightly as rustfmt;
17
18 use std::{env, error};
19 use std::fs::File;
20 use std::io::{self, Read, Write};
21 use std::path::{Path, PathBuf};
22 use std::str::FromStr;
23
24 use getopts::{HasArg, Matches, Occur, Options};
25
26 use rustfmt::{run, Input, Summary};
27 use rustfmt::file_lines::FileLines;
28 use rustfmt::config::{get_toml_path, Color, Config, WriteMode};
29
30 type FmtError = Box<error::Error + Send + Sync>;
31 type FmtResult<T> = std::result::Result<T, FmtError>;
32
33 /// Rustfmt operations.
34 enum Operation {
35     /// Format files and their child modules.
36     Format {
37         files: Vec<PathBuf>,
38         config_path: Option<PathBuf>,
39         minimal_config_path: Option<String>,
40     },
41     /// Print the help message.
42     Help,
43     // Print version information
44     Version,
45     /// Print detailed configuration help.
46     ConfigHelp,
47     /// Output default config to a file, or stdout if None
48     ConfigOutputDefault {
49         path: Option<String>,
50     },
51     /// No file specified, read from stdin
52     Stdin {
53         input: String,
54         config_path: Option<PathBuf>,
55     },
56 }
57
58 /// Parsed command line options.
59 #[derive(Clone, Debug, Default)]
60 struct CliOptions {
61     skip_children: bool,
62     verbose: bool,
63     write_mode: Option<WriteMode>,
64     color: Option<Color>,
65     file_lines: FileLines, // Default is all lines in all files.
66     unstable_features: bool,
67 }
68
69 impl CliOptions {
70     fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
71         let mut options = CliOptions::default();
72         options.skip_children = matches.opt_present("skip-children");
73         options.verbose = matches.opt_present("verbose");
74         let unstable_features = matches.opt_present("unstable-features");
75         let rust_nightly = option_env!("CFG_RELEASE_CHANNEL")
76             .map(|c| c == "nightly")
77             .unwrap_or(false);
78         if unstable_features && !rust_nightly {
79             return Err(FmtError::from(
80                 "Unstable features are only available on Nightly channel",
81             ));
82         } else {
83             options.unstable_features = unstable_features;
84         }
85
86         if let Some(ref write_mode) = matches.opt_str("write-mode") {
87             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
88                 options.write_mode = Some(write_mode);
89             } else {
90                 return Err(FmtError::from(format!(
91                     "Invalid write-mode: {}",
92                     write_mode
93                 )));
94             }
95         }
96
97         if let Some(ref color) = matches.opt_str("color") {
98             match Color::from_str(color) {
99                 Ok(color) => options.color = Some(color),
100                 _ => return Err(FmtError::from(format!("Invalid color: {}", color))),
101             }
102         }
103
104         if let Some(ref file_lines) = matches.opt_str("file-lines") {
105             options.file_lines = file_lines.parse()?;
106         }
107
108         Ok(options)
109     }
110
111     fn apply_to(self, config: &mut Config) {
112         config.set().skip_children(self.skip_children);
113         config.set().verbose(self.verbose);
114         config.set().file_lines(self.file_lines);
115         config.set().unstable_features(self.unstable_features);
116         if let Some(write_mode) = self.write_mode {
117             config.set().write_mode(write_mode);
118         }
119         if let Some(color) = self.color {
120             config.set().color(color);
121         }
122     }
123 }
124
125 /// read the given config file path recursively if present else read the project file path
126 fn match_cli_path_or_file(
127     config_path: Option<PathBuf>,
128     input_file: &Path,
129 ) -> FmtResult<(Config, Option<PathBuf>)> {
130     if let Some(config_file) = config_path {
131         let toml = Config::from_toml_path(config_file.as_ref())?;
132         return Ok((toml, Some(config_file)));
133     }
134     Config::from_resolved_toml_path(input_file).map_err(FmtError::from)
135 }
136
137 fn make_opts() -> Options {
138     let mut opts = Options::new();
139     opts.optflag("h", "help", "show this message");
140     opts.optflag("V", "version", "show version information");
141     opts.optflag("v", "verbose", "print verbose output");
142     opts.optopt(
143         "",
144         "write-mode",
145         "how to write output (not usable when piping from stdin)",
146         "[replace|overwrite|display|plain|diff|coverage|checkstyle]",
147     );
148     opts.optopt(
149         "",
150         "color",
151         "use colored output (if supported)",
152         "[always|never|auto]",
153     );
154     opts.optflag("", "skip-children", "don't reformat child modules");
155
156     opts.optflag(
157         "",
158         "unstable-features",
159         "Enables unstable features. Only available on nightly channel",
160     );
161
162     opts.optflag(
163         "",
164         "config-help",
165         "show details of rustfmt configuration options",
166     );
167     opts.opt(
168         "",
169         "dump-default-config",
170         "Dumps default configuration to PATH. PATH defaults to stdout, if omitted.",
171         "PATH",
172         HasArg::Maybe,
173         Occur::Optional,
174     );
175     opts.optopt(
176         "",
177         "dump-minimal-config",
178         "Dumps configuration options that were checked during formatting to a file.",
179         "PATH",
180     );
181     opts.optopt(
182         "",
183         "config-path",
184         "Recursively searches the given path for the rustfmt.toml config file. If not \
185          found reverts to the input file path",
186         "[Path for the configuration file]",
187     );
188     opts.optopt(
189         "",
190         "file-lines",
191         "Format specified line ranges. See README for more detail on the JSON format.",
192         "JSON",
193     );
194
195     opts
196 }
197
198 fn execute(opts: &Options) -> FmtResult<Summary> {
199     let matches = opts.parse(env::args().skip(1))?;
200
201     match determine_operation(&matches)? {
202         Operation::Help => {
203             print_usage_to_stdout(opts, "");
204             Summary::print_exit_codes();
205             Ok(Summary::default())
206         }
207         Operation::Version => {
208             print_version();
209             Ok(Summary::default())
210         }
211         Operation::ConfigHelp => {
212             Config::print_docs();
213             Ok(Summary::default())
214         }
215         Operation::ConfigOutputDefault { path } => {
216             let toml = Config::default().all_options().to_toml()?;
217             if let Some(path) = path {
218                 let mut file = File::create(path)?;
219                 file.write_all(toml.as_bytes())?;
220             } else {
221                 io::stdout().write_all(toml.as_bytes())?;
222             }
223             Ok(Summary::default())
224         }
225         Operation::Stdin { input, config_path } => {
226             // try to read config from local directory
227             let (mut config, _) =
228                 match_cli_path_or_file(config_path, &env::current_dir().unwrap())?;
229
230             // write_mode is always Plain for Stdin.
231             config.set().write_mode(WriteMode::Plain);
232
233             // parse file_lines
234             if let Some(ref file_lines) = matches.opt_str("file-lines") {
235                 config.set().file_lines(file_lines.parse()?);
236                 for f in config.file_lines().files() {
237                     if f != "stdin" {
238                         eprintln!("Warning: Extra file listed in file_lines option '{}'", f);
239                     }
240                 }
241             }
242
243             let mut error_summary = Summary::default();
244             if config.version_meets_requirement(&mut error_summary) {
245                 error_summary.add(run(Input::Text(input), &config));
246             }
247
248             Ok(error_summary)
249         }
250         Operation::Format {
251             files,
252             config_path,
253             minimal_config_path,
254         } => {
255             let options = CliOptions::from_matches(&matches)?;
256
257             for f in options.file_lines.files() {
258                 if !files.contains(&PathBuf::from(f)) {
259                     eprintln!("Warning: Extra file listed in file_lines option '{}'", f);
260                 }
261             }
262
263             let mut config = Config::default();
264             // Load the config path file if provided
265             if let Some(config_file) = config_path.as_ref() {
266                 config = Config::from_toml_path(config_file.as_ref())?;
267             };
268
269             if options.verbose {
270                 if let Some(path) = config_path.as_ref() {
271                     println!("Using rustfmt config file {}", path.display());
272                 }
273             }
274
275             let mut error_summary = Summary::default();
276             for file in files {
277                 if !file.exists() {
278                     eprintln!("Error: file `{}` does not exist", file.to_str().unwrap());
279                     error_summary.add_operational_error();
280                 } else if file.is_dir() {
281                     eprintln!("Error: `{}` is a directory", file.to_str().unwrap());
282                     error_summary.add_operational_error();
283                 } else {
284                     // Check the file directory if the config-path could not be read or not provided
285                     if config_path.is_none() {
286                         let (config_tmp, path_tmp) =
287                             Config::from_resolved_toml_path(file.parent().unwrap())?;
288                         if options.verbose {
289                             if let Some(path) = path_tmp.as_ref() {
290                                 println!(
291                                     "Using rustfmt config file {} for {}",
292                                     path.display(),
293                                     file.display()
294                                 );
295                             }
296                         }
297                         config = config_tmp;
298                     }
299
300                     if !config.version_meets_requirement(&mut error_summary) {
301                         break;
302                     }
303
304                     options.clone().apply_to(&mut config);
305                     error_summary.add(run(Input::File(file), &config));
306                 }
307             }
308
309             // If we were given a path via dump-minimal-config, output any options
310             // that were used during formatting as TOML.
311             if let Some(path) = minimal_config_path {
312                 let mut file = File::create(path)?;
313                 let toml = config.used_options().to_toml()?;
314                 file.write_all(toml.as_bytes())?;
315             }
316
317             Ok(error_summary)
318         }
319     }
320 }
321
322 fn main() {
323     let _ = env_logger::init();
324
325     let opts = make_opts();
326
327     let exit_code = match execute(&opts) {
328         Ok(summary) => {
329             if summary.has_operational_errors() {
330                 1
331             } else if summary.has_parsing_errors() {
332                 2
333             } else if summary.has_formatting_errors() {
334                 3
335             } else if summary.has_diff {
336                 // should only happen in diff mode
337                 4
338             } else {
339                 assert!(summary.has_no_errors());
340                 0
341             }
342         }
343         Err(e) => {
344             print_usage_to_stderr(&opts, &e.to_string());
345             1
346         }
347     };
348     // Make sure standard output is flushed before we exit.
349     std::io::stdout().flush().unwrap();
350
351     // Exit with given exit code.
352     //
353     // NOTE: This immediately terminates the process without doing any cleanup,
354     // so make sure to finish all necessary cleanup before this is called.
355     std::process::exit(exit_code);
356 }
357
358 macro_rules! print_usage {
359     ($print:ident, $opts:ident, $reason:expr) => ({
360         let msg = format!(
361             "{}\n\nusage: {} [options] <file>...",
362             $reason,
363             env::args_os().next().unwrap().to_string_lossy()
364         );
365         $print!("{}", $opts.usage(&msg));
366     })
367 }
368
369 fn print_usage_to_stdout(opts: &Options, reason: &str) {
370     print_usage!(println, opts, reason);
371 }
372
373 fn print_usage_to_stderr(opts: &Options, reason: &str) {
374     print_usage!(eprintln, opts, reason);
375 }
376
377 fn print_version() {
378     println!(
379         "{}-nightly{}",
380         env!("CARGO_PKG_VERSION"),
381         include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
382     )
383 }
384
385 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
386     if matches.opt_present("h") {
387         return Ok(Operation::Help);
388     }
389
390     if matches.opt_present("config-help") {
391         return Ok(Operation::ConfigHelp);
392     }
393
394     if matches.opt_present("dump-default-config") {
395         // NOTE for some reason when configured with HasArg::Maybe + Occur::Optional opt_default
396         // doesn't recognize `--foo bar` as a long flag with an argument but as a long flag with no
397         // argument *plus* a free argument. Thus we check for that case in this branch -- this is
398         // required for backward compatibility.
399         if let Some(path) = matches.free.get(0) {
400             return Ok(Operation::ConfigOutputDefault {
401                 path: Some(path.clone()),
402             });
403         } else {
404             return Ok(Operation::ConfigOutputDefault {
405                 path: matches.opt_str("dump-default-config"),
406             });
407         }
408     }
409
410     if matches.opt_present("version") {
411         return Ok(Operation::Version);
412     }
413
414     let config_path_not_found = |path: &str| -> FmtResult<Operation> {
415         Err(FmtError::from(format!(
416             "Error: unable to find a config file for the given path: `{}`",
417             path
418         )))
419     };
420
421     // Read the config_path and convert to parent dir if a file is provided.
422     // If a config file cannot be found from the given path, return error.
423     let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
424         Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
425         Some(ref path) if path.is_dir() => {
426             let config_file_path = get_toml_path(path)?;
427             if config_file_path.is_some() {
428                 config_file_path
429             } else {
430                 return config_path_not_found(path.to_str().unwrap());
431             }
432         }
433         path => path,
434     };
435
436     // If no path is given, we won't output a minimal config.
437     let minimal_config_path = matches.opt_str("dump-minimal-config");
438
439     // if no file argument is supplied, read from stdin
440     if matches.free.is_empty() {
441         let mut buffer = String::new();
442         io::stdin().read_to_string(&mut buffer)?;
443
444         return Ok(Operation::Stdin {
445             input: buffer,
446             config_path: config_path,
447         });
448     }
449
450     let files: Vec<_> = matches
451         .free
452         .iter()
453         .map(|s| {
454             let p = PathBuf::from(s);
455             // we will do comparison later, so here tries to canonicalize first
456             // to get the expected behavior.
457             p.canonicalize().unwrap_or(p)
458         })
459         .collect();
460
461     Ok(Operation::Format {
462         files: files,
463         config_path: config_path,
464         minimal_config_path: minimal_config_path,
465     })
466 }