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 type FmtError = Box<error::Error + Send + Sync>;
33 type FmtResult<T> = std::result::Result<T, FmtError>;
35 /// Rustfmt operations.
37 /// Format files and their child modules.
40 config_path: Option<PathBuf>,
41 minimal_config_path: Option<String>,
43 /// Print the help message.
45 // Print version information
47 /// Print detailed configuration help.
49 /// Output default config to a file
50 ConfigOutputDefault { path: String },
51 /// No file specified, read from stdin
54 config_path: Option<PathBuf>,
58 /// Parsed command line options.
59 #[derive(Clone, Debug, Default)]
63 write_mode: Option<WriteMode>,
64 file_lines: FileLines, // Default is all lines in all files.
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");
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);
77 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
81 if let Some(ref file_lines) = matches.opt_str("file-lines") {
82 options.file_lines = file_lines.parse()?;
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);
98 const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
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)
109 current = fs::canonicalize(current)?;
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
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.
121 if e.kind() != ErrorKind::NotFound {
122 return Err(FmtError::from(e));
129 // If the current directory has no parent, we're done searching.
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)),
146 /// Resolve the config for input in `dir`.
148 /// Returns the `Config` to use, and the path of the project file if there was
150 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
151 let path = lookup_project_file(dir)?;
153 return Ok((Config::default(), None));
155 open_config_file(&path.unwrap())
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>,
161 -> FmtResult<(Config, Option<PathBuf>)> {
163 if let Some(config_file) = config_path {
164 let (toml, path) = open_config_file(config_file.as_ref())?;
166 return Ok((toml, path));
169 resolve_config(input_file)
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");
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");
185 "show details of rustfmt configuration options");
187 "dump-default-config",
188 "Dumps the default configuration to a file and exits.",
191 "dump-minimal-config",
192 "Dumps configuration options that were checked during formatting to a file.",
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]");
201 "Format specified line ranges. See README for more detail on the JSON format.",
207 fn execute(opts: &Options) -> FmtResult<Summary> {
208 let matches = opts.parse(env::args().skip(1))?;
210 match determine_operation(&matches)? {
212 print_usage(opts, "");
213 Summary::print_exit_codes();
216 Operation::Version => {
220 Operation::ConfigHelp => {
221 Config::print_docs();
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())?;
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())?;
235 // write_mode is always Plain for Stdin.
236 config.set().write_mode(WriteMode::Plain);
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() {
243 println!("Warning: Extra file listed in file_lines option '{}'", f);
248 Ok(run(Input::Text(input), &config))
255 let options = CliOptions::from_matches(&matches)?;
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);
263 let mut config = Config::default();
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())?;
273 if let Some(path) = path.as_ref() {
274 println!("Using rustfmt config file {}", path.display());
278 let mut error_summary = Summary::new();
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();
287 // Check the file directory if the config-path could not be read or not provided
289 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())?;
291 if let Some(path) = path_tmp.as_ref() {
292 println!("Using rustfmt config file {} for {}",
300 options.clone().apply_to(&mut config);
301 error_summary.add(run(Input::File(file), &config));
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())?;
319 let _ = env_logger::init();
321 let opts = make_opts();
323 let exit_code = match execute(&opts) {
325 if summary.has_operational_errors() {
327 } else if summary.has_parsing_errors() {
329 } else if summary.has_formatting_errors() {
331 } else if summary.has_diff {
332 // should only happen in diff mode
335 assert!(summary.has_no_errors());
340 print_usage(&opts, &e.to_string());
344 // Make sure standard output is flushed before we exit.
345 std::io::stdout().flush().unwrap();
347 // Exit with given exit code.
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);
354 fn print_usage(opts: &Options, reason: &str) {
355 let reason = format!("{}\n\nusage: {} [options] <file>...",
357 env::args_os().next().unwrap().to_string_lossy());
358 println!("{}", opts.usage(&reason));
362 println!("{}-nightly{}",
363 env!("CARGO_PKG_VERSION"),
364 include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt")))
367 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
368 if matches.opt_present("h") {
369 return Ok(Operation::Help);
372 if matches.opt_present("config-help") {
373 return Ok(Operation::ConfigHelp);
376 if let Some(path) = matches.opt_str("dump-default-config") {
377 return Ok(Operation::ConfigOutputDefault { path });
380 if matches.opt_present("version") {
381 return Ok(Operation::Version);
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: `{}`",
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);
401 if config_file_path.is_some() {
404 return config_path_not_found(path.to_str().unwrap());
410 // If no path is given, we won't output a minimal config.
411 let minimal_config_path = matches.opt_str("dump-minimal-config");
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)?;
418 return Ok(Operation::Stdin {
420 config_path: config_path,
424 let files: Vec<_> = matches
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)
435 Ok(Operation::Format {
437 config_path: config_path,
438 minimal_config_path: minimal_config_path,