cargo-feature-combinations 0.1.0

run cargo commands for all feature combinations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! CLI argument parsing, options, and help text.

use color_eyre::eyre::{self, WrapErr};
use std::collections::HashSet;
use std::path::PathBuf;

/// High-level command requested by the user.
#[derive(Debug)]
pub enum Command {
    /// Print a JSON feature matrix to stdout.
    ///
    /// The matrix is produced by combining [`crate::Package::feature_matrix`]
    /// for all selected packages into a single JSON array.
    FeatureMatrix {
        /// Whether to pretty-print the JSON feature matrix.
        pretty: bool,
    },
    /// Print the tool version and exit.
    Version,
    /// Print help text and exit.
    Help,
}

/// Command-line options recognized by this crate.
///
/// Instances of this type are produced by [`parse_arguments`] and consumed by
/// [`crate::run`] to drive command selection and filtering.
#[derive(Debug, Default)]
pub struct Options {
    /// Optional path to the Cargo manifest that should be inspected.
    pub manifest_path: Option<PathBuf>,
    /// Explicit list of package names to include.
    pub packages: HashSet<String>,
    /// List of package names to exclude.
    pub exclude_packages: HashSet<String>,
    /// High-level command to execute.
    pub command: Option<Command>,
    /// Whether to restrict processing to packages with a library target.
    pub only_packages_with_lib_target: bool,
    /// Whether to hide cargo output and only show the final summary.
    ///
    /// Set by `--summary-only` or its backward-compatible aliases `--summary`
    /// and `--silent`.
    pub summary_only: bool,
    /// Whether to show only diagnostics (warnings/errors) per feature
    /// combination, suppressing compilation progress noise.
    ///
    /// Requires the invoked subcommand to accept `--message-format=...` and
    /// emit rustc's JSON diagnostic format. Built-in cargo subcommands like
    /// `build`, `check`, `clippy`, and `doc` qualify; so does any alias or
    /// custom subcommand that does the same.
    ///
    /// Set by `--diagnostics-only`.
    pub diagnostics_only: bool,
    /// Whether to deduplicate diagnostics across feature combinations.
    ///
    /// Implies `--diagnostics-only`. Identical diagnostics are printed only
    /// once; the summary reports how many diagnostics already shown by earlier
    /// feature combinations were suppressed.
    pub dedupe: bool,
    /// Whether to print more verbose information such as the full cargo command.
    pub verbose: bool,
    /// Whether to treat warnings like errors for the summary and `--fail-fast`.
    pub pedantic: bool,
    /// Whether to silence warnings from rustc and only show errors.
    pub errors_only: bool,
    /// Whether to only list packages instead of all feature combinations.
    pub packages_only: bool,
    /// Whether to stop processing after the first failing feature combination.
    pub fail_fast: bool,
    /// Whether to disable automatic pruning of implied feature combinations.
    ///
    /// Set by `--no-prune-implied`.
    pub no_prune_implied: bool,
    /// Whether to show pruned feature combinations in the summary.
    ///
    /// Set by `--show-pruned`.
    pub show_pruned: bool,
    /// Whether to use aggregate target execution mode.
    ///
    /// Set by `--aggregate-targets`. When enabled, one Cargo invocation per
    /// `(package, combo)` carries every target sharing that combo as repeated
    /// `--target` flags. The default (flag absent) is serial per-target.
    pub aggregate_targets: bool,
    /// Whether to ignore configured target lists for this invocation.
    ///
    /// Set by `--no-targets`. Temporarily disables running for all configured
    /// targets and falls back to Cargo's default single effective target
    /// (`--target`, then `CARGO_BUILD_TARGET`, then host). An alternative to
    /// passing an explicit `--target <triple>`.
    pub no_targets: bool,
    /// Whether to install missing Rust target components before execution.
    ///
    /// Set by `--install-missing-targets`. cargo-fc deduplicates the planned
    /// target triples, skips the host target, and invokes `rustup target add`
    /// once for targets that are not installed yet.
    pub install_missing_targets: bool,
}

/// Helper trait to provide simple argument parsing over `Vec<String>`.
pub trait ArgumentParser {
    /// Check whether an argument flag exists, either as a standalone flag or
    /// in `--flag=value` form.
    fn contains(&self, arg: &str) -> bool;
    /// Extract all occurrences of an argument and their values.
    ///
    /// When `has_value` is `true`, this matches `--flag value` and
    /// `--flag=value` forms and returns the value part. When `has_value` is
    /// `false`, it matches bare flags like `--flag`.
    fn get_all(&self, arg: &str, has_value: bool)
    -> Vec<(std::ops::RangeInclusive<usize>, String)>;
}

impl ArgumentParser for Vec<String> {
    fn contains(&self, arg: &str) -> bool {
        self.iter()
            .any(|a| a == arg || a.starts_with(&format!("{arg}=")))
    }

    fn get_all(
        &self,
        arg: &str,
        has_value: bool,
    ) -> Vec<(std::ops::RangeInclusive<usize>, String)> {
        let mut matched = Vec::new();
        for (idx, a) in self.iter().enumerate() {
            match (a, self.get(idx + 1)) {
                (key, Some(value)) if key == arg && has_value => {
                    matched.push((idx..=idx + 1, value.clone()));
                }
                (key, _) if key == arg && !has_value => {
                    matched.push((idx..=idx, key.clone()));
                }
                (key, _) if key.starts_with(&format!("{arg}=")) => {
                    let value = key.trim_start_matches(&format!("{arg}="));
                    matched.push((idx..=idx, value.to_string()));
                }
                _ => {}
            }
        }
        matched.reverse();
        matched
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum CargoSubcommand {
    Build,
    Check,
    Lint,
    Test,
    Doc,
    Run,
    Other,
}

/// Determine the cargo subcommand implied by the argument list.
pub(crate) fn cargo_subcommand(args: &[impl AsRef<str>]) -> CargoSubcommand {
    match cargo_subcommand_token(args) {
        Some(token) => subcommand_from_token(&token),
        None => CargoSubcommand::Other,
    }
}

fn subcommand_from_token(arg: &str) -> CargoSubcommand {
    match arg {
        "build" | "b" => CargoSubcommand::Build,
        "check" | "c" => CargoSubcommand::Check,
        "clippy" => CargoSubcommand::Lint,
        "test" | "t" => CargoSubcommand::Test,
        "doc" | "d" => CargoSubcommand::Doc,
        "run" | "r" => CargoSubcommand::Run,
        _ => CargoSubcommand::Other,
    }
}

/// Extract the raw cargo subcommand token from the argument list.
///
/// Unlike [`cargo_subcommand`], this preserves the literal token (e.g. `lint`,
/// `clippy`, `c`) so the command target-capability registry can reason about
/// aliases that the [`CargoSubcommand`] enum collapses to `Other`.
///
/// Returns `None` when no subcommand token is present (e.g. an unknown leading
/// flag or an early `--`).
pub(crate) fn cargo_subcommand_token(args: &[impl AsRef<str>]) -> Option<String> {
    fn is_no_value_flag(arg: &str) -> bool {
        matches!(
            arg,
            "-q" | "--quiet"
                | "--frozen"
                | "--locked"
                | "--offline"
                | "-h"
                | "--help"
                | "-V"
                | "--version"
                | "--list"
                | "--verbose"
        ) || arg.starts_with("-v")
    }

    fn takes_value(arg: &str) -> bool {
        matches!(arg, "--color" | "--config" | "--explain" | "-C" | "-Z")
    }

    fn has_inline_value(arg: &str) -> bool {
        arg.starts_with("--color=")
            || arg.starts_with("--config=")
            || arg.starts_with("--explain=")
            || (arg.starts_with("-C") && arg.len() > 2)
            || (arg.starts_with("-Z") && arg.len() > 2)
    }

    let mut skip_next = false;
    for arg in args.iter().map(AsRef::as_ref) {
        if skip_next {
            skip_next = false;
            continue;
        }
        if arg == "--" {
            return None;
        }
        if arg.starts_with('+') {
            continue;
        }
        if is_no_value_flag(arg) {
            continue;
        }
        if takes_value(arg) {
            skip_next = true;
            continue;
        }
        if has_inline_value(arg) {
            continue;
        }

        if arg.starts_with("--") {
            return None;
        }

        if arg.starts_with('-') {
            return None;
        }

        return Some(arg.to_string());
    }

    None
}

/// Extract a rustup toolchain override from forwarded Cargo args.
///
/// Cargo accepts `+toolchain` before the subcommand. When cargo-fc installs
/// missing target components, rustup must receive the same override or it may
/// install targets into the default toolchain instead.
pub(crate) fn rustup_toolchain(args: &[impl AsRef<str>]) -> Option<String> {
    let first = args.first()?.as_ref();
    first
        .strip_prefix('+')
        .filter(|toolchain| !toolchain.is_empty())
        .map(ToOwned::to_owned)
}

/// Canonical long command name for built-in cargo subcommands cargo-fc knows
/// accept Cargo's `--target` flag.
///
/// This is the initial target-capability registry. It tracks the command
/// tokens cargo-fc already recognizes today (`build`, `check`, `clippy`,
/// `test`, `doc`, `run`) plus their short aliases. `matrix` is handled
/// separately because it is not a forwarded cargo command.
fn builtin_target_command_key(token: &str) -> Option<&'static str> {
    match token {
        "build" | "b" => Some("build"),
        "check" | "c" => Some("check"),
        "clippy" => Some("clippy"),
        "test" | "t" => Some("test"),
        "doc" | "d" => Some("doc"),
        "run" | "r" => Some("run"),
        _ => None,
    }
}

/// Resolved configured-target policy for a cargo command token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ConfiguredTargetPolicy {
    /// Whether configured target lists apply to this command.
    pub enabled: bool,
    /// Whether the decision came from workspace config.
    ///
    /// This lets callers avoid warning when `targets = false` is an intentional
    /// opt-out rather than the unknown-command default.
    pub explicit: bool,
}

/// Whether the selected command may expand configured target lists and have
/// `--target <triple>` injected.
///
/// Built-in commands default to `targets = true`; unknown aliases default to
/// `targets = false`. Workspace `subcommands.<token>.targets` overrides either
/// default. For built-in short aliases, an exact alias entry wins; otherwise the
/// long command's entry applies.
#[must_use]
pub(crate) fn configured_target_policy(
    token: Option<&str>,
    subcommands: &std::collections::BTreeMap<String, crate::config::CommandTargetCapability>,
) -> ConfiguredTargetPolicy {
    let Some(token) = token else {
        return ConfiguredTargetPolicy {
            enabled: false,
            explicit: false,
        };
    };

    if let Some(capability) = subcommands.get(token) {
        return ConfiguredTargetPolicy {
            enabled: capability.targets,
            explicit: true,
        };
    }

    if let Some(command_key) = builtin_target_command_key(token) {
        if let Some(capability) = subcommands.get(command_key) {
            return ConfiguredTargetPolicy {
                enabled: capability.targets,
                explicit: true,
            };
        }
        return ConfiguredTargetPolicy {
            enabled: true,
            explicit: false,
        };
    }

    ConfiguredTargetPolicy {
        enabled: false,
        explicit: false,
    }
}

static VALID_BOOLS: [&str; 4] = ["yes", "true", "y", "t"];

const HELP_TEXT: &str = r#"Run cargo commands for all feature combinations

USAGE:
    cargo fc [+toolchain] [SUBCOMMAND] [SUBCOMMAND_OPTIONS]
    cargo fc [+toolchain] [OPTIONS] [CARGO_OPTIONS] [CARGO_SUBCOMMAND]

SUBCOMMAND:
    matrix                  Print JSON feature combination matrix to stdout
        --pretty            Print pretty JSON

OPTIONS:
    --help                  Print help information
    --diagnostics-only      Show only diagnostics (warnings/errors) per
                            feature combination. Subcommand must accept
                            --message-format=... and emit rustc JSON
                            diagnostics (e.g. build, check, clippy, doc,
                            or any alias/wrapper that does the same)
    --dedupe                Like --diagnostics-only, but also deduplicate
                            identical diagnostics across feature combinations
    --summary-only          Hide cargo output and only show the final summary
    --fail-fast             Fail fast on the first bad feature combination
    --errors-only           Allow all warnings, show errors only (-Awarnings)
    --exclude-package       Exclude a package from feature combinations
    --only-packages-with-lib-target
                            Only consider packages with a library target
    --pedantic              Treat warnings like errors in summary and
                            when using --fail-fast
    --no-prune-implied      Disable automatic pruning of redundant feature
                            combinations implied by other features
    --show-pruned           Show pruned feature combinations in the summary
    --aggregate-targets     Batch each combination's configured targets into a
                            single Cargo invocation (one `--target` per target)
                            instead of one invocation per target. Faster on
                            many cores; reports results per target group. Falls
                            back to serial for `run` and pruned summaries.
    --no-targets            Ignore configured target lists for this invocation
                            and use Cargo's default single target (--target,
                            then CARGO_BUILD_TARGET, then host). An alternative
                            to passing an explicit --target <triple>.
    --install-missing-targets
                            Install missing Rust target components with rustup
                            before running Cargo. Explicit opt-in because this
                            may mutate the toolchain and use the network.

Feature sets can be configured in your Cargo.toml configuration.
The following metadata key aliases are all supported:

    [package.metadata.cargo-fc]            (recommended)
    [package.metadata.fc]
    [package.metadata.cargo-feature-combinations]
    [package.metadata.feature-combinations]

For example:

```toml
[package.metadata.cargo-fc]

# Exclude groupings of features that are incompatible or do not make sense
exclude_feature_sets = [ ["foo", "bar"], ] # formerly "skip_feature_sets"

# To exclude only the empty feature set from the matrix, you can either enable
# `no_empty_feature_set = true` or explicitly list an empty set here:
#
# exclude_feature_sets = [[]]

# Exclude features from the feature combination matrix
exclude_features = ["default", "full"] # formerly "denylist"

# Include features in the feature combination matrix
#
# These features will be added to every generated feature combination.
# This does not restrict which features are varied for the combinatorial
# matrix. To restrict the matrix to a specific allowlist of features, use
# `only_features`.
include_features = ["feature-that-must-always-be-set"]

# Only consider these features when generating the combinatorial matrix.
#
# When set, features not listed here are ignored for the combinatorial matrix.
# When empty, all package features are considered.
only_features = ["default", "full"]

# Skip implicit features that correspond to optional dependencies from the
# matrix.
#
# When enabled, the implicit features that Cargo generates for optional
# dependencies (of the form `foo = ["dep:foo"]` in the feature graph) are
# removed from the combinatorial matrix. This mirrors the behaviour of the
# `skip_optional_dependencies` flag in the `cargo-all-features` crate.
skip_optional_dependencies = true

# In the end, always add these exact combinations to the overall feature matrix,
# unless one is already present there.
#
# Non-existent features are ignored. Other configuration options are ignored.
include_feature_sets = [
    ["foo-a", "bar-a", "other-a"],
] # formerly "exact_combinations"

# Allow only the listed feature sets.
#
# When this list is non-empty, the feature matrix will consist exactly of the
# configured sets (after dropping non-existent features). No powerset is
# generated.
allow_feature_sets = [
    ["hydrate"],
    ["ssr"],
]

# When enabled, never include the empty feature set (no `--features`), even if
# it would otherwise be generated.
no_empty_feature_set = true

# Automatically prune redundant feature combinations whose resolved feature
# set (after Cargo's feature unification) matches a smaller combination.
# Enabled by default. Disable with `prune_implied = false`.
# prune_implied = true

# When at least one isolated feature set is configured, stop taking all project
# features as a whole, and instead take them in these isolated sets. Build a
# sub-matrix for each isolated set, then merge sub-matrices into the overall
# feature matrix. If any two isolated sets produce an identical feature
# combination, such combination will be included in the overall matrix only once.
#
# This feature is intended for projects with large number of features, sub-sets
# of which are completely independent, and thus don't need cross-play.
#
# Other configuration options are still respected.
isolated_feature_sets = [
    ["foo-a", "foo-b", "foo-c"],
    ["bar-a", "bar-b"],
    ["other-a", "other-b", "other-c"],
]
```

Target-specific configuration can be expressed via Cargo-style `cfg(...)` selectors:

```toml
[package.metadata.cargo-fc]
exclude_features = ["default"]

[package.metadata.cargo-fc.target.'cfg(target_os = "linux")']
exclude_features = { add = ["metal"] }
```

Notes:

- Arrays in target overrides are always treated as overrides.
  Use `{ add = [...] }` / `{ remove = [...] }` for additive changes.
- Patches are applied in order: override (or base), then remove, then add.
  If a value appears in both `add` and `remove`, add wins.
- When multiple sections match, their `add`/`remove` sets are unioned.
  Conflicting `override` values result in an error.
- `replace = true` starts from a fresh default config for that target.
  When `replace = true` is set, patchable fields must not use `add`/`remove`.
- `cfg(feature = "...")` predicates are not supported in target override keys.
- If `--target <triple>` or `CARGO_BUILD_TARGET` is set, it is used to select
  matching target overrides (this also applies to `cargo fc matrix`).

When using a cargo workspace, you can also exclude packages in your workspace `Cargo.toml`:

```toml
[workspace.metadata.cargo-fc]
# Exclude packages in the workspace metadata, or the metadata of the *root* package.
exclude_packages = ["package-a", "package-b"]
```

For more information, see 'https://github.com/romnn/cargo-feature-combinations'.

See 'cargo help <command>' for more information on a specific command.
"#;

/// Print the help text to stdout.
pub(crate) fn print_help() {
    println!("{HELP_TEXT}");
}

/// Parse command-line arguments for the `cargo-*` binary.
///
/// The returned [`Options`] drives workspace discovery and filtering, while
/// the remaining `Vec<String>` contains the raw cargo arguments.
///
/// # Errors
///
/// Returns an error if the manifest path passed via `--manifest-path` does
/// not exist or can not be canonicalized.
pub fn parse_arguments(bin_name: &str) -> eyre::Result<(Options, Vec<String>)> {
    let mut args: Vec<String> = std::env::args_os()
        // Skip executable name
        .skip(1)
        // Skip our own cargo-* command name
        .skip_while(|arg| {
            let arg = arg.as_os_str();
            arg == bin_name || arg == "cargo"
        })
        .map(|s| s.to_string_lossy().to_string())
        .collect();

    let mut options = Options {
        verbose: VALID_BOOLS.contains(
            &std::env::var("VERBOSE")
                .unwrap_or_default()
                .to_lowercase()
                .as_str(),
        ),
        ..Options::default()
    };

    // Extract path to manifest to operate on
    for (span, manifest_path) in args.get_all("--manifest-path", true) {
        let manifest_path = PathBuf::from(manifest_path);
        let manifest_path = manifest_path
            .canonicalize()
            .wrap_err_with(|| format!("manifest {} does not exist", manifest_path.display()))?;
        options.manifest_path = Some(manifest_path);
        args.drain(span);
    }

    // Extract packages to operate on
    for flag in ["--package", "-p"] {
        for (span, package) in args.get_all(flag, true) {
            options.packages.insert(package);
            args.drain(span);
        }
    }

    for (span, package) in args.get_all("--exclude-package", true) {
        options.exclude_packages.insert(package.trim().to_string());
        args.drain(span);
    }

    for (span, _) in args.get_all("--only-packages-with-lib-target", false) {
        options.only_packages_with_lib_target = true;
        args.drain(span);
    }

    // Check for matrix command
    for (span, _) in args.get_all("matrix", false) {
        options.command = Some(Command::FeatureMatrix { pretty: false });
        args.drain(span);
    }
    // Check for pretty matrix option
    for (span, _) in args.get_all("--pretty", false) {
        if let Some(Command::FeatureMatrix { ref mut pretty }) = options.command {
            *pretty = true;
        }
        args.drain(span);
    }

    // Check for help command
    for (span, _) in args.get_all("--help", false) {
        options.command = Some(Command::Help);
        args.drain(span);
    }

    // Check for version flag
    for (span, _) in args.get_all("--version", false) {
        options.command = Some(Command::Version);
        args.drain(span);
    }

    // Check for version command
    for (span, _) in args.get_all("version", false) {
        options.command = Some(Command::Version);
        args.drain(span);
    }

    let mut drain_flag = |flag: &str, field: &mut bool| {
        for (span, _) in args.get_all(flag, false) {
            *field = true;
            args.drain(span);
        }
    };
    drain_flag("--pedantic", &mut options.pedantic);
    drain_flag("--errors-only", &mut options.errors_only);
    drain_flag("--packages-only", &mut options.packages_only);
    drain_flag("--diagnostics-only", &mut options.diagnostics_only);
    drain_flag("--fail-fast", &mut options.fail_fast);
    drain_flag("--no-prune-implied", &mut options.no_prune_implied);
    drain_flag("--show-pruned", &mut options.show_pruned);
    drain_flag("--aggregate-targets", &mut options.aggregate_targets);
    drain_flag("--no-targets", &mut options.no_targets);
    drain_flag(
        "--install-missing-targets",
        &mut options.install_missing_targets,
    );

    // --dedupe implies --diagnostics-only
    for flag in ["--dedupe", "--dedup"] {
        for (span, _) in args.get_all(flag, false) {
            options.dedupe = true;
            options.diagnostics_only = true;
            args.drain(span);
        }
    }

    // --summary-only aliases
    for flag in ["--summary-only", "--summary", "--silent"] {
        for (span, _) in args.get_all(flag, false) {
            options.summary_only = true;
            args.drain(span);
        }
    }

    // Ignore `--workspace`. This tool already discovers the relevant workspace
    // packages via `cargo metadata` and then runs cargo separately in each
    // package's directory. Forwarding `--workspace` to those per-package
    // invocations would re-enable workspace-level feature application and can
    // cause spurious errors when some workspace members do not define a
    // particular feature.
    for (span, _) in args.get_all("--workspace", false) {
        args.drain(span);
    }

    Ok((options, args))
}

#[cfg(test)]
mod test {
    use super::{
        CargoSubcommand, cargo_subcommand, cargo_subcommand_token, configured_target_policy,
        rustup_toolchain,
    };
    use crate::config::CommandTargetCapability;
    use similar_asserts::assert_eq as sim_assert_eq;
    use std::collections::BTreeMap;

    #[test]
    fn cargo_subcommand_detects_build_and_short_build() {
        sim_assert_eq!(cargo_subcommand(&["build"]), CargoSubcommand::Build);
        sim_assert_eq!(cargo_subcommand(&["b"]), CargoSubcommand::Build);
    }

    #[test]
    fn cargo_subcommand_detects_check_and_short_check() {
        sim_assert_eq!(cargo_subcommand(&["check"]), CargoSubcommand::Check);
        sim_assert_eq!(cargo_subcommand(&["c"]), CargoSubcommand::Check);
    }

    #[test]
    fn cargo_subcommand_detects_clippy_as_lint() {
        sim_assert_eq!(cargo_subcommand(&["clippy"]), CargoSubcommand::Lint);
    }

    #[test]
    fn cargo_subcommand_detects_test_and_short_test() {
        sim_assert_eq!(cargo_subcommand(&["test"]), CargoSubcommand::Test);
        sim_assert_eq!(cargo_subcommand(&["t"]), CargoSubcommand::Test);
    }

    #[test]
    fn cargo_subcommand_detects_doc_and_short_doc() {
        sim_assert_eq!(cargo_subcommand(&["doc"]), CargoSubcommand::Doc);
        sim_assert_eq!(cargo_subcommand(&["d"]), CargoSubcommand::Doc);
    }

    #[test]
    fn cargo_subcommand_detects_run_and_short_run() {
        sim_assert_eq!(cargo_subcommand(&["run"]), CargoSubcommand::Run);
        sim_assert_eq!(cargo_subcommand(&["r"]), CargoSubcommand::Run);
    }

    #[test]
    fn cargo_subcommand_skips_known_leading_cargo_flags_and_values() {
        let subcommand = cargo_subcommand(&[
            "+nightly",
            "--config",
            "net.retry=2",
            "--color=always",
            "-vv",
            "--frozen",
            "clippy",
            "build",
        ]);

        sim_assert_eq!(subcommand, CargoSubcommand::Lint);
    }

    #[test]
    fn cargo_subcommand_handles_help_and_version_flags_before_subcommand() {
        sim_assert_eq!(
            cargo_subcommand(&["--verbose", "--help", "clippy"]),
            CargoSubcommand::Lint
        );
        sim_assert_eq!(
            cargo_subcommand(&["-vv", "--frozen", "test"]),
            CargoSubcommand::Test
        );
    }

    #[test]
    fn cargo_subcommand_returns_other_for_unknown_leading_flag() {
        let subcommand = cargo_subcommand(&["--mystery-flag", "clippy"]);

        sim_assert_eq!(subcommand, CargoSubcommand::Other);
    }

    #[test]
    fn cargo_subcommand_treats_unknown_aliases_as_other() {
        sim_assert_eq!(cargo_subcommand(&["lint"]), CargoSubcommand::Other);
        sim_assert_eq!(cargo_subcommand(&["lint", "build"]), CargoSubcommand::Other);
    }

    #[test]
    fn cargo_subcommand_token_preserves_literal_token() {
        sim_assert_eq!(
            cargo_subcommand_token(&["clippy"]),
            Some("clippy".to_string())
        );
        sim_assert_eq!(cargo_subcommand_token(&["lint"]), Some("lint".to_string()));
        sim_assert_eq!(cargo_subcommand_token(&["c"]), Some("c".to_string()));
        sim_assert_eq!(
            cargo_subcommand_token(&["+nightly", "--frozen", "lint", "build"]),
            Some("lint".to_string())
        );
    }

    #[test]
    fn cargo_subcommand_token_none_for_missing_command() {
        let empty: [&str; 0] = [];
        sim_assert_eq!(cargo_subcommand_token(&empty), None);
        sim_assert_eq!(cargo_subcommand_token(&["--mystery-flag"]), None);
        sim_assert_eq!(cargo_subcommand_token(&["--"]), None);
    }

    #[test]
    fn rustup_toolchain_detects_cargo_toolchain_override() {
        sim_assert_eq!(
            rustup_toolchain(&["+nightly", "--frozen", "check"]),
            Some("nightly".to_string())
        );
    }

    #[test]
    fn rustup_toolchain_ignores_args_after_double_dash() {
        sim_assert_eq!(rustup_toolchain(&["run", "--", "+nightly"]), None);
    }

    #[test]
    fn rustup_toolchain_ignores_plus_values_after_leading_position() {
        sim_assert_eq!(rustup_toolchain(&["check", "--target-dir", "+out"]), None);
    }

    #[test]
    fn builtin_clippy_has_target_capability() {
        let subcommands = BTreeMap::new();
        let policy = configured_target_policy(Some("clippy"), &subcommands);
        assert!(policy.enabled);
        assert!(!policy.explicit);
    }

    #[test]
    fn unknown_lint_lacks_target_capability_unless_configured() {
        let empty = BTreeMap::new();
        let policy = configured_target_policy(Some("lint"), &empty);
        assert!(!policy.enabled);
        assert!(!policy.explicit);

        let mut configured = BTreeMap::new();
        configured.insert(
            "lint".to_string(),
            CommandTargetCapability { targets: true },
        );
        let policy = configured_target_policy(Some("lint"), &configured);
        assert!(policy.enabled);
        assert!(policy.explicit);
    }

    #[test]
    fn configured_alias_with_targets_false_is_denied() {
        let mut configured = BTreeMap::new();
        configured.insert(
            "lint".to_string(),
            CommandTargetCapability { targets: false },
        );
        let policy = configured_target_policy(Some("lint"), &configured);
        assert!(!policy.enabled);
        assert!(policy.explicit);
    }

    #[test]
    fn configured_builtin_with_targets_false_is_denied() {
        let mut configured = BTreeMap::new();
        configured.insert(
            "check".to_string(),
            CommandTargetCapability { targets: false },
        );
        let policy = configured_target_policy(Some("check"), &configured);
        assert!(!policy.enabled);
        assert!(policy.explicit);
    }

    #[test]
    fn builtin_short_alias_inherits_long_command_policy() {
        let mut configured = BTreeMap::new();
        configured.insert(
            "build".to_string(),
            CommandTargetCapability { targets: false },
        );
        let policy = configured_target_policy(Some("b"), &configured);
        assert!(!policy.enabled);
        assert!(policy.explicit);
    }

    #[test]
    fn builtin_short_alias_exact_policy_wins_over_long_command_policy() {
        let mut configured = BTreeMap::new();
        configured.insert(
            "build".to_string(),
            CommandTargetCapability { targets: false },
        );
        configured.insert("b".to_string(), CommandTargetCapability { targets: true });

        let policy = configured_target_policy(Some("b"), &configured);
        assert!(policy.enabled);
        assert!(policy.explicit);
    }
}