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
//! 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.

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

pub use cli::{ArgumentParser, Command, Options, parse_arguments};
pub use package::{FeatureCombinationError, Package};
pub use runner::{
    ExitCode, MatrixOptions, color_spec, error_counts, print_feature_matrix_for_target,
    print_summary, run_cargo_command_for_target, warning_counts,
};
pub use workspace::Workspace;

use cfg_eval::RustcCfgEvaluator;
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 (e.g. `cargo lint`) are common and the tool handles
/// unknown subcommands 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!());

/// 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 selected: Vec<target_plan::SelectedPackage<'_>> = packages
        .iter()
        .zip(&configs)
        .map(|(package, config)| target_plan::SelectedPackage { package, config })
        .collect();

    // Preserve the original String args for `--target` detection.
    let cargo_args_owned = cargo_args;
    let cargo_args: Vec<&str> = cargo_args_owned.iter().map(String::as_str).collect();

    // Parse an explicit `--target` only before `--`.
    let cli_target = target::parse_cli_target(&cargo_args_owned);

    // 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);
    let capability_allowed =
        resolve_capability_and_warn(&options, &cargo_args, &ws_config, ws_key, &selected);

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

    let target_plans = target_plan::build_target_plans(
        &selected,
        &ws_config,
        &base_exclude,
        cli_target.as_deref(),
        capability_allowed,
        &env,
        &mut evaluator,
    )?;

    let result = match options.command {
        Some(Command::Help | Command::Version) => Ok(None),
        Some(Command::FeatureMatrix { pretty }) => {
            let plan_set = runner::build_execution_plans(
                &target_plans,
                &options,
                options.packages_only,
                &mut evaluator,
            )?;
            if options.install_missing_targets {
                print_note!(
                    "--install-missing-targets has no effect for matrix output; matrix only prints planned targets"
                );
            }
            if options.aggregate_targets {
                print_note!(
                    "--aggregate-targets has no effect for matrix output; matrix rows are always per target"
                );
            }
            let matrix_opts = runner::MatrixOptions {
                pretty,
                packages_only: options.packages_only,
                no_prune_implied: options.no_prune_implied,
            };
            runner::print_matrix_for_execution_plans(&plan_set, &matrix_opts)
        }
        None => {
            if WARN_UNKNOWN_SUBCOMMAND
                && cargo_subcommand(cargo_args.as_slice()) == cli::CargoSubcommand::Other
            {
                print_warning!(
                    "`cargo {bin_name}` only supports cargo's `build`, `test`, `run`, `check`, `doc`, and `clippy` subcommands"
                );
            }
            let plan_set =
                runner::build_execution_plans(&target_plans, &options, false, &mut evaluator)?;
            maybe_install_missing_targets(&options, &ws_config, &plan_set, &env, &cargo_args)?;
            let mode = resolve_execution_mode(&options, &cargo_args, &plan_set);
            runner::run_execution_plans(&plan_set, cargo_args, &options, mode)
        }
    };

    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)
        }
    }
}

/// 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()));

    if options.only_packages_with_lib_target {
        // Filter only packages with a library target
        packages.retain(|p| {
            p.targets
                .iter()
                .any(|t| t.kind.contains(&cargo_metadata::TargetKind::Lib))
        });
    }

    // 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(
    options: &Options,
    ws_config: &config::WorkspaceConfig,
    plan_set: &runner::ExecutionPlanSet<'_>,
    env: &impl target::TargetEnvironment,
    cargo_args: &[&str],
) -> eyre::Result<()> {
    if options.install_missing_targets || ws_config.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(())
}

/// Resolve the selected command's target capability and warn (once) if
/// configured targets exist but the command can not accept them.
///
/// `matrix` is not a forwarded cargo command: it always uses configured target
/// planning. The warning is driven from raw config state, not from the planned
/// targets after capability filtering.
fn resolve_capability_and_warn(
    options: &Options,
    cargo_args: &[&str],
    ws_config: &config::WorkspaceConfig,
    ws_key: &str,
    selected: &[target_plan::SelectedPackage<'_>],
) -> bool {
    // `--no-targets` deliberately ignores configured target lists and falls back
    // to Cargo's default single target, so deny without warning.
    if options.no_targets {
        return false;
    }

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

    let token = cli::cargo_subcommand_token(cargo_args);
    let policy = cli::configured_target_policy(token.as_deref(), &ws_config.subcommand_overrides);
    if policy.enabled {
        return true;
    }

    // Capability denied: warn (once) only when the user actually configured
    // targets that we are now skipping.
    let has_raw_configured_targets = !ws_config.workspace_targets.is_empty()
        || selected.iter().any(|s| {
            s.config
                .package_targets
                .as_ref()
                .is_some_and(|t| !t.is_empty())
        });
    if has_raw_configured_targets
        && !policy.explicit
        && let Some(token) = token.as_deref().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",
            ws_metadata_section(ws_key),
        );
    }

    false
}

/// 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(
    options: &Options,
    cargo_args: &[&str],
    plan_set: &runner::ExecutionPlanSet<'_>,
) -> runner::TargetExecutionMode {
    use runner::TargetExecutionMode;

    if !options.aggregate_targets {
        return TargetExecutionMode::SerialPerTarget;
    }

    if plan_set.plans.len() <= 1 {
        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 color_eyre::eyre;
    use serde_json::json;

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

    #[test]
    fn aggregate_execution_mode_selected_for_supported_multi_target_command() {
        let options = Options {
            aggregate_targets: true,
            ..Options::default()
        };
        let plan_set = execution_plan_set(&["t1", "t2"], false);

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

    #[test]
    fn aggregate_execution_mode_falls_back_for_run() {
        let options = Options {
            aggregate_targets: true,
            ..Options::default()
        };
        let plan_set = execution_plan_set(&["t1", "t2"], false);

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

    #[test]
    fn aggregate_execution_mode_falls_back_for_pruned_summaries() {
        let options = Options {
            aggregate_targets: true,
            ..Options::default()
        };
        let plan_set = execution_plan_set(&["t1", "t2"], true);

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

    #[test]
    fn aggregate_execution_mode_is_noop_for_single_target() {
        let options = Options {
            aggregate_targets: true,
            ..Options::default()
        };
        let plan_set = execution_plan_set(&["t1"], false);

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

    #[test]
    fn no_targets_flag_denies_capability() {
        let options = Options {
            no_targets: true,
            ..Options::default()
        };
        let ws = config::WorkspaceConfig::default();
        // Even a target-capable built-in command is denied configured targets
        // when `--no-targets` is set.
        assert!(!resolve_capability_and_warn(
            &options,
            &["check"],
            &ws,
            DEFAULT_METADATA_KEY,
            &[]
        ));
    }

    #[test]
    fn builtin_command_allows_capability_without_no_targets() {
        let options = Options::default();
        let ws = config::WorkspaceConfig::default();
        assert!(resolve_capability_and_warn(
            &options,
            &["check"],
            &ws,
            DEFAULT_METADATA_KEY,
            &[]
        ));
    }

    #[test]
    fn builtin_command_can_be_disabled_by_workspace_policy() {
        let options = Options::default();
        let mut ws = config::WorkspaceConfig::default();
        ws.subcommand_overrides.insert(
            "build".to_string(),
            config::CommandTargetCapability { targets: false },
        );

        assert!(!resolve_capability_and_warn(
            &options,
            &["build"],
            &ws,
            DEFAULT_METADATA_KEY,
            &[]
        ));
    }

    #[test]
    fn no_targets_flag_denies_capability_for_matrix() {
        let options = Options {
            no_targets: true,
            command: Some(Command::FeatureMatrix { pretty: false }),
            ..Options::default()
        };
        let ws = config::WorkspaceConfig::default();
        let empty: [&str; 0] = [];
        assert!(!resolve_capability_and_warn(
            &options,
            &empty,
            &ws,
            DEFAULT_METADATA_KEY,
            &[]
        ));
    }

    #[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");
    }
}