]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
Merge pull request #1620 from topecongiro/rfc-if
[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, Summary};
21 use rustfmt::file_lines::FileLines;
22 use rustfmt::config::{Config, WriteMode, get_toml_path};
23
24 use std::{env, error};
25 use std::fs::File;
26 use std::io::{self, Read, Write};
27 use std::path::{Path, PathBuf};
28 use std::str::FromStr;
29
30 use getopts::{Matches, Options};
31
32 type FmtError = Box<error::Error + Send + Sync>;
33 type FmtResult<T> = std::result::Result<T, FmtError>;
34
35 /// Rustfmt operations.
36 enum Operation {
37     /// Format files and their child modules.
38     Format {
39         files: Vec<PathBuf>,
40         config_path: Option<PathBuf>,
41         minimal_config_path: Option<String>,
42     },
43     /// Print the help message.
44     Help,
45     // Print version information
46     Version,
47     /// Print detailed configuration help.
48     ConfigHelp,
49     /// Output default config to a file
50     ConfigOutputDefault { path: String },
51     /// No file specified, read from stdin
52     Stdin {
53         input: String,
54         config_path: Option<PathBuf>,
55     },
56 }
57
58 /// Parsed command line options.
59 #[derive(Clone, Debug, Default)]
60 struct CliOptions {
61     skip_children: bool,
62     verbose: bool,
63     write_mode: Option<WriteMode>,
64     file_lines: FileLines, // Default is all lines in all files.
65 }
66
67 impl CliOptions {
68     fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
69         let mut options = CliOptions::default();
70         options.skip_children = matches.opt_present("skip-children");
71         options.verbose = matches.opt_present("verbose");
72
73         if let Some(ref write_mode) = matches.opt_str("write-mode") {
74             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
75                 options.write_mode = Some(write_mode);
76             } else {
77                 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
78             }
79         }
80
81         if let Some(ref file_lines) = matches.opt_str("file-lines") {
82             options.file_lines = file_lines.parse()?;
83         }
84
85         Ok(options)
86     }
87
88     fn apply_to(self, config: &mut Config) {
89         config.set().skip_children(self.skip_children);
90         config.set().verbose(self.verbose);
91         config.set().file_lines(self.file_lines);
92         if let Some(write_mode) = self.write_mode {
93             config.set().write_mode(write_mode);
94         }
95     }
96 }
97
98 /// read the given config file path recursively if present else read the project file path
99 fn match_cli_path_or_file(config_path: Option<PathBuf>,
100                           input_file: &Path)
101                           -> FmtResult<(Config, Option<PathBuf>)> {
102
103     if let Some(config_file) = config_path {
104         let toml = Config::from_toml_path(config_file.as_ref())?;
105         return Ok((toml, Some(config_file)));
106     }
107     Config::from_resolved_toml_path(input_file).map_err(|e| FmtError::from(e))
108 }
109
110 fn make_opts() -> Options {
111     let mut opts = Options::new();
112     opts.optflag("h", "help", "show this message");
113     opts.optflag("V", "version", "show version information");
114     opts.optflag("v", "verbose", "print verbose output");
115     opts.optopt("",
116                 "write-mode",
117                 "mode to write in (not usable when piping from stdin)",
118                 "[replace|overwrite|display|diff|coverage|checkstyle]");
119     opts.optflag("", "skip-children", "don't reformat child modules");
120
121     opts.optflag("",
122                  "config-help",
123                  "show details of rustfmt configuration options");
124     opts.optopt("",
125                 "dump-default-config",
126                 "Dumps the default configuration to a file and exits.",
127                 "PATH");
128     opts.optopt("",
129                 "dump-minimal-config",
130                 "Dumps configuration options that were checked during formatting to a file.",
131                 "PATH");
132     opts.optopt("",
133                 "config-path",
134                 "Recursively searches the given path for the rustfmt.toml config file. If not \
135                  found reverts to the input file path",
136                 "[Path for the configuration file]");
137     opts.optopt("",
138                 "file-lines",
139                 "Format specified line ranges. See README for more detail on the JSON format.",
140                 "JSON");
141
142     opts
143 }
144
145 fn execute(opts: &Options) -> FmtResult<Summary> {
146     let matches = opts.parse(env::args().skip(1))?;
147
148     match determine_operation(&matches)? {
149         Operation::Help => {
150             print_usage(opts, "");
151             Summary::print_exit_codes();
152             Ok(Summary::new())
153         }
154         Operation::Version => {
155             print_version();
156             Ok(Summary::new())
157         }
158         Operation::ConfigHelp => {
159             Config::print_docs();
160             Ok(Summary::new())
161         }
162         Operation::ConfigOutputDefault { path } => {
163             let mut file = File::create(path)?;
164             let toml = Config::default().all_options().to_toml()?;
165             file.write_all(toml.as_bytes())?;
166             Ok(Summary::new())
167         }
168         Operation::Stdin { input, config_path } => {
169             // try to read config from local directory
170             let (mut config, _) = match_cli_path_or_file(config_path,
171                                                          &env::current_dir().unwrap())?;
172
173             // write_mode is always Plain for Stdin.
174             config.set().write_mode(WriteMode::Plain);
175
176             // parse file_lines
177             if let Some(ref file_lines) = matches.opt_str("file-lines") {
178                 config.set().file_lines(file_lines.parse()?);
179                 for f in config.file_lines().files() {
180                     if f != "stdin" {
181                         println!("Warning: Extra file listed in file_lines option '{}'", f);
182                     }
183                 }
184             }
185
186             Ok(run(Input::Text(input), &config))
187         }
188         Operation::Format {
189             files,
190             config_path,
191             minimal_config_path,
192         } => {
193             let options = CliOptions::from_matches(&matches)?;
194
195             for f in options.file_lines.files() {
196                 if !files.contains(&PathBuf::from(f)) {
197                     println!("Warning: Extra file listed in file_lines option '{}'", f);
198                 }
199             }
200
201             let mut config = Config::default();
202             // Load the config path file if provided
203             if let Some(config_file) = config_path.as_ref() {
204                 config = Config::from_toml_path(config_file.as_ref())?;
205             };
206
207             if options.verbose {
208                 if let Some(path) = config_path.as_ref() {
209                     println!("Using rustfmt config file {}", path.display());
210                 }
211             }
212
213             let mut error_summary = Summary::new();
214             for file in files {
215                 if !file.exists() {
216                     println!("Error: file `{}` does not exist", file.to_str().unwrap());
217                     error_summary.add_operational_error();
218                 } else if file.is_dir() {
219                     println!("Error: `{}` is a directory", file.to_str().unwrap());
220                     error_summary.add_operational_error();
221                 } else {
222                     // Check the file directory if the config-path could not be read or not provided
223                     if config_path.is_none() {
224                         let (config_tmp, path_tmp) =
225                             Config::from_resolved_toml_path(file.parent().unwrap())?;
226                         if options.verbose {
227                             if let Some(path) = path_tmp.as_ref() {
228                                 println!("Using rustfmt config file {} for {}",
229                                          path.display(),
230                                          file.display());
231                             }
232                         }
233                         config = config_tmp;
234                     }
235
236                     options.clone().apply_to(&mut config);
237                     error_summary.add(run(Input::File(file), &config));
238                 }
239             }
240
241             // If we were given a path via dump-minimal-config, output any options
242             // that were used during formatting as TOML.
243             if let Some(path) = minimal_config_path {
244                 let mut file = File::create(path)?;
245                 let toml = config.used_options().to_toml()?;
246                 file.write_all(toml.as_bytes())?;
247             }
248
249             Ok(error_summary)
250         }
251     }
252 }
253
254 fn main() {
255     let _ = env_logger::init();
256
257     let opts = make_opts();
258
259     let exit_code = match execute(&opts) {
260         Ok(summary) => {
261             if summary.has_operational_errors() {
262                 1
263             } else if summary.has_parsing_errors() {
264                 2
265             } else if summary.has_formatting_errors() {
266                 3
267             } else if summary.has_diff {
268                 // should only happen in diff mode
269                 4
270             } else {
271                 assert!(summary.has_no_errors());
272                 0
273             }
274         }
275         Err(e) => {
276             print_usage(&opts, &e.to_string());
277             1
278         }
279     };
280     // Make sure standard output is flushed before we exit.
281     std::io::stdout().flush().unwrap();
282
283     // Exit with given exit code.
284     //
285     // NOTE: This immediately terminates the process without doing any cleanup,
286     // so make sure to finish all necessary cleanup before this is called.
287     std::process::exit(exit_code);
288 }
289
290 fn print_usage(opts: &Options, reason: &str) {
291     let reason = format!("{}\n\nusage: {} [options] <file>...",
292                          reason,
293                          env::args_os().next().unwrap().to_string_lossy());
294     println!("{}", opts.usage(&reason));
295 }
296
297 fn print_version() {
298     println!("{}-nightly{}",
299              env!("CARGO_PKG_VERSION"),
300              include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt")))
301 }
302
303 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
304     if matches.opt_present("h") {
305         return Ok(Operation::Help);
306     }
307
308     if matches.opt_present("config-help") {
309         return Ok(Operation::ConfigHelp);
310     }
311
312     if let Some(path) = matches.opt_str("dump-default-config") {
313         return Ok(Operation::ConfigOutputDefault { path });
314     }
315
316     if matches.opt_present("version") {
317         return Ok(Operation::Version);
318     }
319
320     let config_path_not_found = |path: &str| -> FmtResult<Operation> {
321         Err(FmtError::from(format!("Error: unable to find a config file for the given path: `{}`",
322                                    path)))
323     };
324
325     // Read the config_path and convert to parent dir if a file is provided.
326     // If a config file cannot be found from the given path, return error.
327     let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
328         Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
329         Some(ref path) if path.is_dir() => {
330             let config_file_path = get_toml_path(path)?;
331             if config_file_path.is_some() {
332                 config_file_path
333             } else {
334                 return config_path_not_found(path.to_str().unwrap());
335             }
336         }
337         path @ _ => path,
338     };
339
340     // If no path is given, we won't output a minimal config.
341     let minimal_config_path = matches.opt_str("dump-minimal-config");
342
343     // if no file argument is supplied, read from stdin
344     if matches.free.is_empty() {
345         let mut buffer = String::new();
346         io::stdin().read_to_string(&mut buffer)?;
347
348         return Ok(Operation::Stdin {
349                       input: buffer,
350                       config_path: config_path,
351                   });
352     }
353
354     let files: Vec<_> = matches
355         .free
356         .iter()
357         .map(|s| {
358                  let p = PathBuf::from(s);
359                  // we will do comparison later, so here tries to canonicalize first
360                  // to get the expected behavior.
361                  p.canonicalize().unwrap_or(p)
362              })
363         .collect();
364
365     Ok(Operation::Format {
366            files: files,
367            config_path: config_path,
368            minimal_config_path: minimal_config_path,
369        })
370 }