serenade_config/
document.rs1use std::collections::BTreeMap;
4use std::path::Path;
5
6use serde_json::{Map, Value};
7use serenade_di::ParameterBag;
8
9use crate::ConfigError;
10
11#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct Config {
14 value: Value,
15}
16
17impl Config {
18 #[must_use]
20 pub fn empty() -> Self {
21 Self {
22 value: Value::Object(Map::new()),
23 }
24 }
25
26 pub fn from_yaml(text: &str) -> Result<Self, ConfigError> {
32 let yaml: serde_yaml::Value = serde_yaml::from_str(text)?;
33 Self::from_value(serde_json::to_value(yaml)?)
34 }
35
36 pub fn from_toml(text: &str) -> Result<Self, ConfigError> {
55 let table: toml::Table = text.parse()?;
56 Self::from_value(serde_json::to_value(table)?)
57 }
58
59 pub fn from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
65 let path = path.as_ref();
66 let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Io {
67 path: path.to_path_buf(),
68 source,
69 })?;
70 match path
71 .extension()
72 .and_then(|ext| ext.to_str())
73 .map(str::to_ascii_lowercase)
74 .as_deref()
75 {
76 Some("yaml" | "yml") => Self::from_yaml(&text),
77 Some("toml") => Self::from_toml(&text),
78 _ => Err(ConfigError::UnsupportedFormat {
79 path: path.to_path_buf(),
80 }),
81 }
82 }
83
84 #[must_use]
86 pub fn merged(&self, overlay: &Self) -> Self {
87 Self {
88 value: merge_values(self.value.clone(), overlay.value.clone()),
89 }
90 }
91
92 pub fn interpolate_env(&self) -> Result<Self, ConfigError> {
98 Ok(Self {
99 value: interpolate_value(self.value.clone())?,
100 })
101 }
102
103 #[must_use]
105 pub fn parameters(&self) -> BTreeMap<String, String> {
106 let mut out = BTreeMap::new();
107 flatten("", &self.value, &mut out);
108 out
109 }
110
111 pub fn apply_to(&self, bag: &mut ParameterBag) {
113 for (key, value) in self.parameters() {
114 bag.set(key, value);
115 }
116 }
117
118 #[must_use]
120 pub const fn value(&self) -> &Value {
121 &self.value
122 }
123
124 #[must_use]
129 pub fn section(&self, key: &str) -> Self {
130 match self.value.get(key) {
131 Some(Value::Object(map)) => Self {
132 value: Value::Object(map.clone()),
133 },
134 _ => Self::empty(),
135 }
136 }
137
138 fn from_value(value: Value) -> Result<Self, ConfigError> {
139 if value.is_object() {
140 Ok(Self { value })
141 } else {
142 Err(ConfigError::InvalidRoot)
143 }
144 }
145}
146
147fn merge_values(base: Value, overlay: Value) -> Value {
148 match (base, overlay) {
149 (Value::Object(mut base_map), Value::Object(overlay_map)) => {
150 for (key, overlay_value) in overlay_map {
151 let merged = match base_map.remove(&key) {
152 Some(existing) => merge_values(existing, overlay_value),
153 None => overlay_value,
154 };
155 base_map.insert(key, merged);
156 }
157 Value::Object(base_map)
158 }
159 (_, overlay) => overlay,
160 }
161}
162
163fn interpolate_value(value: Value) -> Result<Value, ConfigError> {
164 match value {
165 Value::String(text) => Ok(Value::String(interpolate_string(&text)?)),
166 Value::Array(items) => {
167 let mut out = Vec::with_capacity(items.len());
168 for item in items {
169 out.push(interpolate_value(item)?);
170 }
171 Ok(Value::Array(out))
172 }
173 Value::Object(map) => {
174 let mut out = Map::new();
175 for (key, child) in map {
176 out.insert(key, interpolate_value(child)?);
177 }
178 Ok(Value::Object(out))
179 }
180 other => Ok(other),
181 }
182}
183
184fn interpolate_string(input: &str) -> Result<String, ConfigError> {
185 let mut remaining = input;
186 let mut out = String::new();
187 while let Some(start) = remaining.find("${") {
188 out.push_str(&remaining[..start]);
189 remaining = &remaining[start + 2..];
190 let end = remaining
191 .find('}')
192 .ok_or(ConfigError::InvalidInterpolation)?;
193 let inner = &remaining[..end];
194 remaining = &remaining[end + 1..];
195 let (name, default) = match inner.split_once(":-") {
196 Some((name, default)) => (name, Some(default)),
197 None => (inner, None),
198 };
199 if !is_ident(name) {
200 return Err(ConfigError::InvalidInterpolation);
201 }
202 match std::env::var(name) {
203 Ok(value) => out.push_str(&value),
204 Err(_) => match default {
205 Some(fallback) => out.push_str(fallback),
206 None => {
207 return Err(ConfigError::MissingEnvironment {
208 name: name.to_owned(),
209 });
210 }
211 },
212 }
213 }
214 out.push_str(remaining);
215 Ok(out)
216}
217
218fn is_ident(name: &str) -> bool {
219 let mut chars = name.chars();
220 let Some(first) = chars.next() else {
221 return false;
222 };
223 if !first.is_ascii_alphabetic() && first != '_' {
224 return false;
225 }
226 chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
227}
228
229fn flatten(prefix: &str, value: &Value, out: &mut BTreeMap<String, String>) {
230 match value {
231 Value::Object(map) => {
232 for (key, child) in map {
233 let next = if prefix.is_empty() {
234 key.clone()
235 } else {
236 format!("{prefix}.{key}")
237 };
238 flatten(&next, child, out);
239 }
240 }
241 Value::String(text) => {
242 if !prefix.is_empty() {
243 out.insert(prefix.to_owned(), text.clone());
244 }
245 }
246 Value::Number(number) => {
247 if !prefix.is_empty() {
248 out.insert(prefix.to_owned(), number.to_string());
249 }
250 }
251 Value::Bool(flag) => {
252 if !prefix.is_empty() {
253 out.insert(prefix.to_owned(), flag.to_string());
254 }
255 }
256 Value::Null | Value::Array(_) => {}
257 }
258}