Skip to main content

rustfmt/
main.rs

1#![feature(rustc_private)]
2
3use anyhow::{Result, format_err};
4
5use io::Error as IoError;
6use thiserror::Error;
7
8use rustfmt_nightly as rustfmt;
9
10use std::collections::HashMap;
11use std::env;
12use std::fs::File;
13use std::io::{self, Read, Write, stdout};
14use std::path::{Path, PathBuf};
15use std::str::FromStr;
16
17use getopts::{Matches, Options};
18
19use crate::rustfmt::{
20    CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName,
21    FormatReportFormatterBuilder, Input, Session, StyleEdition, Verbosity, Version, load_config,
22};
23
24const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rustfmt/issues/new?labels=bug";
25
26// N.B. these crates are loaded from the sysroot, so they need extern crate.
27extern crate rustc_driver;
28extern crate rustc_session;
29
30use rustc_session::EarlyDiagCtxt;
31use rustc_session::output::ErrorOutputType;
32
33fn main() {
34    rustc_driver::install_ice_hook(BUG_REPORT_URL, |_| ());
35
36    setup_tracing();
37
38    let opts = make_opts();
39
40    let exit_code = match execute(&opts) {
41        Ok(code) => code,
42        Err(e) => {
43            eprintln!("{e:#}");
44            1
45        }
46    };
47    // Make sure standard output is flushed before we exit.
48    std::io::stdout().flush().unwrap();
49
50    // Exit with given exit code.
51    //
52    // NOTE: this immediately terminates the process without doing any cleanup,
53    // so make sure to finish all necessary cleanup before this is called.
54    std::process::exit(exit_code);
55}
56
57fn setup_tracing() {
58    use tracing_subscriber::EnvFilter;
59    use tracing_subscriber::layer::SubscriberExt;
60    use tracing_subscriber::util::SubscriberInitExt;
61    use tracing_tree::HierarchicalLayer;
62
63    let layer = HierarchicalLayer::default()
64        .with_writer(std::io::stderr)
65        .with_targets(true)
66        .with_bracketed_fields(true)
67        .with_indent_amount(2);
68
69    tracing_subscriber::registry()
70        .with(EnvFilter::from_env("RUSTFMT_LOG"))
71        .with(layer)
72        .init();
73}
74
75/// Rustfmt operations.
76enum Operation {
77    /// Format files and their child modules.
78    Format {
79        files: Vec<PathBuf>,
80        minimal_config_path: Option<String>,
81    },
82    /// Print the help message.
83    Help(HelpOp),
84    /// Print version information
85    Version,
86    /// Output default config to a file, or stdout if None
87    ConfigOutputDefault { path: Option<String> },
88    /// Output current config (as if formatting to a file) to stdout
89    ConfigOutputCurrent { path: Option<String> },
90    /// No file specified, read from stdin
91    Stdin { input: String },
92}
93
94/// Rustfmt operations errors.
95#[derive(Error, Debug)]
96pub enum OperationError {
97    /// An unknown help topic was requested.
98    #[error("Unknown help topic: `{0}`.")]
99    UnknownHelpTopic(String),
100    /// An io error during reading or writing.
101    #[error("{0}")]
102    IoError(IoError),
103    /// Attempt to use --emit with a mode which is not currently
104    /// supported with standard input.
105    #[error("Emit mode {0} not supported with standard output.")]
106    StdinBadEmit(EmitMode),
107    #[error(transparent)]
108    PrintConfig(PrintConfigError),
109}
110
111// Errors related to the '--print-config' option.
112#[derive(Error, Debug)]
113pub enum PrintConfigError {
114    /// An unknown print-config option was requested.
115    #[error("Unknown print-config option: `{0}`.")]
116    UnknownOption(String),
117    #[error("The `--print-config=minimal` option requires an output path to write to")]
118    MinimalPathNoPath,
119    /// Attempt to generate a minimal config from standard input.
120    #[error("The `--print-config=minimal` option doesn't work with standard input.")]
121    MinimalPathWithStdin,
122}
123
124impl From<IoError> for OperationError {
125    fn from(e: IoError) -> OperationError {
126        OperationError::IoError(e)
127    }
128}
129
130/// Arguments to `--help`
131enum HelpOp {
132    None,
133    Config,
134    FileLines,
135}
136
137fn make_opts() -> Options {
138    let mut opts = Options::new();
139
140    opts.optflag(
141        "",
142        "check",
143        "Run in 'check' mode. Exits with 0 if input is formatted correctly. Exits \
144         with 1 and prints a diff if formatting is required.",
145    );
146    let is_nightly = is_nightly();
147    let emit_opts = if is_nightly {
148        "[files|stdout|coverage|checkstyle|json]"
149    } else {
150        "[files|stdout]"
151    };
152    opts.optopt("", "emit", "What data to emit and how", emit_opts);
153    opts.optflag("", "backup", "Backup any modified files.");
154    opts.optopt(
155        "",
156        "config-path",
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]",
160    );
161    opts.optopt(
162        "",
163        "edition",
164        "Rust edition to use",
165        "[2015|2018|2021|2024]",
166    );
167    opts.optopt(
168        "",
169        "color",
170        "Use colored output (if supported)",
171        "[always|never|auto]",
172    );
173    opts.optopt(
174        "",
175        "print-config",
176        "Dumps a default or minimal config to PATH. A minimal config is the \
177         subset of the current config file used for formatting the current program. \
178         `current` writes to stdout current config as if formatting the file at PATH.",
179        "[default|minimal|current] PATH",
180    );
181    opts.optflag(
182        "l",
183        "files-with-diff",
184        "Prints the names of mismatched files that were formatted. Prints the names of \
185         files that would be formatted when used with `--check` mode. ",
186    );
187    opts.optmulti(
188        "",
189        "config",
190        "Set options from command line. These settings take priority over .rustfmt.toml",
191        "[key1=val1,key2=val2...]",
192    );
193    opts.optopt(
194        "",
195        "style-edition",
196        "The edition of the Style Guide.",
197        "[2015|2018|2021|2024]",
198    );
199
200    if is_nightly {
201        opts.optflag(
202            "",
203            "unstable-features",
204            "Enables unstable features. Only available on nightly channel.",
205        );
206        opts.optopt(
207            "",
208            "file-lines",
209            "Format specified line ranges. Run with `--help=file-lines` for \
210             more detail (unstable).",
211            "JSON",
212        );
213        opts.optflag(
214            "",
215            "error-on-unformatted",
216            "Error if unable to get comments or string literals within max_width, \
217             or they are left with trailing whitespaces (unstable).",
218        );
219        opts.optflag(
220            "",
221            "skip-children",
222            "Don't reformat child modules (unstable).",
223        );
224    }
225
226    opts.optflag("v", "verbose", "Print verbose output");
227    opts.optflag("q", "quiet", "Print less output");
228    opts.optflag("V", "version", "Show version information");
229    let help_topics = if is_nightly {
230        "`config` or `file-lines`"
231    } else {
232        "`config`"
233    };
234    let mut help_topic_msg = "Show this message or help about a specific topic: ".to_owned();
235    help_topic_msg.push_str(help_topics);
236
237    opts.optflagopt("h", "help", &help_topic_msg, "=TOPIC");
238
239    opts
240}
241
242fn is_nightly() -> bool {
243    option_env!("CFG_RELEASE_CHANNEL").map_or(true, |c| c == "nightly" || c == "dev")
244}
245
246// Returned i32 is an exit code
247fn execute(opts: &Options) -> Result<i32> {
248    let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
249    let cmdline_args = env::args().skip(1).collect::<Vec<String>>();
250    // if we saw a `@path` arg, read arguments from that file and merge them with the other
251    // arguments.
252    let args = rustc_driver::args::arg_expand_all(&early_dcx, &cmdline_args);
253
254    let matches = opts.parse(&args)?;
255    let options = GetOptsOptions::from_matches(&matches)?;
256
257    match determine_operation(&matches)? {
258        Operation::Help(HelpOp::None) => {
259            print_usage_to_stdout(opts, "");
260            Ok(0)
261        }
262        Operation::Help(HelpOp::Config) => {
263            Config::print_docs(&mut stdout(), options.unstable_features);
264            Ok(0)
265        }
266        Operation::Help(HelpOp::FileLines) => {
267            print_help_file_lines();
268            Ok(0)
269        }
270        Operation::Version => {
271            print_version();
272            Ok(0)
273        }
274        Operation::ConfigOutputDefault { path } => {
275            let toml = Config::default().all_options().to_toml()?;
276            if let Some(path) = path {
277                let mut file = File::create(path)?;
278                file.write_all(toml.as_bytes())?;
279            } else {
280                io::stdout().write_all(toml.as_bytes())?;
281            }
282            Ok(0)
283        }
284        Operation::ConfigOutputCurrent { path } => {
285            let path = match path {
286                Some(path) => path,
287                None => return Err(format_err!("PATH required for `--print-config current`")),
288            };
289
290            let file = PathBuf::from(path);
291            let file = file.canonicalize().unwrap_or(file);
292
293            let (config, _) = load_config(Some(file.parent().unwrap()), Some(options))?;
294            let toml = config.all_options().to_toml()?;
295            io::stdout().write_all(toml.as_bytes())?;
296
297            Ok(0)
298        }
299        Operation::Stdin { input } => format_string(input, options),
300        Operation::Format {
301            files,
302            minimal_config_path,
303        } => format(files, minimal_config_path, &options),
304    }
305}
306
307fn format_string(input: String, options: GetOptsOptions) -> Result<i32> {
308    // try to read config from local directory
309    let (mut config, _) = load_config(Some(Path::new(".")), Some(options.clone()))?;
310
311    if options.check {
312        config.set_cli().emit_mode(EmitMode::Diff);
313    } else {
314        match options.emit_mode {
315            // Emit modes which work with standard input
316            // None means default, which is Stdout.
317            None => {
318                config
319                    .set()
320                    .emit_mode(options.emit_mode.unwrap_or(EmitMode::Stdout));
321            }
322            Some(EmitMode::Stdout) | Some(EmitMode::Checkstyle) | Some(EmitMode::Json) => {
323                config
324                    .set_cli()
325                    .emit_mode(options.emit_mode.unwrap_or(EmitMode::Stdout));
326            }
327            Some(emit_mode) => {
328                return Err(OperationError::StdinBadEmit(emit_mode).into());
329            }
330        }
331    }
332    config.set().verbose(Verbosity::Quiet);
333
334    // parse file_lines
335    if options.file_lines.is_all() {
336        config.set().file_lines(options.file_lines);
337    } else {
338        config.set_cli().file_lines(options.file_lines);
339    }
340
341    for f in config.file_lines().files() {
342        match *f {
343            FileName::Stdin => {}
344            _ => eprintln!("Warning: Extra file listed in file_lines option '{f}'"),
345        }
346    }
347
348    let out = &mut stdout();
349    let mut session = Session::new(config, Some(out));
350    format_and_emit_report(&mut session, Input::Text(input));
351
352    let exit_code = if session.has_operational_errors() || session.has_parsing_errors() {
353        1
354    } else {
355        0
356    };
357    Ok(exit_code)
358}
359
360fn format(
361    files: Vec<PathBuf>,
362    minimal_config_path: Option<String>,
363    options: &GetOptsOptions,
364) -> Result<i32> {
365    options.verify_file_lines(&files);
366    let (config, config_path) = load_config(None, Some(options.clone()))?;
367
368    if config.verbose() == Verbosity::Verbose {
369        if let Some(path) = config_path.as_ref() {
370            println!("Using rustfmt config file {}", path.display());
371        }
372    }
373
374    let out = &mut stdout();
375    let mut session = Session::new(config, Some(out));
376
377    for file in files {
378        if !file.exists() {
379            eprintln!("Error: file `{}` does not exist", file.display());
380            session.add_operational_error();
381        } else if file.is_dir() {
382            eprintln!("Error: `{}` is a directory", file.display());
383            session.add_operational_error();
384        } else {
385            // Check the file directory if the config-path could not be read or not provided
386            if config_path.is_none() {
387                let (local_config, config_path) =
388                    load_config(Some(file.parent().unwrap()), Some(options.clone()))?;
389                if local_config.verbose() == Verbosity::Verbose {
390                    if let Some(path) = config_path {
391                        println!(
392                            "Using rustfmt config file {} for {}",
393                            path.display(),
394                            file.display()
395                        );
396                    }
397                }
398
399                session.override_config(local_config, |sess| {
400                    format_and_emit_report(sess, Input::File(file))
401                });
402            } else {
403                format_and_emit_report(&mut session, Input::File(file));
404            }
405        }
406    }
407
408    // If we were given a path via dump-minimal-config, output any options
409    // that were used during formatting as TOML.
410    if let Some(path) = minimal_config_path {
411        let mut file = File::create(path)?;
412        let toml = session.config.used_options().to_toml()?;
413        file.write_all(toml.as_bytes())?;
414    }
415
416    let exit_code = if session.has_operational_errors()
417        || session.has_parsing_errors()
418        || ((session.has_diff() || session.has_check_errors()) && options.check)
419    {
420        1
421    } else {
422        0
423    };
424    Ok(exit_code)
425}
426
427fn format_and_emit_report<T: Write>(session: &mut Session<'_, T>, input: Input) {
428    match session.format(input) {
429        Ok(report) => {
430            if report.has_warnings() {
431                eprintln!(
432                    "{}",
433                    FormatReportFormatterBuilder::new(&report)
434                        .enable_colors(should_print_with_colors(session))
435                        .build()
436                );
437            }
438        }
439        Err(msg) => {
440            eprintln!("Error writing files: {msg}");
441            session.add_operational_error();
442        }
443    }
444}
445
446fn should_print_with_colors<T: Write>(session: &mut Session<'_, T>) -> bool {
447    term::stderr().is_some_and(|t| {
448        session.config.color().use_colored_tty()
449            && t.supports_color()
450            && t.supports_attr(term::Attr::Bold)
451    })
452}
453
454fn print_usage_to_stdout(opts: &Options, reason: &str) {
455    let sep = if reason.is_empty() {
456        String::new()
457    } else {
458        format!("{reason}\n\n")
459    };
460    let msg = format!("{sep}Format Rust code\n\nusage: rustfmt [options] <file>...");
461    print!("{}", opts.usage(&msg));
462    println!(
463        "    @path               Read newline separated options from the file at `path`. \
464        Can be specified more than once."
465    );
466}
467
468fn print_help_file_lines() {
469    println!(
470        "If you want to restrict reformatting to specific sets of lines, you can
471use the `--file-lines` option. Its argument is a JSON array of objects
472with `file` and `range` properties, where `file` is a file name, and
473`range` is an array representing a range of lines like `[7,13]`. Ranges
474are 1-based and inclusive of both end points. Specifying an empty array
475will result in no files being formatted. For example,
476
477```
478rustfmt src/lib.rs src/foo.rs --file-lines '[
479    {{\"file\":\"src/lib.rs\",\"range\":[7,13]}},
480    {{\"file\":\"src/lib.rs\",\"range\":[21,29]}},
481    {{\"file\":\"src/foo.rs\",\"range\":[10,11]}},
482    {{\"file\":\"src/foo.rs\",\"range\":[15,15]}}]'
483```
484
485would format lines `7-13` and `21-29` of `src/lib.rs`, and lines `10-11`,
486and `15` of `src/foo.rs`. No other files would be formatted, even if they
487are included as out of line modules from `src/lib.rs`."
488    );
489}
490
491fn print_version() {
492    let version_number = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown");
493    let commit_info = include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"));
494
495    if commit_info.is_empty() {
496        println!("rustfmt {version_number}");
497    } else {
498        println!("rustfmt {version_number}-{commit_info}");
499    }
500}
501
502fn determine_operation(matches: &Matches) -> Result<Operation, OperationError> {
503    if matches.opt_present("h") {
504        let Some(topic) = matches.opt_str("h") else {
505            return Ok(Operation::Help(HelpOp::None));
506        };
507
508        return match topic.as_str() {
509            "config" => Ok(Operation::Help(HelpOp::Config)),
510            "file-lines" if is_nightly() => Ok(Operation::Help(HelpOp::FileLines)),
511            _ => Err(OperationError::UnknownHelpTopic(topic)),
512        };
513    }
514    let mut free_matches = matches.free.iter();
515
516    let minimal_config_path = match matches.opt_str("print-config") {
517        None => None,
518        Some(kind) => {
519            let path = free_matches.next().cloned();
520            match kind.as_str() {
521                "default" => return Ok(Operation::ConfigOutputDefault { path }),
522                "current" => return Ok(Operation::ConfigOutputCurrent { path }),
523                "minimal" => Some(path.ok_or(OperationError::PrintConfig(
524                    PrintConfigError::MinimalPathNoPath,
525                ))?),
526                _ => {
527                    return Err(OperationError::PrintConfig(
528                        PrintConfigError::UnknownOption(kind),
529                    ));
530                }
531            }
532        }
533    };
534
535    if matches.opt_present("version") {
536        return Ok(Operation::Version);
537    }
538
539    let files: Vec<_> = free_matches
540        .map(|s| {
541            let p = PathBuf::from(s);
542            // we will do comparison later, so here tries to canonicalize first
543            // to get the expected behavior.
544            p.canonicalize().unwrap_or(p)
545        })
546        .collect();
547
548    // if no file argument is supplied, read from stdin
549    if files.is_empty() {
550        if minimal_config_path.is_some() {
551            return Err(OperationError::PrintConfig(
552                PrintConfigError::MinimalPathWithStdin,
553            ));
554        }
555        let mut buffer = String::new();
556        io::stdin().read_to_string(&mut buffer)?;
557
558        return Ok(Operation::Stdin { input: buffer });
559    }
560
561    Ok(Operation::Format {
562        files,
563        minimal_config_path,
564    })
565}
566
567const STABLE_EMIT_MODES: [EmitMode; 3] = [EmitMode::Files, EmitMode::Stdout, EmitMode::Diff];
568
569/// Parsed command line options.
570#[derive(Clone, Debug, Default)]
571struct GetOptsOptions {
572    skip_children: Option<bool>,
573    quiet: bool,
574    verbose: bool,
575    config_path: Option<PathBuf>,
576    inline_config: HashMap<String, String>,
577    emit_mode: Option<EmitMode>,
578    backup: bool,
579    check: bool,
580    edition: Option<Edition>,
581    style_edition: Option<StyleEdition>,
582    color: Option<Color>,
583    file_lines: FileLines, // Default is all lines in all files.
584    unstable_features: bool,
585    error_on_unformatted: Option<bool>,
586    print_misformatted_file_names: bool,
587}
588
589impl GetOptsOptions {
590    pub fn from_matches(matches: &Matches) -> Result<GetOptsOptions> {
591        let mut options = GetOptsOptions::default();
592        options.verbose = matches.opt_present("verbose");
593        options.quiet = matches.opt_present("quiet");
594        if options.verbose && options.quiet {
595            return Err(format_err!("Can't use both `--verbose` and `--quiet`"));
596        }
597
598        let rust_nightly = is_nightly();
599
600        if rust_nightly {
601            options.unstable_features = matches.opt_present("unstable-features");
602
603            if options.unstable_features {
604                if matches.opt_present("skip-children") {
605                    options.skip_children = Some(true);
606                }
607                if matches.opt_present("error-on-unformatted") {
608                    options.error_on_unformatted = Some(true);
609                }
610                if let Some(ref file_lines) = matches.opt_str("file-lines") {
611                    options.file_lines = file_lines.parse()?;
612                }
613            } else {
614                let mut unstable_options = vec![];
615                if matches.opt_present("skip-children") {
616                    unstable_options.push("`--skip-children`");
617                }
618                if matches.opt_present("error-on-unformatted") {
619                    unstable_options.push("`--error-on-unformatted`");
620                }
621                if matches.opt_present("file-lines") {
622                    unstable_options.push("`--file-lines`");
623                }
624                if !unstable_options.is_empty() {
625                    let s = if unstable_options.len() == 1 { "" } else { "s" };
626                    return Err(format_err!(
627                        "Unstable option{} ({}) used without `--unstable-features`",
628                        s,
629                        unstable_options.join(", "),
630                    ));
631                }
632            }
633        }
634
635        options.config_path = matches.opt_str("config-path").map(PathBuf::from);
636
637        options.inline_config = matches
638            .opt_strs("config")
639            .iter()
640            .flat_map(|config| config.split(','))
641            .map(
642                |key_val| match key_val.char_indices().find(|(_, ch)| *ch == '=') {
643                    Some((middle, _)) => {
644                        let (key, val) = (&key_val[..middle], &key_val[middle + 1..]);
645                        if !Config::is_valid_key_val(key, val) {
646                            Err(format_err!("invalid key=val pair: `{}`", key_val))
647                        } else {
648                            Ok((key.to_string(), val.to_string()))
649                        }
650                    }
651
652                    None => Err(format_err!(
653                        "--config expects comma-separated list of key=val pairs, found `{}`",
654                        key_val
655                    )),
656                },
657            )
658            .collect::<Result<HashMap<_, _>, _>>()?;
659
660        options.check = matches.opt_present("check");
661        if let Some(ref emit_str) = matches.opt_str("emit") {
662            if options.check {
663                return Err(format_err!("Invalid to use `--emit` and `--check`"));
664            }
665
666            options.emit_mode = Some(emit_mode_from_emit_str(emit_str)?);
667        }
668
669        if options.inline_config.contains_key("emit_mode") {
670            if options.check {
671                return Err(format_err!(
672                    "Invalid to use `--config=emit_mode=<mode>` and `--check`"
673                ));
674            }
675            if options.emit_mode.is_some() {
676                return Err(format_err!(
677                    "Invalid to use `--config=emit_mode=<mode>` and `--emit`"
678                ));
679            }
680        }
681
682        if let Some(ref edition_str) = matches.opt_str("edition") {
683            options.edition = Some(edition_from_edition_str(edition_str)?);
684        }
685
686        if let Some(ref edition_str) = matches.opt_str("style-edition") {
687            options.style_edition = Some(style_edition_from_style_edition_str(edition_str)?);
688        }
689
690        if matches.opt_present("backup") {
691            options.backup = true;
692        }
693
694        if matches.opt_present("files-with-diff") {
695            options.print_misformatted_file_names = true;
696        }
697
698        if !rust_nightly {
699            if let Some(ref emit_mode) = options.emit_mode {
700                if !STABLE_EMIT_MODES.contains(emit_mode) {
701                    return Err(format_err!(
702                        "Invalid value for `--emit` - using an unstable \
703                         value without `--unstable-features`",
704                    ));
705                }
706            }
707        }
708
709        if let Some(ref color) = matches.opt_str("color") {
710            match Color::from_str(color) {
711                Ok(color) => options.color = Some(color),
712                _ => return Err(format_err!("Invalid color: {}", color)),
713            }
714        }
715
716        if let Some(ref edition_str) = matches.opt_str("style-edition") {
717            options.style_edition = Some(style_edition_from_style_edition_str(edition_str)?);
718        }
719
720        Ok(options)
721    }
722
723    fn verify_file_lines(&self, files: &[PathBuf]) {
724        for f in self.file_lines.files() {
725            match *f {
726                FileName::Real(ref f) if files.contains(f) => {}
727                FileName::Real(_) => {
728                    eprintln!("Warning: Extra file listed in file_lines option '{f}'")
729                }
730                FileName::Stdin => eprintln!("Warning: Not a file '{f}'"),
731            }
732        }
733    }
734}
735
736impl CliOptions for GetOptsOptions {
737    fn apply_to(self, config: &mut Config) {
738        if self.verbose {
739            config.set_cli().verbose(Verbosity::Verbose);
740        } else if self.quiet {
741            config.set_cli().verbose(Verbosity::Quiet);
742        } else {
743            config.set().verbose(Verbosity::Normal);
744        }
745
746        if self.file_lines.is_all() {
747            config.set().file_lines(self.file_lines);
748        } else {
749            config.set_cli().file_lines(self.file_lines);
750        }
751
752        if self.unstable_features {
753            config.set_cli().unstable_features(self.unstable_features);
754        } else {
755            config.set().unstable_features(self.unstable_features);
756        }
757        if let Some(skip_children) = self.skip_children {
758            config.set_cli().skip_children(skip_children);
759        }
760        if let Some(error_on_unformatted) = self.error_on_unformatted {
761            config.set_cli().error_on_unformatted(error_on_unformatted);
762        }
763        if let Some(edition) = self.edition {
764            config.set_cli().edition(edition);
765        }
766        if let Some(edition) = self.style_edition {
767            config.set_cli().style_edition(edition);
768        }
769        if self.check {
770            config.set_cli().emit_mode(EmitMode::Diff);
771        } else if let Some(emit_mode) = self.emit_mode {
772            config.set_cli().emit_mode(emit_mode);
773        }
774        if self.backup {
775            config.set_cli().make_backup(true);
776        }
777        if let Some(color) = self.color {
778            config.set_cli().color(color);
779        }
780        if self.print_misformatted_file_names {
781            config.set_cli().print_misformatted_file_names(true);
782        }
783
784        for (key, val) in self.inline_config {
785            config.override_value(&key, &val);
786        }
787    }
788
789    fn config_path(&self) -> Option<&Path> {
790        self.config_path.as_deref()
791    }
792
793    fn edition(&self) -> Option<Edition> {
794        self.inline_config
795            .get("edition")
796            .map_or(self.edition, |e| Edition::from_str(e).ok())
797    }
798
799    fn style_edition(&self) -> Option<StyleEdition> {
800        self.inline_config
801            .get("style_edition")
802            .map_or(self.style_edition, |se| StyleEdition::from_str(se).ok())
803    }
804
805    fn version(&self) -> Option<Version> {
806        self.inline_config
807            .get("version")
808            .map(|version| Version::from_str(version).ok())
809            .flatten()
810    }
811}
812
813fn edition_from_edition_str(edition_str: &str) -> Result<Edition> {
814    match edition_str {
815        "2015" => Ok(Edition::Edition2015),
816        "2018" => Ok(Edition::Edition2018),
817        "2021" => Ok(Edition::Edition2021),
818        "2024" => Ok(Edition::Edition2024),
819        _ => Err(format_err!("Invalid value for `--edition`")),
820    }
821}
822
823fn style_edition_from_style_edition_str(edition_str: &str) -> Result<StyleEdition> {
824    match edition_str {
825        "2015" => Ok(StyleEdition::Edition2015),
826        "2018" => Ok(StyleEdition::Edition2018),
827        "2021" => Ok(StyleEdition::Edition2021),
828        "2024" => Ok(StyleEdition::Edition2024),
829        "2027" => Ok(StyleEdition::Edition2027),
830        _ => Err(format_err!("Invalid value for `--style-edition`")),
831    }
832}
833
834fn emit_mode_from_emit_str(emit_str: &str) -> Result<EmitMode> {
835    match emit_str {
836        "files" => Ok(EmitMode::Files),
837        "stdout" => Ok(EmitMode::Stdout),
838        "coverage" => Ok(EmitMode::Coverage),
839        "checkstyle" => Ok(EmitMode::Checkstyle),
840        "json" => Ok(EmitMode::Json),
841        _ => Err(format_err!("Invalid value for `--emit`")),
842    }
843}
844
845#[cfg(test)]
846#[allow(dead_code)]
847mod test {
848    use super::*;
849    use rustfmt_config_proc_macro::nightly_only_test;
850
851    fn get_config<O: CliOptions>(path: Option<&Path>, options: Option<O>) -> Config {
852        load_config(path, options).unwrap().0
853    }
854
855    #[nightly_only_test]
856    #[test]
857    fn flag_sets_style_edition_override_correctly() {
858        let mut options = GetOptsOptions::default();
859        options.style_edition = Some(StyleEdition::Edition2024);
860        let config = get_config(None, Some(options));
861        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
862    }
863
864    #[nightly_only_test]
865    #[test]
866    fn edition_sets_style_edition_override_correctly() {
867        let mut options = GetOptsOptions::default();
868        options.edition = Some(Edition::Edition2024);
869        let config = get_config(None, Some(options));
870        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
871    }
872
873    #[nightly_only_test]
874    #[test]
875    fn version_sets_style_edition_override_correctly() {
876        let mut options = GetOptsOptions::default();
877        options.inline_config = HashMap::from([("version".to_owned(), "Two".to_owned())]);
878        let config = get_config(None, Some(options));
879        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
880    }
881
882    #[test]
883    fn emit_mode_from_inline_config_is_rejected() {
884        // Regression for #6999.
885        let emit_modes = [
886            "Files",
887            "Stdout",
888            "Coverage",
889            "Checkstyle",
890            "Json",
891            "ModifiedLines",
892            "Diff",
893        ];
894        for mode in emit_modes {
895            let config = format!("emit_mode={mode}");
896
897            let matches = make_opts().parse(["--check", "--config", &config]).unwrap();
898            assert!(
899                GetOptsOptions::from_matches(&matches).is_err(),
900                "`--check` with `--config={config}` should be rejected"
901            );
902
903            let matches = make_opts()
904                .parse(["--emit", "stdout", "--config", &config])
905                .unwrap();
906            assert!(
907                GetOptsOptions::from_matches(&matches).is_err(),
908                "`--emit` with `--config={config}` should be rejected"
909            );
910        }
911    }
912
913    #[nightly_only_test]
914    #[test]
915    fn version_config_file_sets_style_edition_override_correctly() {
916        let options = GetOptsOptions::default();
917        let config_file = Some(Path::new("tests/config/style-edition/just-version"));
918        let config = get_config(config_file, Some(options));
919        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
920    }
921
922    #[nightly_only_test]
923    #[test]
924    fn style_edition_flag_has_correct_precedence_over_edition() {
925        let mut options = GetOptsOptions::default();
926        options.style_edition = Some(StyleEdition::Edition2021);
927        options.edition = Some(Edition::Edition2024);
928        let config = get_config(None, Some(options));
929        assert_eq!(config.style_edition(), StyleEdition::Edition2021);
930    }
931
932    #[nightly_only_test]
933    #[test]
934    fn style_edition_flag_has_correct_precedence_over_version() {
935        let mut options = GetOptsOptions::default();
936        options.style_edition = Some(StyleEdition::Edition2018);
937        options.inline_config = HashMap::from([("version".to_owned(), "Two".to_owned())]);
938        let config = get_config(None, Some(options));
939        assert_eq!(config.style_edition(), StyleEdition::Edition2018);
940    }
941
942    #[nightly_only_test]
943    #[test]
944    fn style_edition_flag_has_correct_precedence_over_edition_version() {
945        let mut options = GetOptsOptions::default();
946        options.style_edition = Some(StyleEdition::Edition2021);
947        options.edition = Some(Edition::Edition2018);
948        options.inline_config = HashMap::from([("version".to_owned(), "Two".to_owned())]);
949        let config = get_config(None, Some(options));
950        assert_eq!(config.style_edition(), StyleEdition::Edition2021);
951    }
952
953    #[nightly_only_test]
954    #[test]
955    fn style_edition_inline_has_correct_precedence_over_edition_version() {
956        let mut options = GetOptsOptions::default();
957        options.edition = Some(Edition::Edition2018);
958        options.inline_config = HashMap::from([
959            ("version".to_owned(), "One".to_owned()),
960            ("style_edition".to_owned(), "2024".to_owned()),
961        ]);
962        let config = get_config(None, Some(options));
963        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
964    }
965
966    #[nightly_only_test]
967    #[test]
968    fn style_edition_config_file_trumps_edition_flag_version_inline() {
969        let mut options = GetOptsOptions::default();
970        let config_file = Some(Path::new("tests/config/style-edition/just-style-edition"));
971        options.edition = Some(Edition::Edition2018);
972        options.inline_config = HashMap::from([("version".to_owned(), "One".to_owned())]);
973        let config = get_config(config_file, Some(options));
974        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
975    }
976
977    #[nightly_only_test]
978    #[test]
979    fn style_edition_config_file_trumps_edition_config_and_version_inline() {
980        let mut options = GetOptsOptions::default();
981        let config_file = Some(Path::new(
982            "tests/config/style-edition/style-edition-and-edition",
983        ));
984        options.inline_config = HashMap::from([("version".to_owned(), "Two".to_owned())]);
985        let config = get_config(config_file, Some(options));
986        assert_eq!(config.style_edition(), StyleEdition::Edition2021);
987        assert_eq!(config.edition(), Edition::Edition2024);
988    }
989
990    #[nightly_only_test]
991    #[test]
992    fn version_config_trumps_edition_config_and_flag() {
993        let mut options = GetOptsOptions::default();
994        let config_file = Some(Path::new("tests/config/style-edition/version-edition"));
995        options.edition = Some(Edition::Edition2018);
996        let config = get_config(config_file, Some(options));
997        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
998    }
999
1000    #[nightly_only_test]
1001    #[test]
1002    fn style_edition_config_file_trumps_version_config() {
1003        let options = GetOptsOptions::default();
1004        let config_file = Some(Path::new(
1005            "tests/config/style-edition/version-style-edition",
1006        ));
1007        let config = get_config(config_file, Some(options));
1008        assert_eq!(config.style_edition(), StyleEdition::Edition2021);
1009    }
1010
1011    #[nightly_only_test]
1012    #[test]
1013    fn style_edition_config_file_trumps_edition_version_config() {
1014        let options = GetOptsOptions::default();
1015        let config_file = Some(Path::new(
1016            "tests/config/style-edition/version-style-edition-and-edition",
1017        ));
1018        let config = get_config(config_file, Some(options));
1019        assert_eq!(config.style_edition(), StyleEdition::Edition2021);
1020    }
1021
1022    #[nightly_only_test]
1023    #[test]
1024    fn correct_defaults_for_style_edition_loaded() {
1025        let mut options = GetOptsOptions::default();
1026        options.style_edition = Some(StyleEdition::Edition2024);
1027        let config = get_config(None, Some(options));
1028        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
1029    }
1030
1031    #[nightly_only_test]
1032    #[test]
1033    fn style_edition_defaults_overridden_from_config() {
1034        let options = GetOptsOptions::default();
1035        let config_file = Some(Path::new("tests/config/style-edition/overrides"));
1036        let config = get_config(config_file, Some(options));
1037        assert_eq!(config.style_edition(), StyleEdition::Edition2024);
1038        // FIXME: this test doesn't really exercise anything, since
1039        // `overflow_delimited_expr` is disabled by default in edition 2024.
1040        assert_eq!(config.overflow_delimited_expr(), false);
1041    }
1042
1043    #[nightly_only_test]
1044    #[test]
1045    fn style_edition_defaults_overridden_from_cli() {
1046        let mut options = GetOptsOptions::default();
1047        let config_file = Some(Path::new("tests/config/style-edition/just-style-edition"));
1048        options.inline_config =
1049            HashMap::from([("overflow_delimited_expr".to_owned(), "true".to_owned())]);
1050        let config = get_config(config_file, Some(options));
1051        // FIXME: this test doesn't really exercise anything, since
1052        // `overflow_delimited_expr` is disabled by default in edition 2024.
1053        assert_eq!(config.overflow_delimited_expr(), true);
1054    }
1055}