Skip to main content

vault_core/
toml_import.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Import TOML config values as environment-style name/value pairs.
4
5use std::collections::BTreeMap;
6
7/// Parse TOML and flatten tables into uppercase underscore-separated names.
8pub fn parse(source: &str) -> Result<Vec<(String, String)>, String> {
9    let value: toml::Value = toml::from_str(source).map_err(|error| error.to_string())?;
10    let mut values = BTreeMap::new();
11    flatten("", &value, &mut values)?;
12    Ok(values.into_iter().collect())
13}
14
15fn flatten(
16    prefix: &str,
17    value: &toml::Value,
18    output: &mut BTreeMap<String, String>,
19) -> Result<(), String> {
20    if let Some(table) = value.as_table() {
21        for (key, value) in table {
22            let key = key
23                .chars()
24                .map(|ch| {
25                    if ch.is_ascii_alphanumeric() {
26                        ch.to_ascii_uppercase()
27                    } else {
28                        '_'
29                    }
30                })
31                .collect::<String>();
32            let name = if prefix.is_empty() {
33                key
34            } else {
35                format!("{prefix}_{key}")
36            };
37            flatten(&name, value, output)?;
38        }
39    } else {
40        if prefix.is_empty() {
41            return Err("TOML root must be a table".into());
42        }
43        if output.insert(prefix.to_owned(), scalar(value)).is_some() {
44            return Err(format!(
45                "TOML keys collide after environment-name conversion: {prefix}"
46            ));
47        }
48    }
49    Ok(())
50}
51
52fn scalar(value: &toml::Value) -> String {
53    match value {
54        toml::Value::String(value) => value.clone(),
55        _ => value.to_string(),
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::parse;
62
63    #[test]
64    fn flattens_tables_and_preserves_scalar_values() {
65        assert_eq!(
66            parse("token = 'abc'\n[bot]\nchannel_id = 123456789012345678\ncolour = 0x800000")
67                .unwrap(),
68            vec![
69                ("BOT_CHANNEL_ID".into(), "123456789012345678".into()),
70                ("BOT_COLOUR".into(), "8388608".into()),
71                ("TOKEN".into(), "abc".into()),
72            ]
73        );
74    }
75
76    #[test]
77    fn refuses_invalid_toml_and_colliding_names() {
78        assert!(parse("token = [").is_err());
79        assert!(parse("a-b = 1\na_b = 2").is_err());
80    }
81}