1 use anyhow::{format_err, Result};
3 use io::Error as IoError;
6 use rustfmt_nightly as rustfmt;
8 use std::collections::HashMap;
11 use std::io::{self, stdout, Read, Write};
12 use std::path::{Path, PathBuf};
13 use std::str::FromStr;
15 use getopts::{Matches, Options};
18 load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName,
19 FormatReportFormatterBuilder, Input, Session, Verbosity,
24 let opts = make_opts();
26 let exit_code = match execute(&opts) {
29 eprintln!("{}", e.to_string());
33 // Make sure standard output is flushed before we exit.
34 std::io::stdout().flush().unwrap();
36 // Exit with given exit code.
38 // NOTE: this immediately terminates the process without doing any cleanup,
39 // so make sure to finish all necessary cleanup before this is called.
40 std::process::exit(exit_code);
43 /// Rustfmt operations.
45 /// Format files and their child modules.
48 minimal_config_path: Option<String>,
50 /// Print the help message.
52 /// Print version information
54 /// Output default config to a file, or stdout if None
55 ConfigOutputDefault { path: Option<String> },
56 /// Output current config (as if formatting to a file) to stdout
57 ConfigOutputCurrent { path: Option<String> },
58 /// No file specified, read from stdin
59 Stdin { input: String },
62 /// Rustfmt operations errors.
63 #[derive(Error, Debug)]
64 pub enum OperationError {
65 /// An unknown help topic was requested.
66 #[error("Unknown help topic: `{0}`.")]
67 UnknownHelpTopic(String),
68 /// An unknown print-config option was requested.
69 #[error("Unknown print-config option: `{0}`.")]
70 UnknownPrintConfigTopic(String),
71 /// Attempt to generate a minimal config from standard input.
72 #[error("The `--print-config=minimal` option doesn't work with standard input.")]
74 /// An io error during reading or writing.
77 /// Attempt to use --check with stdin, which isn't currently
79 #[error("The `--check` option is not supported with standard input.")]
81 /// Attempt to use --emit=json with stdin, which isn't currently
83 #[error("Using `--emit` other than stdout is not supported with standard input.")]
87 impl From<IoError> for OperationError {
88 fn from(e: IoError) -> OperationError {
89 OperationError::IoError(e)
93 /// Arguments to `--help`
100 fn make_opts() -> Options {
101 let mut opts = Options::new();
106 "Run in 'check' mode. Exits with 0 if input is formatted correctly. Exits \
107 with 1 and prints a diff if formatting is required.",
109 let is_nightly = is_nightly();
110 let emit_opts = if is_nightly {
111 "[files|stdout|coverage|checkstyle|json]"
115 opts.optopt("", "emit", "What data to emit and how", emit_opts);
116 opts.optflag("", "backup", "Backup any modified files.");
120 "Recursively searches the given path for the rustfmt.toml config file. If not \
121 found reverts to the input file path",
122 "[Path for the configuration file]",
124 opts.optopt("", "edition", "Rust edition to use", "[2015|2018|2021]");
128 "Use colored output (if supported)",
129 "[always|never|auto]",
134 "Dumps a default or minimal config to PATH. A minimal config is the \
135 subset of the current config file used for formatting the current program. \
136 `current` writes to stdout current config as if formatting the file at PATH.",
137 "[default|minimal|current] PATH",
142 "Prints the names of mismatched files that were formatted. Prints the names of \
143 files that would be formated when used with `--check` mode. ",
148 "Set options from command line. These settings take priority over .rustfmt.toml",
149 "[key1=val1,key2=val2...]",
156 "Enables unstable features. Only available on nightly channel.",
161 "Format specified line ranges. Run with `--help=file-lines` for \
162 more detail (unstable).",
167 "error-on-unformatted",
168 "Error if unable to get comments or string literals within max_width, \
169 or they are left with trailing whitespaces (unstable).",
174 "Don't reformat child modules (unstable).",
178 opts.optflag("v", "verbose", "Print verbose output");
179 opts.optflag("q", "quiet", "Print less output");
180 opts.optflag("V", "version", "Show version information");
181 let help_topics = if is_nightly {
182 "`config` or `file-lines`"
186 let mut help_topic_msg = "Show this message or help about a specific topic: ".to_owned();
187 help_topic_msg.push_str(help_topics);
189 opts.optflagopt("h", "help", &help_topic_msg, "=TOPIC");
194 fn is_nightly() -> bool {
195 option_env!("CFG_RELEASE_CHANNEL").map_or(true, |c| c == "nightly" || c == "dev")
198 // Returned i32 is an exit code
199 fn execute(opts: &Options) -> Result<i32> {
200 let matches = opts.parse(env::args().skip(1))?;
201 let options = GetOptsOptions::from_matches(&matches)?;
203 match determine_operation(&matches)? {
204 Operation::Help(HelpOp::None) => {
205 print_usage_to_stdout(opts, "");
208 Operation::Help(HelpOp::Config) => {
209 Config::print_docs(&mut stdout(), options.unstable_features);
212 Operation::Help(HelpOp::FileLines) => {
213 print_help_file_lines();
216 Operation::Version => {
220 Operation::ConfigOutputDefault { path } => {
221 let toml = Config::default().all_options().to_toml()?;
222 if let Some(path) = path {
223 let mut file = File::create(path)?;
224 file.write_all(toml.as_bytes())?;
226 io::stdout().write_all(toml.as_bytes())?;
230 Operation::ConfigOutputCurrent { path } => {
231 let path = match path {
233 None => return Err(format_err!("PATH required for `--print-config current`")),
236 let file = PathBuf::from(path);
237 let file = file.canonicalize().unwrap_or(file);
239 let (config, _) = load_config(Some(file.parent().unwrap()), Some(options))?;
240 let toml = config.all_options().to_toml()?;
241 io::stdout().write_all(toml.as_bytes())?;
245 Operation::Stdin { input } => format_string(input, options),
249 } => format(files, minimal_config_path, &options),
253 fn format_string(input: String, options: GetOptsOptions) -> Result<i32> {
254 // try to read config from local directory
255 let (mut config, _) = load_config(Some(Path::new(".")), Some(options.clone()))?;
258 return Err(OperationError::CheckWithStdin.into());
260 if let Some(emit_mode) = options.emit_mode {
261 if emit_mode != EmitMode::Stdout {
262 return Err(OperationError::EmitWithStdin.into());
265 // emit mode is always Stdout for Stdin.
266 config.set().emit_mode(EmitMode::Stdout);
267 config.set().verbose(Verbosity::Quiet);
270 config.set().file_lines(options.file_lines);
271 for f in config.file_lines().files() {
273 FileName::Stdin => {}
274 _ => eprintln!("Warning: Extra file listed in file_lines option '{}'", f),
278 let out = &mut stdout();
279 let mut session = Session::new(config, Some(out));
280 format_and_emit_report(&mut session, Input::Text(input));
282 let exit_code = if session.has_operational_errors() || session.has_parsing_errors() {
292 minimal_config_path: Option<String>,
293 options: &GetOptsOptions,
295 options.verify_file_lines(&files);
296 let (config, config_path) = load_config(None, Some(options.clone()))?;
298 if config.verbose() == Verbosity::Verbose {
299 if let Some(path) = config_path.as_ref() {
300 println!("Using rustfmt config file {}", path.display());
304 let out = &mut stdout();
305 let mut session = Session::new(config, Some(out));
309 eprintln!("Error: file `{}` does not exist", file.to_str().unwrap());
310 session.add_operational_error();
311 } else if file.is_dir() {
312 eprintln!("Error: `{}` is a directory", file.to_str().unwrap());
313 session.add_operational_error();
315 // Check the file directory if the config-path could not be read or not provided
316 if config_path.is_none() {
317 let (local_config, config_path) =
318 load_config(Some(file.parent().unwrap()), Some(options.clone()))?;
319 if local_config.verbose() == Verbosity::Verbose {
320 if let Some(path) = config_path {
322 "Using rustfmt config file {} for {}",
329 session.override_config(local_config, |sess| {
330 format_and_emit_report(sess, Input::File(file))
333 format_and_emit_report(&mut session, Input::File(file));
338 // If we were given a path via dump-minimal-config, output any options
339 // that were used during formatting as TOML.
340 if let Some(path) = minimal_config_path {
341 let mut file = File::create(path)?;
342 let toml = session.config.used_options().to_toml()?;
343 file.write_all(toml.as_bytes())?;
346 let exit_code = if session.has_operational_errors()
347 || session.has_parsing_errors()
348 || ((session.has_diff() || session.has_check_errors()) && options.check)
357 fn format_and_emit_report<T: Write>(session: &mut Session<'_, T>, input: Input) {
358 match session.format(input) {
360 if report.has_warnings() {
363 FormatReportFormatterBuilder::new(&report)
364 .enable_colors(should_print_with_colors(session))
370 eprintln!("Error writing files: {}", msg);
371 session.add_operational_error();
376 fn should_print_with_colors<T: Write>(session: &mut Session<'_, T>) -> bool {
377 match term::stderr() {
379 if session.config.color().use_colored_tty()
380 && t.supports_color()
381 && t.supports_attr(term::Attr::Bold) =>
389 fn print_usage_to_stdout(opts: &Options, reason: &str) {
390 let sep = if reason.is_empty() {
393 format!("{}\n\n", reason)
396 "{}Format Rust code\n\nusage: {} [options] <file>...",
398 env::args_os().next().unwrap().to_string_lossy()
400 println!("{}", opts.usage(&msg));
403 fn print_help_file_lines() {
405 "If you want to restrict reformatting to specific sets of lines, you can
406 use the `--file-lines` option. Its argument is a JSON array of objects
407 with `file` and `range` properties, where `file` is a file name, and
408 `range` is an array representing a range of lines like `[7,13]`. Ranges
409 are 1-based and inclusive of both end points. Specifying an empty array
410 will result in no files being formatted. For example,
413 rustfmt --file-lines '[
414 {{\"file\":\"src/lib.rs\",\"range\":[7,13]}},
415 {{\"file\":\"src/lib.rs\",\"range\":[21,29]}},
416 {{\"file\":\"src/foo.rs\",\"range\":[10,11]}},
417 {{\"file\":\"src/foo.rs\",\"range\":[15,15]}}]'
420 would format lines `7-13` and `21-29` of `src/lib.rs`, and lines `10-11`,
421 and `15` of `src/foo.rs`. No other files would be formatted, even if they
422 are included as out of line modules from `src/lib.rs`."
427 let version_info = format!(
429 option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
430 include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
433 println!("rustfmt {}", version_info);
436 fn determine_operation(matches: &Matches) -> Result<Operation, OperationError> {
437 if matches.opt_present("h") {
438 let topic = matches.opt_str("h");
440 return Ok(Operation::Help(HelpOp::None));
441 } else if topic == Some("config".to_owned()) {
442 return Ok(Operation::Help(HelpOp::Config));
443 } else if topic == Some("file-lines".to_owned()) && is_nightly() {
444 return Ok(Operation::Help(HelpOp::FileLines));
446 return Err(OperationError::UnknownHelpTopic(topic.unwrap()));
449 let mut free_matches = matches.free.iter();
451 let mut minimal_config_path = None;
452 if let Some(kind) = matches.opt_str("print-config") {
453 let path = free_matches.next().cloned();
454 match kind.as_str() {
455 "default" => return Ok(Operation::ConfigOutputDefault { path }),
456 "current" => return Ok(Operation::ConfigOutputCurrent { path }),
458 minimal_config_path = path;
459 if minimal_config_path.is_none() {
460 eprintln!("WARNING: PATH required for `--print-config minimal`.");
464 return Err(OperationError::UnknownPrintConfigTopic(kind));
469 if matches.opt_present("version") {
470 return Ok(Operation::Version);
473 let files: Vec<_> = free_matches
475 let p = PathBuf::from(s);
476 // we will do comparison later, so here tries to canonicalize first
477 // to get the expected behavior.
478 p.canonicalize().unwrap_or(p)
482 // if no file argument is supplied, read from stdin
483 if files.is_empty() {
484 if minimal_config_path.is_some() {
485 return Err(OperationError::MinimalPathWithStdin);
487 let mut buffer = String::new();
488 io::stdin().read_to_string(&mut buffer)?;
490 return Ok(Operation::Stdin { input: buffer });
493 Ok(Operation::Format {
499 const STABLE_EMIT_MODES: [EmitMode; 3] = [EmitMode::Files, EmitMode::Stdout, EmitMode::Diff];
501 /// Parsed command line options.
502 #[derive(Clone, Debug, Default)]
503 struct GetOptsOptions {
504 skip_children: Option<bool>,
507 config_path: Option<PathBuf>,
508 inline_config: HashMap<String, String>,
509 emit_mode: Option<EmitMode>,
512 edition: Option<Edition>,
513 color: Option<Color>,
514 file_lines: FileLines, // Default is all lines in all files.
515 unstable_features: bool,
516 error_on_unformatted: Option<bool>,
517 print_misformatted_file_names: bool,
520 impl GetOptsOptions {
521 pub fn from_matches(matches: &Matches) -> Result<GetOptsOptions> {
522 let mut options = GetOptsOptions::default();
523 options.verbose = matches.opt_present("verbose");
524 options.quiet = matches.opt_present("quiet");
525 if options.verbose && options.quiet {
526 return Err(format_err!("Can't use both `--verbose` and `--quiet`"));
529 let rust_nightly = is_nightly();
532 options.unstable_features = matches.opt_present("unstable-features");
534 if options.unstable_features {
535 if matches.opt_present("skip-children") {
536 options.skip_children = Some(true);
538 if matches.opt_present("error-on-unformatted") {
539 options.error_on_unformatted = Some(true);
541 if let Some(ref file_lines) = matches.opt_str("file-lines") {
542 options.file_lines = file_lines.parse()?;
545 let mut unstable_options = vec![];
546 if matches.opt_present("skip-children") {
547 unstable_options.push("`--skip-children`");
549 if matches.opt_present("error-on-unformatted") {
550 unstable_options.push("`--error-on-unformatted`");
552 if matches.opt_present("file-lines") {
553 unstable_options.push("`--file-lines`");
555 if !unstable_options.is_empty() {
556 let s = if unstable_options.len() == 1 { "" } else { "s" };
557 return Err(format_err!(
558 "Unstable option{} ({}) used without `--unstable-features`",
560 unstable_options.join(", "),
566 options.config_path = matches.opt_str("config-path").map(PathBuf::from);
568 options.inline_config = matches
571 .flat_map(|config| config.split(','))
573 |key_val| match key_val.char_indices().find(|(_, ch)| *ch == '=') {
574 Some((middle, _)) => {
575 let (key, val) = (&key_val[..middle], &key_val[middle + 1..]);
576 if !Config::is_valid_key_val(key, val) {
577 Err(format_err!("invalid key=val pair: `{}`", key_val))
579 Ok((key.to_string(), val.to_string()))
583 None => Err(format_err!(
584 "--config expects comma-separated list of key=val pairs, found `{}`",
589 .collect::<Result<HashMap<_, _>, _>>()?;
591 options.check = matches.opt_present("check");
592 if let Some(ref emit_str) = matches.opt_str("emit") {
594 return Err(format_err!("Invalid to use `--emit` and `--check`"));
597 options.emit_mode = Some(emit_mode_from_emit_str(emit_str)?);
600 if let Some(ref edition_str) = matches.opt_str("edition") {
601 options.edition = Some(edition_from_edition_str(edition_str)?);
604 if matches.opt_present("backup") {
605 options.backup = true;
608 if matches.opt_present("files-with-diff") {
609 options.print_misformatted_file_names = true;
613 if let Some(ref emit_mode) = options.emit_mode {
614 if !STABLE_EMIT_MODES.contains(emit_mode) {
615 return Err(format_err!(
616 "Invalid value for `--emit` - using an unstable \
617 value without `--unstable-features`",
623 if let Some(ref color) = matches.opt_str("color") {
624 match Color::from_str(color) {
625 Ok(color) => options.color = Some(color),
626 _ => return Err(format_err!("Invalid color: {}", color)),
633 fn verify_file_lines(&self, files: &[PathBuf]) {
634 for f in self.file_lines.files() {
636 FileName::Real(ref f) if files.contains(f) => {}
637 FileName::Real(_) => {
638 eprintln!("Warning: Extra file listed in file_lines option '{}'", f)
640 FileName::Stdin => eprintln!("Warning: Not a file '{}'", f),
646 impl CliOptions for GetOptsOptions {
647 fn apply_to(self, config: &mut Config) {
649 config.set().verbose(Verbosity::Verbose);
650 } else if self.quiet {
651 config.set().verbose(Verbosity::Quiet);
653 config.set().verbose(Verbosity::Normal);
655 config.set().file_lines(self.file_lines);
656 config.set().unstable_features(self.unstable_features);
657 if let Some(skip_children) = self.skip_children {
658 config.set().skip_children(skip_children);
660 if let Some(error_on_unformatted) = self.error_on_unformatted {
661 config.set().error_on_unformatted(error_on_unformatted);
663 if let Some(edition) = self.edition {
664 config.set().edition(edition);
667 config.set().emit_mode(EmitMode::Diff);
668 } else if let Some(emit_mode) = self.emit_mode {
669 config.set().emit_mode(emit_mode);
672 config.set().make_backup(true);
674 if let Some(color) = self.color {
675 config.set().color(color);
677 if self.print_misformatted_file_names {
678 config.set().print_misformatted_file_names(true);
681 for (key, val) in self.inline_config {
682 config.override_value(&key, &val);
686 fn config_path(&self) -> Option<&Path> {
687 self.config_path.as_deref()
691 fn edition_from_edition_str(edition_str: &str) -> Result<Edition> {
693 "2015" => Ok(Edition::Edition2015),
694 "2018" => Ok(Edition::Edition2018),
695 "2021" => Ok(Edition::Edition2021),
696 _ => Err(format_err!("Invalid value for `--edition`")),
700 fn emit_mode_from_emit_str(emit_str: &str) -> Result<EmitMode> {
702 "files" => Ok(EmitMode::Files),
703 "stdout" => Ok(EmitMode::Stdout),
704 "coverage" => Ok(EmitMode::Coverage),
705 "checkstyle" => Ok(EmitMode::Checkstyle),
706 "json" => Ok(EmitMode::Json),
707 _ => Err(format_err!("Invalid value for `--emit`")),