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};
33 match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
35 Err(x) => panic!("Unable to write to stderr: {}", x),
40 /// Rustfmt operations.
42 /// Format files and their child modules.
45 config_path: Option<PathBuf>,
47 /// Print the help message.
49 // Print version information
51 /// Print detailed configuration help.
53 /// Invalid program input.
57 /// No file specified, read from stdin
60 config_path: Option<PathBuf>,
64 /// Try to find a project file in the given directory and its parents. Returns the path of a the
65 /// nearest project file if one exists, or `None` if no project file was found.
66 fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
67 let mut current = if dir.is_relative() {
68 try!(env::current_dir()).join(dir)
73 current = try!(fs::canonicalize(current));
76 let config_file = current.join("rustfmt.toml");
77 match fs::metadata(&config_file) {
79 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
81 return Ok(Some(config_file));
84 // If it's not found, we continue searching; otherwise something went wrong and we
87 if e.kind() != ErrorKind::NotFound {
93 // If the current directory has no parent, we're done searching.
100 /// Resolve the config for input in `dir`.
102 /// Returns the `Config` to use, and the path of the project file if there was
104 fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
105 let path = try!(lookup_project_file(dir));
107 return Ok((Config::default(), None));
109 let path = path.unwrap();
110 let mut file = try!(File::open(&path));
111 let mut toml = String::new();
112 try!(file.read_to_string(&mut toml));
113 Ok((Config::from_toml(&toml), Some(path)))
116 /// read the given config file path recursively if present else read the project file path
117 fn match_cli_path_or_file(config_path: Option<PathBuf>,
119 -> io::Result<(Config, Option<PathBuf>)> {
121 if let Some(config_file) = config_path {
122 let (toml, path) = try!(resolve_config(config_file.as_ref()));
124 return Ok((toml, path));
127 resolve_config(input_file)
130 fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
131 config.verbose = matches.opt_present("verbose");
132 config.skip_children = matches.opt_present("skip-children");
134 let write_mode = matches.opt_str("write-mode");
135 match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
137 Some(Ok(write_mode)) => {
138 config.write_mode = write_mode;
141 Some(Err(_)) => Err(format!("Invalid write-mode: {}", write_mode.expect("cannot happen"))),
145 fn execute() -> i32 {
146 let mut opts = Options::new();
147 opts.optflag("h", "help", "show this message");
148 opts.optflag("V", "version", "show version information");
149 opts.optflag("v", "verbose", "show progress");
152 "mode to write in (not usable when piping from stdin)",
153 "[replace|overwrite|display|diff|coverage|checkstyle]");
154 opts.optflag("", "skip-children", "don't reformat child modules");
158 "show details of rustfmt configuration options");
161 "Recursively searches the given path for the rustfmt.toml config file. If not \
162 found reverts to the input file path",
163 "[Path for the configuration file]");
165 let matches = match opts.parse(env::args().skip(1)) {
168 print_usage(&opts, &e.to_string());
173 let operation = determine_operation(&matches);
176 Operation::InvalidInput { reason } => {
177 print_usage(&opts, &reason);
181 print_usage(&opts, "");
184 Operation::Version => {
188 Operation::ConfigHelp => {
189 Config::print_docs();
192 Operation::Stdin { input, config_path } => {
193 // try to read config from local directory
194 let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
195 .expect("Error resolving config");
197 // write_mode is always Plain for Stdin.
198 config.write_mode = WriteMode::Plain;
200 run_from_stdin(input, &config);
203 Operation::Format { files, config_path } => {
204 let mut config = Config::default();
206 // Load the config path file if provided
207 if let Some(config_file) = config_path {
208 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
209 .expect(&format!("Error resolving config for {:?}",
214 if let Some(path) = path.as_ref() {
215 println!("Using rustfmt config file {}", path.display());
218 // Check the file directory if the config-path could not be read or not provided
220 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
221 .expect(&format!("Error resolving config \
224 if let Some(path) = path_tmp.as_ref() {
225 println!("Using rustfmt config file {} for {}",
232 if let Err(e) = update_config(&mut config, &matches) {
233 print_usage(&opts, &e);
244 let _ = env_logger::init();
245 let exit_code = execute();
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) -> Operation {
273 if matches.opt_present("h") {
274 return Operation::Help;
277 if matches.opt_present("config-help") {
278 return Operation::ConfigHelp;
281 if matches.opt_present("version") {
282 return 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 match io::stdin().read_to_string(&mut buffer) {
301 Err(e) => return Operation::InvalidInput { reason: e.to_string() },
304 return Operation::Stdin {
306 config_path: config_path,
310 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
314 config_path: config_path,