]> git.lizzy.rs Git - rust.git/blob - src/bin/main.rs
Merge pull request #2693 from gnzlbg/integration
[rust.git] / src / bin / main.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 extern crate env_logger;
14 extern crate failure;
15 extern crate getopts;
16 extern crate rustfmt_nightly as rustfmt;
17
18 use std::env;
19 use std::fs::File;
20 use std::io::{self, stdout, Read, Write};
21 use std::path::{Path, PathBuf};
22
23 use failure::err_msg;
24
25 use getopts::{Matches, Options};
26
27 use rustfmt::{
28     emit_post_matter, emit_pre_matter, format_and_emit_report, load_config, CliOptions, Config,
29     FileName, FmtResult, Input, Summary, Verbosity, WriteMode, WRITE_MODE_LIST,
30 };
31
32 fn main() {
33     env_logger::init();
34     let opts = make_opts();
35
36     let exit_code = match execute(&opts) {
37         Ok((write_mode, summary)) => {
38             if summary.has_operational_errors()
39                 || summary.has_parsing_errors()
40                 || (summary.has_diff && write_mode == WriteMode::Check)
41             {
42                 1
43             } else {
44                 0
45             }
46         }
47         Err(e) => {
48             eprintln!("{}", e.to_string());
49             1
50         }
51     };
52     // Make sure standard output is flushed before we exit.
53     std::io::stdout().flush().unwrap();
54
55     // Exit with given exit code.
56     //
57     // NOTE: This immediately terminates the process without doing any cleanup,
58     // so make sure to finish all necessary cleanup before this is called.
59     std::process::exit(exit_code);
60 }
61
62 /// Rustfmt operations.
63 enum Operation {
64     /// Format files and their child modules.
65     Format {
66         files: Vec<PathBuf>,
67         minimal_config_path: Option<String>,
68     },
69     /// Print the help message.
70     Help(HelpOp),
71     // Print version information
72     Version,
73     /// Output default config to a file, or stdout if None
74     ConfigOutputDefault {
75         path: Option<String>,
76     },
77     /// No file specified, read from stdin
78     Stdin {
79         input: String,
80     },
81 }
82
83 /// Arguments to `--help`
84 enum HelpOp {
85     None,
86     Config,
87     FileLines,
88 }
89
90 fn make_opts() -> Options {
91     let mut opts = Options::new();
92
93     // Sorted in alphabetical order.
94     opts.optflag(
95         "",
96         "check",
97         "Run in 'check' mode. Exits with 0 if input if formatted correctly. Exits \
98          with 1 and prints a diff if formatting is required.",
99     );
100     opts.optopt(
101         "",
102         "color",
103         "Use colored output (if supported)",
104         "[always|never|auto]",
105     );
106     opts.optopt(
107         "",
108         "config-path",
109         "Recursively searches the given path for the rustfmt.toml config file. If not \
110          found reverts to the input file path",
111         "[Path for the configuration file]",
112     );
113     opts.optflag(
114         "",
115         "error-on-unformatted",
116         "Error if unable to get comments or string literals within max_width, \
117          or they are left with trailing whitespaces",
118     );
119     opts.optopt(
120         "",
121         "file-lines",
122         "Format specified line ranges. See README for more detail on the JSON format.",
123         "JSON",
124     );
125     opts.optflagopt(
126         "h",
127         "help",
128         "Show this message or help about a specific topic: config or file-lines",
129         "=TOPIC",
130     );
131     opts.optopt(
132         "",
133         "print-config",
134         "Dumps a default or minimal config to PATH. A minimal config is the \
135          subset of the current config file used for formatting the current program.",
136         "[minimal|default] PATH",
137     );
138     opts.optflag("", "skip-children", "Don't reformat child modules");
139     opts.optflag(
140         "",
141         "unstable-features",
142         "Enables unstable features. Only available on nightly channel",
143     );
144     opts.optflag("v", "verbose", "Print verbose output");
145     opts.optflag("q", "quiet", "Print less output");
146     opts.optflag("V", "version", "Show version information");
147     opts.optopt(
148         "",
149         "write-mode",
150         "How to write output (not usable when piping from stdin)",
151         WRITE_MODE_LIST,
152     );
153
154     opts
155 }
156
157 fn execute(opts: &Options) -> FmtResult<(WriteMode, Summary)> {
158     let matches = opts.parse(env::args().skip(1))?;
159
160     match determine_operation(&matches)? {
161         Operation::Help(HelpOp::None) => {
162             print_usage_to_stdout(opts, "");
163             Summary::print_exit_codes();
164             Ok((WriteMode::None, Summary::default()))
165         }
166         Operation::Help(HelpOp::Config) => {
167             Config::print_docs(&mut stdout(), matches.opt_present("unstable-features"));
168             Ok((WriteMode::None, Summary::default()))
169         }
170         Operation::Help(HelpOp::FileLines) => {
171             print_help_file_lines();
172             Ok((WriteMode::None, Summary::default()))
173         }
174         Operation::Version => {
175             print_version();
176             Ok((WriteMode::None, Summary::default()))
177         }
178         Operation::ConfigOutputDefault { path } => {
179             let toml = Config::default().all_options().to_toml().map_err(err_msg)?;
180             if let Some(path) = path {
181                 let mut file = File::create(path)?;
182                 file.write_all(toml.as_bytes())?;
183             } else {
184                 io::stdout().write_all(toml.as_bytes())?;
185             }
186             Ok((WriteMode::None, Summary::default()))
187         }
188         Operation::Stdin { input } => {
189             // try to read config from local directory
190             let options = CliOptions::from_matches(&matches)?;
191             let (mut config, _) = load_config(Some(Path::new(".")), Some(&options))?;
192
193             // write_mode is always Display for Stdin.
194             config.set().write_mode(WriteMode::Display);
195             config.set().verbose(Verbosity::Quiet);
196
197             // parse file_lines
198             if let Some(ref file_lines) = matches.opt_str("file-lines") {
199                 config
200                     .set()
201                     .file_lines(file_lines.parse().map_err(err_msg)?);
202                 for f in config.file_lines().files() {
203                     match *f {
204                         FileName::Custom(ref f) if f == "stdin" => {}
205                         _ => eprintln!("Warning: Extra file listed in file_lines option '{}'", f),
206                     }
207                 }
208             }
209
210             let mut error_summary = Summary::default();
211             emit_pre_matter(&config)?;
212             match format_and_emit_report(Input::Text(input), &config) {
213                 Ok(summary) => error_summary.add(summary),
214                 Err(_) => error_summary.add_operational_error(),
215             }
216             emit_post_matter(&config)?;
217
218             Ok((WriteMode::Display, error_summary))
219         }
220         Operation::Format {
221             files,
222             minimal_config_path,
223         } => {
224             let options = CliOptions::from_matches(&matches)?;
225             format(files, minimal_config_path, options)
226         }
227     }
228 }
229
230 fn format(
231     files: Vec<PathBuf>,
232     minimal_config_path: Option<String>,
233     options: CliOptions,
234 ) -> FmtResult<(WriteMode, Summary)> {
235     options.verify_file_lines(&files);
236     let (config, config_path) = load_config(None, Some(&options))?;
237
238     if config.verbose() == Verbosity::Verbose {
239         if let Some(path) = config_path.as_ref() {
240             println!("Using rustfmt config file {}", path.display());
241         }
242     }
243
244     emit_pre_matter(&config)?;
245     let mut error_summary = Summary::default();
246
247     for file in files {
248         if !file.exists() {
249             eprintln!("Error: file `{}` does not exist", file.to_str().unwrap());
250             error_summary.add_operational_error();
251         } else if file.is_dir() {
252             eprintln!("Error: `{}` is a directory", file.to_str().unwrap());
253             error_summary.add_operational_error();
254         } else {
255             // Check the file directory if the config-path could not be read or not provided
256             let local_config = if config_path.is_none() {
257                 let (local_config, config_path) =
258                     load_config(Some(file.parent().unwrap()), Some(&options))?;
259                 if local_config.verbose() == Verbosity::Verbose {
260                     if let Some(path) = config_path {
261                         println!(
262                             "Using rustfmt config file {} for {}",
263                             path.display(),
264                             file.display()
265                         );
266                     }
267                 }
268                 local_config
269             } else {
270                 config.clone()
271             };
272
273             match format_and_emit_report(Input::File(file), &local_config) {
274                 Ok(summary) => error_summary.add(summary),
275                 Err(_) => {
276                     error_summary.add_operational_error();
277                     break;
278                 }
279             }
280         }
281     }
282     emit_post_matter(&config)?;
283
284     // If we were given a path via dump-minimal-config, output any options
285     // that were used during formatting as TOML.
286     if let Some(path) = minimal_config_path {
287         let mut file = File::create(path)?;
288         let toml = config.used_options().to_toml().map_err(err_msg)?;
289         file.write_all(toml.as_bytes())?;
290     }
291
292     Ok((config.write_mode(), error_summary))
293 }
294
295 fn print_usage_to_stdout(opts: &Options, reason: &str) {
296     let sep = if reason.is_empty() {
297         String::new()
298     } else {
299         format!("{}\n\n", reason)
300     };
301     let msg = format!(
302         "{}Format Rust code\n\nusage: {} [options] <file>...",
303         sep,
304         env::args_os().next().unwrap().to_string_lossy()
305     );
306     println!("{}", opts.usage(&msg));
307 }
308
309 fn print_help_file_lines() {
310     println!(
311         "If you want to restrict reformatting to specific sets of lines, you can
312 use the `--file-lines` option. Its argument is a JSON array of objects
313 with `file` and `range` properties, where `file` is a file name, and
314 `range` is an array representing a range of lines like `[7,13]`. Ranges
315 are 1-based and inclusive of both end points. Specifying an empty array
316 will result in no files being formatted. For example,
317
318 ```
319 rustfmt --file-lines '[
320     {{\"file\":\"src/lib.rs\",\"range\":[7,13]}},
321     {{\"file\":\"src/lib.rs\",\"range\":[21,29]}},
322     {{\"file\":\"src/foo.rs\",\"range\":[10,11]}},
323     {{\"file\":\"src/foo.rs\",\"range\":[15,15]}}]'
324 ```
325
326 would format lines `7-13` and `21-29` of `src/lib.rs`, and lines `10-11`,
327 and `15` of `src/foo.rs`. No other files would be formatted, even if they
328 are included as out of line modules from `src/lib.rs`."
329     );
330 }
331
332 fn print_version() {
333     let version_info = format!(
334         "{}-{}",
335         option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
336         include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
337     );
338
339     println!("rustfmt {}", version_info);
340 }
341
342 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
343     if matches.opt_present("h") {
344         let topic = matches.opt_str("h");
345         if topic == None {
346             return Ok(Operation::Help(HelpOp::None));
347         } else if topic == Some("config".to_owned()) {
348             return Ok(Operation::Help(HelpOp::Config));
349         } else if topic == Some("file-lines".to_owned()) {
350             return Ok(Operation::Help(HelpOp::FileLines));
351         } else {
352             println!("Unknown help topic: `{}`\n", topic.unwrap());
353             return Ok(Operation::Help(HelpOp::None));
354         }
355     }
356
357     let mut minimal_config_path = None;
358     if matches.opt_present("print-config") {
359         let kind = matches.opt_str("print-config");
360         let path = matches.free.get(0);
361         if kind == "default" {
362             return Ok(Operation::ConfigOutputDefault { path: path.clone() });
363         } else if kind = "minimal" {
364             minimal_config_path = path;
365             if minimal_config_path.is_none() {
366                 println!("WARNING: PATH required for `--print-config minimal`");
367             }
368         }
369     }
370
371     if matches.opt_present("version") {
372         return Ok(Operation::Version);
373     }
374
375     // if no file argument is supplied, read from stdin
376     if matches.free.is_empty() {
377         let mut buffer = String::new();
378         io::stdin().read_to_string(&mut buffer)?;
379
380         return Ok(Operation::Stdin { input: buffer });
381     }
382
383     let files: Vec<_> = matches
384         .free
385         .iter()
386         .map(|s| {
387             let p = PathBuf::from(s);
388             // we will do comparison later, so here tries to canonicalize first
389             // to get the expected behavior.
390             p.canonicalize().unwrap_or(p)
391         })
392         .collect();
393
394     Ok(Operation::Format {
395         files,
396         minimal_config_path,
397     })
398 }