]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
Change return type of 'from_toml' from 'Config' to 'Result<Config>'
[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 // Include git commit hash and worktree status; contents are like
33 //   const COMMIT_HASH: Option<&'static str> = Some("c31a366");
34 //   const WORKTREE_CLEAN: Option<bool> = Some(false);
35 // with `None` if running git failed, eg if it is not installed.
36 include!(concat!(env!("OUT_DIR"), "/git_info.rs"));
37
38 type FmtError = Box<error::Error + Send + Sync>;
39 type FmtResult<T> = std::result::Result<T, FmtError>;
40
41 /// Rustfmt operations.
42 enum Operation {
43     /// Format files and their child modules.
44     Format {
45         files: Vec<PathBuf>,
46         config_path: Option<PathBuf>,
47     },
48     /// Print the help message.
49     Help,
50     // Print version information
51     Version,
52     /// Print detailed configuration help.
53     ConfigHelp,
54     /// No file specified, read from stdin
55     Stdin {
56         input: String,
57         config_path: Option<PathBuf>,
58     },
59 }
60
61 /// Parsed command line options.
62 #[derive(Clone, Debug, Default)]
63 struct CliOptions {
64     skip_children: bool,
65     verbose: bool,
66     write_mode: Option<WriteMode>,
67     file_lines: FileLines, // Default is all lines in all files.
68 }
69
70 impl CliOptions {
71     fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
72         let mut options = CliOptions::default();
73         options.skip_children = matches.opt_present("skip-children");
74         options.verbose = matches.opt_present("verbose");
75
76         if let Some(ref write_mode) = matches.opt_str("write-mode") {
77             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
78                 options.write_mode = Some(write_mode);
79             } else {
80                 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
81             }
82         }
83
84         if let Some(ref file_lines) = matches.opt_str("file-lines") {
85             options.file_lines = try!(file_lines.parse());
86         }
87
88         Ok(options)
89     }
90
91     fn apply_to(self, config: &mut Config) {
92         config.skip_children = self.skip_children;
93         config.verbose = self.verbose;
94         config.file_lines = self.file_lines;
95         if let Some(write_mode) = self.write_mode {
96             config.write_mode = write_mode;
97         }
98     }
99 }
100
101 /// Try to find a project file in the given directory and its parents. Returns the path of a the
102 /// nearest project file if one exists, or `None` if no project file was found.
103 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
104     let mut current = if dir.is_relative() {
105         try!(env::current_dir()).join(dir)
106     } else {
107         dir.to_path_buf()
108     };
109
110     current = try!(fs::canonicalize(current));
111
112     const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
113
114     loop {
115         for config_file_name in &CONFIG_FILE_NAMES {
116             let config_file = current.join(config_file_name);
117             match fs::metadata(&config_file) {
118                 // Only return if it's a file to handle the unlikely situation of a directory named
119                 // `rustfmt.toml`.
120                 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
121                 // Return the error if it's something other than `NotFound`; otherwise we didn't
122                 // find the project file yet, and continue searching.
123                 Err(e) => {
124                     if e.kind() != ErrorKind::NotFound {
125                         return Err(FmtError::from(e));
126                     }
127                 }
128                 _ => {}
129             }
130         }
131
132         // If the current directory has no parent, we're done searching.
133         if !current.pop() {
134             return Ok(None);
135         }
136     }
137 }
138
139 /// Resolve the config for input in `dir`.
140 ///
141 /// Returns the `Config` to use, and the path of the project file if there was
142 /// one.
143 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
144     let path = try!(lookup_project_file(dir));
145     if path.is_none() {
146         return Ok((Config::default(), None));
147     }
148     let path = path.unwrap();
149     let mut file = try!(File::open(&path));
150     let mut toml = String::new();
151     try!(file.read_to_string(&mut toml));
152     match Config::from_toml(&toml) {
153         Ok(cfg) => Ok((cfg, Some(path))),
154         Err(err) => Err(FmtError::from(err)),
155     }
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) = try!(resolve_config(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                 "config-path",
188                 "Recursively searches the given path for the rustfmt.toml config file. If not \
189                  found reverts to the input file path",
190                 "[Path for the configuration file]");
191     opts.optopt("",
192                 "file-lines",
193                 "Format specified line ranges. See README for more detail on the JSON format.",
194                 "JSON");
195
196     opts
197 }
198
199 fn execute(opts: &Options) -> FmtResult<Summary> {
200     let matches = try!(opts.parse(env::args().skip(1)));
201
202     match try!(determine_operation(&matches)) {
203         Operation::Help => {
204             print_usage(opts, "");
205             Ok(Summary::new())
206         }
207         Operation::Version => {
208             print_version();
209             Ok(Summary::new())
210         }
211         Operation::ConfigHelp => {
212             Config::print_docs();
213             Ok(Summary::new())
214         }
215         Operation::Stdin { input, config_path } => {
216             // try to read config from local directory
217             let (mut config, _) = match_cli_path_or_file(config_path,
218                                                          &env::current_dir().unwrap())?;
219
220             // write_mode is always Plain for Stdin.
221             config.write_mode = WriteMode::Plain;
222
223             Ok(run(Input::Text(input), &config))
224         }
225         Operation::Format {
226             mut files,
227             config_path,
228         } => {
229             let options = try!(CliOptions::from_matches(&matches));
230
231             // Add any additional files that were specified via `--file-lines`.
232             files.extend(options.file_lines.files().cloned().map(PathBuf::from));
233
234             let mut config = Config::default();
235             let mut path = None;
236             // Load the config path file if provided
237             if let Some(config_file) = config_path {
238                 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())?;
239                 config = cfg_tmp;
240                 path = path_tmp;
241             };
242
243             if options.verbose {
244                 if let Some(path) = path.as_ref() {
245                     println!("Using rustfmt config file {}", path.display());
246                 }
247             }
248
249             let mut error_summary = Summary::new();
250             for file in files {
251                 // Check the file directory if the config-path could not be read or not provided
252                 if path.is_none() {
253                     let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())?;
254                     if options.verbose {
255                         if let Some(path) = path_tmp.as_ref() {
256                             println!("Using rustfmt config file {} for {}",
257                                      path.display(),
258                                      file.display());
259                         }
260                     }
261                     config = config_tmp;
262                 }
263
264                 options.clone().apply_to(&mut config);
265                 error_summary.add(run(Input::File(file), &config));
266             }
267             Ok(error_summary)
268         }
269     }
270 }
271
272 fn main() {
273     let _ = env_logger::init();
274
275     let opts = make_opts();
276
277     let exit_code = match execute(&opts) {
278         Ok(summary) => {
279             if summary.has_operational_errors() {
280                 1
281             } else if summary.has_parsing_errors() {
282                 2
283             } else if summary.has_formatting_errors() {
284                 3
285             } else if summary.has_diff {
286                 // should only happen in diff mode
287                 4
288             } else {
289                 assert!(summary.has_no_errors());
290                 0
291             }
292         }
293         Err(e) => {
294             print_usage(&opts, &e.to_string());
295             1
296         }
297     };
298     // Make sure standard output is flushed before we exit.
299     std::io::stdout().flush().unwrap();
300
301     // Exit with given exit code.
302     //
303     // NOTE: This immediately terminates the process without doing any cleanup,
304     // so make sure to finish all necessary cleanup before this is called.
305     std::process::exit(exit_code);
306 }
307
308 fn print_usage(opts: &Options, reason: &str) {
309     let reason = format!("{}\nusage: {} [options] <file>...",
310                          reason,
311                          env::args_os().next().unwrap().to_string_lossy());
312     println!("{}", opts.usage(&reason));
313 }
314
315 fn print_version() {
316     println!("{} ({}{})",
317              option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
318              COMMIT_HASH.unwrap_or("git commit unavailable"),
319              match WORKTREE_CLEAN {
320                  Some(false) => " worktree dirty",
321                  _ => "",
322              });
323 }
324
325 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
326     if matches.opt_present("h") {
327         return Ok(Operation::Help);
328     }
329
330     if matches.opt_present("config-help") {
331         return Ok(Operation::ConfigHelp);
332     }
333
334     if matches.opt_present("version") {
335         return Ok(Operation::Version);
336     }
337
338     // Read the config_path and convert to parent dir if a file is provided.
339     let config_path: Option<PathBuf> = matches
340         .opt_str("config-path")
341         .map(PathBuf::from)
342         .and_then(|dir| {
343                       if dir.is_file() {
344                           return dir.parent().map(|v| v.into());
345                       }
346                       Some(dir)
347                   });
348
349     // if no file argument is supplied and `--file-lines` is not specified, read from stdin
350     if matches.free.is_empty() && !matches.opt_present("file-lines") {
351
352         let mut buffer = String::new();
353         try!(io::stdin().read_to_string(&mut buffer));
354
355         return Ok(Operation::Stdin {
356                       input: buffer,
357                       config_path: config_path,
358                   });
359     }
360
361     // We append files from `--file-lines` later in `execute()`.
362     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
363
364     Ok(Operation::Format {
365            files: files,
366            config_path: config_path,
367        })
368 }