cargo-feature-combinations 0.2.1

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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
//! Run cargo commands for all feature combinations across a workspace.
//!
//! This crate powers the `cargo-fc` and `cargo-feature-combinations` binaries.
//! The main entry point for consumers is [`run`], which parses CLI arguments
//! and dispatches the requested command.

/// Resolve cargo command aliases from the `.cargo/config.toml` hierarchy.
mod cargo_alias;
/// Evaluate Cargo-style `cfg(...)` expressions against a concrete target.
pub mod cfg_eval;
/// CLI argument parsing, options, and help text.
mod cli;
/// Configuration types and resolution logic for feature combination generation.
pub mod config;
/// Diagnostics-only output mode (JSON parsing and deduplication).
mod diagnostics_only;
/// Feature implication graph and redundant-combination pruning.
pub mod implication;
/// JSON matrix output from resolved execution plans.
mod matrix;
/// Package-level configuration, feature combination generation, and error types.
pub mod package;
/// Planning stages that prepare target and execution plans before Cargo runs.
pub mod plan;
/// Cargo command execution, output parsing, summary printing, and matrix output.
mod runner;
/// Target triple handling and host/flag based detection.
pub mod target;
/// Optional Rust target installation.
mod target_install;
/// IO utilities.
mod tee;
/// Workspace-level configuration and package discovery.
pub mod workspace;

pub use cfg_eval::{CfgEvaluator, RustcCfgEvaluator};
pub use cli::{Command, Options, parse_arguments};
pub use config::patch::{FeatureSetVecPatch, StringSetPatch};
pub use config::resolve::resolve_config;
pub use config::{
    CommandCapabilities, Config, FlagConfig, ResolvedFlags, TargetOverride, WorkspaceConfig,
    WorkspaceTargetOverride,
};
pub use implication::{PruneResult, PrunedCombination, maybe_prune};
pub use matrix::build_matrix_rows;
pub use package::{FeatureCombinationError, Package};
pub use plan::execution::{
    ExecutionPlan, ExecutionPlanSet, PackageExecutionPlan, PlanBuildContext, build_execution_plans,
};
pub use plan::targets::{
    PlannedPackage, SelectedPackage, TargetPlan, TargetPlans, build_target_plans,
};
pub use runner::{ExitCode, TargetExecutionMode, run_execution_plans};
pub use target::{EffectiveTarget, TargetEnvironment, TargetSource, TargetTriple};
pub use workspace::Workspace;

use cli::cargo_subcommand;
use color_eyre::eyre;
use runner::print_feature_combination_error;
use std::process;
use target::RustcTargetEnvironment;

/// Yellow+bold color spec used by the [`print_warning!`] macro.
static WARNING_COLOR: std::sync::LazyLock<termcolor::ColorSpec> = std::sync::LazyLock::new(|| {
    let mut spec = termcolor::ColorSpec::new();
    spec.set_fg(Some(termcolor::Color::Yellow));
    spec.set_bold(true);
    spec
});

/// Cyan+bold color spec used by the [`print_note!`] macro.
static NOTE_COLOR: std::sync::LazyLock<termcolor::ColorSpec> = std::sync::LazyLock::new(|| {
    let mut spec = termcolor::ColorSpec::new();
    spec.set_fg(Some(termcolor::Color::Cyan));
    spec.set_bold(true);
    spec
});

/// Print a colored warning to stderr.
///
/// Formats as `warning: <message>` with the `warning:` prefix in yellow.
/// Accepts the same arguments as [`format!`].
macro_rules! print_warning {
    ($($arg:tt)*) => {{
        use std::io::Write as _;
        use termcolor::WriteColor as _;
        let mut stderr = termcolor::StandardStream::stderr(termcolor::ColorChoice::Auto);
        let _ = stderr.set_color(&$crate::WARNING_COLOR);
        let _ = write!(&mut stderr, "warning");
        let _ = stderr.reset();
        let _ = writeln!(&mut stderr, ": {}", format_args!($($arg)*));
    }};
}
pub(crate) use print_warning;

/// Print a colored informational note to stderr.
///
/// Formats as `note: <message>` with the `note:` prefix in cyan. Used for
/// non-fatal mode fallbacks/no-ops such as `--aggregate-targets` adjustments.
macro_rules! print_note {
    ($($arg:tt)*) => {{
        use std::io::Write as _;
        use termcolor::WriteColor as _;
        let mut stderr = termcolor::StandardStream::stderr(termcolor::ColorChoice::Auto);
        let _ = stderr.set_color(&$crate::NOTE_COLOR);
        let _ = write!(&mut stderr, "note");
        let _ = stderr.reset();
        let _ = writeln!(&mut stderr, ": {}", format_args!($($arg)*));
    }};
}
pub(crate) use print_note;

/// Whether to warn when the cargo subcommand is not one of the known commands
/// (`build`, `test`, `run`, `check`, `doc`, `clippy`). Disabled by default
/// because cargo aliases and custom subcommands are common and the tool handles
/// unresolved commands gracefully via best-effort output parsing.
const WARN_UNKNOWN_SUBCOMMAND: bool = false;

/// Expands to the default metadata key literal.
macro_rules! default_metadata_key {
    () => {
        "cargo-fc"
    };
}

/// All recognized metadata key aliases, tried in order during lookup.
///
/// Longest (most explicit) keys come first so that when a manifest
/// contains more than one alias the most specific one wins.
pub(crate) const METADATA_KEYS: &[&str] = &[
    "cargo-feature-combinations",
    "feature-combinations",
    "cargo-fc",
    "fc",
];

/// Default metadata key used in hints and help text when no existing
/// usage is detected.
pub(crate) const DEFAULT_METADATA_KEY: &str = default_metadata_key!();

/// Default dotted `package.metadata.<key>` path for per-package configuration
/// (no brackets; callers wrap it in `[...]`).
pub(crate) const DEFAULT_PKG_METADATA_SECTION: &str =
    concat!("package.metadata.", default_metadata_key!());

#[derive(Clone, Copy)]
struct CommandTokens<'a> {
    raw: Option<&'a str>,
    resolved: Option<&'a str>,
}

struct PreparedCargoCommand {
    args: Vec<String>,
    raw_token: Option<String>,
    resolved_token: Option<String>,
    cli_target: Option<String>,
    /// Aliases expanded through `cargo run ... --` keep Cargo's alias argument
    /// placement: generated matrix args are appended after the expansion.
    matrix_args_after_extra_args: bool,
}

impl PreparedCargoCommand {
    fn tokens(&self) -> CommandTokens<'_> {
        CommandTokens {
            raw: self.raw_token.as_deref(),
            resolved: self.resolved_token.as_deref(),
        }
    }
}

struct CargoCommandDispatch<'a> {
    bin_name: &'a str,
    target_plans: &'a plan::targets::TargetPlans<'a>,
    options: &'a Options,
    cargo_args: Vec<&'a str>,
    tokens: CommandTokens<'a>,
    matrix_args_after_extra_args: bool,
    workspace_config: &'a config::WorkspaceConfig,
    workspace_key: &'a str,
}

/// Look up configuration from any recognized metadata key alias.
///
/// Returns the first matching value and the alias that matched, or
/// `None` if none of the aliases are present.
pub(crate) fn find_metadata_value(
    metadata: &serde_json::Value,
) -> Option<(&serde_json::Value, &'static str)> {
    for &key in METADATA_KEYS {
        if let Some(value) = metadata.get(key) {
            return Some((value, key));
        }
    }
    None
}

/// Format the dotted `package.metadata.<key>` path (no brackets).
///
/// Callers wrap it in `[...]` and may append a sub-key, e.g.
/// `[{pkg_metadata_section(key)}.target.'cfg(...)']`.
pub(crate) fn pkg_metadata_section(key: &str) -> String {
    format!("package.metadata.{key}")
}

/// Format the dotted `workspace.metadata.<key>` path (no brackets).
///
/// Callers wrap it in `[...]` and may append a sub-key, e.g.
/// `[{ws_metadata_section(key)}.subcommands.<token>]`.
pub(crate) fn ws_metadata_section(key: &str) -> String {
    format!("workspace.metadata.{key}")
}

/// Run the cargo subcommand for all relevant feature combinations.
///
/// This is the main entry point used by the binaries in this crate.
///
/// # Errors
///
/// Returns an error if argument parsing fails or `cargo metadata` can not be
/// executed successfully.
pub fn run(bin_name: &str) -> eyre::Result<()> {
    color_eyre::install()?;

    let (options, cargo_args) = parse_arguments(bin_name)?;

    if let Some(Command::Help) = options.command {
        cli::print_help();
        return Ok(());
    }

    if let Some(Command::Version) = options.command {
        println!("cargo-{bin_name} v{}", env!("CARGO_PKG_VERSION"));
        return Ok(());
    }

    // Get metadata for cargo package
    let mut cmd = cargo_metadata::MetadataCommand::new();
    if let Some(ref manifest_path) = options.manifest_path {
        cmd.manifest_path(manifest_path);
    }
    let metadata = cmd.exec()?;

    let ws_config = metadata.workspace_config()?;
    // Discover candidate packages without applying workspace exclusions; those
    // (and their target-specific patches) are applied per target during
    // planning.
    let packages = select_candidate_packages(&metadata, &options)?;

    // Cache each selected package's base config once so planning and execution
    // never re-read the manifest (which would duplicate deprecation warnings).
    let configs: Vec<config::Config> = packages
        .iter()
        .map(|package| package.config())
        .collect::<eyre::Result<Vec<_>>>()?;

    let prepared = prepare_cargo_command(cargo_args, metadata.workspace_root.as_std_path());
    let tokens = prepared.tokens();
    let selected =
        selected_packages_for_target_planning(&packages, &configs, &options, &ws_config, tokens)?;

    // Echo the user's own metadata alias in capability hints/warnings.
    let ws_key = find_metadata_value(&metadata.workspace_metadata)
        .map_or(DEFAULT_METADATA_KEY, |(_, key)| key);
    warn_if_configured_targets_ignored(
        &options,
        tokens.raw,
        tokens.resolved,
        &ws_config,
        ws_key,
        &selected,
    );

    let env = RustcTargetEnvironment;
    let mut evaluator = RustcCfgEvaluator::default();
    let base_exclude = metadata.base_workspace_exclude_packages()?;

    let target_plans = plan::targets::build_target_plans(
        &selected,
        &ws_config,
        &base_exclude,
        prepared.cli_target.as_deref(),
        selected
            .iter()
            .any(|package| !package.ignore_configured_targets),
        &env,
        &mut evaluator,
    )?;

    let result = match options.command {
        Some(Command::Help | Command::Version) => Ok(None),
        Some(Command::FeatureMatrix { pretty }) => print_matrix_command(
            &target_plans,
            &options,
            &ws_config,
            tokens,
            pretty,
            &mut evaluator,
        ),
        None => run_cargo_command(
            CargoCommandDispatch {
                bin_name,
                target_plans: &target_plans,
                options: &options,
                cargo_args: prepared.args.iter().map(String::as_str).collect(),
                tokens,
                matrix_args_after_extra_args: prepared.matrix_args_after_extra_args,
                workspace_config: &ws_config,
                workspace_key: ws_key,
            },
            &env,
            &mut evaluator,
        ),
    };

    match result {
        Ok(Some(exit_code)) => process::exit(exit_code),
        Ok(None) => Ok(()),
        Err(err) => {
            if let Some(e) = err.downcast_ref::<FeatureCombinationError>() {
                print_feature_combination_error(e);
                process::exit(2);
            }
            Err(err)
        }
    }
}

fn prepare_cargo_command(
    args: Vec<String>,
    workspace_root: &std::path::Path,
) -> PreparedCargoCommand {
    let raw_token = cli::cargo_subcommand_token(&args);
    // Resolve cargo command aliases so target policy and build-driver dispatch
    // see the underlying built-in subcommand when one is configured.
    let alias_expansion = cargo_alias::expand_aliases_with_info(args, workspace_root);
    let expanded_args = alias_expansion.args;
    let resolved_token = cli::cargo_subcommand_token(&expanded_args);
    let cli_target = target::parse_cli_target(&expanded_args);
    let matrix_args_after_extra_args = alias_expansion.expanded
        && matches!(
            cargo_subcommand(expanded_args.as_slice()),
            cli::CargoSubcommand::Run
        )
        && expanded_args.iter().any(|arg| arg == "--");

    PreparedCargoCommand {
        args: expanded_args,
        raw_token,
        resolved_token,
        cli_target,
        matrix_args_after_extra_args,
    }
}

fn selected_packages_for_target_planning<'a>(
    packages: &[&'a cargo_metadata::Package],
    configs: &'a [config::Config],
    options: &Options,
    ws_config: &config::WorkspaceConfig,
    tokens: CommandTokens<'_>,
) -> eyre::Result<Vec<plan::targets::SelectedPackage<'a>>> {
    let command_token = tokens.resolved.or(tokens.raw);
    let default_target_capability = matches!(options.command, Some(Command::FeatureMatrix { .. }))
        || cli::builtin_target_capability(command_token);
    let default_diagnostics_allowed = cli::builtin_diagnostics_safe(command_token);

    let mut selected = Vec::new();
    let empty_target_subcommands = std::collections::BTreeMap::new();
    for (package, package_config) in packages.iter().zip(configs) {
        let command_config = config::resolve_command_config(config::ResolveCommandConfigArgs {
            workspace: ws_config,
            workspace_target_flags: config::FlagConfig::default(),
            workspace_target_subcommands: &empty_target_subcommands,
            package_flags: package_config.flags,
            package_subcommands: &package_config.subcommand_overrides,
            package_target_flags: config::FlagConfig::default(),
            package_target_subcommands: &empty_target_subcommands,
            raw_command: tokens.raw,
            resolved_command: tokens.resolved,
            cli_flags: options.flags,
            default_diagnostics_allowed,
            default_targets_enabled: default_target_capability,
        })?;
        selected.push(plan::targets::SelectedPackage {
            package,
            config: package_config,
            ignore_configured_targets: command_config.flags.no_targets
                || !command_config.targets_enabled,
            target_decision_explicit: command_config.flags.no_targets
                || command_config.targets_explicit,
        });
    }
    Ok(selected)
}

fn print_matrix_command(
    target_plans: &plan::targets::TargetPlans<'_>,
    options: &Options,
    workspace: &config::WorkspaceConfig,
    tokens: CommandTokens<'_>,
    pretty: bool,
    evaluator: &mut impl cfg_eval::CfgEvaluator,
) -> eyre::Result<ExitCode> {
    let context = plan::execution::PlanBuildContext {
        workspace_config: workspace,
        raw_command: tokens.raw,
        resolved_command: tokens.resolved,
        default_diagnostics_allowed: false,
        matrix: true,
    };
    let plan_set =
        plan::execution::build_execution_plans(target_plans, options.flags, &context, evaluator)?;
    note_matrix_noop_flags(options);
    matrix::print_matrix_for_execution_plans(&plan_set, pretty)?;
    Ok(None)
}

fn run_cargo_command(
    dispatch: CargoCommandDispatch<'_>,
    env: &impl target::TargetEnvironment,
    evaluator: &mut impl cfg_eval::CfgEvaluator,
) -> eyre::Result<ExitCode> {
    if WARN_UNKNOWN_SUBCOMMAND
        && cargo_subcommand(dispatch.cargo_args.as_slice()) == cli::CargoSubcommand::Other
    {
        print_warning!(
            "`cargo {}` only supports cargo's `build`, `test`, `run`, `check`, `doc`, and `clippy` subcommands",
            dispatch.bin_name,
        );
    }

    let options = dispatch.options;
    let default_diagnostics_allowed =
        cli::builtin_diagnostics_safe(dispatch.tokens.resolved.or(dispatch.tokens.raw));
    let context = plan::execution::PlanBuildContext {
        workspace_config: dispatch.workspace_config,
        raw_command: dispatch.tokens.raw,
        resolved_command: dispatch.tokens.resolved,
        default_diagnostics_allowed,
        matrix: false,
    };
    let plan_set = plan::execution::build_execution_plans(
        dispatch.target_plans,
        options.flags,
        &context,
        evaluator,
    )?;
    maybe_install_missing_targets(&plan_set, env, &dispatch.cargo_args)?;
    let mode = resolve_execution_mode(&dispatch.cargo_args, &plan_set);
    let driver = resolve_driver(options, dispatch.workspace_config, &plan_set, env)?;
    warn_ignored_diagnostics_config(
        options,
        dispatch.tokens.raw,
        dispatch.tokens.resolved,
        dispatch.workspace_key,
        &plan_set,
    );
    runner::run_execution_plans(
        &plan_set,
        dispatch.cargo_args,
        mode,
        driver.as_deref(),
        dispatch.matrix_args_after_extra_args,
    )
}

/// Discover candidate workspace packages and apply CLI-level package filters.
///
/// Workspace `exclude_packages` (and its target-specific patches) are applied
/// later, per target, by the planner — not here.
fn select_candidate_packages<'a>(
    metadata: &'a cargo_metadata::Metadata,
    options: &Options,
) -> eyre::Result<Vec<&'a cargo_metadata::Package>> {
    let mut packages = metadata.candidate_packages_for_fc()?;

    // When `--manifest-path` points to a workspace member, `cargo metadata`
    // still returns the entire workspace. Unless the user explicitly selected
    // packages via `-p/--package`, default to only processing the root package
    // resolved by Cargo for the given manifest.
    if options.manifest_path.is_some()
        && options.packages.is_empty()
        && let Some(root) = metadata.root_package()
    {
        packages.retain(|p| p.id == root.id);
    }

    // Filter excluded packages via CLI arguments
    packages.retain(|p| !options.exclude_packages.contains(p.name.as_str()));

    // Filter packages based on CLI options
    if !options.packages.is_empty() {
        packages.retain(|p| options.packages.contains(p.name.as_str()));
    }

    Ok(packages)
}

fn maybe_install_missing_targets(
    plan_set: &plan::execution::ExecutionPlanSet<'_>,
    env: &impl target::TargetEnvironment,
    cargo_args: &[&str],
) -> eyre::Result<()> {
    if plan_set.plans.iter().any(|plan| {
        plan.package_plans
            .iter()
            .any(|package_plan| package_plan.flags.install_missing_targets)
    }) {
        let installer =
            target_install::RustupTargetInstaller::new(cli::rustup_toolchain(cargo_args));
        target_install::ensure_missing_targets_installed(plan_set, env, &installer)?;
    }
    Ok(())
}

/// Warn once when configured targets were skipped only because of the built-in
/// unknown-command default.
///
/// `matrix` is not a forwarded cargo command: it always uses configured target
/// planning.
fn warn_if_configured_targets_ignored(
    options: &Options,
    raw_token: Option<&str>,
    resolved_token: Option<&str>,
    ws_config: &config::WorkspaceConfig,
    ws_key: &str,
    selected: &[plan::targets::SelectedPackage<'_>],
) {
    // `--no-targets` deliberately ignores configured target lists and falls back
    // to Cargo's default single target, so it should not also warn.
    if options.flags.no_targets == Some(true) {
        return;
    }

    if selected
        .iter()
        .any(|package| !package.ignore_configured_targets)
    {
        return;
    }

    // `matrix` is not a forwarded cargo command: it always uses configured
    // target planning.
    if matches!(options.command, Some(Command::FeatureMatrix { .. })) {
        return;
    }

    let has_implicitly_skipped_configured_targets = selected.iter().any(|package| {
        !package.target_decision_explicit
            && (!ws_config.workspace_targets.is_empty()
                || package
                    .config
                    .package_targets
                    .as_ref()
                    .is_some_and(|targets| !targets.is_empty()))
    });
    let warning_token = raw_token.or(resolved_token);
    if cli::known_quiet_cargo_subcommand(raw_token)
        || cli::known_quiet_cargo_subcommand(resolved_token)
    {
        return;
    }
    if has_implicitly_skipped_configured_targets
        && let Some(token) = warning_token.filter(|t| !t.is_empty())
    {
        print_warning!(
            "not passing configured targets to cargo command `{token}` because it has no targets capability"
        );
        eprintln!(
            "hint: add [{}.subcommands.{token}] targets = true if this command accepts --target, or targets = false to silence this warning",
            ws_metadata_section(ws_key),
        );
    }
}

fn warn_ignored_diagnostics_config(
    options: &Options,
    raw_token: Option<&str>,
    resolved_token: Option<&str>,
    ws_key: &str,
    plan_set: &plan::execution::ExecutionPlanSet<'_>,
) {
    let cli_flags = options.flags;
    if cli::known_quiet_cargo_subcommand(raw_token)
        || cli::known_quiet_cargo_subcommand(resolved_token)
    {
        return;
    }
    if cli_flags.diagnostics_only != Some(true)
        && cli_flags.dedupe != Some(true)
        && plan_set.plans.iter().any(|plan| {
            plan.package_plans.iter().any(|package_plan| {
                package_plan.ignored_diagnostics_config && !package_plan.flags.diagnostics_only
            })
        })
        && let Some(token) = raw_token.or(resolved_token).filter(|t| !t.is_empty())
    {
        print_warning!(
            "not enabling configured diagnostics-only/dedupe for cargo command `{token}` because it is not diagnostics-safe by default"
        );
        eprintln!(
            "hint: set [{}.subcommands.{token}] diagnostics_only = true or dedupe = true to force diagnostics mode for this command, or diagnostics_only = false to silence this warning",
            ws_metadata_section(ws_key),
        );
    }
}

/// Emit one note per run-only flag that has no effect on `cargo fc matrix`
/// output, so the silent no-op is visible to the user.
fn note_matrix_noop_flags(options: &Options) {
    let flags = options.flags;
    if flags.install_missing_targets == Some(true) {
        print_note!(
            "--install-missing-targets has no effect for matrix output; matrix only prints planned targets"
        );
    }
    if flags.aggregate_targets == Some(true) {
        print_note!(
            "--aggregate-targets has no effect for matrix output; matrix rows are always per target"
        );
    }
    if options.driver.is_some() {
        print_note!("--driver has no effect for matrix output; matrix only prints planned targets");
    }
}

/// Resolve the build driver used to spawn each combination.
///
/// An explicit `--driver` or `[workspace.metadata.cargo-fc].driver` always wins.
/// Otherwise cargo-fc defaults to `cargo-zigbuild` when any non-host target is
/// planned — so crates with native-C build dependencies cross-compile via zig —
/// and to plain `cargo` (`None`, i.e. `$CARGO`) for host-only runs. Users who
/// want a different wrapper, or plain `cargo` even when cross-compiling, set
/// `driver` explicitly.
fn resolve_driver(
    options: &Options,
    ws_config: &config::WorkspaceConfig,
    plan_set: &plan::execution::ExecutionPlanSet,
    env: &impl target::TargetEnvironment,
) -> eyre::Result<Option<String>> {
    if let Some(driver) = &options.driver {
        return normalize_driver(driver, "--driver");
    }
    if let Some(driver) = &ws_config.driver {
        return normalize_driver(driver, "[workspace.metadata.cargo-fc].driver");
    }
    if plan_set.plans.is_empty() {
        return Ok(None);
    }
    // Detecting the host is only needed to decide whether any planned target is a
    // cross target. If that fails, fall back to plain `cargo` (the conservative
    // default) instead of aborting the whole run, mirroring how missing-target
    // installation degrades on the same failure.
    let host = match env.host_target() {
        Ok(host) => host,
        Err(err) => {
            print_warning!(
                "could not detect host target to select a build driver: {err}; using plain cargo"
            );
            return Ok(None);
        }
    };
    let cross = plan_set.plans.iter().any(|plan| plan.target != host);
    if cross {
        Ok(Some("cargo-zigbuild".to_string()))
    } else {
        Ok(None)
    }
}

fn normalize_driver(driver: &str, source: &str) -> eyre::Result<Option<String>> {
    let driver = driver.trim();
    if driver.is_empty() {
        eyre::bail!("{source} must not be empty");
    }
    // `driver = "cargo"` selects plain Cargo; resolve it to `None` so the spawn
    // still honors `$CARGO` (e.g. a rustup or CI override), matching the default
    // host-only path rather than forcing the literal `cargo` on `PATH`.
    if driver == "cargo" {
        Ok(None)
    } else {
        Ok(Some(driver.to_string()))
    }
}

/// Resolve the effective target execution mode, emitting a note when an
/// explicitly requested `--aggregate-targets` falls back to serial or is a
/// no-op.
fn resolve_execution_mode(
    cargo_args: &[&str],
    plan_set: &plan::execution::ExecutionPlanSet<'_>,
) -> runner::TargetExecutionMode {
    use runner::TargetExecutionMode;

    let mut requested = 0usize;
    let mut total = 0usize;
    for plan in &plan_set.plans {
        for package_plan in &plan.package_plans {
            total += 1;
            requested += usize::from(package_plan.flags.aggregate_targets);
        }
    }

    if requested == 0 {
        return TargetExecutionMode::SerialPerTarget;
    }

    if requested != total {
        print_note!(
            "aggregate target execution is disabled because it resolves differently across package-targets; running targets serially"
        );
        return TargetExecutionMode::SerialPerTarget;
    }

    if plan_set.plans.len() <= 1 {
        if !plan_set.show_target {
            return TargetExecutionMode::SerialPerTarget;
        }
        print_note!("--aggregate-targets has no effect for a single target; running normally");
        return TargetExecutionMode::SerialPerTarget;
    }

    if cargo_subcommand(cargo_args) == cli::CargoSubcommand::Run {
        print_note!(
            "--aggregate-targets does not apply to `run` (cargo runs one target at a time); running targets serially"
        );
        return TargetExecutionMode::SerialPerTarget;
    }

    if plan_set.show_pruned {
        print_note!(
            "--aggregate-targets is disabled because pruned summaries are target-specific; running targets serially"
        );
        return TargetExecutionMode::SerialPerTarget;
    }

    TargetExecutionMode::Aggregate
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::package::test::package as test_package;
    use assert_fs::TempDir;
    use assert_fs::prelude::*;
    use color_eyre::eyre;
    use serde_json::json;

    fn workspace_with_aliases(body: &str) -> eyre::Result<TempDir> {
        let tmp = TempDir::new()?;
        tmp.child(".cargo").create_dir_all()?;
        tmp.child(".cargo/config.toml").write_str(body)?;
        Ok(tmp)
    }

    fn execution_plan_set(
        targets: &[&str],
        show_pruned: bool,
    ) -> plan::execution::ExecutionPlanSet<'static> {
        plan::execution::ExecutionPlanSet {
            plans: targets
                .iter()
                .map(|target| plan::execution::ExecutionPlan {
                    target: target::TargetTriple((*target).to_string()),
                    package_plans: Vec::new(),
                })
                .collect(),
            show_pruned,
            show_target: targets.len() > 1,
        }
    }

    fn execution_plan_set_with_flags<'a>(
        targets: &[&str],
        show_pruned: bool,
        package: &'a cargo_metadata::Package,
        flags: config::ResolvedFlags,
    ) -> plan::execution::ExecutionPlanSet<'a> {
        plan::execution::ExecutionPlanSet {
            plans: targets
                .iter()
                .map(|target| {
                    let target = target::TargetTriple((*target).to_string());
                    plan::execution::ExecutionPlan {
                        target: target.clone(),
                        package_plans: vec![plan::execution::PackageExecutionPlan {
                            package,
                            target: target::EffectiveTarget {
                                triple: target,
                                source: target::TargetSource::WorkspaceConfig,
                            },
                            combinations: Vec::new(),
                            pruned: Vec::new(),
                            matrix: serde_json::Map::new(),
                            flags,
                            ignored_diagnostics_config: false,
                        }],
                    }
                })
                .collect(),
            show_pruned,
            show_target: targets.len() > 1,
        }
    }

    struct DriverTestEnv {
        host: Option<&'static str>,
    }

    impl target::TargetEnvironment for DriverTestEnv {
        fn cargo_build_target(&self) -> Option<String> {
            None
        }

        fn host_target(&self) -> eyre::Result<target::TargetTriple> {
            let Some(host) = self.host else {
                eyre::bail!("host failed");
            };
            Ok(target::TargetTriple(host.to_string()))
        }
    }

    fn target_selection_state(
        options: &Options,
        ws: &config::WorkspaceConfig,
        raw: Option<&str>,
        resolved: Option<&str>,
    ) -> eyre::Result<(bool, bool)> {
        let package = test_package("a")?;
        let config = config::Config::default();
        let packages = [&package];
        let configs = [config];
        let selected = selected_packages_for_target_planning(
            &packages,
            &configs,
            options,
            ws,
            CommandTokens { raw, resolved },
        )?;
        let [selected] = selected.as_slice() else {
            eyre::bail!("expected one selected package, got {}", selected.len());
        };
        Ok((
            selected.ignore_configured_targets,
            selected.target_decision_explicit,
        ))
    }

    #[test]
    fn prepare_cargo_command_marks_nested_run_wrapper_aliases() -> eyre::Result<()> {
        let workspace = workspace_with_aliases(
            r#"
            [alias]
            clippy-wrapper = "run --package clippy-wrapper --"
            lint = "clippy-wrapper lint"
            "#,
        )?;

        let prepared = prepare_cargo_command(vec!["lint".to_string()], workspace.path());

        assert_eq!(prepared.raw_token.as_deref(), Some("lint"));
        assert_eq!(prepared.resolved_token.as_deref(), Some("run"));
        assert!(prepared.matrix_args_after_extra_args);
        assert_eq!(
            prepared.args,
            vec!["run", "--package", "clippy-wrapper", "--", "lint"],
        );
        Ok(())
    }

    #[test]
    fn prepare_cargo_command_keeps_direct_run_args_on_cargo_side() -> eyre::Result<()> {
        let workspace = workspace_with_aliases("[alias]\n")?;

        let prepared = prepare_cargo_command(
            vec!["run".to_string(), "--".to_string(), "lint".to_string()],
            workspace.path(),
        );

        assert_eq!(prepared.raw_token.as_deref(), Some("run"));
        assert_eq!(prepared.resolved_token.as_deref(), Some("run"));
        assert!(!prepared.matrix_args_after_extra_args);
        Ok(())
    }

    #[test]
    fn prepare_cargo_command_preserves_run_alias_argument_position() -> eyre::Result<()> {
        let workspace = workspace_with_aliases(
            r#"
            [alias]
            serve = "run --package app -- serve"
            "#,
        )?;

        let prepared = prepare_cargo_command(vec!["serve".to_string()], workspace.path());

        assert_eq!(prepared.raw_token.as_deref(), Some("serve"));
        assert_eq!(prepared.resolved_token.as_deref(), Some("run"));
        assert!(prepared.matrix_args_after_extra_args);
        assert_eq!(
            prepared.args,
            vec!["run", "--package", "app", "--", "serve"],
        );
        Ok(())
    }

    #[test]
    fn resolve_driver_defaults_to_plain_cargo_for_host_only_plan() -> eyre::Result<()> {
        let driver = resolve_driver(
            &Options::default(),
            &config::WorkspaceConfig::default(),
            &execution_plan_set(&["host"], false),
            &DriverTestEnv { host: Some("host") },
        )?;

        assert_eq!(driver, None);
        Ok(())
    }

    #[test]
    fn resolve_driver_defaults_to_zigbuild_for_cross_plan() -> eyre::Result<()> {
        let driver = resolve_driver(
            &Options::default(),
            &config::WorkspaceConfig::default(),
            &execution_plan_set(&["host", "wasm"], false),
            &DriverTestEnv { host: Some("host") },
        )?;

        assert_eq!(driver, Some("cargo-zigbuild".to_string()));
        Ok(())
    }

    #[test]
    fn resolve_driver_treats_explicit_cargo_as_plain_cargo() -> eyre::Result<()> {
        let options = Options {
            driver: Some("cargo".to_string()),
            ..Options::default()
        };
        let driver = resolve_driver(
            &options,
            &config::WorkspaceConfig::default(),
            &execution_plan_set(&["host", "wasm"], false),
            &DriverTestEnv { host: Some("host") },
        )?;

        assert_eq!(driver, None);
        Ok(())
    }

    #[test]
    fn resolve_driver_uses_explicit_custom_driver() -> eyre::Result<()> {
        let options = Options {
            driver: Some("cross".to_string()),
            ..Options::default()
        };
        let driver = resolve_driver(
            &options,
            &config::WorkspaceConfig::default(),
            &execution_plan_set(&["host"], false),
            &DriverTestEnv { host: Some("host") },
        )?;

        assert_eq!(driver, Some("cross".to_string()));
        Ok(())
    }

    #[test]
    fn resolve_driver_falls_back_to_plain_cargo_when_host_detection_fails() -> eyre::Result<()> {
        let driver = resolve_driver(
            &Options::default(),
            &config::WorkspaceConfig::default(),
            &execution_plan_set(&["wasm"], false),
            &DriverTestEnv { host: None },
        )?;

        assert_eq!(driver, None);
        Ok(())
    }

    #[test]
    fn aggregate_execution_mode_selected_for_supported_multi_target_command() -> eyre::Result<()> {
        let package = test_package("a")?;
        let flags = config::ResolvedFlags {
            aggregate_targets: true,
            ..config::ResolvedFlags::default()
        };
        let plan_set = execution_plan_set_with_flags(&["t1", "t2"], false, &package, flags);

        assert_eq!(
            resolve_execution_mode(&["check"], &plan_set),
            runner::TargetExecutionMode::Aggregate
        );
        Ok(())
    }

    #[test]
    fn aggregate_execution_mode_falls_back_for_run() -> eyre::Result<()> {
        let package = test_package("a")?;
        let flags = config::ResolvedFlags {
            aggregate_targets: true,
            ..config::ResolvedFlags::default()
        };
        let plan_set = execution_plan_set_with_flags(&["t1", "t2"], false, &package, flags);

        assert_eq!(
            resolve_execution_mode(&["run"], &plan_set),
            runner::TargetExecutionMode::SerialPerTarget
        );
        Ok(())
    }

    #[test]
    fn aggregate_execution_mode_falls_back_for_pruned_summaries() -> eyre::Result<()> {
        let package = test_package("a")?;
        let flags = config::ResolvedFlags {
            aggregate_targets: true,
            ..config::ResolvedFlags::default()
        };
        let plan_set = execution_plan_set_with_flags(&["t1", "t2"], true, &package, flags);

        assert_eq!(
            resolve_execution_mode(&["check"], &plan_set),
            runner::TargetExecutionMode::SerialPerTarget
        );
        Ok(())
    }

    #[test]
    fn aggregate_execution_mode_is_noop_for_single_target() -> eyre::Result<()> {
        let package = test_package("a")?;
        let flags = config::ResolvedFlags {
            aggregate_targets: true,
            ..config::ResolvedFlags::default()
        };
        let plan_set = execution_plan_set_with_flags(&["t1"], false, &package, flags);

        assert_eq!(
            resolve_execution_mode(&["check"], &plan_set),
            runner::TargetExecutionMode::SerialPerTarget
        );
        Ok(())
    }

    #[test]
    fn no_targets_flag_disables_configured_targets() -> eyre::Result<()> {
        let options = Options {
            flags: config::FlagConfig {
                no_targets: Some(true),
                ..config::FlagConfig::default()
            },
            ..Options::default()
        };
        let ws = config::WorkspaceConfig::default();
        let (ignore_configured_targets, target_decision_explicit) =
            target_selection_state(&options, &ws, Some("check"), Some("check"))?;

        assert!(ignore_configured_targets);
        assert!(target_decision_explicit);
        Ok(())
    }

    #[test]
    fn builtin_command_allows_capability_without_no_targets() -> eyre::Result<()> {
        let options = Options::default();
        let ws = config::WorkspaceConfig::default();
        let (ignore_configured_targets, target_decision_explicit) =
            target_selection_state(&options, &ws, Some("check"), Some("check"))?;

        assert!(!ignore_configured_targets);
        assert!(!target_decision_explicit);
        Ok(())
    }

    #[test]
    fn builtin_command_can_be_disabled_by_workspace_policy() -> eyre::Result<()> {
        let options = Options::default();
        let mut ws = config::WorkspaceConfig::default();
        ws.subcommand_overrides.insert(
            "build".to_string(),
            config::CommandCapabilities {
                targets: Some(false),
                ..config::CommandCapabilities::default()
            },
        );
        let (ignore_configured_targets, target_decision_explicit) =
            target_selection_state(&options, &ws, Some("build"), Some("build"))?;

        assert!(ignore_configured_targets);
        assert!(target_decision_explicit);
        Ok(())
    }

    #[test]
    fn resolved_alias_inherits_builtin_capability_by_default() -> eyre::Result<()> {
        let options = Options::default();
        let ws = config::WorkspaceConfig::default();
        let (ignore_configured_targets, target_decision_explicit) =
            target_selection_state(&options, &ws, Some("lint"), Some("clippy"))?;

        assert!(!ignore_configured_targets);
        assert!(!target_decision_explicit);
        Ok(())
    }

    #[test]
    fn explicit_alias_policy_wins_over_resolved_builtin_policy() -> eyre::Result<()> {
        let options = Options::default();
        let mut ws = config::WorkspaceConfig::default();
        ws.subcommand_overrides.insert(
            "lint".to_string(),
            config::CommandCapabilities {
                targets: Some(false),
                ..config::CommandCapabilities::default()
            },
        );
        let (ignore_configured_targets, target_decision_explicit) =
            target_selection_state(&options, &ws, Some("lint"), Some("clippy"))?;

        assert!(ignore_configured_targets);
        assert!(target_decision_explicit);
        Ok(())
    }

    #[test]
    fn explicit_alias_policy_can_enable_unresolved_expanded_command() -> eyre::Result<()> {
        let options = Options::default();
        let mut ws = config::WorkspaceConfig::default();
        ws.subcommand_overrides.insert(
            "lint".to_string(),
            config::CommandCapabilities {
                targets: Some(true),
                ..config::CommandCapabilities::default()
            },
        );
        let (ignore_configured_targets, target_decision_explicit) =
            target_selection_state(&options, &ws, Some("lint"), Some("custom-wrapper"))?;

        assert!(!ignore_configured_targets);
        assert!(target_decision_explicit);
        Ok(())
    }

    #[test]
    fn no_targets_flag_disables_configured_targets_for_matrix() -> eyre::Result<()> {
        let options = Options {
            command: Some(Command::FeatureMatrix { pretty: false }),
            flags: config::FlagConfig {
                no_targets: Some(true),
                ..config::FlagConfig::default()
            },
            ..Options::default()
        };
        let ws = config::WorkspaceConfig::default();
        let (ignore_configured_targets, target_decision_explicit) =
            target_selection_state(&options, &ws, None, None)?;

        assert!(ignore_configured_targets);
        assert!(target_decision_explicit);
        Ok(())
    }

    #[test]
    fn find_metadata_value_returns_none_for_empty_object() {
        let meta = json!({});
        assert!(find_metadata_value(&meta).is_none());
    }

    #[test]
    fn find_metadata_value_returns_none_for_unrelated_keys() {
        let meta = json!({ "other-tool": { "key": "value" } });
        assert!(find_metadata_value(&meta).is_none());
    }

    #[test]
    fn find_metadata_value_finds_each_alias() -> eyre::Result<()> {
        for &alias in METADATA_KEYS {
            let meta = json!({ alias: { "exclude_features": ["default"] } });
            let (value, matched) =
                find_metadata_value(&meta).ok_or_else(|| eyre::eyre!("no match for {alias}"))?;
            assert_eq!(matched, alias);
            assert!(value.get("exclude_features").is_some());
        }
        Ok(())
    }

    #[test]
    fn find_metadata_value_prefers_longest_alias() -> eyre::Result<()> {
        let meta = json!({
            "cargo-feature-combinations": { "source": "long" },
            "fc": { "source": "short" },
        });
        let (value, matched) = find_metadata_value(&meta).ok_or_else(|| eyre::eyre!("no match"))?;
        assert_eq!(matched, "cargo-feature-combinations");
        assert_eq!(value["source"], "long");
        Ok(())
    }

    #[test]
    fn find_metadata_value_prefers_cargo_fc_over_fc() -> eyre::Result<()> {
        let meta = json!({
            "cargo-fc": { "source": "cargo-fc" },
            "fc": { "source": "fc" },
        });
        let (_, matched) = find_metadata_value(&meta).ok_or_else(|| eyre::eyre!("no match"))?;
        assert_eq!(matched, "cargo-fc");
        Ok(())
    }

    #[test]
    fn pkg_metadata_section_formats_correctly() {
        assert_eq!(
            pkg_metadata_section("cargo-fc"),
            "package.metadata.cargo-fc"
        );
        assert_eq!(pkg_metadata_section("fc"), "package.metadata.fc");
    }

    #[test]
    fn ws_metadata_section_formats_correctly() {
        assert_eq!(
            ws_metadata_section("cargo-fc"),
            "workspace.metadata.cargo-fc"
        );
    }

    #[test]
    fn default_metadata_key_is_cargo_fc() {
        assert_eq!(DEFAULT_METADATA_KEY, "cargo-fc");
    }

    #[test]
    fn default_pkg_metadata_section_uses_default_key() {
        assert_eq!(DEFAULT_PKG_METADATA_SECTION, "package.metadata.cargo-fc");
    }
}