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::{HasArg, Matches, Occur, Options};
25 use rustfmt::{run, Input, Summary};
26 use rustfmt::file_lines::FileLines;
27 use rustfmt::config::{get_toml_path, Color, Config, WriteMode};
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,
69 fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
70 let mut options = CliOptions::default();
71 options.skip_children = matches.opt_present("skip-children");
72 options.verbose = matches.opt_present("verbose");
73 let unstable_features = matches.opt_present("unstable-features");
74 let rust_nightly = option_env!("CFG_RELEASE_CHANNEL")
75 .map(|c| c == "nightly")
77 if unstable_features && !rust_nightly {
78 return Err(FmtError::from(
79 "Unstable features are only available on Nightly channel",
82 options.unstable_features = unstable_features;
85 if let Some(ref write_mode) = matches.opt_str("write-mode") {
86 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
87 options.write_mode = Some(write_mode);
89 return Err(FmtError::from(format!(
90 "Invalid write-mode: {}",
96 if let Some(ref color) = matches.opt_str("color") {
97 match Color::from_str(color) {
98 Ok(color) => options.color = Some(color),
99 _ => return Err(FmtError::from(format!("Invalid color: {}", color))),
103 if let Some(ref file_lines) = matches.opt_str("file-lines") {
104 options.file_lines = file_lines.parse()?;
110 fn apply_to(self, config: &mut Config) {
111 config.set().skip_children(self.skip_children);
112 config.set().verbose(self.verbose);
113 config.set().file_lines(self.file_lines);
114 config.set().unstable_features(self.unstable_features);
115 if let Some(write_mode) = self.write_mode {
116 config.set().write_mode(write_mode);
118 if let Some(color) = self.color {
119 config.set().color(color);
124 /// read the given config file path recursively if present else read the project file path
125 fn match_cli_path_or_file(
126 config_path: Option<PathBuf>,
128 ) -> FmtResult<(Config, Option<PathBuf>)> {
129 if let Some(config_file) = config_path {
130 let toml = Config::from_toml_path(config_file.as_ref())?;
131 return Ok((toml, Some(config_file)));
133 Config::from_resolved_toml_path(input_file).map_err(FmtError::from)
136 fn make_opts() -> Options {
137 let mut opts = Options::new();
139 opts.optflag("h", "help", "Show this message");
140 opts.optflag("V", "version", "Show version information");
141 opts.optflag("v", "verbose", "Print verbose output");
142 opts.optflag("", "skip-children", "Don't reformat child modules");
146 "Enables unstable features. Only available on nightly channel",
151 "Show details of rustfmt configuration options",
155 "error-on-unformatted",
156 "Error if unable to get comments or string literals within max_width, \
157 or they are left with trailing whitespaces",
163 "How to write output (not usable when piping from stdin)",
164 "[replace|overwrite|display|plain|diff|coverage|checkstyle]",
169 "Use colored output (if supported)",
170 "[always|never|auto]",
174 "dump-default-config",
175 "Dumps default configuration to PATH. PATH defaults to stdout, if omitted.",
180 "dump-minimal-config",
181 "Dumps configuration options that were checked during formatting to a file.",
187 "Recursively searches the given path for the rustfmt.toml config file. If not \
188 found reverts to the input file path",
189 "[Path for the configuration file]",
194 "Format specified line ranges. See README for more detail on the JSON format.",
201 fn execute(opts: &Options) -> FmtResult<Summary> {
202 let matches = opts.parse(env::args().skip(1))?;
204 match determine_operation(&matches)? {
206 print_usage_to_stdout(opts, "");
207 Summary::print_exit_codes();
208 Ok(Summary::default())
210 Operation::Version => {
212 Ok(Summary::default())
214 Operation::ConfigHelp => {
215 Config::print_docs();
216 Ok(Summary::default())
218 Operation::ConfigOutputDefault { path } => {
219 let toml = Config::default().all_options().to_toml()?;
220 if let Some(path) = path {
221 let mut file = File::create(path)?;
222 file.write_all(toml.as_bytes())?;
224 io::stdout().write_all(toml.as_bytes())?;
226 Ok(Summary::default())
228 Operation::Stdin { input, config_path } => {
229 // try to read config from local directory
230 let (mut config, _) =
231 match_cli_path_or_file(config_path, &env::current_dir().unwrap())?;
233 // write_mode is always Plain for Stdin.
234 config.set().write_mode(WriteMode::Plain);
237 if let Some(ref file_lines) = matches.opt_str("file-lines") {
238 config.set().file_lines(file_lines.parse()?);
239 for f in config.file_lines().files() {
241 eprintln!("Warning: Extra file listed in file_lines option '{}'", f);
246 let mut error_summary = Summary::default();
247 if config.version_meets_requirement(&mut error_summary) {
248 error_summary.add(run(Input::Text(input), &config));
258 let options = CliOptions::from_matches(&matches)?;
260 for f in options.file_lines.files() {
261 if !files.contains(&PathBuf::from(f)) {
262 eprintln!("Warning: Extra file listed in file_lines option '{}'", f);
266 let mut config = Config::default();
267 // Load the config path file if provided
268 if let Some(config_file) = config_path.as_ref() {
269 config = Config::from_toml_path(config_file.as_ref())?;
273 if let Some(path) = config_path.as_ref() {
274 println!("Using rustfmt config file {}", path.display());
278 let mut error_summary = Summary::default();
281 eprintln!("Error: file `{}` does not exist", file.to_str().unwrap());
282 error_summary.add_operational_error();
283 } else if file.is_dir() {
284 eprintln!("Error: `{}` is a directory", file.to_str().unwrap());
285 error_summary.add_operational_error();
287 // Check the file directory if the config-path could not be read or not provided
288 if config_path.is_none() {
289 let (config_tmp, path_tmp) =
290 Config::from_resolved_toml_path(file.parent().unwrap())?;
292 if let Some(path) = path_tmp.as_ref() {
294 "Using rustfmt config file {} for {}",
303 if !config.version_meets_requirement(&mut error_summary) {
307 options.clone().apply_to(&mut config);
308 error_summary.add(run(Input::File(file), &config));
312 // If we were given a path via dump-minimal-config, output any options
313 // that were used during formatting as TOML.
314 if let Some(path) = minimal_config_path {
315 let mut file = File::create(path)?;
316 let toml = config.used_options().to_toml()?;
317 file.write_all(toml.as_bytes())?;
326 let _ = env_logger::init();
328 let opts = make_opts();
330 let exit_code = match execute(&opts) {
332 if summary.has_operational_errors() {
334 } else if summary.has_parsing_errors() {
336 } else if summary.has_formatting_errors() {
338 } else if summary.has_diff {
339 // should only happen in diff mode
342 assert!(summary.has_no_errors());
347 print_usage_to_stderr(&opts, &e.to_string());
351 // Make sure standard output is flushed before we exit.
352 std::io::stdout().flush().unwrap();
354 // Exit with given exit code.
356 // NOTE: This immediately terminates the process without doing any cleanup,
357 // so make sure to finish all necessary cleanup before this is called.
358 std::process::exit(exit_code);
361 macro_rules! print_usage {
362 ($print:ident, $opts:ident, $reason:expr) => ({
364 "{}\n\nusage: {} [options] <file>...",
366 env::args_os().next().unwrap().to_string_lossy()
368 $print!("{}", $opts.usage(&msg));
372 fn print_usage_to_stdout(opts: &Options, reason: &str) {
373 print_usage!(println, opts, reason);
376 fn print_usage_to_stderr(opts: &Options, reason: &str) {
377 print_usage!(eprintln, opts, reason);
383 env!("CARGO_PKG_VERSION"),
384 include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
388 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
389 if matches.opt_present("h") {
390 return Ok(Operation::Help);
393 if matches.opt_present("config-help") {
394 return Ok(Operation::ConfigHelp);
397 if matches.opt_present("dump-default-config") {
398 // NOTE for some reason when configured with HasArg::Maybe + Occur::Optional opt_default
399 // doesn't recognize `--foo bar` as a long flag with an argument but as a long flag with no
400 // argument *plus* a free argument. Thus we check for that case in this branch -- this is
401 // required for backward compatibility.
402 if let Some(path) = matches.free.get(0) {
403 return Ok(Operation::ConfigOutputDefault {
404 path: Some(path.clone()),
407 return Ok(Operation::ConfigOutputDefault {
408 path: matches.opt_str("dump-default-config"),
413 if matches.opt_present("version") {
414 return Ok(Operation::Version);
417 let config_path_not_found = |path: &str| -> FmtResult<Operation> {
418 Err(FmtError::from(format!(
419 "Error: unable to find a config file for the given path: `{}`",
424 // Read the config_path and convert to parent dir if a file is provided.
425 // If a config file cannot be found from the given path, return error.
426 let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
427 Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
428 Some(ref path) if path.is_dir() => {
429 let config_file_path = get_toml_path(path)?;
430 if config_file_path.is_some() {
433 return config_path_not_found(path.to_str().unwrap());
439 // If no path is given, we won't output a minimal config.
440 let minimal_config_path = matches.opt_str("dump-minimal-config");
442 // if no file argument is supplied, read from stdin
443 if matches.free.is_empty() {
444 let mut buffer = String::new();
445 io::stdin().read_to_string(&mut buffer)?;
447 return Ok(Operation::Stdin {
449 config_path: config_path,
453 let files: Vec<_> = matches
457 let p = PathBuf::from(s);
458 // we will do comparison later, so here tries to canonicalize first
459 // to get the expected behavior.
460 p.canonicalize().unwrap_or(p)
464 Ok(Operation::Format {
466 config_path: config_path,
467 minimal_config_path: minimal_config_path,