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::config::{Config, WriteMode};
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 use std::str::FromStr;
29 use getopts::{Matches, Options};
31 type FmtError = Box<error::Error + Send + Sync>;
32 type FmtResult<T> = std::result::Result<T, FmtError>;
34 /// Rustfmt operations.
36 /// Format files and their child modules.
39 config_path: Option<PathBuf>,
41 /// Print the help message.
43 // Print version information
45 /// Print detailed configuration help.
47 /// No file specified, read from stdin
50 config_path: Option<PathBuf>,
54 /// Try to find a project file in the given directory and its parents. Returns the path of a the
55 /// nearest project file if one exists, or `None` if no project file was found.
56 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
57 let mut current = if dir.is_relative() {
58 try!(env::current_dir()).join(dir)
63 current = try!(fs::canonicalize(current));
66 let config_file = current.join("rustfmt.toml");
67 match fs::metadata(&config_file) {
68 // Only return if it's a file to handle the unlikely situation of a directory named
70 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
71 // Return the error if it's something other than `NotFound`; otherwise we didn't find
72 // the project file yet, and continue searching.
74 if e.kind() != ErrorKind::NotFound {
75 return Err(FmtError::from(e));
81 // If the current directory has no parent, we're done searching.
88 /// Resolve the config for input in `dir`.
90 /// Returns the `Config` to use, and the path of the project file if there was
92 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
93 let path = try!(lookup_project_file(dir));
95 return Ok((Config::default(), None));
97 let path = path.unwrap();
98 let mut file = try!(File::open(&path));
99 let mut toml = String::new();
100 try!(file.read_to_string(&mut toml));
101 Ok((Config::from_toml(&toml), Some(path)))
104 /// read the given config file path recursively if present else read the project file path
105 fn match_cli_path_or_file(config_path: Option<PathBuf>,
107 -> FmtResult<(Config, Option<PathBuf>)> {
109 if let Some(config_file) = config_path {
110 let (toml, path) = try!(resolve_config(config_file.as_ref()));
112 return Ok((toml, path));
115 resolve_config(input_file)
118 fn update_config(config: &mut Config, matches: &Matches) -> FmtResult<()> {
119 config.verbose = matches.opt_present("verbose");
120 config.skip_children = matches.opt_present("skip-children");
122 let write_mode = matches.opt_str("write-mode");
123 match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
125 Some(Ok(write_mode)) => {
126 config.write_mode = write_mode;
130 Err(FmtError::from(format!("Invalid write-mode: {}",
131 write_mode.expect("cannot happen"))))
136 fn make_opts() -> Options {
137 let mut opts = Options::new();
138 opts.optflag("h", "help", "show this message");
139 opts.optflag("V", "version", "show version information");
140 opts.optflag("v", "verbose", "show progress");
143 "mode to write in (not usable when piping from stdin)",
144 "[replace|overwrite|display|diff|coverage|checkstyle]");
145 opts.optflag("", "skip-children", "don't reformat child modules");
149 "show details of rustfmt configuration options");
152 "Recursively searches the given path for the rustfmt.toml config file. If not \
153 found reverts to the input file path",
154 "[Path for the configuration file]");
159 fn execute(opts: &Options) -> FmtResult<Summary> {
160 let matches = try!(opts.parse(env::args().skip(1)));
162 match try!(determine_operation(&matches)) {
164 print_usage(&opts, "");
167 Operation::Version => {
171 Operation::ConfigHelp => {
172 Config::print_docs();
175 Operation::Stdin { input, config_path } => {
176 // try to read config from local directory
177 let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
178 .expect("Error resolving config");
180 // write_mode is always Plain for Stdin.
181 config.write_mode = WriteMode::Plain;
183 Ok(run(Input::Text(input), &config))
185 Operation::Format { files, config_path } => {
186 let mut config = Config::default();
188 // Load the config path file if provided
189 if let Some(config_file) = config_path {
190 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
191 .expect(&format!("Error resolving config for {:?}",
196 if let Some(path) = path.as_ref() {
197 println!("Using rustfmt config file {}", path.display());
200 let mut error_summary = Summary::new();
202 // Check the file directory if the config-path could not be read or not provided
204 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
205 .expect(&format!("Error resolving config \
208 if let Some(path) = path_tmp.as_ref() {
209 println!("Using rustfmt config file {} for {}",
216 try!(update_config(&mut config, &matches));
217 error_summary.add(run(Input::File(file), &config));
225 let _ = env_logger::init();
227 let opts = make_opts();
229 let exit_code = match execute(&opts) {
231 if summary.has_operational_errors() {
233 } else if summary.has_parsing_errors() {
235 } else if summary.has_formatting_errors() {
238 assert!(summary.has_no_errors());
243 print_usage(&opts, &e.to_string());
247 // Make sure standard output is flushed before we exit.
248 std::io::stdout().flush().unwrap();
250 // Exit with given exit code.
252 // NOTE: This immediately terminates the process without doing any cleanup,
253 // so make sure to finish all necessary cleanup before this is called.
254 std::process::exit(exit_code);
257 fn print_usage(opts: &Options, reason: &str) {
258 let reason = format!("{}\nusage: {} [options] <file>...",
260 env::args_os().next().unwrap().to_string_lossy());
261 println!("{}", opts.usage(&reason));
265 println!("{}.{}.{}{}",
266 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
267 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
268 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
269 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
272 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
273 if matches.opt_present("h") {
274 return Ok(Operation::Help);
277 if matches.opt_present("config-help") {
278 return Ok(Operation::ConfigHelp);
281 if matches.opt_present("version") {
282 return Ok(Operation::Version);
285 // Read the config_path and convert to parent dir if a file is provided.
286 let config_path: Option<PathBuf> = matches.opt_str("config-path")
290 return dir.parent().map(|v| v.into());
295 // if no file argument is supplied, read from stdin
296 if matches.free.is_empty() {
298 let mut buffer = String::new();
299 try!(io::stdin().read_to_string(&mut buffer));
301 return Ok(Operation::Stdin {
303 config_path: config_path,
307 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
309 Ok(Operation::Format {
311 config_path: config_path,