diff --git a/src/bin/main.rs b/src/bin/main.rs index 2dc9657a020..f01c260adff 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -91,6 +91,12 @@ fn make_opts() -> Options { let mut opts = Options::new(); // Sorted in alphabetical order. + opts.optflag( + "", + "check", + "Run in 'check' mode. Exits with 0 if input if formatted correctly. Exits \ + with 1 and prints a diff if formatting is required.", + ); opts.optopt( "", "color", @@ -308,7 +314,8 @@ fn print_usage_to_stdout(opts: &Options, reason: &str) { } fn print_help_file_lines() { - println!("If you want to restrict reformatting to specific sets of lines, you can + println!( + "If you want to restrict reformatting to specific sets of lines, you can use the `--file-lines` option. Its argument is a JSON array of objects with `file` and `range` properties, where `file` is a file name, and `range` is an array representing a range of lines like `[7,13]`. Ranges @@ -325,7 +332,8 @@ rustfmt --file-lines '[ would format lines `7-13` and `21-29` of `src/lib.rs`, and lines `10-11`, and `15` of `src/foo.rs`. No other files would be formatted, even if they -are included as out of line modules from `src/lib.rs`."); +are included as out of line modules from `src/lib.rs`." + ); } fn print_version() { diff --git a/src/config/options.rs b/src/config/options.rs index a11e1f01eaf..be3aa1f13d4 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -332,6 +332,7 @@ pub struct CliOptions { verbose: bool, pub(super) config_path: Option, write_mode: Option, + check: bool, color: Option, file_lines: FileLines, // Default is all lines in all files. unstable_features: bool, @@ -361,7 +362,11 @@ impl CliOptions { options.config_path = matches.opt_str("config-path").map(PathBuf::from); + options.check = matches.opt_present("check"); if let Some(ref write_mode) = matches.opt_str("write-mode") { + if options.check { + return Err(format_err!("Invalid to set write-mode and `--check`")); + } if let Ok(write_mode) = WriteMode::from_str(write_mode) { options.write_mode = Some(write_mode); } else { @@ -410,7 +415,9 @@ impl CliOptions { if let Some(error_on_unformatted) = self.error_on_unformatted { config.set().error_on_unformatted(error_on_unformatted); } - if let Some(write_mode) = self.write_mode { + if self.check { + config.set().write_mode(WriteMode::Check); + } else if let Some(write_mode) = self.write_mode { config.set().write_mode(write_mode); } if let Some(color) = self.color { diff --git a/src/lib.rs b/src/lib.rs index 115b21f4b11..98983da1164 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -68,8 +68,7 @@ pub use config::{file_lines, load_config, Config, Verbosity, WriteMode}; pub type FmtResult = std::result::Result; -pub const WRITE_MODE_LIST: &str = - "[replace|overwrite|display|plain|diff|coverage|checkstyle|check]"; +pub const WRITE_MODE_LIST: &str = "[replace|overwrite|display|plain|diff|coverage|checkstyle]"; #[macro_use] mod utils;