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