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