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 type FmtError = Box<error::Error + Send + Sync>;
33 type FmtResult<T> = std::result::Result<T, FmtError>;
35 /// Rustfmt operations.
37 /// Format files and their child modules.
40 config_path: Option<PathBuf>,
42 /// Print the help message.
44 // Print version information
46 /// Print detailed configuration help.
48 /// No file specified, read from stdin
51 config_path: Option<PathBuf>,
55 /// Parsed command line options.
56 #[derive(Clone, Debug, Default)]
60 write_mode: Option<WriteMode>,
61 file_lines: FileLines, // Default is all lines in all files.
65 fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
66 let mut options = CliOptions::default();
67 options.skip_children = matches.opt_present("skip-children");
68 options.verbose = matches.opt_present("verbose");
70 if let Some(ref write_mode) = matches.opt_str("write-mode") {
71 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
72 options.write_mode = Some(write_mode);
74 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
78 if let Some(ref file_lines) = matches.opt_str("file-lines") {
79 options.file_lines = try!(file_lines.parse());
85 fn apply_to(self, config: &mut Config) {
86 config.skip_children = self.skip_children;
87 config.verbose = self.verbose;
88 config.file_lines = self.file_lines;
89 if let Some(write_mode) = self.write_mode {
90 config.write_mode = write_mode;
95 /// Try to find a project file in the given directory and its parents. Returns the path of a the
96 /// nearest project file if one exists, or `None` if no project file was found.
97 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
98 let mut current = if dir.is_relative() {
99 try!(env::current_dir()).join(dir)
104 current = try!(fs::canonicalize(current));
107 let config_file = current.join("rustfmt.toml");
108 match fs::metadata(&config_file) {
109 // Only return if it's a file to handle the unlikely situation of a directory named
111 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
112 // Return the error if it's something other than `NotFound`; otherwise we didn't find
113 // the project file yet, and continue searching.
115 if e.kind() != ErrorKind::NotFound {
116 return Err(FmtError::from(e));
122 // If the current directory has no parent, we're done searching.
129 /// Resolve the config for input in `dir`.
131 /// Returns the `Config` to use, and the path of the project file if there was
133 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
134 let path = try!(lookup_project_file(dir));
136 return Ok((Config::default(), None));
138 let path = path.unwrap();
139 let mut file = try!(File::open(&path));
140 let mut toml = String::new();
141 try!(file.read_to_string(&mut toml));
142 Ok((Config::from_toml(&toml), Some(path)))
145 /// read the given config file path recursively if present else read the project file path
146 fn match_cli_path_or_file(config_path: Option<PathBuf>,
148 -> FmtResult<(Config, Option<PathBuf>)> {
150 if let Some(config_file) = config_path {
151 let (toml, path) = try!(resolve_config(config_file.as_ref()));
153 return Ok((toml, path));
156 resolve_config(input_file)
159 fn make_opts() -> Options {
160 let mut opts = Options::new();
161 opts.optflag("h", "help", "show this message");
162 opts.optflag("V", "version", "show version information");
163 opts.optflag("v", "verbose", "show progress");
166 "mode to write in (not usable when piping from stdin)",
167 "[replace|overwrite|display|diff|coverage|checkstyle]");
168 opts.optflag("", "skip-children", "don't reformat child modules");
172 "show details of rustfmt configuration options");
175 "Recursively searches the given path for the rustfmt.toml config file. If not \
176 found reverts to the input file path",
177 "[Path for the configuration file]");
180 "Format specified line ranges. See README for more detail on the JSON format.",
186 fn execute(opts: &Options) -> FmtResult<Summary> {
187 let matches = try!(opts.parse(env::args().skip(1)));
189 match try!(determine_operation(&matches)) {
191 print_usage(&opts, "");
194 Operation::Version => {
198 Operation::ConfigHelp => {
199 Config::print_docs();
202 Operation::Stdin { input, config_path } => {
203 // try to read config from local directory
204 let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
205 .expect("Error resolving config");
207 // write_mode is always Plain for Stdin.
208 config.write_mode = WriteMode::Plain;
210 Ok(run(Input::Text(input), &config))
212 Operation::Format { mut files, config_path } => {
213 let options = try!(CliOptions::from_matches(&matches));
215 // Add any additional files that were specified via `--file-lines`.
216 files.extend(options.file_lines.files().cloned().map(PathBuf::from));
218 let mut config = Config::default();
220 // Load the config path file if provided
221 if let Some(config_file) = config_path {
222 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
223 .expect(&format!("Error resolving config for {:?}", config_file));
227 if let Some(path) = path.as_ref() {
228 println!("Using rustfmt config file {}", path.display());
231 let mut error_summary = Summary::new();
233 // Check the file directory if the config-path could not be read or not provided
235 let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
236 .expect(&format!("Error resolving config for {}", file.display()));
237 if let Some(path) = path_tmp.as_ref() {
238 println!("Using rustfmt config file {} for {}",
245 options.clone().apply_to(&mut config);
246 error_summary.add(run(Input::File(file), &config));
254 let _ = env_logger::init();
256 let opts = make_opts();
258 let exit_code = match execute(&opts) {
260 if summary.has_operational_errors() {
262 } else if summary.has_parsing_errors() {
264 } else if summary.has_formatting_errors() {
267 assert!(summary.has_no_errors());
272 print_usage(&opts, &e.to_string());
276 // Make sure standard output is flushed before we exit.
277 std::io::stdout().flush().unwrap();
279 // Exit with given exit code.
281 // NOTE: This immediately terminates the process without doing any cleanup,
282 // so make sure to finish all necessary cleanup before this is called.
283 std::process::exit(exit_code);
286 fn print_usage(opts: &Options, reason: &str) {
287 let reason = format!("{}\nusage: {} [options] <file>...",
289 env::args_os().next().unwrap().to_string_lossy());
290 println!("{}", opts.usage(&reason));
294 println!("{}.{}.{}{}",
295 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
296 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
297 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
298 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
301 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
302 if matches.opt_present("h") {
303 return Ok(Operation::Help);
306 if matches.opt_present("config-help") {
307 return Ok(Operation::ConfigHelp);
310 if matches.opt_present("version") {
311 return Ok(Operation::Version);
314 // Read the config_path and convert to parent dir if a file is provided.
315 let config_path: Option<PathBuf> = matches.opt_str("config-path")
319 return dir.parent().map(|v| v.into());
324 // if no file argument is supplied and `--file-lines` is not specified, read from stdin
325 if matches.free.is_empty() && !matches.opt_present("file-lines") {
327 let mut buffer = String::new();
328 try!(io::stdin().read_to_string(&mut buffer));
330 return Ok(Operation::Stdin {
332 config_path: config_path,
336 // We append files from `--file-lines` later in `execute()`.
337 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
339 Ok(Operation::Format {
341 config_path: config_path,