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