1use std::collections::BTreeMap;
10
11use crate::error::{Result, TuffError};
12
13pub type HostTables = BTreeMap<String, toml::Table>;
15
16pub type HostTablesJson = BTreeMap<String, serde_json::Value>;
19
20pub fn validate(tables: &HostTables, place: &str) -> Result<()> {
27 for namespace in tables.keys() {
28 let plain = !namespace.is_empty()
29 && namespace
30 .chars()
31 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
32 if !plain {
33 return Err(TuffError::usage(format!(
34 "{place}: host table namespace '{}' must be letters, digits, '-' and '_'",
35 namespace.escape_debug()
36 ))
37 .with_hint("write host settings as [x.<namespace>], such as [x.myapp]"));
38 }
39 }
40 Ok(())
41}
42
43pub fn to_json(tables: &HostTables) -> HostTablesJson {
46 tables
47 .iter()
48 .map(|(namespace, table)| (namespace.clone(), table_to_json(table)))
49 .collect()
50}
51
52fn table_to_json(table: &toml::Table) -> serde_json::Value {
53 serde_json::Value::Object(
54 table
55 .iter()
56 .map(|(key, value)| (key.clone(), value_to_json(value)))
57 .collect(),
58 )
59}
60
61fn value_to_json(value: &toml::Value) -> serde_json::Value {
62 match value {
63 toml::Value::String(text) => serde_json::Value::String(text.clone()),
64 toml::Value::Integer(number) => serde_json::Value::from(*number),
65 toml::Value::Float(number) => serde_json::Number::from_f64(*number)
66 .map(serde_json::Value::Number)
67 .unwrap_or(serde_json::Value::Null),
68 toml::Value::Boolean(flag) => serde_json::Value::Bool(*flag),
69 toml::Value::Datetime(datetime) => serde_json::Value::String(datetime.to_string()),
70 toml::Value::Array(items) => {
71 serde_json::Value::Array(items.iter().map(value_to_json).collect())
72 }
73 toml::Value::Table(table) => table_to_json(table),
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[derive(serde::Deserialize)]
82 struct Doc {
83 x: HostTables,
84 }
85
86 #[test]
87 fn host_tables_convert_to_json_with_dates_as_strings() {
88 let doc: Doc = toml::from_str(
89 r#"
90[x.host]
91default_level = "read"
92retries = 3
93ratio = 0.5
94since = 2026-11-26
95screens = [{ resource = "ui://changelog/preview", may_call = ["list_pull_requests"] }]
96"#,
97 )
98 .unwrap();
99 validate(&doc.x, "tuff-pack.toml").unwrap();
100 let json = to_json(&doc.x);
101 assert_eq!(
102 json["host"],
103 serde_json::json!({
104 "default_level": "read",
105 "retries": 3,
106 "ratio": 0.5,
107 "since": "2026-11-26",
108 "screens": [{ "resource": "ui://changelog/preview", "may_call": ["list_pull_requests"] }]
109 })
110 );
111 }
112
113 #[test]
114 fn a_namespace_must_be_a_plain_name_and_a_value_must_be_a_table() {
115 let doc: Doc = toml::from_str("[x.\"my app\"]\nkey = 1\n").unwrap();
116 let error = validate(&doc.x, "tuff-pack.toml").unwrap_err();
117 assert!(error.to_string().contains("'my app'"), "{error}");
118 assert!(toml::from_str::<Doc>("[x]\nhost = 1\n").is_err());
119 }
120}