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.
34 Format(Vec<PathBuf>, Option<PathBuf>),
35 /// Print the help message.
37 // Print version information
39 /// Print detailed configuration help.
41 /// Invalid program input, including reason.
43 /// No file specified, read from stdin
44 Stdin(String, Option<PathBuf>),
47 /// Try to find a project file in the given directory and its parents. Returns the path of a the
48 /// nearest project file if one exists, or `None` if no project file was found.
49 fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
50 let mut current = if dir.is_relative() {
51 try!(env::current_dir()).join(dir)
56 current = try!(fs::canonicalize(current));
59 let config_file = current.join("rustfmt.toml");
60 match fs::metadata(&config_file) {
62 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
64 return Ok(Some(config_file));
67 // If it's not found, we continue searching; otherwise something went wrong and we
70 if e.kind() != ErrorKind::NotFound {
76 // If the current directory has no parent, we're done searching.
83 /// Resolve the config for input in `dir`.
85 /// Returns the `Config` to use, and the path of the project file if there was
87 fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
88 let path = try!(lookup_project_file(dir));
90 return Ok((Config::default(), None));
92 let path = path.unwrap();
93 let mut file = try!(File::open(&path));
94 let mut toml = String::new();
95 try!(file.read_to_string(&mut toml));
96 Ok((Config::from_toml(&toml), Some(path)))
99 /// read the given config file path recursively if present else read the project file path
100 fn match_cli_path_or_file(config_path: Option<PathBuf>,
102 -> io::Result<(Config, Option<PathBuf>)> {
104 if let Some(config_file) = config_path {
105 let (toml, path) = try!(resolve_config(config_file.as_ref()));
107 return Ok((toml, path));
110 resolve_config(input_file)
113 fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
114 config.verbose = matches.opt_present("verbose");
115 config.skip_children = matches.opt_present("skip-children");
117 let write_mode = matches.opt_str("write-mode");
118 match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
120 Some(Ok(write_mode)) => {
121 config.write_mode = write_mode;
124 Some(Err(_)) => Err(format!("Invalid write-mode: {}", write_mode.expect("cannot happen"))),
128 fn execute() -> i32 {
129 let mut opts = Options::new();
130 opts.optflag("h", "help", "show this message");
131 opts.optflag("V", "version", "show version information");
132 opts.optflag("v", "verbose", "show progress");
135 "mode to write in (not usable when piping from stdin)",
136 "[replace|overwrite|display|diff|coverage|checkstyle]");
137 opts.optflag("", "skip-children", "don't reformat child modules");
141 "show details of rustfmt configuration options");
144 "Recursively searches the given path for the rustfmt.toml config file. If not \
145 found reverts to the input file path",
146 "[Path for the configuration file]");
148 let matches = match opts.parse(env::args().skip(1)) {
151 print_usage(&opts, &e.to_string());
156 let operation = determine_operation(&matches);
159 Operation::InvalidInput(reason) => {
160 print_usage(&opts, &reason);
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 run_from_stdin(input, &config);
186 Operation::Format(files, config_path) => {
187 let mut config = Config::default();
189 // Load the config path file if provided
190 if let Some(config_file) = config_path {
191 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
192 .expect(&format!("Error resolving config for {:?}",
197 if let Some(path) = path.as_ref() {
198 println!("Using rustfmt config file {}", path.display());
201 // Check the file directory if the config-path could not be read or not provided
203 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
204 .expect(&format!("Error resolving config \
207 if let Some(path) = path_tmp.as_ref() {
208 println!("Using rustfmt config file {} for {}",
215 if let Err(e) = update_config(&mut config, &matches) {
216 print_usage(&opts, &e);
227 let _ = env_logger::init();
228 let exit_code = execute();
230 // Make sure standard output is flushed before we exit.
231 std::io::stdout().flush().unwrap();
233 // Exit with given exit code.
235 // NOTE: This immediately terminates the process without doing any cleanup,
236 // so make sure to finish all necessary cleanup before this is called.
237 std::process::exit(exit_code);
240 fn print_usage(opts: &Options, reason: &str) {
241 let reason = format!("{}\nusage: {} [options] <file>...",
243 env::args_os().next().unwrap().to_string_lossy());
244 println!("{}", opts.usage(&reason));
248 println!("{}.{}.{}{}",
249 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
250 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
251 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
252 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
255 fn determine_operation(matches: &Matches) -> Operation {
256 if matches.opt_present("h") {
257 return Operation::Help;
260 if matches.opt_present("config-help") {
261 return Operation::ConfigHelp;
264 if matches.opt_present("version") {
265 return Operation::Version;
268 // Read the config_path and convert to parent dir if a file is provided.
269 let config_path: Option<PathBuf> = matches.opt_str("config-path")
273 return dir.parent().map(|v| v.into());
278 // if no file argument is supplied, read from stdin
279 if matches.free.is_empty() {
281 let mut buffer = String::new();
282 match io::stdin().read_to_string(&mut buffer) {
284 Err(e) => return Operation::InvalidInput(e.to_string()),
287 return Operation::Stdin(buffer, config_path);
290 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
292 Operation::Format(files, config_path)