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