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