vergen_lib/
utils.rs

1use crate::{constants::VERGEN_IDEMPOTENT_DEFAULT, CargoRustcEnvMap, CargoWarning, VergenKey};
2use std::env;
3
4/// Add a [`VergenKey`] entry as a default string into the [`CargoRustcEnvMap`].
5/// The value is either from an environment variable override or [`crate::constants::VERGEN_IDEMPOTENT_DEFAULT`]
6///
7/// # Example
8/// ```
9/// # use std::collections::BTreeMap;
10/// # use temp_env::with_var;
11/// # use vergen_lib::{add_default_map_entry, CargoRustcEnvMap, CargoWarning, VergenKey};
12/// with_var("VERGEN_BUILD_DATE", Some("my own date"), || {
13///     let mut map: CargoRustcEnvMap = BTreeMap::new();
14///     let mut warning: CargoWarning = vec![];
15#[cfg_attr(
16    feature = "build",
17    doc = r"    add_default_map_entry(VergenKey::BuildDate, &mut map, &mut warning);
18assert_eq!(1, map.len());
19assert_eq!(1, warning.len());"
20)]
21/// });
22/// ```
23///
24pub fn add_default_map_entry(
25    key: VergenKey,
26    map: &mut CargoRustcEnvMap,
27    warnings: &mut CargoWarning,
28) {
29    if let Ok(value) = env::var(key.name()) {
30        add_map_entry(key, value, map);
31        warnings.push(format!("{} overidden", key.name()));
32    } else {
33        add_map_entry(key, VERGEN_IDEMPOTENT_DEFAULT, map);
34        warnings.push(format!("{} set to default", key.name()));
35    }
36}
37
38/// Add a [`VergenKey`] entry as a string into the [`CargoRustcEnvMap`].
39///
40/// # Example
41/// ```
42/// # use std::collections::BTreeMap;
43/// # use vergen_lib::{add_map_entry, CargoRustcEnvMap, VergenKey};
44/// let mut map: CargoRustcEnvMap = BTreeMap::new();
45#[cfg_attr(
46    feature = "build",
47    doc = r#"add_map_entry(VergenKey::BuildDate, "test", &mut map);
48assert_eq!(1, map.len());"#
49)]
50/// ```
51///
52pub fn add_map_entry<T>(key: VergenKey, value: T, map: &mut CargoRustcEnvMap)
53where
54    T: Into<String>,
55{
56    let _old = map.insert(key, value.into());
57}
58
59/// Count the number of idempotent entries in a [`CargoRustcEnvMap`]
60///
61/// **NOTE** - This is mainly used for testing.
62///
63/// # Example
64///
65/// ```
66/// # use std::collections::BTreeMap;
67/// # use vergen_lib::{count_idempotent, CargoRustcEnvMap, VergenKey, constants::VERGEN_IDEMPOTENT_DEFAULT};
68/// #
69/// let mut map: CargoRustcEnvMap = BTreeMap::new();
70/// assert_eq!(0, count_idempotent(&map));
71#[cfg_attr(
72    feature = "build",
73    doc = r"_ = map.insert(VergenKey::BuildDate, VERGEN_IDEMPOTENT_DEFAULT.to_string());"
74)]
75#[cfg_attr(feature = "build", doc = r"assert_eq!(1, count_idempotent(&map));")]
76/// ```
77///
78#[must_use]
79pub fn count_idempotent(map: &CargoRustcEnvMap) -> usize {
80    map.values()
81        .filter(|x| *x == VERGEN_IDEMPOTENT_DEFAULT)
82        .count()
83}