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.
15 extern crate rustfmt_nightly as rustfmt;
17 extern crate env_logger;
20 use std::{env, error};
22 use std::io::{self, Read, Write};
23 use std::path::{Path, PathBuf};
24 use std::str::FromStr;
26 use getopts::{Matches, Options};
28 use rustfmt::{run, Input, Summary};
29 use rustfmt::file_lines::FileLines;
30 use rustfmt::config::{get_toml_path, Config, WriteMode};
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>,
41 minimal_config_path: Option<String>,
43 /// Print the help message.
45 // Print version information
47 /// Print detailed configuration help.
49 /// Output default config to a file
50 ConfigOutputDefault { path: String },
51 /// No file specified, read from stdin
54 config_path: Option<PathBuf>,
58 /// Parsed command line options.
59 #[derive(Clone, Debug, Default)]
63 write_mode: Option<WriteMode>,
64 file_lines: FileLines, // Default is all lines in all files.
68 fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
69 let mut options = CliOptions::default();
70 options.skip_children = matches.opt_present("skip-children");
71 options.verbose = matches.opt_present("verbose");
73 if let Some(ref write_mode) = matches.opt_str("write-mode") {
74 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
75 options.write_mode = Some(write_mode);
77 return Err(FmtError::from(
78 format!("Invalid write-mode: {}", write_mode),
81 } else if !matches.opt_present("no-warn-write-mode") {
83 "Warning: the default write-mode for Rustfmt will soon change to overwrite \
84 - this will not leave backups of changed files."
88 if let Some(ref file_lines) = matches.opt_str("file-lines") {
89 options.file_lines = file_lines.parse()?;
95 fn apply_to(self, config: &mut Config) {
96 config.set().skip_children(self.skip_children);
97 config.set().verbose(self.verbose);
98 config.set().file_lines(self.file_lines);
99 if let Some(write_mode) = self.write_mode {
100 config.set().write_mode(write_mode);
105 /// read the given config file path recursively if present else read the project file path
106 fn match_cli_path_or_file(
107 config_path: Option<PathBuf>,
109 ) -> FmtResult<(Config, Option<PathBuf>)> {
111 if let Some(config_file) = config_path {
112 let toml = Config::from_toml_path(config_file.as_ref())?;
113 return Ok((toml, Some(config_file)));
115 Config::from_resolved_toml_path(input_file).map_err(|e| FmtError::from(e))
118 fn make_opts() -> Options {
119 let mut opts = Options::new();
120 opts.optflag("h", "help", "show this message");
121 opts.optflag("V", "version", "show version information");
122 opts.optflag("v", "verbose", "print verbose output");
123 // Suppress warning. Remove this option after the default write mode changed to overwrite.
126 "no-warn-write-mode",
127 "inhibit warning about write-mode change",
132 "mode to write in (not usable when piping from stdin)",
133 "[replace|overwrite|display|diff|coverage|checkstyle]",
135 opts.optflag("", "skip-children", "don't reformat child modules");
140 "show details of rustfmt configuration options",
144 "dump-default-config",
145 "Dumps the default configuration to a file and exits.",
150 "dump-minimal-config",
151 "Dumps configuration options that were checked during formatting to a file.",
157 "Recursively searches the given path for the rustfmt.toml config file. If not \
158 found reverts to the input file path",
159 "[Path for the configuration file]",
164 "Format specified line ranges. See README for more detail on the JSON format.",
171 fn execute(opts: &Options) -> FmtResult<Summary> {
172 let matches = opts.parse(env::args().skip(1))?;
174 match determine_operation(&matches)? {
176 print_usage(opts, "");
177 Summary::print_exit_codes();
180 Operation::Version => {
184 Operation::ConfigHelp => {
185 Config::print_docs();
188 Operation::ConfigOutputDefault { path } => {
189 let mut file = File::create(path)?;
190 let toml = Config::default().all_options().to_toml()?;
191 file.write_all(toml.as_bytes())?;
194 Operation::Stdin { input, config_path } => {
195 // try to read config from local directory
196 let (mut config, _) =
197 match_cli_path_or_file(config_path, &env::current_dir().unwrap())?;
199 // write_mode is always Plain for Stdin.
200 config.set().write_mode(WriteMode::Plain);
203 if let Some(ref file_lines) = matches.opt_str("file-lines") {
204 config.set().file_lines(file_lines.parse()?);
205 for f in config.file_lines().files() {
207 println!("Warning: Extra file listed in file_lines option '{}'", f);
212 Ok(run(Input::Text(input), &config))
219 let options = CliOptions::from_matches(&matches)?;
221 for f in options.file_lines.files() {
222 if !files.contains(&PathBuf::from(f)) {
223 println!("Warning: Extra file listed in file_lines option '{}'", f);
227 let mut config = Config::default();
228 // Load the config path file if provided
229 if let Some(config_file) = config_path.as_ref() {
230 config = Config::from_toml_path(config_file.as_ref())?;
234 if let Some(path) = config_path.as_ref() {
235 println!("Using rustfmt config file {}", path.display());
239 let mut error_summary = Summary::new();
242 println!("Error: file `{}` does not exist", file.to_str().unwrap());
243 error_summary.add_operational_error();
244 } else if file.is_dir() {
245 println!("Error: `{}` is a directory", file.to_str().unwrap());
246 error_summary.add_operational_error();
248 // Check the file directory if the config-path could not be read or not provided
249 if config_path.is_none() {
250 let (config_tmp, path_tmp) =
251 Config::from_resolved_toml_path(file.parent().unwrap())?;
253 if let Some(path) = path_tmp.as_ref() {
255 "Using rustfmt config file {} for {}",
264 options.clone().apply_to(&mut config);
265 error_summary.add(run(Input::File(file), &config));
269 // If we were given a path via dump-minimal-config, output any options
270 // that were used during formatting as TOML.
271 if let Some(path) = minimal_config_path {
272 let mut file = File::create(path)?;
273 let toml = config.used_options().to_toml()?;
274 file.write_all(toml.as_bytes())?;
283 let _ = env_logger::init();
285 let opts = make_opts();
287 let exit_code = match execute(&opts) {
289 if summary.has_operational_errors() {
291 } else if summary.has_parsing_errors() {
293 } else if summary.has_formatting_errors() {
295 } else if summary.has_diff {
296 // should only happen in diff mode
299 assert!(summary.has_no_errors());
304 print_usage(&opts, &e.to_string());
308 // Make sure standard output is flushed before we exit.
309 std::io::stdout().flush().unwrap();
311 // Exit with given exit code.
313 // NOTE: This immediately terminates the process without doing any cleanup,
314 // so make sure to finish all necessary cleanup before this is called.
315 std::process::exit(exit_code);
318 fn print_usage(opts: &Options, reason: &str) {
319 let reason = format!(
320 "{}\n\nusage: {} [options] <file>...",
322 env::args_os().next().unwrap().to_string_lossy()
324 println!("{}", opts.usage(&reason));
330 env!("CARGO_PKG_VERSION"),
331 include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
335 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
336 if matches.opt_present("h") {
337 return Ok(Operation::Help);
340 if matches.opt_present("config-help") {
341 return Ok(Operation::ConfigHelp);
344 if let Some(path) = matches.opt_str("dump-default-config") {
345 return Ok(Operation::ConfigOutputDefault { path });
348 if matches.opt_present("version") {
349 return Ok(Operation::Version);
352 let config_path_not_found = |path: &str| -> FmtResult<Operation> {
353 Err(FmtError::from(format!(
354 "Error: unable to find a config file for the given path: `{}`",
359 // Read the config_path and convert to parent dir if a file is provided.
360 // If a config file cannot be found from the given path, return error.
361 let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
362 Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
363 Some(ref path) if path.is_dir() => {
364 let config_file_path = get_toml_path(path)?;
365 if config_file_path.is_some() {
368 return config_path_not_found(path.to_str().unwrap());
374 // If no path is given, we won't output a minimal config.
375 let minimal_config_path = matches.opt_str("dump-minimal-config");
377 // if no file argument is supplied, read from stdin
378 if matches.free.is_empty() {
379 let mut buffer = String::new();
380 io::stdin().read_to_string(&mut buffer)?;
382 return Ok(Operation::Stdin {
384 config_path: config_path,
388 let files: Vec<_> = matches
392 let p = PathBuf::from(s);
393 // we will do comparison later, so here tries to canonicalize first
394 // to get the expected behavior.
395 p.canonicalize().unwrap_or(p)
399 Ok(Operation::Format {
401 config_path: config_path,
402 minimal_config_path: minimal_config_path,