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.
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.
17 extern crate env_logger;
20 use rustfmt::{run, Input, Summary};
21 use rustfmt::file_lines::FileLines;
22 use rustfmt::config::{Config, WriteMode};
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;
30 use getopts::{Matches, Options};
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"));
38 type FmtError = Box<error::Error + Send + Sync>;
39 type FmtResult<T> = std::result::Result<T, FmtError>;
41 /// Rustfmt operations.
43 /// Format files and their child modules.
46 config_path: Option<PathBuf>,
47 minimal_config_path: Option<String>,
49 /// Print the help message.
51 // Print version information
53 /// Print detailed configuration help.
55 /// Output default config to a file
56 ConfigOutputDefault { path: String },
57 /// No file specified, read from stdin
60 config_path: Option<PathBuf>,
64 /// Parsed command line options.
65 #[derive(Clone, Debug, Default)]
69 write_mode: Option<WriteMode>,
70 file_lines: FileLines, // Default is all lines in all files.
74 fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
75 let mut options = CliOptions::default();
76 options.skip_children = matches.opt_present("skip-children");
77 options.verbose = matches.opt_present("verbose");
79 if let Some(ref write_mode) = matches.opt_str("write-mode") {
80 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
81 options.write_mode = Some(write_mode);
83 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
87 if let Some(ref file_lines) = matches.opt_str("file-lines") {
88 options.file_lines = file_lines.parse()?;
94 fn apply_to(self, config: &mut Config) {
95 config.set().skip_children(self.skip_children);
96 config.set().verbose(self.verbose);
97 config.set().file_lines(self.file_lines);
98 if let Some(write_mode) = self.write_mode {
99 config.set().write_mode(write_mode);
104 const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
106 /// Try to find a project file in the given directory and its parents. Returns the path of a the
107 /// nearest project file if one exists, or `None` if no project file was found.
108 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
109 let mut current = if dir.is_relative() {
110 env::current_dir()?.join(dir)
115 current = fs::canonicalize(current)?;
118 for config_file_name in &CONFIG_FILE_NAMES {
119 let config_file = current.join(config_file_name);
120 match fs::metadata(&config_file) {
121 // Only return if it's a file to handle the unlikely situation of a directory named
123 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
124 // Return the error if it's something other than `NotFound`; otherwise we didn't
125 // find the project file yet, and continue searching.
127 if e.kind() != ErrorKind::NotFound {
128 return Err(FmtError::from(e));
135 // If the current directory has no parent, we're done searching.
142 fn open_config_file(file_path: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
143 let mut file = File::open(&file_path)?;
144 let mut toml = String::new();
145 file.read_to_string(&mut toml)?;
146 match Config::from_toml(&toml) {
147 Ok(cfg) => Ok((cfg, Some(file_path.to_path_buf()))),
148 Err(err) => Err(FmtError::from(err)),
152 /// Resolve the config for input in `dir`.
154 /// Returns the `Config` to use, and the path of the project file if there was
156 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
157 let path = lookup_project_file(dir)?;
159 return Ok((Config::default(), None));
161 open_config_file(&path.unwrap())
164 /// read the given config file path recursively if present else read the project file path
165 fn match_cli_path_or_file(config_path: Option<PathBuf>,
167 -> FmtResult<(Config, Option<PathBuf>)> {
169 if let Some(config_file) = config_path {
170 let (toml, path) = open_config_file(config_file.as_ref())?;
172 return Ok((toml, path));
175 resolve_config(input_file)
178 fn make_opts() -> Options {
179 let mut opts = Options::new();
180 opts.optflag("h", "help", "show this message");
181 opts.optflag("V", "version", "show version information");
182 opts.optflag("v", "verbose", "print verbose output");
185 "mode to write in (not usable when piping from stdin)",
186 "[replace|overwrite|display|diff|coverage|checkstyle]");
187 opts.optflag("", "skip-children", "don't reformat child modules");
191 "show details of rustfmt configuration options");
193 "dump-default-config",
194 "Dumps the default configuration to a file and exits.",
197 "dump-minimal-config",
198 "Dumps configuration options that were checked during formatting to a file.",
202 "Recursively searches the given path for the rustfmt.toml config file. If not \
203 found reverts to the input file path",
204 "[Path for the configuration file]");
207 "Format specified line ranges. See README for more detail on the JSON format.",
213 fn execute(opts: &Options) -> FmtResult<Summary> {
214 let matches = opts.parse(env::args().skip(1))?;
216 match determine_operation(&matches)? {
218 print_usage(opts, "");
219 Summary::print_exit_codes();
222 Operation::Version => {
226 Operation::ConfigHelp => {
227 Config::print_docs();
230 Operation::ConfigOutputDefault { path } => {
231 let mut file = File::create(path)?;
232 let toml = Config::default().all_options().to_toml()?;
233 file.write_all(toml.as_bytes())?;
236 Operation::Stdin { input, config_path } => {
237 // try to read config from local directory
238 let (mut config, _) = match_cli_path_or_file(config_path,
239 &env::current_dir().unwrap())?;
241 // write_mode is always Plain for Stdin.
242 config.set().write_mode(WriteMode::Plain);
245 if let Some(ref file_lines) = matches.opt_str("file-lines") {
246 config.set().file_lines(file_lines.parse()?);
247 for f in config.file_lines().files() {
249 println!("Warning: Extra file listed in file_lines option '{}'", f);
254 Ok(run(Input::Text(input), &config))
261 let options = CliOptions::from_matches(&matches)?;
263 for f in options.file_lines.files() {
264 if !files.contains(&PathBuf::from(f)) {
265 println!("Warning: Extra file listed in file_lines option '{}'", f);
269 let mut config = Config::default();
271 // Load the config path file if provided
272 if let Some(config_file) = config_path {
273 let (cfg_tmp, path_tmp) = open_config_file(config_file.as_ref())?;
279 if let Some(path) = path.as_ref() {
280 println!("Using rustfmt config file {}", path.display());
284 let mut error_summary = Summary::new();
287 println!("Error: file `{}` does not exist", file.to_str().unwrap());
288 error_summary.add_operational_error();
289 } else if file.is_dir() {
290 println!("Error: `{}` is a directory", file.to_str().unwrap());
291 error_summary.add_operational_error();
293 // Check the file directory if the config-path could not be read or not provided
295 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())?;
297 if let Some(path) = path_tmp.as_ref() {
298 println!("Using rustfmt config file {} for {}",
306 options.clone().apply_to(&mut config);
307 error_summary.add(run(Input::File(file), &config));
311 // If we were given a path via dump-minimal-config, output any options
312 // that were used during formatting as TOML.
313 if let Some(path) = minimal_config_path {
314 let mut file = File::create(path)?;
315 let toml = config.used_options().to_toml()?;
316 file.write_all(toml.as_bytes())?;
325 let _ = env_logger::init();
327 let opts = make_opts();
329 let exit_code = match execute(&opts) {
331 if summary.has_operational_errors() {
333 } else if summary.has_parsing_errors() {
335 } else if summary.has_formatting_errors() {
337 } else if summary.has_diff {
338 // should only happen in diff mode
341 assert!(summary.has_no_errors());
346 print_usage(&opts, &e.to_string());
350 // Make sure standard output is flushed before we exit.
351 std::io::stdout().flush().unwrap();
353 // Exit with given exit code.
355 // NOTE: This immediately terminates the process without doing any cleanup,
356 // so make sure to finish all necessary cleanup before this is called.
357 std::process::exit(exit_code);
360 fn print_usage(opts: &Options, reason: &str) {
361 let reason = format!("{}\n\nusage: {} [options] <file>...",
363 env::args_os().next().unwrap().to_string_lossy());
364 println!("{}", opts.usage(&reason));
368 println!("{} ({}{})",
369 option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
370 COMMIT_HASH.unwrap_or("git commit unavailable"),
371 match WORKTREE_CLEAN {
372 Some(false) => " worktree dirty",
377 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
378 if matches.opt_present("h") {
379 return Ok(Operation::Help);
382 if matches.opt_present("config-help") {
383 return Ok(Operation::ConfigHelp);
386 if let Some(path) = matches.opt_str("dump-default-config") {
387 return Ok(Operation::ConfigOutputDefault { path });
390 if matches.opt_present("version") {
391 return Ok(Operation::Version);
394 let config_path_not_found = |path: &str| -> FmtResult<Operation> {
395 Err(FmtError::from(format!("Error: unable to find a config file for the given path: `{}`",
399 // Read the config_path and convert to parent dir if a file is provided.
400 // If a config file cannot be found from the given path, return error.
401 let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
402 Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
403 Some(ref path) if path.is_dir() => {
404 let mut config_file_path = None;
405 for config_file_name in &CONFIG_FILE_NAMES {
406 let temp_path = path.join(config_file_name);
407 if temp_path.is_file() {
408 config_file_path = Some(temp_path);
411 if config_file_path.is_some() {
414 return config_path_not_found(path.to_str().unwrap());
420 // If no path is given, we won't output a minimal config.
421 let minimal_config_path = matches.opt_str("dump-minimal-config");
423 // if no file argument is supplied, read from stdin
424 if matches.free.is_empty() {
425 let mut buffer = String::new();
426 io::stdin().read_to_string(&mut buffer)?;
428 return Ok(Operation::Stdin {
430 config_path: config_path,
434 let files: Vec<_> = matches
438 let p = PathBuf::from(s);
439 // we will do comparison later, so here tries to canonicalize first
440 // to get the expected behavior.
441 p.canonicalize().unwrap_or(p)
445 Ok(Operation::Format {
447 config_path: config_path,
448 minimal_config_path: minimal_config_path,