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};
23 use std::{env, error};
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 type FmtError = Box<error::Error + Send + Sync>;
32 type FmtResult<T> = std::result::Result<T, FmtError>;
34 /// Rustfmt operations.
36 /// Format files and their child modules.
39 config_path: Option<PathBuf>,
41 /// Print the help message.
43 // Print version information
45 /// Print detailed configuration help.
47 /// No file specified, read from stdin
50 config_path: Option<PathBuf>,
54 /// Try to find a project file in the given directory and its parents. Returns the path of a the
55 /// nearest project file if one exists, or `None` if no project file was found.
56 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
57 let mut current = if dir.is_relative() {
58 try!(env::current_dir()).join(dir)
63 current = try!(fs::canonicalize(current));
66 let config_file = current.join("rustfmt.toml");
67 match fs::metadata(&config_file) {
69 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
71 return Ok(Some(config_file));
74 // If it's not found, we continue searching; otherwise something went wrong and we
77 if e.kind() != ErrorKind::NotFound {
78 return Err(FmtError::from(e));
83 // If the current directory has no parent, we're done searching.
90 /// Resolve the config for input in `dir`.
92 /// Returns the `Config` to use, and the path of the project file if there was
94 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
95 let path = try!(lookup_project_file(dir));
97 return Ok((Config::default(), None));
99 let path = path.unwrap();
100 let mut file = try!(File::open(&path));
101 let mut toml = String::new();
102 try!(file.read_to_string(&mut toml));
103 Ok((Config::from_toml(&toml), Some(path)))
106 /// read the given config file path recursively if present else read the project file path
107 fn match_cli_path_or_file(config_path: Option<PathBuf>,
109 -> FmtResult<(Config, Option<PathBuf>)> {
111 if let Some(config_file) = config_path {
112 let (toml, path) = try!(resolve_config(config_file.as_ref()));
114 return Ok((toml, path));
117 resolve_config(input_file)
120 fn update_config(config: &mut Config, matches: &Matches) -> FmtResult<()> {
121 config.verbose = matches.opt_present("verbose");
122 config.skip_children = matches.opt_present("skip-children");
124 let write_mode = matches.opt_str("write-mode");
125 match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
127 Some(Ok(write_mode)) => {
128 config.write_mode = write_mode;
132 Err(FmtError::from(format!("Invalid write-mode: {}",
133 write_mode.expect("cannot happen"))))
138 fn make_opts() -> Options {
139 let mut opts = Options::new();
140 opts.optflag("h", "help", "show this message");
141 opts.optflag("V", "version", "show version information");
142 opts.optflag("v", "verbose", "show progress");
145 "mode to write in (not usable when piping from stdin)",
146 "[replace|overwrite|display|diff|coverage|checkstyle]");
147 opts.optflag("", "skip-children", "don't reformat child modules");
151 "show details of rustfmt configuration options");
154 "Recursively searches the given path for the rustfmt.toml config file. If not \
155 found reverts to the input file path",
156 "[Path for the configuration file]");
161 fn execute(opts: &Options) -> FmtResult<()> {
162 let matches = try!(opts.parse(env::args().skip(1)));
164 match try!(determine_operation(&matches)) {
166 print_usage(&opts, "");
168 Operation::Version => {
171 Operation::ConfigHelp => {
172 Config::print_docs();
174 Operation::Stdin { input, config_path } => {
175 // try to read config from local directory
176 let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
177 .expect("Error resolving config");
179 // write_mode is always Plain for Stdin.
180 config.write_mode = WriteMode::Plain;
182 run(Input::Text(input), &config);
184 Operation::Format { files, config_path } => {
185 let mut config = Config::default();
187 // Load the config path file if provided
188 if let Some(config_file) = config_path {
189 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
190 .expect(&format!("Error resolving config for {:?}",
195 if let Some(path) = path.as_ref() {
196 println!("Using rustfmt config file {}", path.display());
199 // Check the file directory if the config-path could not be read or not provided
201 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
202 .expect(&format!("Error resolving config \
205 if let Some(path) = path_tmp.as_ref() {
206 println!("Using rustfmt config file {} for {}",
213 try!(update_config(&mut config, &matches));
214 run(Input::File(file), &config);
222 let _ = env_logger::init();
224 let opts = make_opts();
226 let exit_code = match execute(&opts) {
229 print_usage(&opts, &e.to_string());
233 // Make sure standard output is flushed before we exit.
234 std::io::stdout().flush().unwrap();
236 // Exit with given exit code.
238 // NOTE: This immediately terminates the process without doing any cleanup,
239 // so make sure to finish all necessary cleanup before this is called.
240 std::process::exit(exit_code);
243 fn print_usage(opts: &Options, reason: &str) {
244 let reason = format!("{}\nusage: {} [options] <file>...",
246 env::args_os().next().unwrap().to_string_lossy());
247 println!("{}", opts.usage(&reason));
251 println!("{}.{}.{}{}",
252 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
253 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
254 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
255 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
258 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
259 if matches.opt_present("h") {
260 return Ok(Operation::Help);
263 if matches.opt_present("config-help") {
264 return Ok(Operation::ConfigHelp);
267 if matches.opt_present("version") {
268 return Ok(Operation::Version);
271 // Read the config_path and convert to parent dir if a file is provided.
272 let config_path: Option<PathBuf> = matches.opt_str("config-path")
276 return dir.parent().map(|v| v.into());
281 // if no file argument is supplied, read from stdin
282 if matches.free.is_empty() {
284 let mut buffer = String::new();
285 try!(io::stdin().read_to_string(&mut buffer));
287 return Ok(Operation::Stdin {
289 config_path: config_path,
293 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
295 Ok(Operation::Format {
297 config_path: config_path,