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