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.
13 extern crate env_logger;
15 extern crate rustfmt_nightly as rustfmt;
17 use std::{env, error};
19 use std::io::{self, Read, Write};
20 use std::path::{Path, PathBuf};
21 use std::str::FromStr;
23 use getopts::{Matches, Options};
25 use rustfmt::config::{get_toml_path, Color, Config, WriteMode};
26 use rustfmt::config::file_lines::FileLines;
27 use rustfmt::{run, FileName, Input, Summary};
29 type FmtError = Box<error::Error + Send + Sync>;
30 type FmtResult<T> = std::result::Result<T, FmtError>;
32 /// Rustfmt operations.
34 /// Format files and their child modules.
37 config_path: Option<PathBuf>,
38 minimal_config_path: Option<String>,
40 /// Print the help message.
42 // Print version information
44 /// Print detailed configuration help.
46 /// Output default config to a file, or stdout if None
50 /// No file specified, read from stdin
53 config_path: Option<PathBuf>,
57 /// Parsed command line options.
58 #[derive(Clone, Debug, Default)]
62 write_mode: Option<WriteMode>,
64 file_lines: FileLines, // Default is all lines in all files.
65 unstable_features: bool,
66 error_on_unformatted: bool,
70 fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
71 let mut options = CliOptions::default();
72 options.skip_children = matches.opt_present("skip-children");
73 options.verbose = matches.opt_present("verbose");
74 let unstable_features = matches.opt_present("unstable-features");
75 let rust_nightly = option_env!("CFG_RELEASE_CHANNEL")
76 .map(|c| c == "nightly")
78 if unstable_features && !rust_nightly {
79 return Err(FmtError::from(
80 "Unstable features are only available on Nightly channel",
83 options.unstable_features = unstable_features;
86 if let Some(ref write_mode) = matches.opt_str("write-mode") {
87 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
88 options.write_mode = Some(write_mode);
90 return Err(FmtError::from(format!(
91 "Invalid write-mode: {}",
97 if let Some(ref color) = matches.opt_str("color") {
98 match Color::from_str(color) {
99 Ok(color) => options.color = Some(color),
100 _ => return Err(FmtError::from(format!("Invalid color: {}", color))),
104 if let Some(ref file_lines) = matches.opt_str("file-lines") {
105 options.file_lines = file_lines.parse()?;
108 if matches.opt_present("error-on-unformatted") {
109 options.error_on_unformatted = true;
115 fn apply_to(self, config: &mut Config) {
116 config.set().skip_children(self.skip_children);
117 config.set().verbose(self.verbose);
118 config.set().file_lines(self.file_lines);
119 config.set().unstable_features(self.unstable_features);
120 config.set().error_on_unformatted(self.error_on_unformatted);
121 if let Some(write_mode) = self.write_mode {
122 config.set().write_mode(write_mode);
124 if let Some(color) = self.color {
125 config.set().color(color);
130 /// read the given config file path recursively if present else read the project file path
131 fn match_cli_path_or_file(
132 config_path: Option<PathBuf>,
134 ) -> FmtResult<(Config, Option<PathBuf>)> {
135 if let Some(config_file) = config_path {
136 let toml = Config::from_toml_path(config_file.as_ref())?;
137 return Ok((toml, Some(config_file)));
139 Config::from_resolved_toml_path(input_file).map_err(FmtError::from)
142 fn make_opts() -> Options {
143 let mut opts = Options::new();
145 // Sorted in alphabetical order.
149 "Use colored output (if supported)",
150 "[always|never|auto]",
155 "Show details of rustfmt configuration options",
160 "Recursively searches the given path for the rustfmt.toml config file. If not \
161 found reverts to the input file path",
162 "[Path for the configuration file]",
166 "dump-default-config",
167 "Dumps default configuration to PATH. PATH defaults to stdout, if omitted.",
172 "dump-minimal-config",
173 "Dumps configuration options that were checked during formatting to a file.",
178 "error-on-unformatted",
179 "Error if unable to get comments or string literals within max_width, \
180 or they are left with trailing whitespaces",
185 "Format specified line ranges. See README for more detail on the JSON format.",
188 opts.optflag("h", "help", "Show this message");
189 opts.optflag("", "skip-children", "Don't reformat child modules");
193 "Enables unstable features. Only available on nightly channel",
195 opts.optflag("v", "verbose", "Print verbose output");
196 opts.optflag("V", "version", "Show version information");
200 "How to write output (not usable when piping from stdin)",
201 "[replace|overwrite|display|plain|diff|coverage|checkstyle]",
207 fn execute(opts: &Options) -> FmtResult<Summary> {
208 let matches = opts.parse(env::args().skip(1))?;
210 match determine_operation(&matches)? {
212 print_usage_to_stdout(opts, "");
213 Summary::print_exit_codes();
214 Ok(Summary::default())
216 Operation::Version => {
218 Ok(Summary::default())
220 Operation::ConfigHelp => {
221 Config::print_docs();
222 Ok(Summary::default())
224 Operation::ConfigOutputDefault { path } => {
225 let toml = Config::default().all_options().to_toml()?;
226 if let Some(path) = path {
227 let mut file = File::create(path)?;
228 file.write_all(toml.as_bytes())?;
230 io::stdout().write_all(toml.as_bytes())?;
232 Ok(Summary::default())
234 Operation::Stdin { input, config_path } => {
235 // try to read config from local directory
236 let (mut config, _) =
237 match_cli_path_or_file(config_path, &env::current_dir().unwrap())?;
239 // write_mode is always Plain for Stdin.
240 config.set().write_mode(WriteMode::Plain);
243 if let Some(ref file_lines) = matches.opt_str("file-lines") {
244 config.set().file_lines(file_lines.parse()?);
245 for f in config.file_lines().files() {
247 FileName::Custom(ref f) if f == "stdin" => {}
248 _ => eprintln!("Warning: Extra file listed in file_lines option '{}'", f),
253 let mut error_summary = Summary::default();
254 if config.version_meets_requirement(&mut error_summary) {
255 error_summary.add(run(Input::Text(input), &config));
265 let options = CliOptions::from_matches(&matches)?;
267 for f in options.file_lines.files() {
269 FileName::Real(ref f) if files.contains(f) => {}
270 FileName::Real(_) => {
271 eprintln!("Warning: Extra file listed in file_lines option '{}'", f)
273 _ => eprintln!("Warning: Not a file '{}'", f),
277 let mut config = Config::default();
278 // Load the config path file if provided
279 if let Some(config_file) = config_path.as_ref() {
280 config = Config::from_toml_path(config_file.as_ref())?;
284 if let Some(path) = config_path.as_ref() {
285 println!("Using rustfmt config file {}", path.display());
289 let mut error_summary = Summary::default();
292 eprintln!("Error: file `{}` does not exist", file.to_str().unwrap());
293 error_summary.add_operational_error();
294 } else if file.is_dir() {
295 eprintln!("Error: `{}` is a directory", file.to_str().unwrap());
296 error_summary.add_operational_error();
298 // Check the file directory if the config-path could not be read or not provided
299 if config_path.is_none() {
300 let (config_tmp, path_tmp) =
301 Config::from_resolved_toml_path(file.parent().unwrap())?;
303 if let Some(path) = path_tmp.as_ref() {
305 "Using rustfmt config file {} for {}",
314 if !config.version_meets_requirement(&mut error_summary) {
318 options.clone().apply_to(&mut config);
319 error_summary.add(run(Input::File(file), &config));
323 // If we were given a path via dump-minimal-config, output any options
324 // that were used during formatting as TOML.
325 if let Some(path) = minimal_config_path {
326 let mut file = File::create(path)?;
327 let toml = config.used_options().to_toml()?;
328 file.write_all(toml.as_bytes())?;
339 let opts = make_opts();
341 let exit_code = match execute(&opts) {
343 if summary.has_operational_errors() {
345 } else if summary.has_parsing_errors() {
347 } else if summary.has_formatting_errors() {
349 } else if summary.has_diff {
350 // should only happen in diff mode
353 assert!(summary.has_no_errors());
358 eprintln!("{}", e.to_string());
362 // Make sure standard output is flushed before we exit.
363 std::io::stdout().flush().unwrap();
365 // Exit with given exit code.
367 // NOTE: This immediately terminates the process without doing any cleanup,
368 // so make sure to finish all necessary cleanup before this is called.
369 std::process::exit(exit_code);
372 fn print_usage_to_stdout(opts: &Options, reason: &str) {
373 let sep = if reason.is_empty() {
376 format!("{}\n\n", reason)
379 "{}Format Rust code\n\nusage: {} [options] <file>...",
381 env::args_os().next().unwrap().to_string_lossy()
383 println!("{}", opts.usage(&msg));
387 let version_info = format!(
389 option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
391 include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
394 println!("rustfmt {}", version_info);
397 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
398 if matches.opt_present("h") {
399 return Ok(Operation::Help);
402 if matches.opt_present("config-help") {
403 return Ok(Operation::ConfigHelp);
406 if matches.opt_present("dump-default-config") {
407 // NOTE for some reason when configured with HasArg::Maybe + Occur::Optional opt_default
408 // doesn't recognize `--foo bar` as a long flag with an argument but as a long flag with no
409 // argument *plus* a free argument. Thus we check for that case in this branch -- this is
410 // required for backward compatibility.
411 if let Some(path) = matches.free.get(0) {
412 return Ok(Operation::ConfigOutputDefault {
413 path: Some(path.clone()),
416 return Ok(Operation::ConfigOutputDefault {
417 path: matches.opt_str("dump-default-config"),
422 if matches.opt_present("version") {
423 return Ok(Operation::Version);
426 let config_path_not_found = |path: &str| -> FmtResult<Operation> {
427 Err(FmtError::from(format!(
428 "Error: unable to find a config file for the given path: `{}`",
433 // Read the config_path and convert to parent dir if a file is provided.
434 // If a config file cannot be found from the given path, return error.
435 let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
436 Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
437 Some(ref path) if path.is_dir() => {
438 let config_file_path = get_toml_path(path)?;
439 if config_file_path.is_some() {
442 return config_path_not_found(path.to_str().unwrap());
448 // If no path is given, we won't output a minimal config.
449 let minimal_config_path = matches.opt_str("dump-minimal-config");
451 // if no file argument is supplied, read from stdin
452 if matches.free.is_empty() {
453 let mut buffer = String::new();
454 io::stdin().read_to_string(&mut buffer)?;
456 return Ok(Operation::Stdin {
462 let files: Vec<_> = matches
466 let p = PathBuf::from(s);
467 // we will do comparison later, so here tries to canonicalize first
468 // to get the expected behavior.
469 p.canonicalize().unwrap_or(p)
473 Ok(Operation::Format {