Skip to main content

bootstrap/core/config/
flags.rs

1//! Command-line interface of the bootstrap build system.
2//!
3//! This module implements the command-line parsing of the build system which
4//! has various flags to configure how it's run.
5#![expect(
6    clippy::large_unopt_stack_frames,
7    reason = "the clap::Subcommand derive on `Subcommand` triggers this lint"
8)]
9
10use std::path::{Path, PathBuf};
11
12use clap::{CommandFactory, Parser, ValueEnum};
13use clap_complete::Generator;
14#[cfg(feature = "tracing")]
15use tracing::instrument;
16
17use crate::core::backend::CodegenBackendKind;
18use crate::core::build_steps::perf::PerfArgs;
19use crate::core::build_steps::setup::Profile;
20use crate::core::build_steps::test::TestTarget;
21use crate::core::builder::{Builder, Kind};
22use crate::core::config::Config;
23use crate::core::config::target_selection::{TargetSelectionList, target_selection_list};
24use crate::core::session::Session;
25use crate::utils::helpers;
26
27#[derive(Copy, Clone, Default, Debug, ValueEnum)]
28pub enum Color {
29    Always,
30    Never,
31    #[default]
32    Auto,
33}
34
35/// Whether to deny warnings, emit them as warnings, or use the default behavior
36#[derive(Copy, Clone, Default, Debug, ValueEnum)]
37pub enum Warnings {
38    Deny,
39    Warn,
40    #[default]
41    Default,
42}
43
44/// Deserialized version of all flags for this compile.
45#[derive(Debug, Parser)]
46#[command(
47    override_usage = "x.py <subcommand> [options] [<paths>...]",
48    disable_help_subcommand(true),
49    about = "",
50    next_line_help(false)
51)]
52pub struct Flags {
53    #[command(subcommand)]
54    pub cmd: Subcommand,
55
56    #[arg(global = true, short, long, action = clap::ArgAction::Count, conflicts_with = "quiet")]
57    /// use verbose output (-vv for very verbose)
58    pub verbose: u8, // each extra -v after the first is passed to Cargo
59    #[arg(global = true, short, long, conflicts_with = "verbose")]
60    /// use quiet output
61    pub quiet: bool,
62    #[arg(global = true, short, long)]
63    /// use incremental compilation
64    pub incremental: bool,
65    #[arg(global = true, long, value_hint = clap::ValueHint::FilePath, value_name = "FILE")]
66    /// TOML configuration file for build
67    pub config: Option<PathBuf>,
68    #[arg(global = true, long, value_hint = clap::ValueHint::DirPath, value_name = "DIR")]
69    /// Build directory, overrides `build.build-dir` in `bootstrap.toml`
70    pub build_dir: Option<PathBuf>,
71
72    #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "BUILD")]
73    /// host target of the stage0 compiler
74    pub build: Option<String>,
75
76    #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "HOST", value_parser = target_selection_list)]
77    /// host targets to build
78    pub host: Option<TargetSelectionList>,
79
80    #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "TARGET", value_parser = target_selection_list)]
81    /// target targets to build
82    pub target: Option<TargetSelectionList>,
83
84    #[arg(global = true, long, value_name = "PATH")]
85    /// build paths to exclude
86    pub exclude: Vec<PathBuf>, // keeping for client backward compatibility
87    #[arg(global = true, long, value_name = "PATH")]
88    /// build paths to skip
89    pub skip: Vec<PathBuf>,
90    #[arg(global = true, long)]
91    /// include default paths in addition to the provided ones
92    pub include_default_paths: bool,
93
94    /// rustc error format
95    #[arg(global = true, value_hint = clap::ValueHint::Other, long)]
96    pub rustc_error_format: Option<String>,
97
98    #[arg(global = true, long, value_hint = clap::ValueHint::CommandString, value_name = "CMD")]
99    /// command to run on failure
100    pub on_fail: Option<String>,
101    #[arg(global = true, long)]
102    /// dry run; don't build anything
103    pub dry_run: bool,
104    /// Indicates whether to dump the work done from bootstrap shims
105    #[arg(global = true, long)]
106    pub dump_bootstrap_shims: bool,
107    #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
108    /// stage to build (indicates compiler to use/test, e.g., stage 0 uses the
109    /// bootstrap compiler, stage 1 the stage 0 rustc artifacts, etc.)
110    pub stage: Option<u32>,
111
112    #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
113    /// stage(s) to keep without recompiling
114    /// (pass multiple times to keep e.g., both stages 0 and 1)
115    pub keep_stage: Vec<u32>,
116    #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
117    /// stage(s) of the standard library to keep without recompiling
118    /// (pass multiple times to keep e.g., both stages 0 and 1)
119    pub keep_stage_std: Vec<u32>,
120    #[arg(global = true, long, value_hint = clap::ValueHint::DirPath, value_name = "DIR")]
121    /// path to the root of the rust checkout
122    pub src: Option<PathBuf>,
123
124    #[arg(
125        global = true,
126        short,
127        long,
128        value_hint = clap::ValueHint::Other,
129        value_name = "JOBS"
130    )]
131    /// number of jobs to run in parallel
132    pub jobs: Option<u32>,
133    // This overrides the deny-warnings configuration option,
134    // which passes -Dwarnings to the compiler invocations.
135    #[arg(global = true, long)]
136    #[arg(value_enum, default_value_t=Warnings::Default, value_name = "deny|warn")]
137    /// if value is deny, will deny warnings
138    /// if value is warn, will emit warnings
139    /// otherwise, use the default configured behaviour
140    pub warnings: Warnings,
141
142    #[arg(global = true, long)]
143    /// use message-format=json
144    pub json_output: bool,
145    #[arg(global = true, long)]
146    /// only build proc-macros and build scripts (for rust-analyzer)
147    pub compile_time_deps: bool,
148
149    #[arg(global = true, long, value_name = "STYLE")]
150    #[arg(value_enum, default_value_t = Color::Auto)]
151    /// whether to use color in cargo and rustc output
152    pub color: Color,
153
154    #[arg(global = true, long)]
155    /// Bootstrap uses this value to decide whether it should bypass locking the build process.
156    /// This is rarely needed (e.g., compiling the std library for different targets in parallel).
157    ///
158    /// Unless you know exactly what you are doing, you probably don't need this.
159    pub bypass_bootstrap_lock: bool,
160
161    /// generate PGO profile with rustc build
162    #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
163    // FIXME: Remove this option at the end of 2026
164    pub rust_profile_generate: Option<PathBuf>,
165    /// use PGO profile for rustc build
166    // FIXME: Remove this option at the end of 2026
167    #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
168    pub rust_profile_use: Option<PathBuf>,
169    /// use PGO profile for LLVM build
170    // FIXME: Remove this option at the end of 2026
171    #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
172    pub llvm_profile_use: Option<PathBuf>,
173    // LLVM doesn't support a custom location for generating profile
174    // information.
175    //
176    // llvm_out/build/profiles/ is the location this writes to.
177    /// generate PGO profile with llvm built for rustc
178    // FIXME: Remove this option at the end of 2026
179    #[arg(global = true, long)]
180    pub llvm_profile_generate: bool,
181    /// Enable BOLT link flags
182    #[arg(global = true, long)]
183    pub enable_bolt_settings: bool,
184    /// Skip stage0 compiler validation
185    #[arg(global = true, long)]
186    pub skip_stage0_validation: bool,
187    /// Additional reproducible artifacts that should be added to the reproducible artifacts archive.
188    #[arg(global = true, long)]
189    pub reproducible_artifact: Vec<String>,
190    #[arg(global = true)]
191    /// paths for the subcommand
192    pub paths: Vec<PathBuf>,
193    /// override options in bootstrap.toml
194    #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "section.option=value")]
195    pub set: Vec<String>,
196    /// arguments passed to subcommands
197    #[arg(global = true, last(true), value_name = "ARGS")]
198    pub free_args: Vec<String>,
199    /// Make bootstrap to behave as it's running on the CI environment or not.
200    #[arg(global = true, long, value_name = "bool")]
201    pub ci: Option<bool>,
202    /// Skip checking the standard library if `rust.download-rustc` isn't available.
203    /// This is mostly for RA as building the stage1 compiler to check the library tree
204    /// on each code change might be too much for some computers.
205    #[arg(global = true, long)]
206    pub skip_std_check_if_no_download_rustc: bool,
207}
208
209impl Flags {
210    /// Check if `<cmd> -h -v` was passed.
211    /// If yes, print the available paths and return `true`.
212    pub fn try_parse_verbose_help(args: &[String]) -> bool {
213        // We need to check for `<cmd> -h -v`, in which case we list the paths
214        #[derive(Parser)]
215        #[command(disable_help_flag(true))]
216        struct HelpVerboseOnly {
217            #[arg(short, long)]
218            help: bool,
219            #[arg(global = true, short, long, action = clap::ArgAction::Count)]
220            pub verbose: u8,
221            #[arg(value_enum)]
222            cmd: Kind,
223        }
224        if let Ok(HelpVerboseOnly { help: true, verbose: 1.., cmd: subcommand }) =
225            HelpVerboseOnly::try_parse_from(normalize_args(args))
226        {
227            println!("NOTE: updating submodules before printing available paths");
228            let flags = Self::parse(&[String::from("build")]);
229            let config = Config::parse(flags);
230            let sess = Session::new(config);
231            let paths = Builder::get_help(&sess, subcommand);
232            if let Some(s) = paths {
233                println!("{s}");
234            } else {
235                panic!("No paths available for subcommand `{}`", subcommand.as_str());
236            }
237            true
238        } else {
239            false
240        }
241    }
242
243    #[cfg_attr(
244        feature = "tracing",
245        instrument(level = "trace", name = "Flags::parse", skip_all, fields(args = ?args))
246    )]
247    pub fn parse(args: &[String]) -> Self {
248        Flags::parse_from(normalize_args(args))
249    }
250}
251
252fn normalize_args(args: &[String]) -> Vec<String> {
253    let first = String::from("x.py");
254    let it = std::iter::once(first).chain(args.iter().cloned());
255    it.collect()
256}
257
258#[derive(Debug, Clone, clap::Subcommand)]
259pub enum Subcommand {
260    #[command(visible_aliases = ["b"], long_about = "\n
261    Arguments:
262        This subcommand accepts a number of paths to directories to the crates
263        and/or artifacts to compile. For example, for a quick build of a usable
264        compiler:
265            ./x.py build --stage 1 library/std
266        This will build a compiler and standard library from the local source code.
267        Once this is done, build/$ARCH/stage1 contains a usable compiler.
268        If no arguments are passed then the default artifacts for that stage are
269        compiled. For example:
270            ./x.py build --stage 0
271            ./x.py build ")]
272    /// Compile either the compiler or libraries
273    Build {
274        #[arg(long)]
275        /// Pass `--timings` to Cargo to get crate build timings
276        timings: bool,
277    },
278    #[command(visible_aliases = ["c"], long_about = "\n
279    Arguments:
280        This subcommand accepts a number of paths to directories to the crates
281        and/or artifacts to compile. For example:
282            ./x.py check library/std
283        If no arguments are passed then many artifacts are checked.")]
284    /// Compile either the compiler or libraries, using cargo check
285    Check {
286        #[arg(long)]
287        /// Check all targets
288        all_targets: bool,
289        #[arg(long)]
290        /// Pass `--timings` to Cargo to get crate build timings
291        timings: bool,
292    },
293    /// Run Clippy (uses rustup/cargo-installed clippy binary)
294    #[command(long_about = "\n
295    Arguments:
296        This subcommand accepts a number of paths to directories to the crates
297        and/or artifacts to run clippy against. For example:
298            ./x.py clippy library/core
299            ./x.py clippy library/core library/proc_macro")]
300    Clippy {
301        #[arg(long)]
302        fix: bool,
303        #[arg(long, requires = "fix")]
304        allow_dirty: bool,
305        #[arg(long, requires = "fix")]
306        allow_staged: bool,
307        /// clippy lints to allow
308        #[arg(global = true, short = 'A', action = clap::ArgAction::Append, value_name = "LINT")]
309        allow: Vec<String>,
310        /// clippy lints to deny
311        #[arg(global = true, short = 'D', action = clap::ArgAction::Append, value_name = "LINT")]
312        deny: Vec<String>,
313        /// clippy lints to warn on
314        #[arg(global = true, short = 'W', action = clap::ArgAction::Append, value_name = "LINT")]
315        warn: Vec<String>,
316        /// clippy lints to forbid
317        #[arg(global = true, short = 'F', action = clap::ArgAction::Append, value_name = "LINT")]
318        forbid: Vec<String>,
319    },
320
321    /// Run cargo fix
322    #[command(long_about = "\n
323    Arguments:
324        This subcommand accepts a number of paths to directories to the crates
325        and/or artifacts to run `cargo fix` against. For example:
326            ./x.py fix library/core
327            ./x.py fix library/core library/proc_macro")]
328    Fix {
329        /// Pass `--allow-dirty` to `cargo fix`, allowing it to run even if the
330        /// current git checkout has uncommitted changes.
331        #[arg(long)]
332        allow_dirty: bool,
333    },
334
335    /// Run rustfmt
336    #[command(
337        name = "fmt",
338        long_about = "\n
339    Arguments:
340        This subcommand optionally accepts a `--check` flag which succeeds if
341        formatting is correct and fails if it is not. For example:
342            ./x.py fmt
343            ./x.py fmt --check"
344    )]
345    Format {
346        /// check formatting instead of applying
347        #[arg(long)]
348        check: bool,
349
350        /// apply to all appropriate files, not just those that have been modified
351        #[arg(long)]
352        all: bool,
353    },
354    #[command(visible_aliases = ["d"], long_about = "\n
355    Arguments:
356        This subcommand accepts a number of paths to directories of documentation
357        to build. For example:
358            ./x.py doc src/doc/book
359            ./x.py doc src/doc/nomicon
360            ./x.py doc src/doc/book library/std
361            ./x.py doc library/std --json
362            ./x.py doc library/std --open
363        If no arguments are passed then everything is documented:
364            ./x.py doc
365            ./x.py doc --stage 1")]
366    /// Build documentation
367    Doc {
368        #[arg(long)]
369        /// open the docs in a browser
370        open: bool,
371        #[arg(long)]
372        /// render the documentation in JSON format in addition to the usual HTML format
373        json: bool,
374    },
375    #[command(visible_aliases = ["t"], long_about = "\n
376    Arguments:
377        This subcommand accepts a number of paths to test directories that
378        should be compiled and run. For example:
379            ./x.py test tests/ui
380            ./x.py test library/std --test-args hash_map
381            ./x.py test library/std --stage 0 --all-targets
382            ./x.py test tests/ui --bless
383            ./x.py test tests/ui --compare-mode next-solver
384        Note that `test tests/* --stage N` does NOT depend on `build compiler/rustc --stage N`;
385        just like `build library/std --stage N` it tests the compiler produced by the previous
386        stage.
387        Execute tool tests with a tool name argument:
388            ./x.py test tidy
389        If no arguments are passed then the complete artifacts for that stage are
390        compiled and tested.
391            ./x.py test
392            ./x.py test --stage 1")]
393    /// Build and run some test suites
394    Test {
395        #[arg(long)]
396        /// run all tests regardless of failure
397        no_fail_fast: bool,
398        #[arg(long, value_name = "ARGS", allow_hyphen_values(true))]
399        /// extra arguments to be passed for the test tool being used
400        /// (e.g. libtest, compiletest or rustdoc)
401        test_args: Vec<String>,
402        /// extra options to pass the compiler when running compiletest tests
403        #[arg(long, value_name = "ARGS", allow_hyphen_values(true))]
404        compiletest_rustc_args: Vec<String>,
405        #[arg(long)]
406        /// Run all test targets (no doc tests)
407        all_targets: bool,
408        #[arg(long)]
409        /// Only run doc tests
410        doc: bool,
411        /// Only run unit and integration tests
412        #[arg(long)]
413        tests: bool,
414        #[arg(long)]
415        /// whether to automatically update stderr/stdout files
416        bless: bool,
417        #[arg(long)]
418        /// comma-separated list of other files types to check (accepts py, py:lint,
419        /// py:fmt, shell, cpp, cpp:fmt, js, js:lint, js:typecheck, spellcheck)
420        ///
421        /// Any argument can be prefixed with "auto:" to only run if
422        /// relevant files are modified (eg. "auto:py").
423        extra_checks: Option<String>,
424        #[arg(long)]
425        /// rerun tests even if the inputs are unchanged
426        force_rerun: bool,
427        #[arg(long)]
428        /// only run tests that result has been changed
429        only_modified: bool,
430        #[arg(long, value_name = "COMPARE MODE")]
431        /// mode describing what file the actual ui output will be compared to
432        compare_mode: Option<String>,
433        #[arg(long, value_name = "check | build | run")]
434        /// force {check,build,run}-pass tests to this mode.
435        pass: Option<String>,
436        #[arg(long, value_name = "auto | always | never")]
437        /// whether to execute run-* tests
438        run: Option<String>,
439        #[arg(long)]
440        /// enable this to generate a Rustfix coverage file, which is saved in
441        /// `/<build_base>/rustfix_missing_coverage.txt`
442        rustfix_coverage: bool,
443        #[arg(long)]
444        /// don't capture stdout/stderr of tests
445        no_capture: bool,
446        #[arg(long, default_value_t = true, action = clap::ArgAction::Set, default_missing_value = "true", num_args = 0..=1, require_equals = true)]
447        /// whether to show verbose subprocess output for run-make tests;
448        /// set to false to suppress output for passing tests (e.g. for cg_clif with --no-capture)
449        verbose_run_make_subprocess_output: bool,
450        #[arg(long)]
451        /// Use a different codegen backend when running tests.
452        test_codegen_backend: Option<CodegenBackendKind>,
453        #[arg(long)]
454        /// Ignore `//@ ignore-backends` directives.
455        bypass_ignore_backends: bool,
456
457        /// Deprecated. Use `--all-targets` or `--tests` instead.
458        #[arg(long)]
459        #[doc(hidden)]
460        no_doc: bool,
461
462        /// Record all the failed tests in a file in the build directory.
463        ///
464        /// On subsequent invocations, this set of tests can be rerun by passing `--rerun`
465        #[arg(long)]
466        record: bool,
467        /// Rerun tests that previously failed, and stored with `--record`.
468        #[arg(long)]
469        rerun: bool,
470    },
471    /// Build and run some test suites *in Miri*
472    Miri {
473        #[arg(long)]
474        /// run all tests regardless of failure
475        no_fail_fast: bool,
476        #[arg(long, value_name = "ARGS", allow_hyphen_values(true))]
477        /// extra arguments to be passed for the test tool being used
478        /// (e.g. libtest, compiletest or rustdoc)
479        test_args: Vec<String>,
480        #[arg(long)]
481        /// Run all test targets (no doc tests)
482        all_targets: bool,
483        #[arg(long)]
484        /// Only run doc tests
485        doc: bool,
486        /// Only run unit and integration tests
487        #[arg(long)]
488        tests: bool,
489
490        /// Deprecated. Use `--all-targets` or `--tests` instead.
491        #[arg(long)]
492        #[doc(hidden)]
493        no_doc: bool,
494    },
495    /// Build and run some benchmarks
496    Bench {
497        #[arg(long, allow_hyphen_values(true))]
498        test_args: Vec<String>,
499    },
500    /// Clean out build directories
501    Clean {
502        #[arg(long)]
503        /// Clean the entire build directory (not used by default)
504        all: bool,
505        #[arg(long, value_name = "N")]
506        /// Clean a specific stage without touching other artifacts. By default, every stage is cleaned if this option is not used.
507        stage: Option<u32>,
508    },
509    /// Build distribution artifacts
510    Dist,
511    /// Install distribution artifacts
512    Install,
513    #[command(visible_aliases = ["r"], long_about = "\n
514    Arguments:
515        This subcommand accepts a number of paths to tools to build and run. For
516        example:
517            ./x.py run src/tools/bump-stage0
518        At least a tool needs to be called.")]
519    /// Run tools contained in this repository
520    Run {
521        /// arguments for the tool
522        #[arg(long, allow_hyphen_values(true))]
523        args: Vec<String>,
524    },
525    /// Set up the environment for development
526    #[command(long_about = format!(
527        "\n
528x.py setup creates a `bootstrap.toml` which changes the defaults for x.py itself,
529as well as setting up a git pre-push hook, VS Code config and toolchain link.
530Arguments:
531    This subcommand accepts a 'profile' to use for builds. For example:
532        ./x.py setup library
533    The profile is optional and you will be prompted interactively if it is not given.
534    The following profiles are available:
535{}
536    To only set up the git hook, editor config or toolchain link, you may use
537        ./x.py setup hook
538        ./x.py setup editor
539        ./x.py setup link", Profile::all_for_help("        ").trim_end()))]
540    Setup {
541        /// Either the profile for `bootstrap.toml` or another setup action.
542        /// May be omitted to set up interactively
543        #[arg(value_name = "<PROFILE>|hook|editor|link")]
544        profile: Option<PathBuf>,
545    },
546    /// Vendor dependencies
547    Vendor {
548        /// Additional `Cargo.toml` to sync and vendor
549        #[arg(long)]
550        sync: Vec<PathBuf>,
551        /// Always include version in subdir name
552        #[arg(long)]
553        versioned_dirs: bool,
554    },
555    /// Perform profiling and benchmarking of the compiler using `rustc-perf`.
556    Perf(PerfArgs),
557}
558
559impl Default for Subcommand {
560    fn default() -> Self {
561        Subcommand::Build { timings: false }
562    }
563}
564
565impl Subcommand {
566    pub fn compiletest_rustc_args(&self) -> Vec<&str> {
567        match *self {
568            Subcommand::Test { ref compiletest_rustc_args, .. } => {
569                compiletest_rustc_args.iter().flat_map(|s| s.split_whitespace()).collect()
570            }
571            _ => vec![],
572        }
573    }
574
575    pub fn fail_fast(&self) -> bool {
576        match *self {
577            Subcommand::Test { no_fail_fast, .. } | Subcommand::Miri { no_fail_fast, .. } => {
578                !no_fail_fast
579            }
580            _ => false,
581        }
582    }
583
584    pub fn test_target(&self) -> TestTarget {
585        match *self {
586            Subcommand::Test { mut all_targets, doc, tests, no_doc, .. }
587            | Subcommand::Miri { mut all_targets, doc, tests, no_doc, .. } => {
588                // for backwards compatibility --no-doc keeps working
589                all_targets = all_targets || no_doc;
590
591                match (all_targets, doc, tests) {
592                    (true, true, _) | (true, _, true) | (_, true, true) => {
593                        panic!("You can only set one of `--all-targets`, `--doc` and `--tests`.")
594                    }
595                    (true, false, false) => TestTarget::AllTargets,
596                    (false, true, false) => TestTarget::DocOnly,
597                    (false, false, true) => TestTarget::Tests,
598                    (false, false, false) => TestTarget::Default,
599                }
600            }
601            _ => TestTarget::Default,
602        }
603    }
604
605    pub fn no_doc(&self) -> bool {
606        match *self {
607            Subcommand::Test { no_doc, .. } | Subcommand::Miri { no_doc, .. } => no_doc,
608            _ => false,
609        }
610    }
611
612    pub fn bless(&self) -> bool {
613        match *self {
614            Subcommand::Test { bless, .. } => bless,
615            _ => false,
616        }
617    }
618
619    pub fn extra_checks(&self) -> Option<&str> {
620        match *self {
621            Subcommand::Test { ref extra_checks, .. } => extra_checks.as_ref().map(String::as_str),
622            _ => None,
623        }
624    }
625
626    pub fn only_modified(&self) -> bool {
627        match *self {
628            Subcommand::Test { only_modified, .. } => only_modified,
629            _ => false,
630        }
631    }
632
633    pub fn force_rerun(&self) -> bool {
634        match *self {
635            Subcommand::Test { force_rerun, .. } => force_rerun,
636            _ => false,
637        }
638    }
639
640    pub fn no_capture(&self) -> bool {
641        match *self {
642            Subcommand::Test { no_capture, .. } => no_capture,
643            _ => false,
644        }
645    }
646
647    pub fn verbose_run_make_subprocess_output(&self) -> bool {
648        match *self {
649            Subcommand::Test { verbose_run_make_subprocess_output, .. } => {
650                verbose_run_make_subprocess_output
651            }
652            _ => true,
653        }
654    }
655
656    pub fn rustfix_coverage(&self) -> bool {
657        match *self {
658            Subcommand::Test { rustfix_coverage, .. } => rustfix_coverage,
659            _ => false,
660        }
661    }
662
663    pub fn compare_mode(&self) -> Option<&str> {
664        match *self {
665            Subcommand::Test { ref compare_mode, .. } => compare_mode.as_ref().map(|s| &s[..]),
666            _ => None,
667        }
668    }
669
670    pub fn pass(&self) -> Option<&str> {
671        match *self {
672            Subcommand::Test { ref pass, .. } => pass.as_ref().map(|s| &s[..]),
673            _ => None,
674        }
675    }
676
677    pub fn run(&self) -> Option<&str> {
678        match *self {
679            Subcommand::Test { ref run, .. } => run.as_ref().map(|s| &s[..]),
680            _ => None,
681        }
682    }
683
684    pub fn open(&self) -> bool {
685        match *self {
686            Subcommand::Doc { open, .. } => open,
687            _ => false,
688        }
689    }
690
691    pub fn json(&self) -> bool {
692        match *self {
693            Subcommand::Doc { json, .. } => json,
694            _ => false,
695        }
696    }
697
698    pub fn timings(&self) -> bool {
699        match *self {
700            Subcommand::Build { timings, .. } | Subcommand::Check { timings, .. } => timings,
701            _ => false,
702        }
703    }
704
705    pub fn vendor_versioned_dirs(&self) -> bool {
706        match *self {
707            Subcommand::Vendor { versioned_dirs, .. } => versioned_dirs,
708            _ => false,
709        }
710    }
711
712    pub fn vendor_sync_args(&self) -> Vec<PathBuf> {
713        match self {
714            Subcommand::Vendor { sync, .. } => sync.clone(),
715            _ => vec![],
716        }
717    }
718
719    pub fn test_codegen_backend(&self) -> Option<&CodegenBackendKind> {
720        match self {
721            Subcommand::Test { test_codegen_backend, .. } => test_codegen_backend.as_ref(),
722            _ => None,
723        }
724    }
725
726    pub fn bypass_ignore_backends(&self) -> bool {
727        match self {
728            Subcommand::Test { bypass_ignore_backends, .. } => *bypass_ignore_backends,
729            _ => false,
730        }
731    }
732
733    pub fn record(&self) -> bool {
734        match self {
735            Subcommand::Test { record, .. } => *record,
736            _ => false,
737        }
738    }
739
740    pub fn rerun(&self) -> bool {
741        match self {
742            Subcommand::Test { rerun, .. } => *rerun,
743            _ => false,
744        }
745    }
746
747    /// Are we executing a `check --all-targets` command?
748    pub(crate) fn check_all_targets(&self) -> bool {
749        matches!(self, Subcommand::Check { all_targets: true, .. })
750    }
751}
752
753/// Returns the shell completion for a given shell, if the result differs from the current
754/// content of `path`. If `path` does not exist, always returns `Some`.
755pub fn get_completion(shell: &dyn Generator, path: &Path) -> Option<String> {
756    let mut cmd = Flags::command();
757    let current = if !path.exists() {
758        String::new()
759    } else {
760        std::fs::read_to_string(path).unwrap_or_else(|_| {
761            eprintln!("couldn't read {}", path.display());
762            helpers::exit_process(1);
763        })
764    };
765    let mut buf = Vec::new();
766    let (bin_name, _) = path
767        .file_name()
768        .expect("path should be a regular file")
769        .to_str()
770        .expect("file name should be UTF-8")
771        .rsplit_once('.')
772        .expect("file name should have an extension");
773
774    // We sort of replicate `clap_complete::generate` here, because we want to call it with
775    // `&dyn Generator`, but that function requires `G: Generator` instead.
776    cmd.set_bin_name(bin_name);
777    cmd.build();
778    shell.generate(&cmd, &mut buf);
779    if buf == current.as_bytes() {
780        return None;
781    }
782    Some(String::from_utf8(buf).expect("completion script should be UTF-8"))
783}
784
785/// Return the top level help of the bootstrap.
786pub fn top_level_help() -> String {
787    let mut cmd = Flags::command();
788    cmd.render_help().to_string()
789}