]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
Merge pull request #1075 from johannhof/diff-exit
[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     },
48     /// Print the help message.
49     Help,
50     // Print version information
51     Version,
52     /// Print detailed configuration help.
53     ConfigHelp,
54     /// No file specified, read from stdin
55     Stdin {
56         input: String,
57         config_path: Option<PathBuf>,
58     },
59 }
60
61 /// Parsed command line options.
62 #[derive(Clone, Debug, Default)]
63 struct CliOptions {
64     skip_children: bool,
65     verbose: bool,
66     write_mode: Option<WriteMode>,
67     file_lines: FileLines, // Default is all lines in all files.
68 }
69
70 impl CliOptions {
71     fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
72         let mut options = CliOptions::default();
73         options.skip_children = matches.opt_present("skip-children");
74         options.verbose = matches.opt_present("verbose");
75
76         if let Some(ref write_mode) = matches.opt_str("write-mode") {
77             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
78                 options.write_mode = Some(write_mode);
79             } else {
80                 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
81             }
82         }
83
84         if let Some(ref file_lines) = matches.opt_str("file-lines") {
85             options.file_lines = try!(file_lines.parse());
86         }
87
88         Ok(options)
89     }
90
91     fn apply_to(self, config: &mut Config) {
92         config.skip_children = self.skip_children;
93         config.verbose = self.verbose;
94         config.file_lines = self.file_lines;
95         if let Some(write_mode) = self.write_mode {
96             config.write_mode = write_mode;
97         }
98     }
99 }
100
101 /// Try to find a project file in the given directory and its parents. Returns the path of a the
102 /// nearest project file if one exists, or `None` if no project file was found.
103 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
104     let mut current = if dir.is_relative() {
105         try!(env::current_dir()).join(dir)
106     } else {
107         dir.to_path_buf()
108     };
109
110     current = try!(fs::canonicalize(current));
111
112     loop {
113         let config_file = current.join("rustfmt.toml");
114         match fs::metadata(&config_file) {
115             // Only return if it's a file to handle the unlikely situation of a directory named
116             // `rustfmt.toml`.
117             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
118             // Return the error if it's something other than `NotFound`; otherwise we didn't find
119             // the project file yet, and continue searching.
120             Err(e) => {
121                 if e.kind() != ErrorKind::NotFound {
122                     return Err(FmtError::from(e));
123                 }
124             }
125             _ => {}
126         }
127
128         // If the current directory has no parent, we're done searching.
129         if !current.pop() {
130             return Ok(None);
131         }
132     }
133 }
134
135 /// Resolve the config for input in `dir`.
136 ///
137 /// Returns the `Config` to use, and the path of the project file if there was
138 /// one.
139 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
140     let path = try!(lookup_project_file(dir));
141     if path.is_none() {
142         return Ok((Config::default(), None));
143     }
144     let path = path.unwrap();
145     let mut file = try!(File::open(&path));
146     let mut toml = String::new();
147     try!(file.read_to_string(&mut toml));
148     Ok((Config::from_toml(&toml), Some(path)))
149 }
150
151 /// read the given config file path recursively if present else read the project file path
152 fn match_cli_path_or_file(config_path: Option<PathBuf>,
153                           input_file: &Path)
154                           -> FmtResult<(Config, Option<PathBuf>)> {
155
156     if let Some(config_file) = config_path {
157         let (toml, path) = try!(resolve_config(config_file.as_ref()));
158         if path.is_some() {
159             return Ok((toml, path));
160         }
161     }
162     resolve_config(input_file)
163 }
164
165 fn make_opts() -> Options {
166     let mut opts = Options::new();
167     opts.optflag("h", "help", "show this message");
168     opts.optflag("V", "version", "show version information");
169     opts.optflag("v", "verbose", "show progress");
170     opts.optopt("",
171                 "write-mode",
172                 "mode to write in (not usable when piping from stdin)",
173                 "[replace|overwrite|display|diff|coverage|checkstyle]");
174     opts.optflag("", "skip-children", "don't reformat child modules");
175
176     opts.optflag("",
177                  "config-help",
178                  "show details of rustfmt configuration options");
179     opts.optopt("",
180                 "config-path",
181                 "Recursively searches the given path for the rustfmt.toml config file. If not \
182                  found reverts to the input file path",
183                 "[Path for the configuration file]");
184     opts.optopt("",
185                 "file-lines",
186                 "Format specified line ranges. See README for more detail on the JSON format.",
187                 "JSON");
188
189     opts
190 }
191
192 fn execute(opts: &Options) -> FmtResult<Summary> {
193     let matches = try!(opts.parse(env::args().skip(1)));
194
195     match try!(determine_operation(&matches)) {
196         Operation::Help => {
197             print_usage(&opts, "");
198             Ok(Summary::new())
199         }
200         Operation::Version => {
201             print_version();
202             Ok(Summary::new())
203         }
204         Operation::ConfigHelp => {
205             Config::print_docs();
206             Ok(Summary::new())
207         }
208         Operation::Stdin { input, config_path } => {
209             // try to read config from local directory
210             let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
211                 .expect("Error resolving config");
212
213             // write_mode is always Plain for Stdin.
214             config.write_mode = WriteMode::Plain;
215
216             Ok(run(Input::Text(input), &config))
217         }
218         Operation::Format { mut files, config_path } => {
219             let options = try!(CliOptions::from_matches(&matches));
220
221             // Add any additional files that were specified via `--file-lines`.
222             files.extend(options.file_lines.files().cloned().map(PathBuf::from));
223
224             let mut config = Config::default();
225             let mut path = None;
226             // Load the config path file if provided
227             if let Some(config_file) = config_path {
228                 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
229                     .expect(&format!("Error resolving config for {:?}", config_file));
230                 config = cfg_tmp;
231                 path = path_tmp;
232             };
233             if let Some(path) = path.as_ref() {
234                 println!("Using rustfmt config file {}", path.display());
235             }
236
237             let mut error_summary = Summary::new();
238             for file in files {
239                 // Check the file directory if the config-path could not be read or not provided
240                 if path.is_none() {
241                     let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
242                         .expect(&format!("Error resolving config for {}", file.display()));
243                     if let Some(path) = path_tmp.as_ref() {
244                         println!("Using rustfmt config file {} for {}",
245                                  path.display(),
246                                  file.display());
247                     }
248                     config = config_tmp;
249                 }
250
251                 options.clone().apply_to(&mut config);
252                 error_summary.add(run(Input::File(file), &config));
253             }
254             Ok(error_summary)
255         }
256     }
257 }
258
259 fn main() {
260     let _ = env_logger::init();
261
262     let opts = make_opts();
263
264     let exit_code = match execute(&opts) {
265         Ok(summary) => {
266             if summary.has_operational_errors() {
267                 1
268             } else if summary.has_parsing_errors() {
269                 2
270             } else if summary.has_formatting_errors() {
271                 3
272             } else if summary.has_diff {
273                 // should only happen in diff mode
274                 4
275             } else {
276                 assert!(summary.has_no_errors());
277                 0
278             }
279         }
280         Err(e) => {
281             print_usage(&opts, &e.to_string());
282             1
283         }
284     };
285     // Make sure standard output is flushed before we exit.
286     std::io::stdout().flush().unwrap();
287
288     // Exit with given exit code.
289     //
290     // NOTE: This immediately terminates the process without doing any cleanup,
291     // so make sure to finish all necessary cleanup before this is called.
292     std::process::exit(exit_code);
293 }
294
295 fn print_usage(opts: &Options, reason: &str) {
296     let reason = format!("{}\nusage: {} [options] <file>...",
297                          reason,
298                          env::args_os().next().unwrap().to_string_lossy());
299     println!("{}", opts.usage(&reason));
300 }
301
302 fn print_version() {
303     println!("{} ({}{})",
304              option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
305              COMMIT_HASH.unwrap_or("git commit unavailable"),
306              match WORKTREE_CLEAN {
307                  Some(false) => " worktree dirty",
308                  _ => "",
309              });
310 }
311
312 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
313     if matches.opt_present("h") {
314         return Ok(Operation::Help);
315     }
316
317     if matches.opt_present("config-help") {
318         return Ok(Operation::ConfigHelp);
319     }
320
321     if matches.opt_present("version") {
322         return Ok(Operation::Version);
323     }
324
325     // Read the config_path and convert to parent dir if a file is provided.
326     let config_path: Option<PathBuf> = matches.opt_str("config-path")
327         .map(PathBuf::from)
328         .and_then(|dir| {
329             if dir.is_file() {
330                 return dir.parent().map(|v| v.into());
331             }
332             Some(dir)
333         });
334
335     // if no file argument is supplied and `--file-lines` is not specified, read from stdin
336     if matches.free.is_empty() && !matches.opt_present("file-lines") {
337
338         let mut buffer = String::new();
339         try!(io::stdin().read_to_string(&mut buffer));
340
341         return Ok(Operation::Stdin {
342             input: buffer,
343             config_path: config_path,
344         });
345     }
346
347     // We append files from `--file-lines` later in `execute()`.
348     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
349
350     Ok(Operation::Format {
351         files: files,
352         config_path: config_path,
353     })
354 }