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