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, run_from_stdin};
21 use rustfmt::config::{Config, WriteMode};
24 use std::fs::{self, File};
25 use std::io::{self, ErrorKind, Read, Write};
26 use std::path::{Path, PathBuf};
28 use getopts::{Matches, Options};
30 /// Rustfmt operations.
32 /// Format files and their child modules.
33 Format(Vec<PathBuf>, WriteMode, Option<PathBuf>),
34 /// Print the help message.
36 // Print version information
38 /// Print detailed configuration help.
40 /// Invalid program input, including reason.
42 /// No file specified, read from stdin
43 Stdin(String, WriteMode, Option<PathBuf>),
46 /// Try to find a project file in the given directory and its parents. Returns the path of a the
47 /// nearest project file if one exists, or `None` if no project file was found.
48 fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
49 let mut current = if dir.is_relative() {
50 try!(env::current_dir()).join(dir)
55 current = try!(fs::canonicalize(current));
58 let config_file = current.join("rustfmt.toml");
59 match fs::metadata(&config_file) {
61 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
63 return Ok(Some(config_file));
66 // If it's not found, we continue searching; otherwise something went wrong and we
69 if e.kind() != ErrorKind::NotFound {
75 // If the current directory has no parent, we're done searching.
82 /// Resolve the config for input in `dir`.
84 /// Returns the `Config` to use, and the path of the project file if there was
86 fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
87 let path = try!(lookup_project_file(dir));
89 return Ok((Config::default(), None));
91 let path = path.unwrap();
92 let mut file = try!(File::open(&path));
93 let mut toml = String::new();
94 try!(file.read_to_string(&mut toml));
95 Ok((Config::from_toml(&toml), Some(path)))
98 /// read the given config file path recursively if present else read the project file path
99 fn match_cli_path_or_file(config_path: Option<PathBuf>,
101 -> io::Result<(Config, Option<PathBuf>)> {
103 if let Some(config_file) = config_path {
104 let (toml, path) = try!(resolve_config(config_file.as_ref()));
106 return Ok((toml, path));
109 resolve_config(input_file)
112 fn update_config(config: &mut Config, matches: &Matches) {
113 config.verbose = matches.opt_present("verbose");
114 config.skip_children = matches.opt_present("skip-children");
117 fn execute() -> i32 {
118 let mut opts = Options::new();
119 opts.optflag("h", "help", "show this message");
120 opts.optflag("V", "version", "show version information");
121 opts.optflag("v", "verbose", "show progress");
124 "mode to write in (not usable when piping from stdin)",
125 "[replace|overwrite|display|diff|coverage|checkstyle]");
126 opts.optflag("", "skip-children", "don't reformat child modules");
130 "show details of rustfmt configuration options");
133 "Recursively searches the given path for the rustfmt.toml config file. If not \
134 found reverts to the input file path",
135 "[Path for the configuration file]");
137 let matches = match opts.parse(env::args().skip(1)) {
140 print_usage(&opts, &e.to_string());
145 let operation = determine_operation(&matches);
148 Operation::InvalidInput(reason) => {
149 print_usage(&opts, &reason);
153 print_usage(&opts, "");
156 Operation::Version => {
160 Operation::ConfigHelp => {
161 Config::print_docs();
164 Operation::Stdin(input, write_mode, config_path) => {
165 // try to read config from local directory
166 let (config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
167 .expect("Error resolving config");
169 run_from_stdin(input, write_mode, &config);
172 Operation::Format(files, write_mode, config_path) => {
173 let mut config = Config::default();
175 // Load the config path file if provided
176 if let Some(config_file) = config_path {
177 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
178 .expect(&format!("Error resolving config for {:?}",
183 if let Some(path) = path.as_ref() {
184 println!("Using rustfmt config file {}", path.display());
187 // Check the file directory if the config-path could not be read or not provided
189 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
190 .expect(&format!("Error resolving config \
193 if let Some(path) = path_tmp.as_ref() {
194 println!("Using rustfmt config file {} for {}",
201 update_config(&mut config, &matches);
202 run(&file, write_mode, &config);
210 let _ = env_logger::init();
211 let exit_code = execute();
213 // Make sure standard output is flushed before we exit.
214 std::io::stdout().flush().unwrap();
216 // Exit with given exit code.
218 // NOTE: This immediately terminates the process without doing any cleanup,
219 // so make sure to finish all necessary cleanup before this is called.
220 std::process::exit(exit_code);
223 fn print_usage(opts: &Options, reason: &str) {
224 let reason = format!("{}\nusage: {} [options] <file>...",
226 env::args_os().next().unwrap().to_string_lossy());
227 println!("{}", opts.usage(&reason));
231 println!("{}.{}.{}{}",
232 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
233 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
234 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
235 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
238 fn determine_operation(matches: &Matches) -> Operation {
239 if matches.opt_present("h") {
240 return Operation::Help;
243 if matches.opt_present("config-help") {
244 return Operation::ConfigHelp;
247 if matches.opt_present("version") {
248 return Operation::Version;
251 // Read the config_path and convert to parent dir if a file is provided.
252 let config_path: Option<PathBuf> = matches.opt_str("config-path")
256 return dir.parent().map(|v| v.into());
261 // if no file argument is supplied, read from stdin
262 if matches.free.is_empty() {
264 let mut buffer = String::new();
265 match io::stdin().read_to_string(&mut buffer) {
267 Err(e) => return Operation::InvalidInput(e.to_string()),
270 // WriteMode is always plain for Stdin
271 return Operation::Stdin(buffer, WriteMode::Plain, config_path);
274 let write_mode = match matches.opt_str("write-mode") {
278 Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
281 None => WriteMode::Default,
284 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
286 Operation::Format(files, write_mode, config_path)