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};
27 use std::str::FromStr;
29 use getopts::{Matches, Options};
31 /// Rustfmt operations.
33 /// Format files and their child modules.
36 config_path: Option<PathBuf>,
38 /// Print the help message.
40 // Print version information
42 /// Print detailed configuration help.
44 /// Invalid program input.
48 /// No file specified, read from stdin
51 config_path: Option<PathBuf>,
55 /// Try to find a project file in the given directory and its parents. Returns the path of a the
56 /// nearest project file if one exists, or `None` if no project file was found.
57 fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
58 let mut current = if dir.is_relative() {
59 try!(env::current_dir()).join(dir)
64 current = try!(fs::canonicalize(current));
67 let config_file = current.join("rustfmt.toml");
68 match fs::metadata(&config_file) {
70 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
72 return Ok(Some(config_file));
75 // If it's not found, we continue searching; otherwise something went wrong and we
78 if e.kind() != ErrorKind::NotFound {
84 // If the current directory has no parent, we're done searching.
91 /// Resolve the config for input in `dir`.
93 /// Returns the `Config` to use, and the path of the project file if there was
95 fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
96 let path = try!(lookup_project_file(dir));
98 return Ok((Config::default(), None));
100 let path = path.unwrap();
101 let mut file = try!(File::open(&path));
102 let mut toml = String::new();
103 try!(file.read_to_string(&mut toml));
104 Ok((Config::from_toml(&toml), Some(path)))
107 /// read the given config file path recursively if present else read the project file path
108 fn match_cli_path_or_file(config_path: Option<PathBuf>,
110 -> io::Result<(Config, Option<PathBuf>)> {
112 if let Some(config_file) = config_path {
113 let (toml, path) = try!(resolve_config(config_file.as_ref()));
115 return Ok((toml, path));
118 resolve_config(input_file)
121 fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
122 config.verbose = matches.opt_present("verbose");
123 config.skip_children = matches.opt_present("skip-children");
125 let write_mode = matches.opt_str("write-mode");
126 match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
128 Some(Ok(write_mode)) => {
129 config.write_mode = write_mode;
132 Some(Err(_)) => Err(format!("Invalid write-mode: {}", write_mode.expect("cannot happen"))),
136 fn execute() -> i32 {
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]");
156 let matches = match opts.parse(env::args().skip(1)) {
159 print_usage(&opts, &e.to_string());
164 let operation = determine_operation(&matches);
167 Operation::InvalidInput { reason } => {
168 print_usage(&opts, &reason);
172 print_usage(&opts, "");
175 Operation::Version => {
179 Operation::ConfigHelp => {
180 Config::print_docs();
183 Operation::Stdin { input, config_path } => {
184 // try to read config from local directory
185 let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
186 .expect("Error resolving config");
188 // write_mode is always Plain for Stdin.
189 config.write_mode = WriteMode::Plain;
191 run_from_stdin(input, &config);
194 Operation::Format { files, config_path } => {
195 let mut config = Config::default();
197 // Load the config path file if provided
198 if let Some(config_file) = config_path {
199 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
200 .expect(&format!("Error resolving config for {:?}",
205 if let Some(path) = path.as_ref() {
206 println!("Using rustfmt config file {}", path.display());
209 // Check the file directory if the config-path could not be read or not provided
211 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
212 .expect(&format!("Error resolving config \
215 if let Some(path) = path_tmp.as_ref() {
216 println!("Using rustfmt config file {} for {}",
223 if let Err(e) = update_config(&mut config, &matches) {
224 print_usage(&opts, &e);
235 let _ = env_logger::init();
236 let exit_code = execute();
238 // Make sure standard output is flushed before we exit.
239 std::io::stdout().flush().unwrap();
241 // Exit with given exit code.
243 // NOTE: This immediately terminates the process without doing any cleanup,
244 // so make sure to finish all necessary cleanup before this is called.
245 std::process::exit(exit_code);
248 fn print_usage(opts: &Options, reason: &str) {
249 let reason = format!("{}\nusage: {} [options] <file>...",
251 env::args_os().next().unwrap().to_string_lossy());
252 println!("{}", opts.usage(&reason));
256 println!("{}.{}.{}{}",
257 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
258 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
259 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
260 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
263 fn determine_operation(matches: &Matches) -> Operation {
264 if matches.opt_present("h") {
265 return Operation::Help;
268 if matches.opt_present("config-help") {
269 return Operation::ConfigHelp;
272 if matches.opt_present("version") {
273 return Operation::Version;
276 // Read the config_path and convert to parent dir if a file is provided.
277 let config_path: Option<PathBuf> = matches.opt_str("config-path")
281 return dir.parent().map(|v| v.into());
286 // if no file argument is supplied, read from stdin
287 if matches.free.is_empty() {
289 let mut buffer = String::new();
290 match io::stdin().read_to_string(&mut buffer) {
292 Err(e) => return Operation::InvalidInput { reason: e.to_string() },
295 return Operation::Stdin {
297 config_path: config_path,
301 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
305 config_path: config_path,