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
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
use serde::{Deserialize, Serialize};
use std::collections::{BTreeSet, HashSet};

/// Patch operations for a set-like configuration field.
///
/// A patch can either be:
///
/// - a plain array, which is interpreted as a full override
/// - a patch object with explicit `override`, `add`, and `remove` operations
///
/// Arrays are always treated as overrides to avoid ambiguity.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum StringSetPatch {
    /// Shorthand syntax: `key = ["a", "b"]`.
    Override(HashSet<String>),
    /// Explicit patch syntax: `key = { override = [...], add = [...], remove = [...] }`.
    Patch {
        /// If present, replace the entire value instead of applying add/remove.
        #[serde(default)]
        r#override: Option<HashSet<String>>,
        /// Values to add to the base set.
        #[serde(default)]
        add: HashSet<String>,
        /// Values to remove from the base set.
        #[serde(default)]
        remove: HashSet<String>,
    },
}

impl StringSetPatch {
    /// Return the override value, if the patch is an override.
    #[must_use]
    pub fn override_value(&self) -> Option<&HashSet<String>> {
        match self {
            Self::Override(v) => Some(v),
            Self::Patch { r#override, .. } => r#override.as_ref(),
        }
    }

    /// Return the set of values to add.
    #[must_use]
    pub fn add_values(&self) -> &HashSet<String> {
        static EMPTY: std::sync::LazyLock<HashSet<String>> = std::sync::LazyLock::new(HashSet::new);
        match self {
            Self::Override(_) => &EMPTY,
            Self::Patch { add, .. } => add,
        }
    }

    /// Return the set of values to remove.
    #[must_use]
    pub fn remove_values(&self) -> &HashSet<String> {
        static EMPTY: std::sync::LazyLock<HashSet<String>> = std::sync::LazyLock::new(HashSet::new);
        match self {
            Self::Override(_) => &EMPTY,
            Self::Patch { remove, .. } => remove,
        }
    }

    /// Return `true` if the patch contains any add/remove operations.
    #[must_use]
    pub fn has_add_or_remove(&self) -> bool {
        !self.add_values().is_empty() || !self.remove_values().is_empty()
    }
}

/// Patch operations for an ordered target-triple list.
///
/// This has the same TOML surface as [`StringSetPatch`], but it keeps values in
/// declaration order instead of normalizing through a set.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum TargetListPatch {
    /// Shorthand syntax: `targets = ["a", "b"]`.
    Override(Vec<String>),
    /// Explicit patch syntax: `targets = { override = [...], add = [...], remove = [...] }`.
    Patch {
        /// If present, replace the inherited list before applying add/remove.
        #[serde(default)]
        r#override: Option<Vec<String>>,
        /// Values to append to the inherited list.
        #[serde(default)]
        add: Vec<String>,
        /// Values to remove from the inherited list.
        #[serde(default)]
        remove: Vec<String>,
    },
}

impl TargetListPatch {
    /// Return the override value, if the patch is an override.
    #[must_use]
    pub fn override_value(&self) -> Option<&[String]> {
        match self {
            Self::Override(v) => Some(v),
            Self::Patch { r#override, .. } => r#override.as_deref(),
        }
    }

    /// Return the ordered values to add.
    #[must_use]
    pub fn add_values(&self) -> &[String] {
        match self {
            Self::Override(_) => &[],
            Self::Patch { add, .. } => add,
        }
    }

    /// Return the ordered values to remove.
    #[must_use]
    pub fn remove_values(&self) -> &[String] {
        match self {
            Self::Override(_) => &[],
            Self::Patch { remove, .. } => remove,
        }
    }

    /// Return `true` if the patch contains any add/remove operations.
    #[must_use]
    pub fn has_add_or_remove(&self) -> bool {
        !self.add_values().is_empty() || !self.remove_values().is_empty()
    }
}

#[derive(Debug, Clone)]
pub(crate) struct TargetListOps {
    override_value: Option<Vec<String>>,
    add: Vec<String>,
    remove: Vec<String>,
}

impl TargetListOps {
    /// Apply operations while preserving declaration order.
    #[must_use]
    pub(crate) fn apply_to(&self, base: &[String]) -> Vec<String> {
        let mut out = self
            .override_value
            .clone()
            .unwrap_or_else(|| dedup_ordered(base.iter().cloned()));
        let remove: HashSet<&str> = self.remove.iter().map(String::as_str).collect();
        out.retain(|value| !remove.contains(value.as_str()));
        let mut existing: HashSet<String> = out.iter().cloned().collect();
        out.extend(
            self.add
                .iter()
                .filter(|value| existing.insert((*value).clone()))
                .cloned(),
        );
        out
    }
}

/// Combine sibling target-list patches without losing declaration order.
pub(crate) fn combine_target_list_patches<'a>(
    name: &str,
    source_kind: &str,
    patches: impl IntoIterator<Item = (&'a str, &'a TargetListPatch)>,
) -> color_eyre::eyre::Result<Option<TargetListOps>> {
    let mut any = false;
    let mut override_value: Option<Vec<String>> = None;
    let mut add = Vec::new();
    let mut remove = Vec::new();

    for (expr, patch) in patches {
        any = true;

        if let Some(value) = patch.override_value() {
            let value = dedup_ordered(value.iter().cloned());
            match &override_value {
                None => override_value = Some(value),
                Some(existing) if *existing == value => {}
                Some(_) => {
                    color_eyre::eyre::bail!(
                        "conflicting overrides for `{name}` from {source_kind} `{expr}`"
                    );
                }
            }
        }

        extend_ordered_unique(&mut add, patch.add_values().iter().cloned());
        extend_ordered_unique(&mut remove, patch.remove_values().iter().cloned());
    }

    Ok(any.then_some(TargetListOps {
        override_value,
        add,
        remove,
    }))
}

fn dedup_ordered(values: impl IntoIterator<Item = String>) -> Vec<String> {
    let mut seen = HashSet::new();
    values
        .into_iter()
        .filter(|value| seen.insert(value.clone()))
        .collect()
}

fn extend_ordered_unique(out: &mut Vec<String>, values: impl IntoIterator<Item = String>) {
    let mut seen: HashSet<String> = out.iter().cloned().collect();
    out.extend(
        values
            .into_iter()
            .filter(|value| seen.insert(value.clone())),
    );
}

/// Patch operations for a list of feature sets (each represented as a set of strings).
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum FeatureSetVecPatch {
    /// Shorthand syntax: `key = [["a"], ["b", "c"]]`.
    Override(Vec<HashSet<String>>),
    /// Explicit patch syntax.
    Patch {
        /// If present, replace the entire list instead of applying add/remove.
        #[serde(default)]
        r#override: Option<Vec<HashSet<String>>>,
        /// Feature sets to append.
        #[serde(default)]
        add: Vec<HashSet<String>>,
        /// Feature sets to remove.
        #[serde(default)]
        remove: Vec<HashSet<String>>,
    },
}

impl FeatureSetVecPatch {
    /// Return the override value, if the patch is an override.
    #[must_use]
    pub fn override_value(&self) -> Option<&Vec<HashSet<String>>> {
        match self {
            Self::Override(v) => Some(v),
            Self::Patch { r#override, .. } => r#override.as_ref(),
        }
    }

    /// Return the feature sets to add.
    #[must_use]
    pub fn add_values(&self) -> &[HashSet<String>] {
        static EMPTY: std::sync::LazyLock<Vec<HashSet<String>>> =
            std::sync::LazyLock::new(Vec::new);
        match self {
            Self::Override(_) => &EMPTY,
            Self::Patch { add, .. } => add,
        }
    }

    /// Return the feature sets to remove.
    #[must_use]
    pub fn remove_values(&self) -> &[HashSet<String>] {
        static EMPTY: std::sync::LazyLock<Vec<HashSet<String>>> =
            std::sync::LazyLock::new(Vec::new);
        match self {
            Self::Override(_) => &EMPTY,
            Self::Patch { remove, .. } => remove,
        }
    }

    /// Return `true` if the patch contains any add/remove operations.
    #[must_use]
    pub fn has_add_or_remove(&self) -> bool {
        !self.add_values().is_empty() || !self.remove_values().is_empty()
    }
}

/// A single override's contribution to a set-like field, normalized to a set of
/// comparable elements `Elem`.
///
/// Both [`StringSetPatch`] (elements are feature names) and
/// [`FeatureSetVecPatch`] (elements are whole feature sets, normalized to a
/// sorted `Vec<String>`) implement this, so one patch engine
/// ([`combine_set_patches`] + [`SetPatchOps`]) resolves every set-like field
/// regardless of its element type.
pub(crate) trait SetPatchInput {
    type Elem: Ord + Clone;

    /// The full replacement value, if this patch is an override. Materialized as
    /// a `BTreeSet` because it is compared for conflict detection and stored.
    fn override_elems(&self) -> Option<BTreeSet<Self::Elem>>;
    /// Elements to union into the base value.
    fn add_elems(&self) -> impl Iterator<Item = Self::Elem> + '_;
    /// Elements to subtract from the base value.
    fn remove_elems(&self) -> impl Iterator<Item = Self::Elem> + '_;
}

fn normalize_feature_set(set: &HashSet<String>) -> Vec<String> {
    let mut v = set.iter().cloned().collect::<Vec<_>>();
    v.sort();
    v
}

impl SetPatchInput for StringSetPatch {
    type Elem = String;

    fn override_elems(&self) -> Option<BTreeSet<String>> {
        self.override_value().map(|v| v.iter().cloned().collect())
    }
    fn add_elems(&self) -> impl Iterator<Item = String> + '_ {
        self.add_values().iter().cloned()
    }
    fn remove_elems(&self) -> impl Iterator<Item = String> + '_ {
        self.remove_values().iter().cloned()
    }
}

impl SetPatchInput for FeatureSetVecPatch {
    type Elem = Vec<String>;

    fn override_elems(&self) -> Option<BTreeSet<Vec<String>>> {
        self.override_value()
            .map(|v| v.iter().map(normalize_feature_set).collect())
    }
    fn add_elems(&self) -> impl Iterator<Item = Vec<String>> + '_ {
        self.add_values().iter().map(normalize_feature_set)
    }
    fn remove_elems(&self) -> impl Iterator<Item = Vec<String>> + '_ {
        self.remove_values().iter().map(normalize_feature_set)
    }
}

/// The combined patch for one field across all sibling overrides of a layer.
///
/// The order of application is: start from override (or base), then remove, then
/// add. If an element appears in both `add` and `remove`, **add wins**.
#[derive(Debug, Clone)]
pub(crate) struct SetPatchOps<E: Ord + Clone> {
    override_value: Option<BTreeSet<E>>,
    add: BTreeSet<E>,
    remove: BTreeSet<E>,
}

impl<E: Ord + Clone> SetPatchOps<E> {
    /// Build operations from one patch. A single patch cannot have conflicting
    /// overrides, so this is infallible.
    pub(crate) fn from_single<P>(patch: &P) -> Self
    where
        P: SetPatchInput<Elem = E>,
    {
        Self {
            override_value: patch.override_elems(),
            add: patch.add_elems().collect(),
            remove: patch.remove_elems().collect(),
        }
    }

    /// `base` is only materialized when this patch is not a full override, so a
    /// pure-override layer skips converting the base value it would discard.
    fn apply(&self, base: impl FnOnce() -> BTreeSet<E>) -> BTreeSet<E> {
        let mut out = match &self.override_value {
            Some(value) => value.clone(),
            None => base(),
        };
        for value in &self.remove {
            out.remove(value);
        }
        out.extend(self.add.iter().cloned());
        out
    }
}

impl SetPatchOps<String> {
    /// Apply onto a plain string set (e.g. `exclude_features`, `exclude_packages`).
    #[must_use]
    pub(crate) fn apply_to(&self, base: &HashSet<String>) -> HashSet<String> {
        self.apply(|| base.iter().cloned().collect())
            .into_iter()
            .collect()
    }
}

impl SetPatchOps<Vec<String>> {
    /// Apply onto a list of feature sets (e.g. `isolated_feature_sets`).
    #[must_use]
    pub(crate) fn apply_to_feature_sets(&self, base: &[HashSet<String>]) -> Vec<HashSet<String>> {
        self.apply(|| base.iter().map(normalize_feature_set).collect())
            .into_iter()
            .map(|set| set.into_iter().collect())
            .collect()
    }
}

/// Combine the sibling patches of one layer into a single [`SetPatchOps`].
///
/// Conflicting `override` values from different siblings are an error; `add` and
/// `remove` contributions are unioned. Returns `None` when no sibling touched
/// the field. Works for any [`SetPatchInput`], so string sets and feature-set
/// lists share this one implementation.
pub(crate) fn combine_set_patches<'a, P>(
    name: &str,
    source_kind: &str,
    patches: impl IntoIterator<Item = (&'a str, &'a P)>,
) -> color_eyre::eyre::Result<Option<SetPatchOps<P::Elem>>>
where
    P: SetPatchInput + 'a,
{
    let mut any = false;
    let mut override_value: Option<BTreeSet<P::Elem>> = None;
    let mut add: BTreeSet<P::Elem> = BTreeSet::new();
    let mut remove: BTreeSet<P::Elem> = BTreeSet::new();

    for (expr, patch) in patches {
        any = true;

        if let Some(value) = patch.override_elems() {
            match &override_value {
                None => override_value = Some(value),
                Some(existing) if *existing == value => {}
                Some(_) => {
                    color_eyre::eyre::bail!(
                        "conflicting overrides for `{name}` from {source_kind} `{expr}`"
                    );
                }
            }
        }

        add.extend(patch.add_elems());
        remove.extend(patch.remove_elems());
    }

    if any {
        Ok(Some(SetPatchOps {
            override_value,
            add,
            remove,
        }))
    } else {
        Ok(None)
    }
}

#[cfg(test)]
mod test {
    use super::{FeatureSetVecPatch, StringSetPatch, TargetListPatch};
    use color_eyre::eyre;
    use serde_json::json;
    use std::collections::HashSet;

    #[test]
    fn string_set_patch_array_is_override() -> eyre::Result<()> {
        let v = json!(["a", "b"]);
        let p: StringSetPatch = serde_json::from_value(v)?;
        let mut expected: HashSet<String> = HashSet::new();
        expected.insert("a".to_string());
        expected.insert("b".to_string());

        assert_eq!(p.override_value(), Some(&expected));
        assert!(p.add_values().is_empty());
        assert!(p.remove_values().is_empty());
        Ok(())
    }

    #[test]
    fn string_set_patch_object_add_remove() -> eyre::Result<()> {
        let v = json!({"add": ["a"], "remove": ["b"]});
        let p: StringSetPatch = serde_json::from_value(v)?;
        assert!(p.override_value().is_none());
        assert!(p.add_values().contains("a"));
        assert!(p.remove_values().contains("b"));
        Ok(())
    }

    #[test]
    fn feature_set_vec_patch_array_is_override() -> eyre::Result<()> {
        let v = json!([["a"], ["b", "c"]]);
        let p: FeatureSetVecPatch = serde_json::from_value(v)?;
        assert!(p.override_value().is_some());
        assert!(p.add_values().is_empty());
        assert!(p.remove_values().is_empty());
        Ok(())
    }

    fn hs(values: &[&str]) -> HashSet<String> {
        values.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn combine_set_patches_unifies_string_sets() -> eyre::Result<()> {
        // One generic engine handles the `HashSet<String>` element type.
        let base = hs(&["default"]);
        let add: StringSetPatch = serde_json::from_value(json!({ "add": ["cuda"] }))?;
        let remove: StringSetPatch = serde_json::from_value(json!({ "remove": ["default"] }))?;

        let ops = super::combine_set_patches(
            "exclude_features",
            "target override",
            [("cfg(a)", &add), ("cfg(b)", &remove)],
        )?
        .expect("patches present");

        assert_eq!(ops.apply_to(&base), hs(&["cuda"]));
        Ok(())
    }

    #[test]
    fn combine_set_patches_unifies_feature_set_lists() -> eyre::Result<()> {
        // The same engine handles the `Vec<HashSet<String>>` element type.
        let base = vec![hs(&["a"])];
        let add: FeatureSetVecPatch = serde_json::from_value(json!({ "add": [["b", "c"]] }))?;

        let ops = super::combine_set_patches(
            "include_feature_sets",
            "target override",
            [("cfg(a)", &add)],
        )?
        .expect("patch present");

        let mut got = ops.apply_to_feature_sets(&base);
        got.sort_by_key(super::normalize_feature_set);
        assert_eq!(got, vec![hs(&["a"]), hs(&["b", "c"])]);
        Ok(())
    }

    #[test]
    fn combine_set_patches_reports_conflicting_overrides() {
        let a: StringSetPatch = serde_json::from_value(json!(["x"])).unwrap();
        let b: StringSetPatch = serde_json::from_value(json!(["y"])).unwrap();

        let err = super::combine_set_patches(
            "exclude_features",
            "target override",
            [("cfg(a)", &a), ("cfg(b)", &b)],
        )
        .expect_err("conflicting overrides must error");
        assert!(err.to_string().contains("conflicting overrides"));
    }

    #[test]
    fn target_list_patch_array_is_ordered_override() -> eyre::Result<()> {
        let patch: TargetListPatch = serde_json::from_value(json!(["b", "a", "b"]))?;

        let ops = super::combine_target_list_patches("targets", "package config", [("", &patch)])?
            .expect("patch present");

        assert_eq!(ops.apply_to(&["base".to_string()]), vec!["b", "a"]);
        Ok(())
    }

    #[test]
    fn target_list_patch_object_applies_in_declaration_order() -> eyre::Result<()> {
        let patch: TargetListPatch =
            serde_json::from_value(json!({ "remove": ["base"], "add": ["z", "a", "z"] }))?;

        let ops = super::combine_target_list_patches("targets", "package config", [("", &patch)])?
            .expect("patch present");

        assert_eq!(
            ops.apply_to(&["base".to_string(), "kept".to_string()]),
            vec!["kept", "z", "a"],
        );
        Ok(())
    }

    #[test]
    fn target_list_patch_conflicting_overrides_error() -> eyre::Result<()> {
        let a: TargetListPatch = serde_json::from_value(json!(["a", "b"]))?;
        let b: TargetListPatch = serde_json::from_value(json!(["b", "a"]))?;

        let err = super::combine_target_list_patches(
            "targets",
            "workspace target override",
            [("cfg(a)", &a), ("cfg(b)", &b)],
        )
        .expect_err("ordered overrides differ");

        assert!(err.to_string().contains("conflicting overrides"));
        Ok(())
    }
}