]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
return non-zero exit code if there were errors
[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::config::{Config, WriteMode};
22
23 use std::{env, error};
24 use std::fs::{self, File};
25 use std::io::{self, ErrorKind, Read, Write};
26 use std::path::{Path, PathBuf};
27 use std::str::FromStr;
28
29 use getopts::{Matches, Options};
30
31 type FmtError = Box<error::Error + Send + Sync>;
32 type FmtResult<T> = std::result::Result<T, FmtError>;
33
34 /// Rustfmt operations.
35 enum Operation {
36     /// Format files and their child modules.
37     Format {
38         files: Vec<PathBuf>,
39         config_path: Option<PathBuf>,
40     },
41     /// Print the help message.
42     Help,
43     // Print version information
44     Version,
45     /// Print detailed configuration help.
46     ConfigHelp,
47     /// No file specified, read from stdin
48     Stdin {
49         input: String,
50         config_path: Option<PathBuf>,
51     },
52 }
53
54 /// Try to find a project file in the given directory and its parents. Returns the path of a the
55 /// nearest project file if one exists, or `None` if no project file was found.
56 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
57     let mut current = if dir.is_relative() {
58         try!(env::current_dir()).join(dir)
59     } else {
60         dir.to_path_buf()
61     };
62
63     current = try!(fs::canonicalize(current));
64
65     loop {
66         let config_file = current.join("rustfmt.toml");
67         match fs::metadata(&config_file) {
68             // Only return if it's a file to handle the unlikely situation of a directory named
69             // `rustfmt.toml`.
70             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
71             // Return the error if it's something other than `NotFound`; otherwise we didn't find
72             // the project file yet, and continue searching.
73             Err(e) => {
74                 if e.kind() != ErrorKind::NotFound {
75                     return Err(FmtError::from(e));
76                 }
77             }
78             _ => {}
79         }
80
81         // If the current directory has no parent, we're done searching.
82         if !current.pop() {
83             return Ok(None);
84         }
85     }
86 }
87
88 /// Resolve the config for input in `dir`.
89 ///
90 /// Returns the `Config` to use, and the path of the project file if there was
91 /// one.
92 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
93     let path = try!(lookup_project_file(dir));
94     if path.is_none() {
95         return Ok((Config::default(), None));
96     }
97     let path = path.unwrap();
98     let mut file = try!(File::open(&path));
99     let mut toml = String::new();
100     try!(file.read_to_string(&mut toml));
101     Ok((Config::from_toml(&toml), Some(path)))
102 }
103
104 /// read the given config file path recursively if present else read the project file path
105 fn match_cli_path_or_file(config_path: Option<PathBuf>,
106                           input_file: &Path)
107                           -> FmtResult<(Config, Option<PathBuf>)> {
108
109     if let Some(config_file) = config_path {
110         let (toml, path) = try!(resolve_config(config_file.as_ref()));
111         if path.is_some() {
112             return Ok((toml, path));
113         }
114     }
115     resolve_config(input_file)
116 }
117
118 fn update_config(config: &mut Config, matches: &Matches) -> FmtResult<()> {
119     config.verbose = matches.opt_present("verbose");
120     config.skip_children = matches.opt_present("skip-children");
121
122     let write_mode = matches.opt_str("write-mode");
123     match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
124         None => Ok(()),
125         Some(Ok(write_mode)) => {
126             config.write_mode = write_mode;
127             Ok(())
128         }
129         Some(Err(_)) => {
130             Err(FmtError::from(format!("Invalid write-mode: {}",
131                                        write_mode.expect("cannot happen"))))
132         }
133     }
134 }
135
136 fn make_opts() -> Options {
137     let mut opts = Options::new();
138     opts.optflag("h", "help", "show this message");
139     opts.optflag("V", "version", "show version information");
140     opts.optflag("v", "verbose", "show progress");
141     opts.optopt("",
142                 "write-mode",
143                 "mode to write in (not usable when piping from stdin)",
144                 "[replace|overwrite|display|diff|coverage|checkstyle]");
145     opts.optflag("", "skip-children", "don't reformat child modules");
146
147     opts.optflag("",
148                  "config-help",
149                  "show details of rustfmt configuration options");
150     opts.optopt("",
151                 "config-path",
152                 "Recursively searches the given path for the rustfmt.toml config file. If not \
153                  found reverts to the input file path",
154                 "[Path for the configuration file]");
155
156     opts
157 }
158
159 fn execute(opts: &Options) -> FmtResult<Summary> {
160     let matches = try!(opts.parse(env::args().skip(1)));
161
162     match try!(determine_operation(&matches)) {
163         Operation::Help => {
164             print_usage(&opts, "");
165             Ok(Summary::new())
166         }
167         Operation::Version => {
168             print_version();
169             Ok(Summary::new())
170         }
171         Operation::ConfigHelp => {
172             Config::print_docs();
173             Ok(Summary::new())
174         }
175         Operation::Stdin { input, config_path } => {
176             // try to read config from local directory
177             let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
178                                       .expect("Error resolving config");
179
180             // write_mode is always Plain for Stdin.
181             config.write_mode = WriteMode::Plain;
182
183             Ok(run(Input::Text(input), &config))
184         }
185         Operation::Format { files, config_path } => {
186             let mut config = Config::default();
187             let mut path = None;
188             // Load the config path file if provided
189             if let Some(config_file) = config_path {
190                 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
191                                               .expect(&format!("Error resolving config for {:?}",
192                                                                config_file));
193                 config = cfg_tmp;
194                 path = path_tmp;
195             };
196             if let Some(path) = path.as_ref() {
197                 println!("Using rustfmt config file {}", path.display());
198             }
199
200             let mut error_summary = Summary::new();
201             for file in files {
202                 // Check the file directory if the config-path could not be read or not provided
203                 if path.is_none() {
204                     let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
205                                                      .expect(&format!("Error resolving config \
206                                                                        for {}",
207                                                                       file.display()));
208                     if let Some(path) = path_tmp.as_ref() {
209                         println!("Using rustfmt config file {} for {}",
210                                  path.display(),
211                                  file.display());
212                     }
213                     config = config_tmp;
214                 }
215
216                 try!(update_config(&mut config, &matches));
217                 error_summary.add(run(Input::File(file), &config));
218             }
219             Ok(error_summary)
220         }
221     }
222 }
223
224 fn main() {
225     let _ = env_logger::init();
226
227     let opts = make_opts();
228
229     let exit_code = match execute(&opts) {
230         Ok(summary) => {
231             if summary.has_operational_errors() {
232                 1
233             } else if summary.has_parsing_errors() {
234                 2
235             } else if summary.has_formatting_errors() {
236                 3
237             } else {
238                 assert!(summary.has_no_errors());
239                 0
240             }
241         }
242         Err(e) => {
243             print_usage(&opts, &e.to_string());
244             1
245         }
246     };
247     // Make sure standard output is flushed before we exit.
248     std::io::stdout().flush().unwrap();
249
250     // Exit with given exit code.
251     //
252     // NOTE: This immediately terminates the process without doing any cleanup,
253     // so make sure to finish all necessary cleanup before this is called.
254     std::process::exit(exit_code);
255 }
256
257 fn print_usage(opts: &Options, reason: &str) {
258     let reason = format!("{}\nusage: {} [options] <file>...",
259                          reason,
260                          env::args_os().next().unwrap().to_string_lossy());
261     println!("{}", opts.usage(&reason));
262 }
263
264 fn print_version() {
265     println!("{}.{}.{}{}",
266              option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
267              option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
268              option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
269              option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
270 }
271
272 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
273     if matches.opt_present("h") {
274         return Ok(Operation::Help);
275     }
276
277     if matches.opt_present("config-help") {
278         return Ok(Operation::ConfigHelp);
279     }
280
281     if matches.opt_present("version") {
282         return Ok(Operation::Version);
283     }
284
285     // Read the config_path and convert to parent dir if a file is provided.
286     let config_path: Option<PathBuf> = matches.opt_str("config-path")
287                                               .map(PathBuf::from)
288                                               .and_then(|dir| {
289                                                   if dir.is_file() {
290                                                       return dir.parent().map(|v| v.into());
291                                                   }
292                                                   Some(dir)
293                                               });
294
295     // if no file argument is supplied, read from stdin
296     if matches.free.is_empty() {
297
298         let mut buffer = String::new();
299         try!(io::stdin().read_to_string(&mut buffer));
300
301         return Ok(Operation::Stdin {
302             input: buffer,
303             config_path: config_path,
304         });
305     }
306
307     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
308
309     Ok(Operation::Format {
310         files: files,
311         config_path: config_path,
312     })
313 }