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