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