teamy-figue 2.0.2

Type-safe CLI arguments, config files, and environment variables powered by Facet reflection
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
//! Detection of conflicting enum variant initialization.
//!
//! This module detects when a user tries to initialize multiple variants of the same
//! enum simultaneously (e.g., setting both `storage.s3.bucket` and `storage.gcp.project`
//! when `storage` is an enum with `S3` and `Gcp` variants).
//!
//! # Example error
//!
//! ```text
//! Error: Conflicting enum variants for `config.storage`
//!
//! Multiple variants are being initialized:
//!   - S3 (from MYAPP__STORAGE__S3__BUCKET)
//!   - Gcp (from MYAPP__STORAGE__GCP__PROJECT)
//!
//! An enum can only have one active variant.
//! ```

use std::collections::HashMap;
use std::vec::Vec;

use crate::config_value::ConfigValue;
use crate::path::Path;
use crate::provenance::Provenance;
use crate::schema::{ConfigEnumSchema, ConfigStructSchema, ConfigValueSchema, Schema};

/// A detected enum variant conflict.
#[derive(Debug)]
pub struct EnumConflict {
    /// Path to the enum field (e.g., ["config", "storage"]).
    pub path: Path,
    /// Variants that are being initialized, with their sources.
    pub variants: Vec<VariantSource>,
}

/// A variant being initialized with its provenance.
#[derive(Debug)]
pub struct VariantSource {
    /// The variant name (e.g., "S3", "Gcp").
    pub variant_name: String,
    /// Paths of fields being set for this variant.
    pub field_paths: Vec<Path>,
    /// Provenance for one of the fields (for display).
    pub provenance: Option<Provenance>,
}

impl EnumConflict {
    /// Format this conflict as a user-friendly error message.
    pub fn format(&self) -> String {
        let path_str = self.path.join(".");
        let mut msg = format!("Conflicting enum variants for `{path_str}`\n\n");
        msg.push_str("Multiple variants are being initialized:\n");

        for vs in &self.variants {
            let source = vs
                .provenance
                .as_ref()
                .map(|p| format!(" (from {})", p.source_description()))
                .unwrap_or_default();
            msg.push_str(&format!("  - {}{}\n", vs.variant_name, source));
        }

        msg.push_str("\nAn enum can only have one active variant.");
        msg
    }
}

/// Check for enum variant conflicts in a merged ConfigValue.
///
/// Returns a list of all detected conflicts.
pub fn detect_enum_conflicts(value: &ConfigValue, schema: &Schema) -> Vec<EnumConflict> {
    let mut conflicts = Vec::new();

    // Check config struct if present
    if let Some(config_schema) = schema.config()
        && let Some(field_name) = config_schema.field_name()
        && let ConfigValue::Object(sourced) = value
        && let Some(config_value) = sourced.value.get(field_name)
    {
        let mut path = vec![field_name.to_string()];
        check_struct_for_conflicts(config_value, config_schema, &mut path, &mut conflicts);
    }

    conflicts
}

/// Recursively check a struct for enum conflicts.
fn check_struct_for_conflicts(
    value: &ConfigValue,
    schema: &ConfigStructSchema,
    path: &mut Path,
    conflicts: &mut Vec<EnumConflict>,
) {
    let ConfigValue::Object(sourced) = value else {
        return;
    };

    for (field_name, field_schema) in schema.fields() {
        path.push(field_name.clone());

        if let Some(field_value) = sourced.value.get(field_name) {
            check_value_for_conflicts(field_value, field_schema.value(), path, conflicts);
        }

        path.pop();
    }
}

/// Check a value against its schema for enum conflicts.
fn check_value_for_conflicts(
    value: &ConfigValue,
    schema: &ConfigValueSchema,
    path: &mut Path,
    conflicts: &mut Vec<EnumConflict>,
) {
    match schema {
        ConfigValueSchema::Struct(struct_schema) => {
            check_struct_for_conflicts(value, struct_schema, path, conflicts);
        }
        ConfigValueSchema::Option { value: inner, .. } => {
            // Unwrap option and check inner
            check_value_for_conflicts(value, inner, path, conflicts);
        }
        ConfigValueSchema::Vec(vec_schema) => {
            // Check each element
            if let ConfigValue::Array(sourced) = value {
                for (i, elem) in sourced.value.iter().enumerate() {
                    path.push(i.to_string());
                    check_value_for_conflicts(elem, vec_schema.element(), path, conflicts);
                    path.pop();
                }
            }
        }
        ConfigValueSchema::Enum(enum_schema) => {
            // This is where the magic happens - check for conflicting variants
            if let Some(conflict) = check_enum_for_conflict(value, enum_schema, path) {
                conflicts.push(conflict);
            }
        }
        ConfigValueSchema::Leaf(_) => {
            // Leaf values can't have conflicts
        }
    }
}

/// Check an enum value for conflicting variants.
///
/// If the value is an object with keys matching multiple variants, that's a conflict.
fn check_enum_for_conflict(
    value: &ConfigValue,
    enum_schema: &ConfigEnumSchema,
    path: &Path,
) -> Option<EnumConflict> {
    // If it's already an Enum value, no conflict (variant was explicitly selected)
    if let ConfigValue::Enum(_) = value {
        return None;
    }

    // For objects, check if keys match multiple variant names
    let ConfigValue::Object(sourced) = value else {
        return None;
    };

    // Collect which variants have keys set
    let mut variants_with_data: HashMap<String, VariantSource> = HashMap::new();

    for (key, key_value) in &sourced.value {
        // Check if this key is a variant name
        if enum_schema.get_variant(key).is_some() {
            // This key is a variant name - check if it has data
            if let ConfigValue::Object(variant_obj) = key_value {
                if !variant_obj.value.is_empty() {
                    let provenance = get_first_provenance(key_value);
                    let field_paths = collect_field_paths(key_value, &mut path.clone(), key);

                    variants_with_data.insert(
                        key.clone(),
                        VariantSource {
                            variant_name: key.clone(),
                            field_paths,
                            provenance,
                        },
                    );
                }
            } else {
                // Non-empty non-object value for a variant
                let provenance = get_provenance(key_value);
                variants_with_data.insert(
                    key.clone(),
                    VariantSource {
                        variant_name: key.clone(),
                        field_paths: vec![{
                            let mut p = path.clone();
                            p.push(key.clone());
                            p
                        }],
                        provenance,
                    },
                );
            }
        } else {
            // This key might be a field within a variant
            // Check all variants to see if this field belongs to them
            for (variant_name, variant_schema) in enum_schema.variants() {
                if variant_schema.fields().contains_key(key) {
                    let provenance = get_provenance(key_value);
                    let entry = variants_with_data
                        .entry(variant_name.clone())
                        .or_insert_with(|| VariantSource {
                            variant_name: variant_name.clone(),
                            field_paths: Vec::new(),
                            provenance: None,
                        });
                    entry.field_paths.push({
                        let mut p = path.clone();
                        p.push(key.clone());
                        p
                    });
                    if entry.provenance.is_none() {
                        entry.provenance = provenance;
                    }
                }
            }
        }
    }

    // If more than one variant has data, that's a conflict
    if variants_with_data.len() > 1 {
        Some(EnumConflict {
            path: path.clone(),
            variants: variants_with_data.into_values().collect(),
        })
    } else {
        None
    }
}

/// Get provenance from a ConfigValue.
fn get_provenance(value: &ConfigValue) -> Option<Provenance> {
    match value {
        ConfigValue::Null(s) => s.provenance.clone(),
        ConfigValue::Bool(s) => s.provenance.clone(),
        ConfigValue::Integer(s) => s.provenance.clone(),
        ConfigValue::Float(s) => s.provenance.clone(),
        ConfigValue::String(s) => s.provenance.clone(),
        ConfigValue::Array(s) => s.provenance.clone(),
        ConfigValue::Object(s) => s.provenance.clone(),
        ConfigValue::Enum(s) => s.provenance.clone(),
    }
}

/// Get the first provenance from a nested value.
fn get_first_provenance(value: &ConfigValue) -> Option<Provenance> {
    if let Some(prov) = get_provenance(value) {
        return Some(prov);
    }

    match value {
        ConfigValue::Object(sourced) => {
            for v in sourced.value.values() {
                if let Some(prov) = get_first_provenance(v) {
                    return Some(prov);
                }
            }
            None
        }
        ConfigValue::Array(sourced) => {
            for v in &sourced.value {
                if let Some(prov) = get_first_provenance(v) {
                    return Some(prov);
                }
            }
            None
        }
        _ => None,
    }
}

/// Collect all field paths under a value.
fn collect_field_paths(value: &ConfigValue, base_path: &mut Path, key: &str) -> Vec<Path> {
    let mut paths = Vec::new();
    base_path.push(key.to_string());

    match value {
        ConfigValue::Object(sourced) => {
            if sourced.value.is_empty() {
                paths.push(base_path.clone());
            } else {
                for (k, v) in &sourced.value {
                    paths.extend(collect_field_paths(v, base_path, k));
                }
            }
        }
        _ => {
            paths.push(base_path.clone());
        }
    }

    base_path.pop();
    paths
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate as figue;
    use crate::config_value::Sourced;
    use facet::Facet;
    use indexmap::IndexMap;

    // ========================================================================
    // Test schemas
    // ========================================================================

    #[derive(Facet)]
    #[facet(rename_all = "kebab-case")]
    #[repr(u8)]
    #[allow(dead_code)]
    enum Storage {
        S3 { bucket: String, region: String },
        Gcp { project: String, zone: String },
        Local { path: String },
    }

    #[derive(Facet)]
    struct ConfigWithEnum {
        storage: Storage,
        port: u16,
    }

    #[derive(Facet)]
    struct ArgsWithEnumConfig {
        #[facet(figue::config)]
        config: ConfigWithEnum,
    }

    // ========================================================================
    // Helpers
    // ========================================================================

    fn make_object(entries: Vec<(&str, ConfigValue)>) -> ConfigValue {
        let map: IndexMap<String, ConfigValue, std::hash::RandomState> = entries
            .into_iter()
            .map(|(k, v)| (k.to_string(), v))
            .collect();
        ConfigValue::Object(Sourced::new(map))
    }

    fn make_string(value: &str, prov: Option<Provenance>) -> ConfigValue {
        ConfigValue::String(Sourced {
            value: value.to_string(),
            span: None,
            provenance: prov,
        })
    }

    // ========================================================================
    // Tests
    // ========================================================================

    #[test]
    fn test_no_conflict_single_variant() {
        // Only s3 variant is set - no conflict
        let value = make_object(vec![(
            "config",
            make_object(vec![
                (
                    "s3",
                    make_object(vec![
                        ("bucket", make_string("my-bucket", None)),
                        ("region", make_string("us-east-1", None)),
                    ]),
                ),
                ("port", ConfigValue::Integer(Sourced::new(8080))),
            ]),
        )]);

        let schema = Schema::from_shape(ArgsWithEnumConfig::SHAPE).unwrap();
        let conflicts = detect_enum_conflicts(&value, &schema);

        assert!(
            conflicts.is_empty(),
            "should have no conflicts: {conflicts:?}"
        );
    }

    #[test]
    fn test_conflict_two_variants() {
        // Both s3 and gcp variants are set - conflict!
        let value = make_object(vec![(
            "config",
            make_object(vec![
                (
                    "storage",
                    make_object(vec![
                        (
                            "s3",
                            make_object(vec![("bucket", make_string("my-bucket", None))]),
                        ),
                        (
                            "gcp",
                            make_object(vec![("project", make_string("my-project", None))]),
                        ),
                    ]),
                ),
                ("port", ConfigValue::Integer(Sourced::new(8080))),
            ]),
        )]);

        let schema = Schema::from_shape(ArgsWithEnumConfig::SHAPE).unwrap();
        let conflicts = detect_enum_conflicts(&value, &schema);

        assert_eq!(conflicts.len(), 1, "should have one conflict");
        let conflict = &conflicts[0];
        assert_eq!(conflict.path, vec!["config", "storage"]);
        assert_eq!(conflict.variants.len(), 2);

        // Check format includes both variants
        let msg = conflict.format();
        assert!(msg.contains("s3"), "error should mention s3: {msg}");
        assert!(msg.contains("gcp"), "error should mention gcp: {msg}");
    }

    #[test]
    fn test_conflict_with_provenance() {
        // Conflict with provenance tracking
        let env_prov = Provenance::env("MYAPP__STORAGE__S3__BUCKET", "my-bucket");
        let cli_prov = Provenance::cli("--config.storage.gcp.project", "my-project");

        let value = make_object(vec![(
            "config",
            make_object(vec![(
                "storage",
                make_object(vec![
                    (
                        "s3",
                        make_object(vec![("bucket", make_string("my-bucket", Some(env_prov)))]),
                    ),
                    (
                        "gcp",
                        make_object(vec![("project", make_string("my-project", Some(cli_prov)))]),
                    ),
                ]),
            )]),
        )]);

        let schema = Schema::from_shape(ArgsWithEnumConfig::SHAPE).unwrap();
        let conflicts = detect_enum_conflicts(&value, &schema);

        assert_eq!(conflicts.len(), 1);
        let msg = conflicts[0].format();

        // Should mention provenance sources
        assert!(
            msg.contains("MYAPP__STORAGE__S3__BUCKET")
                || msg.contains("--config.storage.gcp.project"),
            "error should mention provenance: {msg}"
        );
    }

    #[test]
    fn test_conflict_three_variants() {
        // All three variants are set - conflict!
        let value = make_object(vec![(
            "config",
            make_object(vec![(
                "storage",
                make_object(vec![
                    (
                        "s3",
                        make_object(vec![("bucket", make_string("my-bucket", None))]),
                    ),
                    (
                        "gcp",
                        make_object(vec![("project", make_string("my-project", None))]),
                    ),
                    (
                        "local",
                        make_object(vec![("path", make_string("/data", None))]),
                    ),
                ]),
            )]),
        )]);

        let schema = Schema::from_shape(ArgsWithEnumConfig::SHAPE).unwrap();
        let conflicts = detect_enum_conflicts(&value, &schema);

        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflicts[0].variants.len(), 3);
    }

    #[derive(Facet)]
    struct ConfigWithOptionalEnum {
        storage: Option<Storage>,
    }

    #[derive(Facet)]
    struct ArgsWithOptionalEnumConfig {
        #[facet(figue::config)]
        config: ConfigWithOptionalEnum,
    }

    #[test]
    fn test_conflict_optional_enum() {
        // Optional enum with conflict
        let value = make_object(vec![(
            "config",
            make_object(vec![(
                "storage",
                make_object(vec![
                    (
                        "s3",
                        make_object(vec![("bucket", make_string("my-bucket", None))]),
                    ),
                    (
                        "gcp",
                        make_object(vec![("project", make_string("my-project", None))]),
                    ),
                ]),
            )]),
        )]);

        let schema = Schema::from_shape(ArgsWithOptionalEnumConfig::SHAPE).unwrap();
        let conflicts = detect_enum_conflicts(&value, &schema);

        assert_eq!(
            conflicts.len(),
            1,
            "optional enum should also detect conflicts"
        );
    }

    #[derive(Facet)]
    struct NestedConfig {
        inner: InnerConfig,
    }

    #[derive(Facet)]
    struct InnerConfig {
        storage: Storage,
    }

    #[derive(Facet)]
    struct ArgsWithNestedEnumConfig {
        #[facet(figue::config)]
        config: NestedConfig,
    }

    #[test]
    fn test_conflict_nested_enum() {
        // Nested enum with conflict
        let value = make_object(vec![(
            "config",
            make_object(vec![(
                "inner",
                make_object(vec![(
                    "storage",
                    make_object(vec![
                        (
                            "s3",
                            make_object(vec![("bucket", make_string("my-bucket", None))]),
                        ),
                        (
                            "gcp",
                            make_object(vec![("project", make_string("my-project", None))]),
                        ),
                    ]),
                )]),
            )]),
        )]);

        let schema = Schema::from_shape(ArgsWithNestedEnumConfig::SHAPE).unwrap();
        let conflicts = detect_enum_conflicts(&value, &schema);

        assert_eq!(conflicts.len(), 1);
        assert_eq!(
            conflicts[0].path,
            vec!["config", "inner", "storage"],
            "should report correct nested path"
        );
    }
}