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