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