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