cargo-feature-combinations 0.7.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
//! Build resolved execution plans from target plans.

use crate::cfg_eval::CfgEvaluator;
use crate::config::{Chain, EnvValue, FlagConfig, ResolvedEnv, ResolvedFlags, WorkspaceConfig};
use crate::implication::PrunedCombination;
use crate::package::{Package, has_lib_target};
use crate::plan::targets::{TargetPlan, TargetPlans};
use crate::print_warning;
use crate::target::{EffectiveTarget, TargetSource, TargetTriple};
use color_eyre::eyre;
use std::collections::BTreeMap;

/// Inputs that affect cargo-fc flag resolution while building execution plans.
pub struct PlanBuildContext<'a> {
    /// Workspace configuration read from the root manifest.
    pub workspace_config: &'a WorkspaceConfig,
    /// Literal command token from the user before alias expansion.
    pub raw_command: Option<&'a str>,
    /// Command token after cargo alias expansion.
    pub resolved_command: Option<&'a str>,
    /// Explicit `--driver <bin>` override; overlaid last in driver resolution.
    pub cli_driver: Option<&'a str>,
    /// Explicit `--env KEY=VALUE` overlays, applied after scoped config.
    pub cli_env_set: &'a [(String, EnvValue)],
    /// Explicit `--unset-env KEY` overlays, applied before CLI additions.
    pub cli_env_remove: &'a [String],
    /// Whether broad diagnostics config is safe for the resolved command.
    pub default_diagnostics_allowed: bool,
    /// The run's host triple, resolved once at startup; `None` when detection
    /// failed. Stored on the built [`ExecutionPlanSet`] so execution can tell
    /// native plans from cross plans.
    pub host: Option<TargetTriple>,
    /// Whether these plans are for `cargo fc matrix`.
    pub matrix: bool,
}

/// A resolved, owned execution plan for one concrete target.
///
/// After [`build_execution_plans`], execution owns a deterministic sequence of
/// resolved `(package, target, combinations, pruned)` units and needs neither a
/// [`CfgEvaluator`] nor package configs.
pub struct ExecutionPlan<'a> {
    /// The concrete target triple this plan is for.
    pub target: TargetTriple,
    /// The per-package execution plans for this target, in plan order.
    pub package_plans: Vec<PackageExecutionPlan<'a>>,
}

/// A resolved, owned execution plan for one package on one target.
pub struct PackageExecutionPlan<'a> {
    /// The package.
    pub package: &'a cargo_metadata::Package,
    /// The concrete target and where it came from.
    pub target: EffectiveTarget,
    /// Feature combinations to execute, in deterministic (sorted) order.
    pub combinations: Vec<Vec<String>>,
    /// Combinations pruned as implied by another combination.
    pub pruned: Vec<PrunedCombination>,
    /// Resolved user matrix metadata for this package-target (matrix output
    /// only; the executor ignores it).
    pub matrix: serde_json::Map<String, serde_json::Value>,
    /// Fully resolved cargo-fc flags for this package-target.
    pub flags: ResolvedFlags,
    /// Build driver resolved from config + `--driver` for this
    /// (package × target × command), before cargo-fc's cross-target default is
    /// applied. `None` means "unset"; `Some("cargo")` means explicit plain
    /// cargo. Finalized to the spawned program by [`crate`]'s driver pass.
    pub driver: Option<String>,
    /// Environment patch for this matrix-cell Cargo process.
    pub env: ResolvedEnv,
    /// Whether broad config requested diagnostics mode but was ignored because
    /// this command is not diagnostics-safe by default.
    pub ignored_diagnostics_config: bool,
}

/// The full set of execution plans plus display flags.
pub struct ExecutionPlanSet<'a> {
    /// Execution plans in deterministic target-plan order.
    pub plans: Vec<ExecutionPlan<'a>>,
    /// Whether pruned combinations should be shown in the summary.
    pub show_pruned: bool,
    /// Whether the `target = ...` field should be shown (not the implicit
    /// single-host default).
    pub show_target: bool,
    /// The run's host triple, resolved once at startup and carried in from
    /// [`PlanBuildContext`]. `None` when host detection failed.
    ///
    /// Execution reads it to decide which plans are native: the driver default
    /// and the injected `--target` flags both differ for the host.
    pub host: Option<TargetTriple>,
}

impl ExecutionPlanSet<'_> {
    /// The `--target <triple>` flags cargo-fc must inject for one invocation.
    ///
    /// An invocation that builds only the host target gets none: Cargo already
    /// defaults to the host, and passing the flag anyway moves the build under
    /// `target/<triple>/`, where an ordinary `cargo build` — which passes no
    /// `--target` — cannot reuse any of it. Cargo also applies `build.rustflags`
    /// to build scripts and proc macros only when no `--target` is given, so the
    /// flag would additionally fingerprint those units differently from every
    /// other build in the same directory.
    ///
    /// An aggregated invocation that mixes the host with cross targets keeps
    /// every flag, including the host's: dropping one would silently narrow what
    /// Cargo builds.
    ///
    /// `omit_host_target_flag = false` opts out, for a workspace that wants the
    /// host row to build under `target/<triple>/` like every other configured
    /// target — for uniform artifact paths, or to keep `build.rustflags` off
    /// host units.
    pub(crate) fn inject_target_args<'t>(
        &self,
        targets: impl IntoIterator<Item = &'t EffectiveTarget>,
        flags: ResolvedFlags,
    ) -> Vec<String> {
        let triples: Vec<String> = targets
            .into_iter()
            .filter(|target| target.source.should_inject_target_arg())
            .map(|target| target.triple.0.clone())
            .collect();
        if flags.inject_host_target_flag {
            return triples;
        }
        match (triples.as_slice(), self.host.as_ref()) {
            ([only], Some(host)) if only.as_str() == host.as_str() => Vec::new(),
            _ => triples,
        }
    }
}

/// Build owned execution plans from target plans and command context.
///
/// Resolves each package assignment's target-specific config from the cached
/// `PlannedPackage::config` (never re-reading the manifest), generates and
/// prunes feature combinations, and stores owned feature strings so execution
/// borrows nothing from temporary configs.
///
/// When resolved `packages_only` is set, feature generation is skipped (matrix
/// output only needs one `"default"` row per package-target).
///
/// # Errors
///
/// Returns an error if a package's config can not be resolved or its feature
/// combinations can not be generated.
pub fn build_execution_plans<'a>(
    target_plans: &TargetPlans<'a>,
    cli_flags: FlagConfig,
    context: &PlanBuildContext<'_>,
    evaluator: &mut impl CfgEvaluator,
) -> eyre::Result<ExecutionPlanSet<'a>> {
    let mut plans = Vec::with_capacity(target_plans.plans.len());
    let mut config_show_pruned = false;
    let mut config_show_target = false;
    let mut package_status = BTreeMap::new();

    for target_plan in &target_plans.plans {
        let mut package_plans = Vec::with_capacity(target_plan.packages.len());
        // Command-aware workspace package exclusion for this target and command.
        let excluded = Chain::workspace(
            context.workspace_config,
            &target_plan.ws_matched,
            context.raw_command,
            context.resolved_command,
        )
        .exclude_packages(&target_plans.base_exclude)?;
        for planned in &target_plan.packages {
            if excluded.contains(planned.package.name.as_str()) {
                continue;
            }
            let status = package_status
                .entry(planned.package.id.repr.clone())
                .or_insert_with(|| PackagePlanningStatus {
                    name: planned.package.name.to_string(),
                    ..PackagePlanningStatus::default()
                });

            let package_plan = match resolve_package_execution_plan(
                target_plan,
                planned,
                cli_flags,
                context,
                evaluator,
            )? {
                PackagePlanOutcome::Kept(package_plan) => *package_plan,
                PackagePlanOutcome::TargetSelectionSkipped => {
                    status.target_selection_skipped = true;
                    continue;
                }
                PackagePlanOutcome::Filtered => continue,
            };
            config_show_pruned = config_show_pruned || package_plan.flags.show_pruned;
            config_show_target = config_show_target || planned.show_target;
            package_plans.push(package_plan);
            status.kept = true;
        }
        if !package_plans.is_empty() {
            plans.push(ExecutionPlan {
                target: target_plan.target.clone(),
                package_plans,
            });
        }
    }

    warn_packages_skipped_by_target_selection(&package_status);

    let show_pruned = config_show_pruned;
    let show_target = config_show_target || plans.len() > 1;

    Ok(ExecutionPlanSet {
        plans,
        show_pruned,
        show_target,
        host: context.host.clone(),
    })
}

fn resolve_package_execution_plan<'a>(
    target_plan: &TargetPlan<'a>,
    planned: &crate::plan::targets::PlannedPackage<'a>,
    cli_flags: FlagConfig,
    context: &PlanBuildContext<'_>,
    evaluator: &mut impl CfgEvaluator,
) -> eyre::Result<PackagePlanOutcome<'a>> {
    let pkg_matched = crate::config::resolve::matching_overrides(
        &planned.config.targets,
        &target_plan.target,
        evaluator,
    )?;
    let resolved = Chain::full(
        context.workspace_config,
        &target_plan.ws_matched,
        planned.config,
        pkg_matched,
        context.raw_command,
        context.resolved_command,
    )
    .resolve(
        crate::config::resolve::CliOverlay {
            flags: cli_flags,
            driver: context.cli_driver,
            env_set: context.cli_env_set,
            env_remove: context.cli_env_remove,
        },
        crate::config::resolve::ResolvePolicy {
            default_diagnostics_allowed: context.default_diagnostics_allowed,
            // Target planning already decided which configured assignments may
            // exist. Execution-plan resolution only lets narrower target-scoped
            // config remove those assignments.
            default_targets_enabled: true,
        },
    )?;
    let flags = resolved.flags;

    let target_selection_skipped = is_configured_target_source(planned.target.source)
        && (flags.no_targets || !resolved.targets_enabled);
    let lib_filter_skipped =
        flags.only_packages_with_lib_target && !has_lib_target(planned.package);
    if target_selection_skipped {
        return Ok(PackagePlanOutcome::TargetSelectionSkipped);
    }
    if lib_filter_skipped {
        return Ok(PackagePlanOutcome::Filtered);
    }

    let packages_only = context.matrix && flags.packages_only;
    let (combinations, pruned) = if packages_only {
        (Vec::new(), Vec::new())
    } else {
        let all_combos = planned.package.feature_combinations(&resolved.features)?;
        let prune_result = crate::implication::prune_with_resolved_features(
            all_combos,
            &planned.package.features,
            &resolved.features,
            flags.no_prune_implied,
        );
        // Own the feature strings before the resolved config is dropped.
        let combinations: Vec<Vec<String>> = prune_result
            .keep
            .into_iter()
            .map(|combo| combo.into_iter().cloned().collect())
            .collect();
        (combinations, prune_result.pruned)
    };

    Ok(PackagePlanOutcome::Kept(Box::new(PackageExecutionPlan {
        package: planned.package,
        target: planned.target.clone(),
        combinations,
        pruned,
        matrix: resolved.features.matrix,
        flags,
        driver: resolved.driver,
        env: resolved.env,
        ignored_diagnostics_config: resolved.ignored_diagnostics_config,
    })))
}

#[derive(Default)]
struct PackagePlanningStatus {
    name: String,
    kept: bool,
    target_selection_skipped: bool,
}

enum PackagePlanOutcome<'a> {
    /// Boxed to keep the outcome small: a resolved plan dwarfs the two skip
    /// variants, which carry nothing.
    Kept(Box<PackageExecutionPlan<'a>>),
    TargetSelectionSkipped,
    Filtered,
}

fn warn_packages_skipped_by_target_selection(status: &BTreeMap<String, PackagePlanningStatus>) {
    for entry in status.values() {
        if entry.target_selection_skipped && !entry.kept {
            print_warning!(
                "not running package `{}` because target-scoped `no_targets` or `subcommands.<name>.expand_targets = false` disabled all configured target assignments",
                entry.name
            );
        }
    }
}

fn is_configured_target_source(source: TargetSource) -> bool {
    matches!(
        source,
        TargetSource::WorkspaceConfig | TargetSource::PackageConfig
    )
}

#[cfg(test)]
mod test {
    use super::{ExecutionPlanSet, PlanBuildContext, build_execution_plans};
    use crate::cfg_eval::CfgEvaluator;
    use crate::config::{
        Config, FlagConfig, ResolvedFlags, ScopeConfig, TargetOverride, WorkspaceTargetOverride,
    };
    use crate::package::Package as _;
    use crate::package::test::{effective_target, package};
    use crate::plan::targets::{PlannedPackage, TargetPlan, TargetPlans};
    use crate::target::{EffectiveTarget, TargetSource, TargetTriple};
    use color_eyre::eyre;
    use similar_asserts::assert_eq as sim_assert_eq;

    #[derive(Default)]
    struct StubEval;

    impl CfgEvaluator for StubEval {
        fn matches(&mut self, _cfg_expr: &str, _target: &TargetTriple) -> eyre::Result<bool> {
            Ok(false)
        }
    }

    struct MatchAllEval;

    impl CfgEvaluator for MatchAllEval {
        fn matches(&mut self, _cfg_expr: &str, _target: &TargetTriple) -> eyre::Result<bool> {
            Ok(true)
        }
    }

    fn string_vec(values: &[&str]) -> Vec<String> {
        values.iter().copied().map(String::from).collect()
    }

    fn test_context(workspace_config: &crate::config::WorkspaceConfig) -> PlanBuildContext<'_> {
        PlanBuildContext {
            workspace_config,
            raw_command: None,
            resolved_command: None,
            cli_driver: None,
            cli_env_set: &[],
            cli_env_remove: &[],
            default_diagnostics_allowed: false,
            host: None,
            matrix: false,
        }
    }

    #[test]
    fn target_scoped_no_targets_skips_configured_assignments() -> eyre::Result<()> {
        let package = package("a")?;
        let config = crate::config::Config::default();
        let ws_override = WorkspaceTargetOverride {
            settings: ScopeConfig {
                flags: FlagConfig {
                    no_targets: Some(true),
                    ..FlagConfig::default()
                },
                ..ScopeConfig::default()
            },
            ..WorkspaceTargetOverride::default()
        };
        let target_plans = TargetPlans {
            plans: vec![TargetPlan {
                target: TargetTriple("configured-target".to_string()),
                ws_matched: vec![("cfg(any())".to_string(), &ws_override)],
                packages: vec![PlannedPackage {
                    package: &package,
                    config: &config,
                    target: effective_target("configured-target"),
                    show_target: true,
                }],
            }],
            base_exclude: std::collections::HashSet::new(),
            contains_configured_assignments: true,
        };
        let mut evaluator = StubEval;

        let workspace_config = crate::config::WorkspaceConfig::default();
        let context = test_context(&workspace_config);
        let plan_set = build_execution_plans(
            &target_plans,
            FlagConfig::default(),
            &context,
            &mut evaluator,
        )?;

        assert!(plan_set.plans.is_empty());
        Ok(())
    }

    #[test]
    fn target_scoped_lib_filter_false_can_reinclude_package() -> eyre::Result<()> {
        let mut package = package("bin-only")?;
        package.targets.clear();
        let mut config = crate::config::Config::default();
        config.targets.insert(
            "cfg(any())".to_string(),
            TargetOverride {
                settings: ScopeConfig {
                    flags: FlagConfig {
                        only_packages_with_lib_target: Some(false),
                        ..FlagConfig::default()
                    },
                    ..ScopeConfig::default()
                },
                ..TargetOverride::default()
            },
        );
        let ws_override = WorkspaceTargetOverride {
            settings: ScopeConfig {
                flags: FlagConfig {
                    only_packages_with_lib_target: Some(true),
                    ..FlagConfig::default()
                },
                ..ScopeConfig::default()
            },
            ..WorkspaceTargetOverride::default()
        };
        let target_plans = TargetPlans {
            plans: vec![TargetPlan {
                target: TargetTriple("configured-target".to_string()),
                ws_matched: vec![("cfg(any())".to_string(), &ws_override)],
                packages: vec![PlannedPackage {
                    package: &package,
                    config: &config,
                    target: effective_target("configured-target"),
                    show_target: true,
                }],
            }],
            base_exclude: std::collections::HashSet::new(),
            contains_configured_assignments: true,
        };

        let workspace_config = crate::config::WorkspaceConfig::default();
        let context = test_context(&workspace_config);
        let mut evaluator = MatchAllEval;
        let plan_set = build_execution_plans(
            &target_plans,
            FlagConfig::default(),
            &context,
            &mut evaluator,
        )?;

        let [plan] = plan_set.plans.as_slice() else {
            eyre::bail!("expected one execution plan, got {}", plan_set.plans.len());
        };
        assert_eq!(plan.package_plans.len(), 1);
        Ok(())
    }

    #[test]
    fn package_replace_does_not_clear_workspace_exclude_packages() -> eyre::Result<()> {
        let package = package("drop")?;
        let mut config = Config::default();
        config.base.settings.deprecated.replace = true;
        let target_plans = TargetPlans {
            plans: vec![TargetPlan {
                target: TargetTriple("configured-target".to_string()),
                ws_matched: Vec::new(),
                packages: vec![PlannedPackage {
                    package: &package,
                    config: &config,
                    target: effective_target("configured-target"),
                    show_target: true,
                }],
            }],
            base_exclude: std::collections::HashSet::from(["drop".to_string()]),
            contains_configured_assignments: true,
        };

        let workspace_config = crate::config::WorkspaceConfig::default();
        let context = test_context(&workspace_config);
        let mut evaluator = StubEval;
        let plan_set = build_execution_plans(
            &target_plans,
            FlagConfig::default(),
            &context,
            &mut evaluator,
        )?;

        assert!(plan_set.plans.is_empty());
        Ok(())
    }

    #[test]
    fn build_execution_plans_keeps_pruned_entries_for_summary() -> eyre::Result<()> {
        let mut package = crate::package::test::package_with_metadata(
            &["A", "B", "C"],
            "cargo-fc",
            &serde_json::json!({ "show_pruned": true }),
        )?;
        let Some(implied_features) = package.features.get_mut("B") else {
            eyre::bail!("test package should contain feature B");
        };
        implied_features.push("A".to_string());

        let config = package.config()?;
        let target_plans = TargetPlans {
            plans: vec![TargetPlan {
                target: TargetTriple("test-target".to_string()),
                ws_matched: Vec::new(),
                packages: vec![PlannedPackage {
                    package: &package,
                    config: &config,
                    target: EffectiveTarget {
                        triple: TargetTriple("test-target".to_string()),
                        source: TargetSource::Cli,
                    },
                    show_target: true,
                }],
            }],
            base_exclude: std::collections::HashSet::new(),
            contains_configured_assignments: false,
        };

        let mut evaluator = StubEval;
        let workspace_config = crate::config::WorkspaceConfig::default();
        let context = test_context(&workspace_config);
        let plan_set = build_execution_plans(
            &target_plans,
            FlagConfig::default(),
            &context,
            &mut evaluator,
        )?;

        assert_pruned_plan(&plan_set)?;
        Ok(())
    }

    fn assert_pruned_plan(plan_set: &ExecutionPlanSet<'_>) -> eyre::Result<()> {
        assert!(plan_set.show_pruned);
        let [plan] = plan_set.plans.as_slice() else {
            eyre::bail!("expected one execution plan, got {}", plan_set.plans.len());
        };
        let [pp] = plan.package_plans.as_slice() else {
            eyre::bail!(
                "expected one package execution plan, got {}",
                plan.package_plans.len()
            );
        };
        sim_assert_eq!(
            &pp.combinations,
            &vec![
                string_vec(&[]),
                string_vec(&["A"]),
                string_vec(&["A", "C"]),
                string_vec(&["B"]),
                string_vec(&["B", "C"]),
                string_vec(&["C"]),
            ],
        );

        let pruned: Vec<_> = pp
            .pruned
            .iter()
            .map(|p| (p.features.clone(), p.equivalent_to.clone()))
            .collect();
        sim_assert_eq!(
            pruned,
            vec![
                (string_vec(&["A", "B"]), string_vec(&["B"])),
                (string_vec(&["A", "B", "C"]), string_vec(&["B", "C"])),
            ],
        );
        Ok(())
    }

    fn plan_set_with_host(host: Option<&str>) -> ExecutionPlanSet<'static> {
        ExecutionPlanSet {
            plans: Vec::new(),
            show_pruned: false,
            show_target: false,
            host: host.map(|host| TargetTriple(host.to_string())),
        }
    }

    fn configured(triple: &str) -> EffectiveTarget {
        EffectiveTarget {
            triple: TargetTriple(triple.to_string()),
            source: TargetSource::WorkspaceConfig,
        }
    }

    /// Resolves through [`FlagConfig`] rather than setting the resolved field,
    /// so these cases also pin the default and the polarity flip.
    fn flags(omit_host_target_flag: Option<bool>) -> ResolvedFlags {
        ResolvedFlags::from_config(FlagConfig {
            omit_host_target_flag,
            ..FlagConfig::default()
        })
    }

    /// The host row must run exactly like a bare `cargo check`, so it lands in
    /// `target/debug` where an ordinary build can reuse it.
    #[test]
    fn host_only_invocation_injects_no_target_flag() {
        let plan_set = plan_set_with_host(Some("host"));

        sim_assert_eq!(
            plan_set.inject_target_args([&configured("host")], flags(None)),
            Vec::<String>::new()
        );
    }

    #[test]
    fn cross_only_invocation_keeps_its_target_flag() {
        let plan_set = plan_set_with_host(Some("host"));

        sim_assert_eq!(
            plan_set.inject_target_args([&configured("wasm")], flags(None)),
            vec!["wasm".to_string()]
        );
    }

    /// Dropping the host flag from an aggregated group would narrow what Cargo
    /// builds to the cross targets alone.
    #[test]
    fn aggregated_group_keeps_the_host_flag_alongside_cross_targets() {
        let plan_set = plan_set_with_host(Some("host"));

        sim_assert_eq!(
            plan_set.inject_target_args([&configured("host"), &configured("wasm")], flags(None)),
            vec!["host".to_string(), "wasm".to_string()]
        );
    }

    #[test]
    fn undetectable_host_keeps_every_configured_target_flag() {
        let plan_set = plan_set_with_host(None);

        sim_assert_eq!(
            plan_set.inject_target_args([&configured("host")], flags(None)),
            vec!["host".to_string()]
        );
    }

    /// `--target` on the CLI and `CARGO_BUILD_TARGET` reach Cargo on their own.
    #[test]
    fn sources_cargo_already_sees_are_never_injected() {
        let plan_set = plan_set_with_host(Some("host"));
        let cli = EffectiveTarget {
            triple: TargetTriple("wasm".to_string()),
            source: TargetSource::Cli,
        };

        sim_assert_eq!(
            plan_set.inject_target_args([&cli], flags(None)),
            Vec::<String>::new()
        );
    }

    #[test]
    fn omit_host_target_flag_false_injects_the_host_flag() {
        let plan_set = plan_set_with_host(Some("host"));

        sim_assert_eq!(
            plan_set.inject_target_args([&configured("host")], flags(Some(false))),
            vec!["host".to_string()]
        );
    }

    /// The opt-out only ever adds the host's own flag back; a source Cargo
    /// already sees stays uninjected.
    #[test]
    fn omit_host_target_flag_false_still_skips_cli_targets() {
        let plan_set = plan_set_with_host(Some("host"));
        let cli = EffectiveTarget {
            triple: TargetTriple("host".to_string()),
            source: TargetSource::Cli,
        };

        sim_assert_eq!(
            plan_set.inject_target_args([&cli], flags(Some(false))),
            Vec::<String>::new()
        );
    }
}