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