]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
refactor: unify run and run_from_stdin
[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 #[macro_use]
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;
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 macro_rules! msg {
32     ($($arg:tt)*) => (
33         match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
34             Ok(_) => {},
35             Err(x) => panic!("Unable to write to stderr: {}", x),
36         }
37     )
38 }
39
40 /// Rustfmt operations.
41 enum Operation {
42     /// Format files and their child modules.
43     Format {
44         files: Vec<PathBuf>,
45         config_path: Option<PathBuf>,
46     },
47     /// Print the help message.
48     Help,
49     // Print version information
50     Version,
51     /// Print detailed configuration help.
52     ConfigHelp,
53     /// Invalid program input.
54     InvalidInput {
55         reason: String,
56     },
57     /// No file specified, read from stdin
58     Stdin {
59         input: String,
60         config_path: Option<PathBuf>,
61     },
62 }
63
64 /// Try to find a project file in the given directory and its parents. Returns the path of a the
65 /// nearest project file if one exists, or `None` if no project file was found.
66 fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
67     let mut current = if dir.is_relative() {
68         try!(env::current_dir()).join(dir)
69     } else {
70         dir.to_path_buf()
71     };
72
73     current = try!(fs::canonicalize(current));
74
75     loop {
76         let config_file = current.join("rustfmt.toml");
77         match fs::metadata(&config_file) {
78             Ok(md) => {
79                 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
80                 if md.is_file() {
81                     return Ok(Some(config_file));
82                 }
83             }
84             // If it's not found, we continue searching; otherwise something went wrong and we
85             // return the error.
86             Err(e) => {
87                 if e.kind() != ErrorKind::NotFound {
88                     return Err(e);
89                 }
90             }
91         }
92
93         // If the current directory has no parent, we're done searching.
94         if !current.pop() {
95             return Ok(None);
96         }
97     }
98 }
99
100 /// Resolve the config for input in `dir`.
101 ///
102 /// Returns the `Config` to use, and the path of the project file if there was
103 /// one.
104 fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
105     let path = try!(lookup_project_file(dir));
106     if path.is_none() {
107         return Ok((Config::default(), None));
108     }
109     let path = path.unwrap();
110     let mut file = try!(File::open(&path));
111     let mut toml = String::new();
112     try!(file.read_to_string(&mut toml));
113     Ok((Config::from_toml(&toml), Some(path)))
114 }
115
116 /// read the given config file path recursively if present else read the project file path
117 fn match_cli_path_or_file(config_path: Option<PathBuf>,
118                           input_file: &Path)
119                           -> io::Result<(Config, Option<PathBuf>)> {
120
121     if let Some(config_file) = config_path {
122         let (toml, path) = try!(resolve_config(config_file.as_ref()));
123         if path.is_some() {
124             return Ok((toml, path));
125         }
126     }
127     resolve_config(input_file)
128 }
129
130 fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
131     config.verbose = matches.opt_present("verbose");
132     config.skip_children = matches.opt_present("skip-children");
133
134     let write_mode = matches.opt_str("write-mode");
135     match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
136         None => Ok(()),
137         Some(Ok(write_mode)) => {
138             config.write_mode = write_mode;
139             Ok(())
140         }
141         Some(Err(_)) => Err(format!("Invalid write-mode: {}", write_mode.expect("cannot happen"))),
142     }
143 }
144
145 fn execute() -> i32 {
146     let mut opts = Options::new();
147     opts.optflag("h", "help", "show this message");
148     opts.optflag("V", "version", "show version information");
149     opts.optflag("v", "verbose", "show progress");
150     opts.optopt("",
151                 "write-mode",
152                 "mode to write in (not usable when piping from stdin)",
153                 "[replace|overwrite|display|diff|coverage|checkstyle]");
154     opts.optflag("", "skip-children", "don't reformat child modules");
155
156     opts.optflag("",
157                  "config-help",
158                  "show details of rustfmt configuration options");
159     opts.optopt("",
160                 "config-path",
161                 "Recursively searches the given path for the rustfmt.toml config file. If not \
162                  found reverts to the input file path",
163                 "[Path for the configuration file]");
164
165     let matches = match opts.parse(env::args().skip(1)) {
166         Ok(m) => m,
167         Err(e) => {
168             print_usage(&opts, &e.to_string());
169             return 1;
170         }
171     };
172
173     let operation = determine_operation(&matches);
174
175     match operation {
176         Operation::InvalidInput { reason } => {
177             print_usage(&opts, &reason);
178             1
179         }
180         Operation::Help => {
181             print_usage(&opts, "");
182             0
183         }
184         Operation::Version => {
185             print_version();
186             0
187         }
188         Operation::ConfigHelp => {
189             Config::print_docs();
190             0
191         }
192         Operation::Stdin { input, config_path } => {
193             // try to read config from local directory
194             let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
195                                       .expect("Error resolving config");
196
197             // write_mode is always Plain for Stdin.
198             config.write_mode = WriteMode::Plain;
199
200             run(Input::Text(input), &config);
201             0
202         }
203         Operation::Format { files, config_path } => {
204             let mut config = Config::default();
205             let mut path = None;
206             // Load the config path file if provided
207             if let Some(config_file) = config_path {
208                 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
209                                               .expect(&format!("Error resolving config for {:?}",
210                                                                config_file));
211                 config = cfg_tmp;
212                 path = path_tmp;
213             };
214             if let Some(path) = path.as_ref() {
215                 msg!("Using rustfmt config file {}", path.display());
216             }
217             for file in files {
218                 // Check the file directory if the config-path could not be read or not provided
219                 if path.is_none() {
220                     let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
221                                                      .expect(&format!("Error resolving config \
222                                                                        for {}",
223                                                                       file.display()));
224                     if let Some(path) = path_tmp.as_ref() {
225                         msg!("Using rustfmt config file {} for {}",
226                              path.display(),
227                              file.display());
228                     }
229                     config = config_tmp;
230                 }
231
232                 if let Err(e) = update_config(&mut config, &matches) {
233                     print_usage(&opts, &e);
234                     return 1;
235                 }
236                 run(Input::File(file), &config);
237             }
238             0
239         }
240     }
241 }
242
243 fn main() {
244     let _ = env_logger::init();
245     let exit_code = execute();
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) -> Operation {
273     if matches.opt_present("h") {
274         return Operation::Help;
275     }
276
277     if matches.opt_present("config-help") {
278         return Operation::ConfigHelp;
279     }
280
281     if matches.opt_present("version") {
282         return 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         match io::stdin().read_to_string(&mut buffer) {
300             Ok(..) => (),
301             Err(e) => return Operation::InvalidInput { reason: e.to_string() },
302         }
303
304         return Operation::Stdin {
305             input: buffer,
306             config_path: config_path,
307         };
308     }
309
310     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
311
312     Operation::Format {
313         files: files,
314         config_path: config_path,
315     }
316 }