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