cargo-feature-combinations 0.3.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
//! Workspace-level configuration and package discovery.

use crate::config::{Config, WorkspaceConfig, validate_workspace_metadata};
use crate::print_warning;
use crate::{
    DEFAULT_METADATA_KEY, METADATA_KEYS, find_metadata_value, pkg_metadata_section,
    ws_metadata_section,
};
use color_eyre::eyre::{self, WrapErr};
use std::collections::HashSet;

/// Workspace-only non-flag metadata keys read solely from the workspace root.
const WORKSPACE_ONLY_KEYS: &[&str] = &[
    "exclude_packages",
    "targets",
    "target",
    "subcommands",
    "driver",
];

/// Abstraction over a Cargo workspace used by this crate.
pub trait Workspace {
    /// Return the workspace configuration section for feature combinations.
    ///
    /// # Errors
    ///
    /// Returns an error if the workspace metadata configuration can not be
    /// deserialized.
    fn workspace_config(&self) -> eyre::Result<WorkspaceConfig>;

    /// Return the candidate packages for feature combinations **without**
    /// applying workspace package exclusions.
    ///
    /// This emits the deprecation and no-op warnings for misplaced workspace
    /// metadata once. Workspace `exclude_packages` (and its target-specific
    /// patches) are applied later, per target, by the planner.
    ///
    /// # Errors
    ///
    /// Returns an error if metadata can not be parsed.
    fn candidate_packages_for_fc(&self) -> eyre::Result<Vec<&cargo_metadata::Package>>;

    /// Return the base, target-independent workspace exclude set.
    ///
    /// This is the union of `[workspace.metadata.*].exclude_packages` and the
    /// deprecated root-package `exclude_packages`. Target-specific workspace
    /// overrides patch this set per target during planning. This method emits
    /// no warnings.
    ///
    /// # Errors
    ///
    /// Returns an error if workspace metadata can not be parsed.
    fn base_workspace_exclude_packages(&self) -> eyre::Result<HashSet<String>>;
}

impl Workspace for cargo_metadata::Metadata {
    fn workspace_config(&self) -> eyre::Result<WorkspaceConfig> {
        let config: WorkspaceConfig = match find_metadata_value(&self.workspace_metadata) {
            Some((value, key)) => {
                validate_workspace_metadata(value, &ws_metadata_section(key))?;
                serde_json::from_value(value.clone()).wrap_err_with(|| {
                    format!(
                        "invalid [{}] configuration in workspace metadata",
                        ws_metadata_section(key)
                    )
                })?
            }
            None => WorkspaceConfig::default(),
        };
        Ok(config)
    }

    fn candidate_packages_for_fc(&self) -> eyre::Result<Vec<&cargo_metadata::Package>> {
        warn_workspace_metadata_misuse(self);
        Ok(self.workspace_packages())
    }

    fn base_workspace_exclude_packages(&self) -> eyre::Result<HashSet<String>> {
        let workspace_config = self.workspace_config()?;
        let mut exclude =
            apply_string_patch_to_empty(workspace_config.base.settings.exclude_packages.as_ref());

        // Fold in the deprecated root-package exclude_packages without emitting
        // warnings here (warnings are emitted once in candidate discovery).
        if let Some(root_package) = self.root_package()
            && let Some((value, _key)) = find_metadata_value(&root_package.metadata)
            && let Ok(config) = serde_json::from_value::<Config>(value.clone())
            && let Some(patch) = config.base.settings.exclude_packages.as_ref()
        {
            exclude.extend(apply_string_patch_to_empty(Some(patch)));
        }

        Ok(exclude)
    }
}

/// Emit deprecation and no-op warnings for misplaced workspace metadata.
///
/// Warnings are intentionally side effects of candidate discovery so they fire
/// once per invocation regardless of how many targets are later planned.
fn warn_workspace_metadata_misuse(metadata: &cargo_metadata::Metadata) {
    let Some(root_package) = metadata.root_package() else {
        return;
    };

    let root_key =
        find_metadata_value(&root_package.metadata).map_or(DEFAULT_METADATA_KEY, |(_, key)| key);

    // Root-package exclude_packages is deprecated in favor of workspace metadata.
    if let Some((value, _key)) = find_metadata_value(&root_package.metadata)
        && let Ok(config) = serde_json::from_value::<Config>(value.clone())
        && config
            .base
            .settings
            .exclude_packages
            .as_ref()
            .is_some_and(string_patch_has_values)
    {
        print_warning!(
            "[{}].exclude_packages in the workspace root package is deprecated; use [{}].exclude_packages instead",
            pkg_metadata_section(root_key),
            ws_metadata_section(root_key),
        );
    }

    let root_id = &root_package.id;
    for package in &metadata.packages {
        if &package.id == root_id {
            continue;
        }

        // [package.metadata.<alias>].exclude_packages in a non-root member is a no-op.
        if let Some((raw, key)) = find_metadata_value(&package.metadata)
            && let Ok(config) = serde_json::from_value::<Config>(raw.clone())
            && config
                .base
                .settings
                .exclude_packages
                .as_ref()
                .is_some_and(string_patch_has_values)
        {
            print_warning!(
                "[{}].exclude_packages in package `{}` has no effect; this field is only read from the workspace root Cargo.toml",
                pkg_metadata_section(key),
                package.name,
            );
        }

        // [workspace.metadata.<alias>].<key> specified in non-root manifests is
        // also a no-op. Detect the JSON shape produced by cargo metadata and
        // warn for any workspace-only key that carries values.
        if let Some(workspace) = package.metadata.get("workspace")
            && let Some((key, tool)) = METADATA_KEYS
                .iter()
                .find_map(|&key| workspace.get(key).map(|tool| (key, tool)))
        {
            for ws_key in WORKSPACE_ONLY_KEYS
                .iter()
                .chain(crate::config::FLAG_KEYS)
                .copied()
            {
                if json_has_values(tool.get(ws_key)) {
                    print_warning!(
                        "[{}].{} in package `{}` has no effect; workspace metadata is only read from the workspace root Cargo.toml",
                        ws_metadata_section(key),
                        ws_key,
                        package.name,
                    );
                }
            }
        }
    }
}

fn apply_string_patch_to_empty(
    patch: Option<&crate::config::patch::StringSetPatch>,
) -> HashSet<String> {
    let mut out = HashSet::new();
    if let Some(patch) = patch {
        if let Some(values) = patch.override_value() {
            out.extend(values.iter().cloned());
        }
        for value in patch.remove_values() {
            out.remove(value);
        }
        out.extend(patch.add_values().iter().cloned());
    }
    out
}

fn string_patch_has_values(patch: &crate::config::patch::StringSetPatch) -> bool {
    patch
        .override_value()
        .is_some_and(|values| !values.is_empty())
        || !patch.add_values().is_empty()
        || !patch.remove_values().is_empty()
}

/// Whether a JSON value carries meaningful (non-empty) configuration.
fn json_has_values(value: Option<&serde_json::Value>) -> bool {
    match value {
        Some(serde_json::Value::Array(values)) => !values.is_empty(),
        Some(serde_json::Value::Object(map)) => !map.is_empty(),
        Some(serde_json::Value::Bool(value)) => *value,
        Some(serde_json::Value::Null) | None => false,
        Some(_) => true,
    }
}

#[cfg(test)]
mod test {
    use super::{Workspace, json_has_values};
    use color_eyre::eyre;
    use serde_json::json;

    static INIT: std::sync::Once = std::sync::Once::new();

    fn init() {
        INIT.call_once(|| {
            color_eyre::install().ok();
        });
    }

    #[test]
    fn workspace_with_package() -> eyre::Result<()> {
        init();

        let package = crate::package::test::package_with_features(&[])?;
        let metadata = workspace_builder()
            .packages(vec![package.clone()])
            .workspace_members(vec![package.id.clone()])
            .build()?;

        let have = packages_after_base_exclude(&metadata)?;
        similar_asserts::assert_eq!(have: have, want: vec![&package]);
        Ok(())
    }

    #[test]
    fn workspace_with_excluded_package() -> eyre::Result<()> {
        init();

        let package = crate::package::test::package_with_features(&[])?;
        let metadata = workspace_builder()
            .packages(vec![package.clone()])
            .workspace_members(vec![package.id.clone()])
            .workspace_metadata(json!({
                "cargo-feature-combinations": {
                    "exclude_packages": [package.name]
                }
            }))
            .build()?;

        let have = packages_after_base_exclude(&metadata)?;
        assert!(have.is_empty(), "expected no packages after exclusion");
        Ok(())
    }

    #[test]
    fn workspace_with_excluded_package_cargo_fc_alias() -> eyre::Result<()> {
        init();

        let package = crate::package::test::package_with_features(&[])?;
        let metadata = workspace_builder()
            .packages(vec![package.clone()])
            .workspace_members(vec![package.id.clone()])
            .workspace_metadata(json!({
                "cargo-fc": {
                    "exclude_packages": [package.name]
                }
            }))
            .build()?;

        let have = packages_after_base_exclude(&metadata)?;
        assert!(
            have.is_empty(),
            "expected no packages after exclusion via cargo-fc alias"
        );
        Ok(())
    }

    #[test]
    fn workspace_with_excluded_package_fc_alias() -> eyre::Result<()> {
        init();

        let package = crate::package::test::package_with_features(&[])?;
        let metadata = workspace_builder()
            .packages(vec![package.clone()])
            .workspace_members(vec![package.id.clone()])
            .workspace_metadata(json!({
                "fc": {
                    "exclude_packages": [package.name]
                }
            }))
            .build()?;

        let have = packages_after_base_exclude(&metadata)?;
        assert!(
            have.is_empty(),
            "expected no packages after exclusion via fc alias"
        );
        Ok(())
    }

    #[test]
    fn workspace_with_excluded_package_feature_combinations_alias() -> eyre::Result<()> {
        init();

        let package = crate::package::test::package_with_features(&[])?;
        let metadata = workspace_builder()
            .packages(vec![package.clone()])
            .workspace_members(vec![package.id.clone()])
            .workspace_metadata(json!({
                "feature-combinations": {
                    "exclude_packages": [package.name]
                }
            }))
            .build()?;

        let have = packages_after_base_exclude(&metadata)?;
        assert!(
            have.is_empty(),
            "expected no packages after exclusion via feature-combinations alias"
        );
        Ok(())
    }

    #[test]
    fn workspace_config_reads_install_missing_targets() -> eyre::Result<()> {
        init();

        let package = crate::package::test::package_with_features(&[])?;
        let metadata = workspace_builder()
            .packages(vec![package.clone()])
            .workspace_members(vec![package.id.clone()])
            .workspace_metadata(json!({
                "cargo-fc": {
                    "install_missing_targets": true
                }
            }))
            .build()?;

        let config = metadata.workspace_config()?;

        assert_eq!(
            config.base.settings.flags.install_missing_targets,
            Some(true)
        );
        Ok(())
    }

    #[test]
    fn workspace_metadata_rejects_unknown_flag_keys() -> eyre::Result<()> {
        init();

        let package = crate::package::test::package_with_features(&[])?;
        let metadata = workspace_builder()
            .packages(vec![package.clone()])
            .workspace_members(vec![package.id.clone()])
            .workspace_metadata(json!({
                "cargo-fc": {
                    "fail-fast": true
                }
            }))
            .build()?;

        let err = metadata
            .workspace_config()
            .expect_err("hyphenated cargo-fc flag should be rejected");

        assert!(err.to_string().contains("unknown cargo-fc config key"));
        assert!(err.to_string().contains("use `_`, not `-`"));
        Ok(())
    }

    #[test]
    fn json_has_values_treats_false_as_default_empty_value() {
        assert!(!json_has_values(Some(&json!(false))));
        assert!(json_has_values(Some(&json!(true))));
    }

    fn workspace_builder() -> cargo_metadata::MetadataBuilder {
        use cargo_metadata::{MetadataBuilder, WorkspaceDefaultMembers};

        MetadataBuilder::default()
            .version(1u8)
            .workspace_default_members(WorkspaceDefaultMembers::default())
            .resolve(None)
            .workspace_root("")
            .workspace_metadata(json!({}))
            .build_directory(None)
            .target_directory("")
    }

    fn packages_after_base_exclude(
        metadata: &cargo_metadata::Metadata,
    ) -> eyre::Result<Vec<&cargo_metadata::Package>> {
        let mut packages = metadata.candidate_packages_for_fc()?;
        let exclude = metadata.base_workspace_exclude_packages()?;
        packages.retain(|package| !exclude.contains(package.name.as_str()));
        Ok(packages)
    }
}