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, Summary};
21 use rustfmt::file_lines::FileLines;
22 use rustfmt::config::{Config, WriteMode};
24 use std::{env, error};
25 use std::fs::{self, File};
26 use std::io::{self, ErrorKind, Read, Write};
27 use std::path::{Path, PathBuf};
28 use std::str::FromStr;
30 use getopts::{Matches, Options};
32 // Include git commit hash and worktree status; contents are like
33 // const COMMIT_HASH: Option<&'static str> = Some("c31a366");
34 // const WORKTREE_CLEAN: Option<bool> = Some(false);
35 // with `None` if running git failed, eg if it is not installed.
36 include!(concat!(env!("OUT_DIR"), "/git_info.rs"));
38 type FmtError = Box<error::Error + Send + Sync>;
39 type FmtResult<T> = std::result::Result<T, FmtError>;
41 /// Rustfmt operations.
43 /// Format files and their child modules.
46 config_path: Option<PathBuf>,
48 /// Print the help message.
50 // Print version information
52 /// Print detailed configuration help.
54 /// No file specified, read from stdin
57 config_path: Option<PathBuf>,
61 /// Parsed command line options.
62 #[derive(Clone, Debug, Default)]
66 write_mode: Option<WriteMode>,
67 file_lines: FileLines, // Default is all lines in all files.
71 fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
72 let mut options = CliOptions::default();
73 options.skip_children = matches.opt_present("skip-children");
74 options.verbose = matches.opt_present("verbose");
76 if let Some(ref write_mode) = matches.opt_str("write-mode") {
77 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
78 options.write_mode = Some(write_mode);
80 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
84 if let Some(ref file_lines) = matches.opt_str("file-lines") {
85 options.file_lines = try!(file_lines.parse());
91 fn apply_to(self, config: &mut Config) {
92 config.skip_children = self.skip_children;
93 config.verbose = self.verbose;
94 config.file_lines = self.file_lines;
95 if let Some(write_mode) = self.write_mode {
96 config.write_mode = write_mode;
101 const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
103 /// Try to find a project file in the given directory and its parents. Returns the path of a the
104 /// nearest project file if one exists, or `None` if no project file was found.
105 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
106 let mut current = if dir.is_relative() {
107 try!(env::current_dir()).join(dir)
112 current = try!(fs::canonicalize(current));
115 for config_file_name in &CONFIG_FILE_NAMES {
116 let config_file = current.join(config_file_name);
117 match fs::metadata(&config_file) {
118 // Only return if it's a file to handle the unlikely situation of a directory named
120 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
121 // Return the error if it's something other than `NotFound`; otherwise we didn't
122 // find the project file yet, and continue searching.
124 if e.kind() != ErrorKind::NotFound {
125 return Err(FmtError::from(e));
132 // If the current directory has no parent, we're done searching.
139 fn open_config_file(file_path: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
140 let mut file = try!(File::open(&file_path));
141 let mut toml = String::new();
142 try!(file.read_to_string(&mut toml));
143 match Config::from_toml(&toml) {
144 Ok(cfg) => Ok((cfg, Some(file_path.to_path_buf()))),
145 Err(err) => Err(FmtError::from(err)),
149 /// Resolve the config for input in `dir`.
151 /// Returns the `Config` to use, and the path of the project file if there was
153 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
154 let path = try!(lookup_project_file(dir));
156 return Ok((Config::default(), None));
158 open_config_file(&path.unwrap())
161 /// read the given config file path recursively if present else read the project file path
162 fn match_cli_path_or_file(config_path: Option<PathBuf>,
164 -> FmtResult<(Config, Option<PathBuf>)> {
166 if let Some(config_file) = config_path {
167 let (toml, path) = try!(open_config_file(config_file.as_ref()));
169 return Ok((toml, path));
172 resolve_config(input_file)
175 fn make_opts() -> Options {
176 let mut opts = Options::new();
177 opts.optflag("h", "help", "show this message");
178 opts.optflag("V", "version", "show version information");
179 opts.optflag("v", "verbose", "print verbose output");
182 "mode to write in (not usable when piping from stdin)",
183 "[replace|overwrite|display|diff|coverage|checkstyle]");
184 opts.optflag("", "skip-children", "don't reformat child modules");
188 "show details of rustfmt configuration options");
191 "Recursively searches the given path for the rustfmt.toml config file. If not \
192 found reverts to the input file path",
193 "[Path for the configuration file]");
196 "Format specified line ranges. See README for more detail on the JSON format.",
202 fn execute(opts: &Options) -> FmtResult<Summary> {
203 let matches = try!(opts.parse(env::args().skip(1)));
205 match try!(determine_operation(&matches)) {
207 print_usage(opts, "");
208 Summary::print_exit_codes();
211 Operation::Version => {
215 Operation::ConfigHelp => {
216 Config::print_docs();
219 Operation::Stdin { input, config_path } => {
220 // try to read config from local directory
221 let (mut config, _) = match_cli_path_or_file(config_path,
222 &env::current_dir().unwrap())?;
224 // write_mode is always Plain for Stdin.
225 config.write_mode = WriteMode::Plain;
228 if let Some(ref file_lines) = matches.opt_str("file-lines") {
229 config.file_lines = try!(file_lines.parse());
230 for f in config.file_lines.files() {
232 println!("Warning: Extra file listed in file_lines option '{}'", f);
237 Ok(run(Input::Text(input), &config))
239 Operation::Format { files, config_path } => {
240 let options = try!(CliOptions::from_matches(&matches));
242 for f in options.file_lines.files() {
243 if !files.contains(&PathBuf::from(f)) {
244 println!("Warning: Extra file listed in file_lines option '{}'", f);
248 let mut config = Config::default();
250 // Load the config path file if provided
251 if let Some(config_file) = config_path {
252 let (cfg_tmp, path_tmp) = open_config_file(config_file.as_ref())?;
258 if let Some(path) = path.as_ref() {
259 println!("Using rustfmt config file {}", path.display());
263 let mut error_summary = Summary::new();
266 println!("Error: file `{}` does not exist", file.to_str().unwrap());
267 error_summary.add_operational_error();
268 } else if file.is_dir() {
269 println!("Error: `{}` is a directory", file.to_str().unwrap());
270 error_summary.add_operational_error();
272 // Check the file directory if the config-path could not be read or not provided
274 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())?;
276 if let Some(path) = path_tmp.as_ref() {
277 println!("Using rustfmt config file {} for {}",
285 options.clone().apply_to(&mut config);
286 error_summary.add(run(Input::File(file), &config));
295 let _ = env_logger::init();
297 let opts = make_opts();
299 let exit_code = match execute(&opts) {
301 if summary.has_operational_errors() {
303 } else if summary.has_parsing_errors() {
305 } else if summary.has_formatting_errors() {
307 } else if summary.has_diff {
308 // should only happen in diff mode
311 assert!(summary.has_no_errors());
316 print_usage(&opts, &e.to_string());
320 // Make sure standard output is flushed before we exit.
321 std::io::stdout().flush().unwrap();
323 // Exit with given exit code.
325 // NOTE: This immediately terminates the process without doing any cleanup,
326 // so make sure to finish all necessary cleanup before this is called.
327 std::process::exit(exit_code);
330 fn print_usage(opts: &Options, reason: &str) {
331 let reason = format!("{}\n\nusage: {} [options] <file>...",
333 env::args_os().next().unwrap().to_string_lossy());
334 println!("{}", opts.usage(&reason));
338 println!("{} ({}{})",
339 option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
340 COMMIT_HASH.unwrap_or("git commit unavailable"),
341 match WORKTREE_CLEAN {
342 Some(false) => " worktree dirty",
347 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
348 if matches.opt_present("h") {
349 return Ok(Operation::Help);
352 if matches.opt_present("config-help") {
353 return Ok(Operation::ConfigHelp);
356 if matches.opt_present("version") {
357 return Ok(Operation::Version);
360 let config_path_not_found = |path: &str| -> FmtResult<Operation> {
361 Err(FmtError::from(format!("Error: unable to find a config file for the given path: `{}`",
365 // Read the config_path and convert to parent dir if a file is provided.
366 // If a config file cannot be found from the given path, return error.
367 let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
368 Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
369 Some(ref path) if path.is_dir() => {
370 let mut config_file_path = None;
371 for config_file_name in &CONFIG_FILE_NAMES {
372 let temp_path = path.join(config_file_name);
373 if temp_path.is_file() {
374 config_file_path = Some(temp_path);
377 if config_file_path.is_some() {
380 return config_path_not_found(path.to_str().unwrap());
386 // if no file argument is supplied, read from stdin
387 if matches.free.is_empty() {
388 let mut buffer = String::new();
389 try!(io::stdin().read_to_string(&mut buffer));
391 return Ok(Operation::Stdin {
393 config_path: config_path,
397 let files: Vec<_> = matches
401 let p = PathBuf::from(s);
402 // we will do comparison later, so here tries to canonicalize first
403 // to get the expected behavior.
404 p.canonicalize().unwrap_or(p)
408 Ok(Operation::Format {
410 config_path: config_path,