esp-config 0.7.0

Configure projects using esp-hal and related packages
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
use core::fmt::Display;
use std::{collections::HashMap, env, fmt, fs, io::Write, path::PathBuf};

use serde::{Deserialize, Serialize};
use somni_expr::TypeSet128;

use crate::generate::{validator::Validator, value::Value};

mod markdown;
pub(crate) mod validator;
pub(crate) mod value;

/// Configuration errors.
#[derive(Clone, PartialEq, Eq)]
pub enum Error {
    /// Parse errors.
    Parse(String),
    /// Validation errors.
    Validation(String),
}

impl Error {
    /// Convenience function for creating parse errors.
    pub fn parse<S>(message: S) -> Self
    where
        S: Into<String>,
    {
        Self::Parse(message.into())
    }

    /// Convenience function for creating validation errors.
    pub fn validation<S>(message: S) -> Self
    where
        S: Into<String>,
    {
        Self::Validation(message.into())
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Parse(message) => write!(f, "{message}"),
            Error::Validation(message) => write!(f, "{message}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        None
    }

    fn description(&self) -> &str {
        "description() is deprecated; use Display"
    }

    fn cause(&self) -> Option<&dyn core::error::Error> {
        self.source()
    }
}

/// The root node of a configuration.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// The crate name.
    #[serde(rename = "crate")]
    pub krate: String,
    /// The config options for this crate.
    pub options: Vec<CfgOption>,
    /// Optionally additional checks.
    pub checks: Option<Vec<String>>,
}

fn true_default() -> String {
    "true".to_string()
}

fn unstable_default() -> Stability {
    Stability::Unstable
}

/// A default value for a configuration option.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct CfgDefaultValue {
    /// Condition which makes this default value used.
    /// You can and have to have exactly one active default value.
    #[serde(rename = "if")]
    #[serde(default = "true_default")]
    pub if_: String,
    /// The default value.
    pub value: Value,
}

/// A configuration option.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct CfgOption {
    /// Name of the configuration option
    pub name: String,
    /// Description of the configuration option.
    /// This will be visible in the documentation and in the tooling.
    pub description: String,
    /// A condition which specified when this option is active.
    #[serde(default = "true_default")]
    pub active: String,
    /// The default value.
    /// Exactly one of the items needs to be active at any time.
    pub default: Vec<CfgDefaultValue>,
    /// Constraints (Validators) to use.
    /// If given at most one item is allowed to be active at any time.
    pub constraints: Option<Vec<CfgConstraint>>,
    /// A display hint for the value.
    /// This is meant for tooling and/or documentation.
    pub display_hint: Option<DisplayHint>,
    /// The stability guarantees of this option.
    #[serde(default = "unstable_default")]
    pub stability: Stability,
}

/// A conditional constraint / validator for a config option.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct CfgConstraint {
    /// Condition which makes this validator used.
    #[serde(rename = "if")]
    #[serde(default = "true_default")]
    if_: String,
    /// The validator to be used.
    #[serde(rename = "type")]
    type_: Validator,
}

/// Generate the config from a YAML definition.
///
/// After deserializing the config and normalizing it, this will call
/// [generate_config] to finally get the currently active configuration.
pub fn generate_config_from_yaml_definition(
    yaml: &str,
    enable_unstable: bool,
    emit_md_tables: bool,
    chip: Option<esp_metadata_generated::Chip>,
) -> Result<HashMap<String, Value>, Error> {
    let features: Vec<String> = env::vars()
        .filter(|(k, _)| k.starts_with("CARGO_FEATURE_"))
        .map(|(k, _)| k)
        .map(|v| {
            v.strip_prefix("CARGO_FEATURE_")
                .unwrap_or_default()
                .to_string()
        })
        .collect();

    let (config, options) = evaluate_yaml_config(yaml, chip, features, false)?;

    let cfg = generate_config(&config.krate, &options, enable_unstable, emit_md_tables);

    do_checks(config.checks.as_ref(), &cfg)?;

    Ok(cfg)
}

/// Check the given actual values by applying checking the given checks
pub fn do_checks(checks: Option<&Vec<String>>, cfg: &HashMap<String, Value>) -> Result<(), Error> {
    if let Some(checks) = checks {
        let mut eval_ctx = somni_expr::Context::<TypeSet128>::new_with_types();
        for (k, v) in cfg.iter() {
            match v {
                Value::Bool(v) => eval_ctx.add_variable(k, *v),
                Value::Integer(v) => eval_ctx.add_variable(k, *v),
                Value::String(v) => eval_ctx.add_variable::<&str>(k, v),
            }
        }
        for check in checks {
            if !eval_ctx
                .evaluate::<bool>(check)
                .map_err(|err| Error::Parse(format!("Validation error: {err:?}")))?
            {
                return Err(Error::Validation(format!("Validation error: '{check}'")));
            }
        }
    };
    Ok(())
}

/// Evaluate the given YAML representation of a config definition.
pub fn evaluate_yaml_config(
    yaml: &str,
    chip: Option<esp_metadata_generated::Chip>,
    features: Vec<String>,
    ignore_feature_gates: bool,
) -> Result<(Config, Vec<ConfigOption>), Error> {
    let config: Config = serde_yaml::from_str(yaml).map_err(|err| Error::Parse(err.to_string()))?;
    let mut options = Vec::new();
    let mut eval_ctx = somni_expr::Context::new();
    if let Some(chip) = chip {
        eval_ctx.add_variable("chip", chip.name());
        eval_ctx.add_variable("ignore_feature_gates", ignore_feature_gates);
        eval_ctx.add_function("feature", move |feature: &str| chip.contains(feature));
        eval_ctx.add_function("cargo_feature", |feature: &str| {
            features.contains(&feature.to_uppercase().replace("-", "_"))
        });
    }
    for option in &config.options {
        let active = eval_ctx
            .evaluate::<bool>(&option.active)
            .map_err(|err| Error::Parse(format!("{err:?}")))?;

        let constraint = {
            let mut active_constraint = None;
            if let Some(constraints) = &option.constraints {
                for constraint in constraints {
                    if eval_ctx
                        .evaluate::<bool>(&constraint.if_)
                        .map_err(|err| Error::Parse(format!("{err:?}")))?
                    {
                        active_constraint = Some(constraint.type_.clone());
                        break;
                    }
                }
            };

            if option.constraints.is_some() && active_constraint.is_none() {
                panic!(
                    "No constraint active for crate {}, option {}",
                    config.krate, option.name
                );
            }

            active_constraint
        };

        let default_value = {
            let mut default_value = None;
            for value in &option.default {
                if eval_ctx
                    .evaluate::<bool>(&value.if_)
                    .map_err(|err| Error::Parse(format!("{err:?}")))?
                {
                    default_value = Some(value.value.clone());
                    break;
                }
            }

            if default_value.is_none() {
                panic!(
                    "No default value active for crate {}, option {}",
                    config.krate, option.name
                );
            }

            default_value
        };

        let option = ConfigOption {
            name: option.name.clone(),
            description: option.description.clone(),
            default_value: default_value.ok_or_else(|| {
                Error::Parse(format!("No default value found for {}", option.name))
            })?,
            constraint,
            stability: option.stability.clone(),
            active,
            display_hint: option.display_hint.unwrap_or(DisplayHint::None),
        };
        options.push(option);
    }
    Ok((config, options))
}

/// Generate and parse config from a prefix, and an array of [ConfigOption].
///
/// This function will parse any `SCREAMING_SNAKE_CASE` environment variables
/// that match the given prefix. It will then attempt to parse the [`Value`] and
/// run any validators which have been specified.
///
/// [`Stability::Unstable`] features will only be enabled if the `unstable`
/// feature is enabled in the dependant crate. If the `unstable` feature is not
/// enabled, setting these options will result in a build error.
///
/// Once the config has been parsed, this function will emit `snake_case` cfg's
/// _without_ the prefix which can be used in the dependant crate. After that,
/// it will create a markdown table in the `OUT_DIR` under the name
/// `{prefix}_config_table.md` where prefix has also been converted to
/// `snake_case`. This can be included in crate documentation to outline the
/// available configuration options for the crate.
///
/// Passing a value of true for the `emit_md_tables` argument will create and
/// write markdown files of the available configuration and selected
/// configuration which can be included in documentation.
///
/// Unknown keys with the supplied prefix will cause this function to panic.
pub fn generate_config(
    crate_name: &str,
    config: &[ConfigOption],
    enable_unstable: bool,
    emit_md_tables: bool,
) -> HashMap<String, Value> {
    let configs = generate_config_internal(std::io::stdout(), crate_name, config, enable_unstable);

    if emit_md_tables {
        let file_name = snake_case(crate_name);

        let mut doc_table = markdown::DOC_TABLE_HEADER.replace(
            "{prefix}",
            format!("{}_CONFIG_*", screaming_snake_case(crate_name)).as_str(),
        );
        let mut selected_config = String::from(markdown::SELECTED_TABLE_HEADER);

        for (name, option, value) in configs.iter() {
            if !option.active {
                continue;
            }
            markdown::write_doc_table_line(&mut doc_table, name, option);
            markdown::write_summary_table_line(&mut selected_config, name, value);
        }

        write_out_file(format!("{file_name}_config_table.md"), doc_table);
        write_out_file(format!("{file_name}_selected_config.md"), selected_config);
    }

    // Remove the ConfigOptions from the output
    configs.into_iter().map(|(k, _, v)| (k, v)).collect()
}

pub fn generate_config_internal<'a>(
    mut stdout: impl Write,
    crate_name: &str,
    config: &'a [ConfigOption],
    enable_unstable: bool,
) -> Vec<(String, &'a ConfigOption, Value)> {
    // Only rebuild if `build.rs` changed. Otherwise, Cargo will rebuild if any
    // other file changed.
    writeln!(stdout, "cargo:rerun-if-changed=build.rs").ok();

    // Ensure that the prefix is `SCREAMING_SNAKE_CASE`:
    let prefix = format!("{}_CONFIG_", screaming_snake_case(crate_name));

    let mut configs = create_config(&prefix, config);
    capture_from_env(crate_name, &prefix, &mut configs, enable_unstable);

    for (_, option, value) in configs.iter() {
        if let Some(ref validator) = option.constraint {
            validator.validate(value).unwrap_or_else(|err| {
                panic!(
                    "Validation error for crate {}, option {}: {err}",
                    crate_name, option.name
                )
            });
        }
    }

    emit_configuration(&mut stdout, &configs);

    configs
}

/// The stability of the configuration option.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum Stability {
    /// Unstable options need to be activated with the `unstable` feature
    /// of the package that defines them.
    Unstable,
    /// Stable options contain the first version in which they were
    /// stabilized.
    Stable(String),
}

impl Display for Stability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Stability::Unstable => write!(f, "⚠️ Unstable"),
            Stability::Stable(version) => write!(f, "Stable since {version}"),
        }
    }
}

/// A display hint (for tooling only)
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum DisplayHint {
    /// No display hint
    None,

    /// Use a binary representation
    Binary,

    /// Use a hexadecimal representation
    Hex,

    /// Use a octal representation
    Octal,
}

impl DisplayHint {
    /// Converts a [Value] to String applying the correct display hint.
    pub fn format_value(self, value: &Value) -> String {
        match value {
            Value::Bool(b) => b.to_string(),
            Value::Integer(i) => match self {
                DisplayHint::None => format!("{i}"),
                DisplayHint::Binary => format!("0b{i:0b}"),
                DisplayHint::Hex => format!("0x{i:X}"),
                DisplayHint::Octal => format!("0o{i:o}"),
            },
            Value::String(s) => s.clone(),
        }
    }
}

/// A configuration option.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ConfigOption {
    /// The name of the configuration option.
    ///
    /// The associated environment variable has the format of
    /// `<PREFIX>_CONFIG_<NAME>`.
    pub name: String,

    /// The description of the configuration option.
    ///
    /// The description will be included in the generated markdown
    /// documentation.
    pub description: String,

    /// The default value of the configuration option.
    pub default_value: Value,

    /// An optional validator for the configuration option.
    pub constraint: Option<Validator>,

    /// The stability of the configuration option.
    pub stability: Stability,

    /// Whether the config option should be offered to the user.
    ///
    /// Inactive options are not included in the documentation, and accessing
    /// them provides the default value.
    pub active: bool,

    /// A display hint (for tooling)
    pub display_hint: DisplayHint,
}

impl ConfigOption {
    /// Get the corresponding ENV_VAR name given the crate-name
    pub fn full_env_var(&self, crate_name: &str) -> String {
        self.env_var(&format!("{}_CONFIG_", screaming_snake_case(crate_name)))
    }

    fn env_var(&self, prefix: &str) -> String {
        format!("{}{}", prefix, screaming_snake_case(&self.name))
    }

    fn cfg_name(&self) -> String {
        snake_case(&self.name)
    }

    fn is_stable(&self) -> bool {
        matches!(self.stability, Stability::Stable(_))
    }
}

fn create_config<'a>(
    prefix: &str,
    config: &'a [ConfigOption],
) -> Vec<(String, &'a ConfigOption, Value)> {
    let mut configs = Vec::with_capacity(config.len());

    for option in config {
        configs.push((option.env_var(prefix), option, option.default_value.clone()));
    }

    configs
}

fn capture_from_env(
    crate_name: &str,
    prefix: &str,
    configs: &mut Vec<(String, &ConfigOption, Value)>,
    enable_unstable: bool,
) {
    let mut unknown = Vec::new();
    let mut failed = Vec::new();
    let mut unstable = Vec::new();

    // Try and capture input from the environment:
    for (var, value) in env::vars() {
        if var.starts_with(prefix) {
            let Some((_, option, cfg)) = configs.iter_mut().find(|(k, _, _)| k == &var) else {
                unknown.push(var);
                continue;
            };

            if !option.active {
                unknown.push(var);
                continue;
            }

            if !enable_unstable && !option.is_stable() {
                unstable.push(var);
                continue;
            }

            if let Err(e) = cfg.parse_in_place(&value) {
                failed.push(format!("{var}: {e}"));
            }
        }
    }

    if !failed.is_empty() {
        panic!("Invalid configuration options detected: {failed:?}");
    }

    if !unstable.is_empty() {
        panic!(
            "The following configuration options are unstable: {unstable:?}. You can enable it by \
            activating the 'unstable' feature in {crate_name}."
        );
    }

    if !unknown.is_empty() {
        panic!("Unknown configuration options detected: {unknown:?}");
    }
}

fn emit_configuration(mut stdout: impl Write, configs: &[(String, &ConfigOption, Value)]) {
    for (env_var_name, option, value) in configs.iter() {
        let cfg_name = option.cfg_name();

        // Output the raw configuration as an env var. Values that haven't been seen
        // will be output here with the default value. Also trigger a rebuild if config
        // environment variable changed.
        writeln!(stdout, "cargo:rustc-env={env_var_name}={value}").ok();
        writeln!(stdout, "cargo:rerun-if-env-changed={env_var_name}").ok();

        // Emit known config symbol:
        writeln!(stdout, "cargo:rustc-check-cfg=cfg({cfg_name})").ok();

        // Emit specially-handled values:
        if let Value::Bool(true) = value {
            writeln!(stdout, "cargo:rustc-cfg={cfg_name}").ok();
        }

        // Emit extra symbols based on the validator (e.g. enumerated values):
        if let Some(validator) = option.constraint.as_ref() {
            validator.emit_cargo_extras(&mut stdout, &cfg_name, value);
        }
    }
}

fn write_out_file(file_name: String, json: String) {
    let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
    let out_file = out_dir.join(file_name);
    fs::write(out_file, json).unwrap();
}

fn snake_case(name: &str) -> String {
    let mut name = name.replace("-", "_");
    name.make_ascii_lowercase();

    name
}

fn screaming_snake_case(name: &str) -> String {
    let mut name = name.replace("-", "_");
    name.make_ascii_uppercase();

    name
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generate::{validator::Validator, value::Value};

    #[test]
    fn value_number_formats() {
        const INPUTS: &[&str] = &["0xAA", "0o252", "0b0000000010101010", "170"];
        let mut v = Value::Integer(0);

        for input in INPUTS {
            v.parse_in_place(input).unwrap();
            // no matter the input format, the output format should be decimal
            assert_eq!(v.to_string(), "170");
        }
    }

    #[test]
    fn value_bool_inputs() {
        let mut v = Value::Bool(false);

        v.parse_in_place("true").unwrap();
        assert_eq!(v.to_string(), "true");

        v.parse_in_place("false").unwrap();
        assert_eq!(v.to_string(), "false");

        v.parse_in_place("else")
            .expect_err("Only true or false are valid");
    }

    #[test]
    fn env_override() {
        temp_env::with_vars(
            [
                ("ESP_TEST_CONFIG_NUMBER", Some("0xaa")),
                ("ESP_TEST_CONFIG_NUMBER_SIGNED", Some("-999")),
                ("ESP_TEST_CONFIG_STRING", Some("Hello world!")),
                ("ESP_TEST_CONFIG_BOOL", Some("true")),
            ],
            || {
                let configs = generate_config(
                    "esp-test",
                    &[
                        ConfigOption {
                            name: String::from("number"),
                            description: String::from("NA"),
                            default_value: Value::Integer(999),
                            constraint: None,
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("number_signed"),
                            description: String::from("NA"),
                            default_value: Value::Integer(-777),
                            constraint: None,
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("string"),
                            description: String::from("NA"),
                            default_value: Value::String("Demo".to_string()),
                            constraint: None,
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("bool"),
                            description: String::from("NA"),
                            default_value: Value::Bool(false),
                            constraint: None,
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("number_default"),
                            description: String::from("NA"),
                            default_value: Value::Integer(999),
                            constraint: None,
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("string_default"),
                            description: String::from("NA"),
                            default_value: Value::String("Demo".to_string()),
                            constraint: None,
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("bool_default"),
                            description: String::from("NA"),
                            default_value: Value::Bool(false),
                            constraint: None,
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                    ],
                    false,
                    false,
                );

                // some values have changed
                assert_eq!(configs["ESP_TEST_CONFIG_NUMBER"], Value::Integer(0xaa));
                assert_eq!(
                    configs["ESP_TEST_CONFIG_NUMBER_SIGNED"],
                    Value::Integer(-999)
                );
                assert_eq!(
                    configs["ESP_TEST_CONFIG_STRING"],
                    Value::String("Hello world!".to_string())
                );
                assert_eq!(configs["ESP_TEST_CONFIG_BOOL"], Value::Bool(true));

                // the rest are the defaults
                assert_eq!(
                    configs["ESP_TEST_CONFIG_NUMBER_DEFAULT"],
                    Value::Integer(999)
                );
                assert_eq!(
                    configs["ESP_TEST_CONFIG_STRING_DEFAULT"],
                    Value::String("Demo".to_string())
                );
                assert_eq!(configs["ESP_TEST_CONFIG_BOOL_DEFAULT"], Value::Bool(false));
            },
        )
    }

    #[test]
    fn builtin_validation_passes() {
        temp_env::with_vars(
            [
                ("ESP_TEST_CONFIG_POSITIVE_NUMBER", Some("7")),
                ("ESP_TEST_CONFIG_NEGATIVE_NUMBER", Some("-1")),
                ("ESP_TEST_CONFIG_NON_NEGATIVE_NUMBER", Some("0")),
                ("ESP_TEST_CONFIG_RANGE", Some("9")),
            ],
            || {
                generate_config(
                    "esp-test",
                    &[
                        ConfigOption {
                            name: String::from("positive_number"),
                            description: String::from("NA"),
                            default_value: Value::Integer(-1),
                            constraint: Some(Validator::PositiveInteger),
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("negative_number"),
                            description: String::from("NA"),
                            default_value: Value::Integer(1),
                            constraint: Some(Validator::NegativeInteger),
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("non_negative_number"),
                            description: String::from("NA"),
                            default_value: Value::Integer(-1),
                            constraint: Some(Validator::NonNegativeInteger),
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                        ConfigOption {
                            name: String::from("range"),
                            description: String::from("NA"),
                            default_value: Value::Integer(0),
                            constraint: Some(Validator::IntegerInRange(5..10)),
                            stability: Stability::Stable(String::from("testing")),
                            active: true,
                            display_hint: DisplayHint::None,
                        },
                    ],
                    false,
                    false,
                )
            },
        );
    }

    #[test]
    #[should_panic]
    fn builtin_validation_bails() {
        temp_env::with_vars([("ESP_TEST_CONFIG_POSITIVE_NUMBER", Some("-99"))], || {
            generate_config(
                "esp-test",
                &[ConfigOption {
                    name: String::from("positive_number"),
                    description: String::from("NA"),
                    default_value: Value::Integer(-1),
                    constraint: Some(Validator::PositiveInteger),
                    stability: Stability::Stable(String::from("testing")),
                    active: true,
                    display_hint: DisplayHint::None,
                }],
                false,
                false,
            )
        });
    }

    #[test]
    #[should_panic]
    fn env_unknown_bails() {
        temp_env::with_vars(
            [
                ("ESP_TEST_CONFIG_NUMBER", Some("0xaa")),
                ("ESP_TEST_CONFIG_RANDOM_VARIABLE", Some("")),
            ],
            || {
                generate_config(
                    "esp-test",
                    &[ConfigOption {
                        name: String::from("number"),
                        description: String::from("NA"),
                        default_value: Value::Integer(999),
                        constraint: None,
                        stability: Stability::Stable(String::from("testing")),
                        active: true,
                        display_hint: DisplayHint::None,
                    }],
                    false,
                    false,
                );
            },
        );
    }

    #[test]
    #[should_panic]
    fn env_invalid_values_bails() {
        temp_env::with_vars([("ESP_TEST_CONFIG_NUMBER", Some("Hello world"))], || {
            generate_config(
                "esp-test",
                &[ConfigOption {
                    name: String::from("number"),
                    description: String::from("NA"),
                    default_value: Value::Integer(999),
                    constraint: None,
                    stability: Stability::Stable(String::from("testing")),
                    active: true,
                    display_hint: DisplayHint::None,
                }],
                false,
                false,
            );
        });
    }

    #[test]
    fn env_unknown_prefix_is_ignored() {
        temp_env::with_vars(
            [("ESP_TEST_OTHER_CONFIG_NUMBER", Some("Hello world"))],
            || {
                generate_config(
                    "esp-test",
                    &[ConfigOption {
                        name: String::from("number"),
                        description: String::from("NA"),
                        default_value: Value::Integer(999),
                        constraint: None,
                        stability: Stability::Stable(String::from("testing")),
                        active: true,
                        display_hint: DisplayHint::None,
                    }],
                    false,
                    false,
                );
            },
        );
    }

    #[test]
    fn enumeration_validator() {
        let mut stdout = Vec::new();
        temp_env::with_vars([("ESP_TEST_CONFIG_SOME_KEY", Some("variant-0"))], || {
            generate_config_internal(
                &mut stdout,
                "esp-test",
                &[ConfigOption {
                    name: String::from("some-key"),
                    description: String::from("NA"),
                    default_value: Value::String("variant-0".to_string()),
                    constraint: Some(Validator::Enumeration(vec![
                        "variant-0".to_string(),
                        "variant-1".to_string(),
                    ])),
                    stability: Stability::Stable(String::from("testing")),
                    active: true,
                    display_hint: DisplayHint::None,
                }],
                false,
            );
        });

        let cargo_lines: Vec<&str> = std::str::from_utf8(&stdout).unwrap().lines().collect();
        assert!(cargo_lines.contains(&"cargo:rustc-check-cfg=cfg(some_key)"));
        assert!(cargo_lines.contains(&"cargo:rustc-env=ESP_TEST_CONFIG_SOME_KEY=variant-0"));
        assert!(cargo_lines.contains(&"cargo:rustc-check-cfg=cfg(some_key_variant_0)"));
        assert!(cargo_lines.contains(&"cargo:rustc-check-cfg=cfg(some_key_variant_1)"));
        assert!(cargo_lines.contains(&"cargo:rustc-cfg=some_key_variant_0"));
    }

    #[test]
    #[should_panic]
    fn unstable_option_panics_unless_enabled() {
        let mut stdout = Vec::new();
        temp_env::with_vars([("ESP_TEST_CONFIG_SOME_KEY", Some("variant-0"))], || {
            generate_config_internal(
                &mut stdout,
                "esp-test",
                &[ConfigOption {
                    name: String::from("some-key"),
                    description: String::from("NA"),
                    default_value: Value::String("variant-0".to_string()),
                    constraint: Some(Validator::Enumeration(vec![
                        "variant-0".to_string(),
                        "variant-1".to_string(),
                    ])),
                    stability: Stability::Unstable,
                    active: true,
                    display_hint: DisplayHint::None,
                }],
                false,
            );
        });
    }

    #[test]
    #[should_panic]
    fn inactive_option_panics() {
        let mut stdout = Vec::new();
        temp_env::with_vars([("ESP_TEST_CONFIG_SOME_KEY", Some("variant-0"))], || {
            generate_config_internal(
                &mut stdout,
                "esp-test",
                &[ConfigOption {
                    name: String::from("some-key"),
                    description: String::from("NA"),
                    default_value: Value::String("variant-0".to_string()),
                    constraint: Some(Validator::Enumeration(vec![
                        "variant-0".to_string(),
                        "variant-1".to_string(),
                    ])),
                    stability: Stability::Stable(String::from("testing")),
                    active: false,
                    display_hint: DisplayHint::None,
                }],
                false,
            );
        });
    }

    #[test]
    fn deserialization() {
        let yml = r#"
crate: esp-bootloader-esp-idf

options:
- name: mmu_page_size
  description: ESP32-C2, ESP32-C6 and ESP32-H2 support configurable page sizes. This is currently only used to populate the app descriptor.
  default:
    - value: '"64k"'
  stability: !Stable xxxx
  constraints:
  - if: true
    type:
      validator: enumeration
      value:
      - 8k
      - 16k
      - 32k
      - 64k

- name: esp_idf_version
  description: ESP-IDF version used in the application descriptor. Currently it's not checked by the bootloader.
  default:
    - if: 'chip == "esp32c6"'
      value: '"esp32c6"'
    - if: 'chip == "esp32"'
      value: '"other"'
  active: true

- name: partition-table-offset
  description: "The address of partition table (by default 0x8000). Allows you to \
    move the partition table, it gives more space for the bootloader. Note that the \
    bootloader and app will both need to be compiled with the same \
    PARTITION_TABLE_OFFSET value."
  default:
    - if: true
      value: 32768
  stability: Unstable
  active: 'chip == "esp32c6"'
"#;

        let (cfg, options) = evaluate_yaml_config(
            yml,
            Some(esp_metadata_generated::Chip::Esp32c6),
            vec![],
            false,
        )
        .unwrap();

        assert_eq!("esp-bootloader-esp-idf", cfg.krate);

        assert_eq!(
            vec![
                    ConfigOption {
                        name: "mmu_page_size".to_string(),
                        description: "ESP32-C2, ESP32-C6 and ESP32-H2 support configurable page sizes. This is currently only used to populate the app descriptor.".to_string(),
                        default_value: Value::String("64k".to_string()),
                        constraint: Some(
                            Validator::Enumeration(
                                vec![
                                    "8k".to_string(),
                                    "16k".to_string(),
                                    "32k".to_string(),
                                    "64k".to_string(),
                                ],
                            ),
                        ),
                        stability: Stability::Stable("xxxx".to_string()),
                        active: true,
                        display_hint: DisplayHint::None,
                    },
                    ConfigOption {
                        name: "esp_idf_version".to_string(),
                        description: "ESP-IDF version used in the application descriptor. Currently it's not checked by the bootloader.".to_string(),
                        default_value: Value::String("esp32c6".to_string()),
                        constraint: None,
                        stability: Stability::Unstable,
                        active: true,
                        display_hint: DisplayHint::None,
                    },
                    ConfigOption {
                        name: "partition-table-offset".to_string(),
                        description: "The address of partition table (by default 0x8000). Allows you to move the partition table, it gives more space for the bootloader. Note that the bootloader and app will both need to be compiled with the same PARTITION_TABLE_OFFSET value.".to_string(),
                        default_value: Value::Integer(32768),
                        constraint: None,
                        stability: Stability::Unstable,
                        active: true,
                        display_hint: DisplayHint::None,
                    },
            ],
            options
        );
    }

    #[test]
    fn deserialization_fallback_default() {
        let yml = r#"
crate: esp-bootloader-esp-idf

options:
- name: esp_idf_version
  description: ESP-IDF version used in the application descriptor. Currently it's not checked by the bootloader.
  default:
    - if: 'chip == "esp32c6"'
      value: '"esp32c6"'
    - if: 'chip == "esp32"'
      value: '"other"'
    - value: '"default"'
  active: true
"#;

        let (cfg, options) = evaluate_yaml_config(
            yml,
            Some(esp_metadata_generated::Chip::Esp32c3),
            vec![],
            false,
        )
        .unwrap();

        assert_eq!("esp-bootloader-esp-idf", cfg.krate);

        assert_eq!(
            vec![
                    ConfigOption {
                        name: "esp_idf_version".to_string(),
                        description: "ESP-IDF version used in the application descriptor. Currently it's not checked by the bootloader.".to_string(),
                        default_value: Value::String("default".to_string()),
                        constraint: None,
                        stability: Stability::Unstable,
                        active: true,
                        display_hint: DisplayHint::None,
                    },
            ],
            options
        );
    }

    #[test]
    fn deserialization_fallback_contraint() {
        let yml = r#"
crate: esp-bootloader-esp-idf

options:
- name: option
  description: Desc
  default:
    - value: 100
  constraints:
    - if: 'chip == "esp32c6"'
      type:
        validator: integer_in_range
        value:
          start: 0
          end: 100
    - if: true
      type:
        validator: integer_in_range
        value:
          start: 0
          end: 50
  active: true
"#;

        let (cfg, options) = evaluate_yaml_config(
            yml,
            Some(esp_metadata_generated::Chip::Esp32),
            vec![],
            false,
        )
        .unwrap();

        assert_eq!("esp-bootloader-esp-idf", cfg.krate);

        assert_eq!(
            vec![ConfigOption {
                name: "option".to_string(),
                description: "Desc".to_string(),
                default_value: Value::Integer(100),
                constraint: Some(Validator::IntegerInRange(0..50)),
                stability: Stability::Unstable,
                active: true,
                display_hint: DisplayHint::None,
            },],
            options
        );
    }
}