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