Skip to main content

quarb_toml/
lib.rs

1//! TOML adapter for Quarb. TOML maps onto the JSON data model, so
2//! a document parses to a [`quarb_json::JsonAdapter`] — the JSON
3//! recipes apply to a `.toml` file unchanged.
4
5use quarb_json::{JsonAdapter, Reading};
6
7/// Parse TOML `text` into a JSON-model adapter.
8pub fn parse(text: &str) -> Result<JsonAdapter, toml::de::Error> {
9    parse_as(text, Reading::Node)
10}
11
12/// Parse TOML `text` under the given reading (the property reading
13/// is `toml2:FILE`).
14pub fn parse_as(text: &str, reading: Reading) -> Result<JsonAdapter, toml::de::Error> {
15    let mut value: serde_json::Value = toml::from_str(text)?;
16    flatten_datetimes(&mut value);
17    Ok(JsonAdapter::from_json_value_as(value, reading))
18}
19
20/// The `toml` crate tunnels every datetime value through serde as a
21/// single-field struct keyed by a private marker, so deserializing
22/// straight into a [`serde_json::Value`] materializes each datetime
23/// as an object `{"$__toml_private_datetime": "…"}` instead of a
24/// scalar — the internal key then leaks into the arbor. The JSON
25/// data model has no datetime type, so collapse those wrappers back
26/// to the plain datetime string (matching how JSON itself carries a
27/// timestamp), leaving the rest of the tree untouched.
28fn flatten_datetimes(value: &mut serde_json::Value) {
29    // The field name `toml_datetime` serializes a datetime under.
30    const TOML_DATETIME_FIELD: &str = "$__toml_private_datetime";
31    match value {
32        serde_json::Value::Object(map) => {
33            let datetime = if map.len() == 1 {
34                match map.get(TOML_DATETIME_FIELD) {
35                    Some(serde_json::Value::String(s)) => Some(s.clone()),
36                    _ => None,
37                }
38            } else {
39                None
40            };
41            if let Some(s) = datetime {
42                *value = serde_json::Value::String(s);
43                return;
44            }
45            for child in map.values_mut() {
46                flatten_datetimes(child);
47            }
48        }
49        serde_json::Value::Array(items) => {
50            for child in items.iter_mut() {
51                flatten_datetimes(child);
52            }
53        }
54        _ => {}
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn datetime_tunnel_collapses_to_scalar_string() {
64        // toml deserializes a datetime as a single-field struct; a
65        // naive parse leaves `when` as an object hiding the private
66        // key. After flattening it is the plain datetime string.
67        let mut v: serde_json::Value = toml::from_str("when = 2026-07-14T10:00:00Z\n").unwrap();
68        assert!(v["when"].is_object(), "precondition: raw datetime tunnel");
69        flatten_datetimes(&mut v);
70        assert_eq!(
71            v["when"],
72            serde_json::Value::String("2026-07-14T10:00:00Z".to_string())
73        );
74    }
75
76    #[test]
77    fn nested_and_array_datetimes_flatten() {
78        let mut v: serde_json::Value = toml::from_str(
79            "stamps = [2026-07-14T10:00:00Z, 2026-07-15]\n\
80             [meta]\ncreated = 1979-05-27\n",
81        )
82        .unwrap();
83        flatten_datetimes(&mut v);
84        assert!(v["stamps"][0].is_string());
85        assert!(v["stamps"][1].is_string());
86        assert!(v["meta"]["created"].is_string());
87    }
88
89    #[test]
90    fn plain_values_are_untouched() {
91        let mut v: serde_json::Value =
92            toml::from_str("name = \"quarb\"\ncount = 3\nok = true\n").unwrap();
93        let before = v.clone();
94        flatten_datetimes(&mut v);
95        assert_eq!(v, before);
96    }
97
98    #[test]
99    fn parse_builds_adapter_for_datetime_document() {
100        assert!(parse("when = 2026-07-14T10:00:00Z\n").is_ok());
101    }
102}