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