]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
add cli option for color
[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 env_logger;
15 extern crate getopts;
16 extern crate rustfmt_nightly as rustfmt;
17
18 use std::{env, error};
19 use std::fs::File;
20 use std::io::{self, Read, Write};
21 use std::path::{Path, PathBuf};
22 use std::str::FromStr;
23
24 use getopts::{HasArg, Matches, Occur, Options};
25
26 use rustfmt::{run, Input, Summary};
27 use rustfmt::file_lines::FileLines;
28 use rustfmt::config::{get_toml_path, Color, Config, WriteMode};
29
30 type FmtError = Box<error::Error + Send + Sync>;
31 type FmtResult<T> = std::result::Result<T, FmtError>;
32
33 /// Rustfmt operations.
34 enum Operation {
35     /// Format files and their child modules.
36     Format {
37         files: Vec<PathBuf>,
38         config_path: Option<PathBuf>,
39         minimal_config_path: Option<String>,
40     },
41     /// Print the help message.
42     Help,
43     // Print version information
44     Version,
45     /// Print detailed configuration help.
46     ConfigHelp,
47     /// Output default config to a file, or stdout if None
48     ConfigOutputDefault { path: Option<String> },
49     /// No file specified, read from stdin
50     Stdin {
51         input: String,
52         config_path: Option<PathBuf>,
53     },
54 }
55
56 /// Parsed command line options.
57 #[derive(Clone, Debug, Default)]
58 struct CliOptions {
59     skip_children: bool,
60     verbose: bool,
61     write_mode: Option<WriteMode>,
62     color: Option<Color>,
63     file_lines: FileLines, // Default is all lines in all files.
64     unstable_features: bool,
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         let unstable_features = matches.opt_present("unstable-features");
73         let rust_nightly = option_env!("CFG_RELEASE_CHANNEL")
74             .map(|c| c == "nightly")
75             .unwrap_or(false);
76         if unstable_features && !rust_nightly {
77             return Err(FmtError::from(
78                 "Unstable features are only available on Nightly channel",
79             ));
80         } else {
81             options.unstable_features = unstable_features;
82         }
83
84         if let Some(ref write_mode) = matches.opt_str("write-mode") {
85             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
86                 options.write_mode = Some(write_mode);
87             } else {
88                 return Err(FmtError::from(
89                     format!("Invalid write-mode: {}", write_mode),
90                 ));
91             }
92         }
93
94         if let Some(ref color) = matches.opt_str("color") {
95             if let Ok(color) = Color::from_str(color) {
96                 options.color = Some(color);
97             } else {
98                 return Err(FmtError::from(format!("Invalid color: {}", color)));
99             }
100         }
101
102         if let Some(ref file_lines) = matches.opt_str("file-lines") {
103             options.file_lines = file_lines.parse()?;
104         }
105
106         Ok(options)
107     }
108
109     fn apply_to(self, config: &mut Config) {
110         config.set().skip_children(self.skip_children);
111         config.set().verbose(self.verbose);
112         config.set().file_lines(self.file_lines);
113         config.set().unstable_features(self.unstable_features);
114         if let Some(write_mode) = self.write_mode {
115             config.set().write_mode(write_mode);
116         }
117         if let Some(color) = self.color {
118             config.set().color(color);
119         }
120     }
121 }
122
123 /// read the given config file path recursively if present else read the project file path
124 fn match_cli_path_or_file(
125     config_path: Option<PathBuf>,
126     input_file: &Path,
127 ) -> FmtResult<(Config, Option<PathBuf>)> {
128     if let Some(config_file) = config_path {
129         let toml = Config::from_toml_path(config_file.as_ref())?;
130         return Ok((toml, Some(config_file)));
131     }
132     Config::from_resolved_toml_path(input_file).map_err(FmtError::from)
133 }
134
135 fn make_opts() -> Options {
136     let mut opts = Options::new();
137     opts.optflag("h", "help", "show this message");
138     opts.optflag("V", "version", "show version information");
139     opts.optflag("v", "verbose", "print verbose output");
140     opts.optopt(
141         "",
142         "write-mode",
143         "how to write output (not usable when piping from stdin)",
144         "[replace|overwrite|display|plain|diff|coverage|checkstyle]",
145     );
146     opts.optopt(
147         "",
148         "color",
149         "use colored output (if supported)",
150         "[always|never|auto]",
151     );
152     opts.optflag("", "skip-children", "don't reformat child modules");
153
154     opts.optflag(
155         "",
156         "unstable-features",
157         "Enables unstable features. Only available on nightly channel",
158     );
159
160     opts.optflag(
161         "",
162         "config-help",
163         "show details of rustfmt configuration options",
164     );
165     opts.opt(
166         "",
167         "dump-default-config",
168         "Dumps default configuration to PATH. PATH defaults to stdout, if omitted.",
169         "PATH",
170         HasArg::Maybe,
171         Occur::Optional,
172     );
173     opts.optopt(
174         "",
175         "dump-minimal-config",
176         "Dumps configuration options that were checked during formatting to a file.",
177         "PATH",
178     );
179     opts.optopt(
180         "",
181         "config-path",
182         "Recursively searches the given path for the rustfmt.toml config file. If not \
183          found reverts to the input file path",
184         "[Path for the configuration file]",
185     );
186     opts.optopt(
187         "",
188         "file-lines",
189         "Format specified line ranges. See README for more detail on the JSON format.",
190         "JSON",
191     );
192
193     opts
194 }
195
196 fn execute(opts: &Options) -> FmtResult<Summary> {
197     let matches = opts.parse(env::args().skip(1))?;
198
199     match determine_operation(&matches)? {
200         Operation::Help => {
201             print_usage_to_stdout(opts, "");
202             Summary::print_exit_codes();
203             Ok(Summary::default())
204         }
205         Operation::Version => {
206             print_version();
207             Ok(Summary::default())
208         }
209         Operation::ConfigHelp => {
210             Config::print_docs();
211             Ok(Summary::default())
212         }
213         Operation::ConfigOutputDefault { path } => {
214             let toml = Config::default().all_options().to_toml()?;
215             if let Some(path) = path {
216                 let mut file = File::create(path)?;
217                 file.write_all(toml.as_bytes())?;
218             } else {
219                 io::stdout().write_all(toml.as_bytes())?;
220             }
221             Ok(Summary::default())
222         }
223         Operation::Stdin { input, config_path } => {
224             // try to read config from local directory
225             let (mut config, _) =
226                 match_cli_path_or_file(config_path, &env::current_dir().unwrap())?;
227
228             // write_mode is always Plain for Stdin.
229             config.set().write_mode(WriteMode::Plain);
230
231             // parse file_lines
232             if let Some(ref file_lines) = matches.opt_str("file-lines") {
233                 config.set().file_lines(file_lines.parse()?);
234                 for f in config.file_lines().files() {
235                     if f != "stdin" {
236                         eprintln!("Warning: Extra file listed in file_lines option '{}'", f);
237                     }
238                 }
239             }
240
241             let mut error_summary = Summary::default();
242             if config.version_meets_requirement(&mut error_summary) {
243                 error_summary.add(run(Input::Text(input), &config));
244             }
245
246             Ok(error_summary)
247         }
248         Operation::Format {
249             files,
250             config_path,
251             minimal_config_path,
252         } => {
253             let options = CliOptions::from_matches(&matches)?;
254
255             for f in options.file_lines.files() {
256                 if !files.contains(&PathBuf::from(f)) {
257                     eprintln!("Warning: Extra file listed in file_lines option '{}'", f);
258                 }
259             }
260
261             let mut config = Config::default();
262             // Load the config path file if provided
263             if let Some(config_file) = config_path.as_ref() {
264                 config = Config::from_toml_path(config_file.as_ref())?;
265             };
266
267             if options.verbose {
268                 if let Some(path) = config_path.as_ref() {
269                     println!("Using rustfmt config file {}", path.display());
270                 }
271             }
272
273             let mut error_summary = Summary::default();
274             for file in files {
275                 if !file.exists() {
276                     eprintln!("Error: file `{}` does not exist", file.to_str().unwrap());
277                     error_summary.add_operational_error();
278                 } else if file.is_dir() {
279                     eprintln!("Error: `{}` is a directory", file.to_str().unwrap());
280                     error_summary.add_operational_error();
281                 } else {
282                     // Check the file directory if the config-path could not be read or not provided
283                     if config_path.is_none() {
284                         let (config_tmp, path_tmp) =
285                             Config::from_resolved_toml_path(file.parent().unwrap())?;
286                         if options.verbose {
287                             if let Some(path) = path_tmp.as_ref() {
288                                 println!(
289                                     "Using rustfmt config file {} for {}",
290                                     path.display(),
291                                     file.display()
292                                 );
293                             }
294                         }
295                         config = config_tmp;
296                     }
297
298                     if !config.version_meets_requirement(&mut error_summary) {
299                         break;
300                     }
301
302                     options.clone().apply_to(&mut config);
303                     error_summary.add(run(Input::File(file), &config));
304                 }
305             }
306
307             // If we were given a path via dump-minimal-config, output any options
308             // that were used during formatting as TOML.
309             if let Some(path) = minimal_config_path {
310                 let mut file = File::create(path)?;
311                 let toml = config.used_options().to_toml()?;
312                 file.write_all(toml.as_bytes())?;
313             }
314
315             Ok(error_summary)
316         }
317     }
318 }
319
320 fn main() {
321     let _ = env_logger::init();
322
323     let opts = make_opts();
324
325     let exit_code = match execute(&opts) {
326         Ok(summary) => {
327             if summary.has_operational_errors() {
328                 1
329             } else if summary.has_parsing_errors() {
330                 2
331             } else if summary.has_formatting_errors() {
332                 3
333             } else if summary.has_diff {
334                 // should only happen in diff mode
335                 4
336             } else {
337                 assert!(summary.has_no_errors());
338                 0
339             }
340         }
341         Err(e) => {
342             print_usage_to_stderr(&opts, &e.to_string());
343             1
344         }
345     };
346     // Make sure standard output is flushed before we exit.
347     std::io::stdout().flush().unwrap();
348
349     // Exit with given exit code.
350     //
351     // NOTE: This immediately terminates the process without doing any cleanup,
352     // so make sure to finish all necessary cleanup before this is called.
353     std::process::exit(exit_code);
354 }
355
356 macro_rules! print_usage {
357     ($print:ident, $opts:ident, $reason:expr) => ({
358         let msg = format!(
359             "{}\n\nusage: {} [options] <file>...",
360             $reason,
361             env::args_os().next().unwrap().to_string_lossy()
362         );
363         $print!("{}", $opts.usage(&msg));
364     })
365 }
366
367 fn print_usage_to_stdout(opts: &Options, reason: &str) {
368     print_usage!(println, opts, reason);
369 }
370
371 fn print_usage_to_stderr(opts: &Options, reason: &str) {
372     print_usage!(eprintln, opts, reason);
373 }
374
375 fn print_version() {
376     println!(
377         "{}-nightly{}",
378         env!("CARGO_PKG_VERSION"),
379         include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
380     )
381 }
382
383 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
384     if matches.opt_present("h") {
385         return Ok(Operation::Help);
386     }
387
388     if matches.opt_present("config-help") {
389         return Ok(Operation::ConfigHelp);
390     }
391
392     if matches.opt_present("dump-default-config") {
393         // NOTE for some reason when configured with HasArg::Maybe + Occur::Optional opt_default
394         // doesn't recognize `--foo bar` as a long flag with an argument but as a long flag with no
395         // argument *plus* a free argument. Thus we check for that case in this branch -- this is
396         // required for backward compatibility.
397         if let Some(path) = matches.free.get(0) {
398             return Ok(Operation::ConfigOutputDefault {
399                 path: Some(path.clone()),
400             });
401         } else {
402             return Ok(Operation::ConfigOutputDefault {
403                 path: matches.opt_str("dump-default-config"),
404             });
405         }
406     }
407
408     if matches.opt_present("version") {
409         return Ok(Operation::Version);
410     }
411
412     let config_path_not_found = |path: &str| -> FmtResult<Operation> {
413         Err(FmtError::from(format!(
414             "Error: unable to find a config file for the given path: `{}`",
415             path
416         )))
417     };
418
419     // Read the config_path and convert to parent dir if a file is provided.
420     // If a config file cannot be found from the given path, return error.
421     let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
422         Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
423         Some(ref path) if path.is_dir() => {
424             let config_file_path = get_toml_path(path)?;
425             if config_file_path.is_some() {
426                 config_file_path
427             } else {
428                 return config_path_not_found(path.to_str().unwrap());
429             }
430         }
431         path => path,
432     };
433
434     // If no path is given, we won't output a minimal config.
435     let minimal_config_path = matches.opt_str("dump-minimal-config");
436
437     // if no file argument is supplied, read from stdin
438     if matches.free.is_empty() {
439         let mut buffer = String::new();
440         io::stdin().read_to_string(&mut buffer)?;
441
442         return Ok(Operation::Stdin {
443             input: buffer,
444             config_path: config_path,
445         });
446     }
447
448     let files: Vec<_> = matches
449         .free
450         .iter()
451         .map(|s| {
452             let p = PathBuf::from(s);
453             // we will do comparison later, so here tries to canonicalize first
454             // to get the expected behavior.
455             p.canonicalize().unwrap_or(p)
456         })
457         .collect();
458
459     Ok(Operation::Format {
460         files: files,
461         config_path: config_path,
462         minimal_config_path: minimal_config_path,
463     })
464 }