]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
rustfmt: Simplify match in project file lookup loop
[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};
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<()> {
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         }
166         Operation::Version => {
167             print_version();
168         }
169         Operation::ConfigHelp => {
170             Config::print_docs();
171         }
172         Operation::Stdin { input, config_path } => {
173             // try to read config from local directory
174             let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
175                                       .expect("Error resolving config");
176
177             // write_mode is always Plain for Stdin.
178             config.write_mode = WriteMode::Plain;
179
180             run(Input::Text(input), &config);
181         }
182         Operation::Format { files, config_path } => {
183             let mut config = Config::default();
184             let mut path = None;
185             // Load the config path file if provided
186             if let Some(config_file) = config_path {
187                 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
188                                               .expect(&format!("Error resolving config for {:?}",
189                                                                config_file));
190                 config = cfg_tmp;
191                 path = path_tmp;
192             };
193             if let Some(path) = path.as_ref() {
194                 println!("Using rustfmt config file {}", path.display());
195             }
196             for file in files {
197                 // Check the file directory if the config-path could not be read or not provided
198                 if path.is_none() {
199                     let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
200                                                      .expect(&format!("Error resolving config \
201                                                                        for {}",
202                                                                       file.display()));
203                     if let Some(path) = path_tmp.as_ref() {
204                         println!("Using rustfmt config file {} for {}",
205                                  path.display(),
206                                  file.display());
207                     }
208                     config = config_tmp;
209                 }
210
211                 try!(update_config(&mut config, &matches));
212                 run(Input::File(file), &config);
213             }
214         }
215     }
216     Ok(())
217 }
218
219 fn main() {
220     let _ = env_logger::init();
221
222     let opts = make_opts();
223
224     let exit_code = match execute(&opts) {
225         Ok(..) => 0,
226         Err(e) => {
227             print_usage(&opts, &e.to_string());
228             1
229         }
230     };
231     // Make sure standard output is flushed before we exit.
232     std::io::stdout().flush().unwrap();
233
234     // Exit with given exit code.
235     //
236     // NOTE: This immediately terminates the process without doing any cleanup,
237     // so make sure to finish all necessary cleanup before this is called.
238     std::process::exit(exit_code);
239 }
240
241 fn print_usage(opts: &Options, reason: &str) {
242     let reason = format!("{}\nusage: {} [options] <file>...",
243                          reason,
244                          env::args_os().next().unwrap().to_string_lossy());
245     println!("{}", opts.usage(&reason));
246 }
247
248 fn print_version() {
249     println!("{}.{}.{}{}",
250              option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
251              option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
252              option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
253              option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
254 }
255
256 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
257     if matches.opt_present("h") {
258         return Ok(Operation::Help);
259     }
260
261     if matches.opt_present("config-help") {
262         return Ok(Operation::ConfigHelp);
263     }
264
265     if matches.opt_present("version") {
266         return Ok(Operation::Version);
267     }
268
269     // Read the config_path and convert to parent dir if a file is provided.
270     let config_path: Option<PathBuf> = matches.opt_str("config-path")
271                                               .map(PathBuf::from)
272                                               .and_then(|dir| {
273                                                   if dir.is_file() {
274                                                       return dir.parent().map(|v| v.into());
275                                                   }
276                                                   Some(dir)
277                                               });
278
279     // if no file argument is supplied, read from stdin
280     if matches.free.is_empty() {
281
282         let mut buffer = String::new();
283         try!(io::stdin().read_to_string(&mut buffer));
284
285         return Ok(Operation::Stdin {
286             input: buffer,
287             config_path: config_path,
288         });
289     }
290
291     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
292
293     Ok(Operation::Format {
294         files: files,
295         config_path: config_path,
296     })
297 }