cargo-matrix 0.4.4

Run feature matrices against cargo commands that support feature lists
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
// Copyright (c) 2024 cargo-matrix developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

use crate::feature::{FeatureMatrix, FeatureSet};
use anyhow::{Result, anyhow};
use figment::{
    Error, Figment, Metadata, Profile, Provider,
    value::{Dict, Map},
};
use getset::{Getters, MutGetters, Setters};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, Getters, MutGetters, Serialize, Setters)]
#[getset(get = "pub(crate)")]
pub(crate) struct Config {
    #[getset(get_mut = "pub(crate)")]
    channel: Vec<Channel>,
    #[getset(skip)]
    #[serde(rename = "skip-package", default)]
    skip_package: Option<bool>,
}

impl Config {
    pub(crate) fn from<T: Provider>(provider: T) -> Result<Self> {
        Ok(Figment::from(provider).extract()?)
    }

    pub(crate) fn seed(&self, channel: &str) -> Result<Option<FeatureSet>> {
        if let Some(seed) = self
            .get_channel(channel)
            .or_else(|_| self.get_default())?
            .seed()
        {
            Ok(Some(seed.clone()))
        } else {
            Ok(self.get_default()?.seed().clone())
        }
    }

    pub(crate) fn always_include(&self, channel: &str) -> Result<FeatureSet> {
        if let Some(always_include) = self
            .get_channel(channel)
            .or_else(|_| self.get_default())?
            .always_include()
        {
            Ok(always_include.clone())
        } else {
            Ok(self
                .get_default()?
                .always_include()
                .clone()
                .unwrap_or_default())
        }
    }

    pub(crate) fn always_deny(&self, channel: &str) -> Result<FeatureSet> {
        if let Some(always_deny) = self
            .get_channel(channel)
            .or_else(|_| self.get_default())?
            .always_deny()
        {
            Ok(always_deny.clone())
        } else {
            Ok(self
                .get_default()?
                .always_deny()
                .clone()
                .unwrap_or_default())
        }
    }

    pub(crate) fn skip(&self, channel: &str) -> Result<FeatureMatrix> {
        if let Some(skip) = self
            .get_channel(channel)
            .or_else(|_| self.get_default())?
            .skip()
        {
            Ok(skip.clone())
        } else {
            Ok(self.get_default()?.skip().clone().unwrap_or_default())
        }
    }

    pub(crate) fn mutually_exclusive(&self, channel: &str) -> Result<FeatureMatrix> {
        if let Some(mutually_exclusive) = self
            .get_channel(channel)
            .or_else(|_| self.get_default())?
            .mutually_exclusive()
        {
            Ok(mutually_exclusive.clone())
        } else {
            Ok(self
                .get_default()?
                .mutually_exclusive()
                .clone()
                .unwrap_or_default())
        }
    }

    pub(crate) fn include_hidden(&self, channel: &str) -> Result<bool> {
        if let Some(include_hidden) = self
            .get_channel(channel)
            .or_else(|_| self.get_default())?
            .include_hidden()
        {
            Ok(*include_hidden)
        } else {
            Ok(self.get_default()?.include_hidden().unwrap_or_default())
        }
    }

    pub(crate) fn include_all_optional(&self, channel: &str) -> Result<bool> {
        if let Some(include_all_optional) = self
            .get_channel(channel)
            .or_else(|_| self.get_default())?
            .include_all_optional()
        {
            Ok(*include_all_optional)
        } else {
            Ok(self
                .get_default()?
                .include_all_optional()
                .unwrap_or_default())
        }
    }

    pub(crate) fn include_optional(&self, channel: &str) -> Result<FeatureSet> {
        if let Some(include_optional) = self
            .get_channel(channel)
            .or_else(|_| self.get_default())?
            .include_optional()
        {
            Ok(include_optional.clone())
        } else {
            Ok(self
                .get_default()?
                .include_optional()
                .clone()
                .unwrap_or_default())
        }
    }

    pub(crate) fn skip_package(&self) -> bool {
        self.skip_package.unwrap_or(false)
    }

    fn get_default(&self) -> Result<&'_ Channel> {
        self.get_channel("default")
    }

    fn get_channel(&self, channel: &str) -> Result<&'_ Channel> {
        self.channel
            .iter()
            .find(|c| c.name() == channel)
            .ok_or_else(|| anyhow!(format!("channel '{channel}' not defined")))
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            channel: vec![Channel {
                name: "default".to_string(),
                ..Default::default()
            }],
            skip_package: None,
        }
    }
}

impl Provider for Config {
    fn metadata(&self) -> Metadata {
        Metadata::named("config")
    }

    fn data(&self) -> Result<Map<Profile, Dict>, Error> {
        figment::providers::Serialized::defaults(self).data()
    }
}

#[derive(Clone, Debug, Default, Deserialize, Getters, Serialize)]
#[getset(get = "pub(crate)")]
pub(crate) struct Channel {
    name: String,

    /// If this set is not empty, only these features will be used to construct the
    /// matrix.
    seed: Option<FeatureSet>,

    /// All of these features will be included in every feature set in the matrix.
    always_include: Option<FeatureSet>,

    /// Any feature set that includes any of these will be excluded from the matrix.
    /// This includes features enabled by other features.
    always_deny: Option<FeatureSet>,

    /// These sets will be dropped from the matrix.
    skip: Option<FeatureMatrix>,

    /// Any feature set that contains two or more features from the same group
    /// will be excluded from the matrix.
    mutually_exclusive: Option<FeatureMatrix>,

    /// Some crates prepend internal features with a double underscore. If this
    /// flag is not set, those features will not be used to build the matrix, but
    /// will be allowed if they are enabled by other features.
    include_hidden: Option<bool>,

    /// Include all optional dependencies
    include_all_optional: Option<bool>,

    /// Include specific optional dependencies.
    /// This is independent of the `include_all_optional` setting.
    include_optional: Option<FeatureSet>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::feature::Feature;
    use figment::providers::{Format, Json};

    fn make_config(json: &str) -> Config {
        let figment = Figment::from(Config::default()).merge(Figment::from(Json::string(json)));
        Config::from(figment).unwrap()
    }

    fn feature_set(features: &[&str]) -> FeatureSet {
        features.iter().map(|&s| Feature::from(s)).collect()
    }

    #[test]
    fn mutually_exclusive_returns_empty_when_not_set() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        let result = config.mutually_exclusive("default").unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn mutually_exclusive_returns_configured_groups() {
        let config = make_config(
            r#"{
            "channel": [{
                "name": "default",
                "mutually_exclusive": [["feat-a", "feat-b"], ["feat-x", "feat-y"]]
            }]
        }"#,
        );
        let result = config.mutually_exclusive("default").unwrap();
        assert_eq!(result.len(), 2);
        assert!(result.contains(&feature_set(&["feat-a", "feat-b"])));
        assert!(result.contains(&feature_set(&["feat-x", "feat-y"])));
    }

    #[test]
    fn mutually_exclusive_falls_back_to_default_channel() {
        let config = make_config(
            r#"{
            "channel": [
                {
                    "name": "default",
                    "mutually_exclusive": [["feat-a", "feat-b"]]
                },
                {
                    "name": "nightly"
                }
            ]
        }"#,
        );
        let result = config.mutually_exclusive("nightly").unwrap();
        assert_eq!(result.len(), 1);
        assert!(result.contains(&feature_set(&["feat-a", "feat-b"])));
    }

    #[test]
    fn mutually_exclusive_named_channel_overrides_default() {
        let config = make_config(
            r#"{
            "channel": [
                {
                    "name": "default",
                    "mutually_exclusive": [["feat-a", "feat-b"]]
                },
                {
                    "name": "nightly",
                    "mutually_exclusive": [["feat-x", "feat-y"]]
                }
            ]
        }"#,
        );
        let result = config.mutually_exclusive("nightly").unwrap();
        assert_eq!(result.len(), 1);
        assert!(result.contains(&feature_set(&["feat-x", "feat-y"])));
        assert!(!result.contains(&feature_set(&["feat-a", "feat-b"])));
    }

    // --- seed ---

    #[test]
    fn seed_returns_none_when_not_set() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(config.seed("default").unwrap().is_none());
    }

    #[test]
    fn seed_returns_value_when_set() {
        let config = make_config(r#"{"channel": [{"name": "default", "seed": ["x", "y"]}]}"#);
        let result = config.seed("default").unwrap();
        assert_eq!(result, Some(feature_set(&["x", "y"])));
    }

    // --- always_include ---

    #[test]
    fn always_include_returns_empty_when_not_set() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(config.always_include("default").unwrap().is_empty());
    }

    #[test]
    fn always_include_returns_configured_features() {
        let config = make_config(
            r#"{"channel": [{"name": "default", "always_include": ["feat-a", "feat-b"]}]}"#,
        );
        let result = config.always_include("default").unwrap();
        assert_eq!(result, feature_set(&["feat-a", "feat-b"]));
    }

    #[test]
    fn always_include_falls_back_to_default_value_for_existing_channel() {
        // Channel exists but has no always_include; falls through else to default's value
        let config = make_config(
            r#"{"channel": [{"name": "default", "always_include": ["feat-a"]}, {"name": "nightly"}]}"#,
        );
        let result = config.always_include("nightly").unwrap();
        assert_eq!(result, feature_set(&["feat-a"]));
    }

    // --- always_deny ---

    #[test]
    fn always_deny_returns_empty_when_not_set() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(config.always_deny("default").unwrap().is_empty());
    }

    #[test]
    fn always_deny_returns_configured_features() {
        let config =
            make_config(r#"{"channel": [{"name": "default", "always_deny": ["bad-feat"]}]}"#);
        let result = config.always_deny("default").unwrap();
        assert_eq!(result, feature_set(&["bad-feat"]));
    }

    // --- skip ---

    #[test]
    fn skip_returns_empty_when_not_set() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(config.skip("default").unwrap().is_empty());
    }

    #[test]
    fn skip_returns_configured_sets() {
        let config =
            make_config(r#"{"channel": [{"name": "default", "skip": [["feat-a", "feat-b"]]}]}"#);
        let result = config.skip("default").unwrap();
        assert_eq!(result.len(), 1);
        assert!(result.contains(&feature_set(&["feat-a", "feat-b"])));
    }

    // --- include_hidden ---

    #[test]
    fn include_hidden_defaults_to_false() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(!config.include_hidden("default").unwrap());
    }

    #[test]
    fn include_hidden_returns_true_when_set() {
        let config = make_config(r#"{"channel": [{"name": "default", "include_hidden": true}]}"#);
        assert!(config.include_hidden("default").unwrap());
    }

    // --- include_all_optional ---

    #[test]
    fn include_all_optional_defaults_to_false() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(!config.include_all_optional("default").unwrap());
    }

    #[test]
    fn include_all_optional_returns_true_when_set() {
        let config =
            make_config(r#"{"channel": [{"name": "default", "include_all_optional": true}]}"#);
        assert!(config.include_all_optional("default").unwrap());
    }

    // --- include_optional ---

    #[test]
    fn include_optional_returns_empty_when_not_set() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(config.include_optional("default").unwrap().is_empty());
    }

    #[test]
    fn include_optional_returns_configured_features() {
        let config =
            make_config(r#"{"channel": [{"name": "default", "include_optional": ["dep-a"]}]}"#);
        let result = config.include_optional("default").unwrap();
        assert_eq!(result, feature_set(&["dep-a"]));
    }

    // --- fallback / error paths ---

    #[test]
    fn all_methods_fall_back_when_channel_not_found() {
        // "no-such" channel doesn't exist; or_else fires and falls back to default
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(config.seed("no-such").unwrap().is_none());
        assert!(config.always_include("no-such").unwrap().is_empty());
        assert!(config.always_deny("no-such").unwrap().is_empty());
        assert!(config.skip("no-such").unwrap().is_empty());
        assert!(config.mutually_exclusive("no-such").unwrap().is_empty());
        assert!(!config.include_hidden("no-such").unwrap());
        assert!(!config.include_all_optional("no-such").unwrap());
        assert!(config.include_optional("no-such").unwrap().is_empty());
    }

    #[test]
    fn get_channel_errors_when_default_missing() {
        // Replace channels entirely with one that isn't "default"
        let config = make_config(r#"{"channel": [{"name": "custom"}]}"#);
        assert!(config.seed("nonexistent").is_err());
    }

    // --- skip_package ---

    #[test]
    fn skip_package_defaults_to_false() {
        let config = Config::from(Figment::from(Config::default())).unwrap();
        assert!(!config.skip_package());
    }

    #[test]
    fn skip_package_returns_true_when_set() {
        let config = make_config(r#"{"skip-package": true, "channel": [{"name": "default"}]}"#);
        assert!(config.skip_package());
    }
}