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};
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};
32 /// Rustfmt operations.
34 /// Format files and their child modules.
37 config_path: Option<PathBuf>,
39 /// Print the help message.
41 // Print version information
43 /// Print detailed configuration help.
45 /// Invalid program input.
49 /// No file specified, read from stdin
52 config_path: Option<PathBuf>,
56 /// Try to find a project file in the given directory and its parents. Returns the path of a the
57 /// nearest project file if one exists, or `None` if no project file was found.
58 fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
59 let mut current = if dir.is_relative() {
60 try!(env::current_dir()).join(dir)
65 current = try!(fs::canonicalize(current));
68 let config_file = current.join("rustfmt.toml");
69 match fs::metadata(&config_file) {
71 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
73 return Ok(Some(config_file));
76 // If it's not found, we continue searching; otherwise something went wrong and we
79 if e.kind() != ErrorKind::NotFound {
85 // If the current directory has no parent, we're done searching.
92 /// Resolve the config for input in `dir`.
94 /// Returns the `Config` to use, and the path of the project file if there was
96 fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
97 let path = try!(lookup_project_file(dir));
99 return Ok((Config::default(), None));
101 let path = path.unwrap();
102 let mut file = try!(File::open(&path));
103 let mut toml = String::new();
104 try!(file.read_to_string(&mut toml));
105 Ok((Config::from_toml(&toml), Some(path)))
108 /// read the given config file path recursively if present else read the project file path
109 fn match_cli_path_or_file(config_path: Option<PathBuf>,
111 -> io::Result<(Config, Option<PathBuf>)> {
113 if let Some(config_file) = config_path {
114 let (toml, path) = try!(resolve_config(config_file.as_ref()));
116 return Ok((toml, path));
119 resolve_config(input_file)
122 fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
123 config.verbose = matches.opt_present("verbose");
124 config.skip_children = matches.opt_present("skip-children");
126 let write_mode = matches.opt_str("write-mode");
127 match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
129 Some(Ok(write_mode)) => {
130 config.write_mode = write_mode;
133 Some(Err(_)) => Err(format!("Invalid write-mode: {}", write_mode.expect("cannot happen"))),
137 fn execute() -> i32 {
138 let mut opts = Options::new();
139 opts.optflag("h", "help", "show this message");
140 opts.optflag("V", "version", "show version information");
141 opts.optflag("v", "verbose", "show progress");
144 "mode to write in (not usable when piping from stdin)",
145 "[replace|overwrite|display|diff|coverage|checkstyle]");
146 opts.optflag("", "skip-children", "don't reformat child modules");
150 "show details of rustfmt configuration options");
153 "Recursively searches the given path for the rustfmt.toml config file. If not \
154 found reverts to the input file path",
155 "[Path for the configuration file]");
157 let matches = match opts.parse(env::args().skip(1)) {
160 print_usage(&opts, &e.to_string());
165 let operation = determine_operation(&matches);
168 Operation::InvalidInput { reason } => {
169 print_usage(&opts, &reason);
173 print_usage(&opts, "");
176 Operation::Version => {
180 Operation::ConfigHelp => {
181 Config::print_docs();
184 Operation::Stdin { input, config_path } => {
185 // try to read config from local directory
186 let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
187 .expect("Error resolving config");
189 // write_mode is always Plain for Stdin.
190 config.write_mode = WriteMode::Plain;
192 run(Input::Text(input), &config);
195 Operation::Format { files, config_path } => {
196 let mut config = Config::default();
198 // Load the config path file if provided
199 if let Some(config_file) = config_path {
200 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
201 .expect(&format!("Error resolving config for {:?}",
206 if let Some(path) = path.as_ref() {
207 println!("Using rustfmt config file {}", path.display());
210 // Check the file directory if the config-path could not be read or not provided
212 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
213 .expect(&format!("Error resolving config \
216 if let Some(path) = path_tmp.as_ref() {
217 println!("Using rustfmt config file {} for {}",
224 if let Err(e) = update_config(&mut config, &matches) {
225 print_usage(&opts, &e);
228 run(Input::File(file), &config);
236 let _ = env_logger::init();
237 let exit_code = execute();
239 // Make sure standard output is flushed before we exit.
240 std::io::stdout().flush().unwrap();
242 // Exit with given exit code.
244 // NOTE: This immediately terminates the process without doing any cleanup,
245 // so make sure to finish all necessary cleanup before this is called.
246 std::process::exit(exit_code);
249 fn print_usage(opts: &Options, reason: &str) {
250 let reason = format!("{}\nusage: {} [options] <file>...",
252 env::args_os().next().unwrap().to_string_lossy());
253 println!("{}", opts.usage(&reason));
257 println!("{}.{}.{}{}",
258 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
259 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
260 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
261 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
264 fn determine_operation(matches: &Matches) -> Operation {
265 if matches.opt_present("h") {
266 return Operation::Help;
269 if matches.opt_present("config-help") {
270 return Operation::ConfigHelp;
273 if matches.opt_present("version") {
274 return Operation::Version;
277 // Read the config_path and convert to parent dir if a file is provided.
278 let config_path: Option<PathBuf> = matches.opt_str("config-path")
282 return dir.parent().map(|v| v.into());
287 // if no file argument is supplied, read from stdin
288 if matches.free.is_empty() {
290 let mut buffer = String::new();
291 match io::stdin().read_to_string(&mut buffer) {
293 Err(e) => return Operation::InvalidInput { reason: e.to_string() },
296 return Operation::Stdin {
298 config_path: config_path,
302 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
306 config_path: config_path,