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 /// Parsed command line options.
55 #[derive(Clone, Debug, Default)]
59 write_mode: Option<WriteMode>,
63 fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
64 let mut options = CliOptions::default();
65 options.skip_children = matches.opt_present("skip-children");
66 options.verbose = matches.opt_present("verbose");
68 if let Some(ref write_mode) = matches.opt_str("write-mode") {
69 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
70 options.write_mode = Some(write_mode);
72 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
79 fn apply_to(&self, config: &mut Config) {
80 config.skip_children = self.skip_children;
81 config.verbose = self.verbose;
82 if let Some(write_mode) = self.write_mode {
83 config.write_mode = write_mode;
88 /// Try to find a project file in the given directory and its parents. Returns the path of a the
89 /// nearest project file if one exists, or `None` if no project file was found.
90 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
91 let mut current = if dir.is_relative() {
92 try!(env::current_dir()).join(dir)
97 current = try!(fs::canonicalize(current));
100 let config_file = current.join("rustfmt.toml");
101 match fs::metadata(&config_file) {
102 // Only return if it's a file to handle the unlikely situation of a directory named
104 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
105 // Return the error if it's something other than `NotFound`; otherwise we didn't find
106 // the project file yet, and continue searching.
108 if e.kind() != ErrorKind::NotFound {
109 return Err(FmtError::from(e));
115 // If the current directory has no parent, we're done searching.
122 /// Resolve the config for input in `dir`.
124 /// Returns the `Config` to use, and the path of the project file if there was
126 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
127 let path = try!(lookup_project_file(dir));
129 return Ok((Config::default(), None));
131 let path = path.unwrap();
132 let mut file = try!(File::open(&path));
133 let mut toml = String::new();
134 try!(file.read_to_string(&mut toml));
135 Ok((Config::from_toml(&toml), Some(path)))
138 /// read the given config file path recursively if present else read the project file path
139 fn match_cli_path_or_file(config_path: Option<PathBuf>,
141 -> FmtResult<(Config, Option<PathBuf>)> {
143 if let Some(config_file) = config_path {
144 let (toml, path) = try!(resolve_config(config_file.as_ref()));
146 return Ok((toml, path));
149 resolve_config(input_file)
152 fn make_opts() -> Options {
153 let mut opts = Options::new();
154 opts.optflag("h", "help", "show this message");
155 opts.optflag("V", "version", "show version information");
156 opts.optflag("v", "verbose", "show progress");
159 "mode to write in (not usable when piping from stdin)",
160 "[replace|overwrite|display|diff|coverage|checkstyle]");
161 opts.optflag("", "skip-children", "don't reformat child modules");
165 "show details of rustfmt configuration options");
168 "Recursively searches the given path for the rustfmt.toml config file. If not \
169 found reverts to the input file path",
170 "[Path for the configuration file]");
175 fn execute(opts: &Options) -> FmtResult<Summary> {
176 let matches = try!(opts.parse(env::args().skip(1)));
178 match try!(determine_operation(&matches)) {
180 print_usage(&opts, "");
183 Operation::Version => {
187 Operation::ConfigHelp => {
188 Config::print_docs();
191 Operation::Stdin { input, config_path } => {
192 // try to read config from local directory
193 let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
194 .expect("Error resolving config");
196 // write_mode is always Plain for Stdin.
197 config.write_mode = WriteMode::Plain;
199 Ok(run(Input::Text(input), &config))
201 Operation::Format { files, config_path } => {
202 let options = try!(CliOptions::from_matches(&matches));
203 let mut config = Config::default();
205 // Load the config path file if provided
206 if let Some(config_file) = config_path {
207 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
208 .expect(&format!("Error resolving config for {:?}",
213 if let Some(path) = path.as_ref() {
214 println!("Using rustfmt config file {}", path.display());
217 let mut error_summary = Summary::new();
219 // Check the file directory if the config-path could not be read or not provided
221 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
222 .expect(&format!("Error resolving config \
225 if let Some(path) = path_tmp.as_ref() {
226 println!("Using rustfmt config file {} for {}",
233 options.apply_to(&mut config);
234 error_summary.add(run(Input::File(file), &config));
242 let _ = env_logger::init();
244 let opts = make_opts();
246 let exit_code = match execute(&opts) {
248 if summary.has_operational_errors() {
250 } else if summary.has_parsing_errors() {
252 } else if summary.has_formatting_errors() {
255 assert!(summary.has_no_errors());
260 print_usage(&opts, &e.to_string());
264 // Make sure standard output is flushed before we exit.
265 std::io::stdout().flush().unwrap();
267 // Exit with given exit code.
269 // NOTE: This immediately terminates the process without doing any cleanup,
270 // so make sure to finish all necessary cleanup before this is called.
271 std::process::exit(exit_code);
274 fn print_usage(opts: &Options, reason: &str) {
275 let reason = format!("{}\nusage: {} [options] <file>...",
277 env::args_os().next().unwrap().to_string_lossy());
278 println!("{}", opts.usage(&reason));
282 println!("{}.{}.{}{}",
283 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
284 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
285 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
286 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
289 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
290 if matches.opt_present("h") {
291 return Ok(Operation::Help);
294 if matches.opt_present("config-help") {
295 return Ok(Operation::ConfigHelp);
298 if matches.opt_present("version") {
299 return Ok(Operation::Version);
302 // Read the config_path and convert to parent dir if a file is provided.
303 let config_path: Option<PathBuf> = matches.opt_str("config-path")
307 return dir.parent().map(|v| v.into());
312 // if no file argument is supplied, read from stdin
313 if matches.free.is_empty() {
315 let mut buffer = String::new();
316 try!(io::stdin().read_to_string(&mut buffer));
318 return Ok(Operation::Stdin {
320 config_path: config_path,
324 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
326 Ok(Operation::Format {
328 config_path: config_path,