1use std::collections::{BTreeMap, HashMap};
4use std::path::{Path, PathBuf};
5
6use sapphire_bridge_api::settings::{
7 Apply, Entry, EntryValue, Kind, Origin, Scope, SecretState, SettingDef, Value,
8};
9
10use crate::owner::SettingsOwner;
11use crate::{Error, Registry, Result};
12
13#[derive(Clone, Debug, Default)]
16pub struct StartState(BTreeMap<String, Option<Value>>);
17
18impl StartState {
19 pub fn capture(reg: &Registry) -> Result<StartState> {
21 let mut cache = Cache::default();
22 let mut values = BTreeMap::new();
23 for (def, owner) in reg.entries() {
24 if def.apply == Apply::Restart {
25 let entry = resolve(def, owner, &mut cache)?;
26 values.insert(def.key.clone(), plain(&entry.value));
27 }
28 }
29 Ok(StartState(values))
30 }
31}
32
33fn plain(value: &EntryValue) -> Option<Value> {
35 match value {
36 EntryValue::Value(v) => Some(v.clone()),
37 _ => None,
38 }
39}
40
41#[derive(Default)]
43struct Cache(HashMap<PathBuf, Option<toml::Table>>);
44
45impl Cache {
46 fn table(&mut self, path: &Path) -> Result<Option<&toml::Table>> {
48 if !self.0.contains_key(path) {
49 let table = match std::fs::read_to_string(path) {
50 Ok(text) => Some(text.parse::<toml::Table>().map_err(|e| Error::Unparsable {
51 file: path.to_path_buf(),
52 message: crate::describe_toml_error(&text, e.span(), e.message()),
53 })?),
54 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
55 Err(e) => return Err(e.into()),
56 };
57 self.0.insert(path.to_path_buf(), table);
58 }
59 Ok(self.0[path].as_ref())
60 }
61
62 fn value(
64 &mut self,
65 owner: &dyn SettingsOwner,
66 scope: Scope,
67 key: &str,
68 ) -> Result<Option<Value>> {
69 let path = owner.file(scope)?;
70 let Some(table) = self.table(&path)? else {
71 return Ok(None);
72 };
73 let mut segments = key.split('.');
74 let mut current = table;
75 let last = segments.next_back().unwrap_or_default();
76 for segment in segments {
77 match current.get(segment) {
78 Some(toml::Value::Table(t)) => current = t,
79 _ => return Ok(None),
80 }
81 }
82 current
83 .get(last)
84 .map(|v| {
85 convert(v).map_err(|m| Error::Unparsable {
86 file: path.clone(),
87 message: format!("`{key}`: {m}"),
88 })
89 })
90 .transpose()
91 }
92}
93
94fn convert(value: &toml::Value) -> std::result::Result<Value, String> {
96 match value {
97 toml::Value::String(s) => Ok(Value::String(s.clone())),
98 toml::Value::Integer(i) => Ok(Value::Int(*i)),
99 toml::Value::Boolean(b) => Ok(Value::Bool(*b)),
100 toml::Value::Array(items) => Ok(Value::List(
101 items
102 .iter()
103 .map(convert)
104 .collect::<std::result::Result<_, _>>()?,
105 )),
106 other => Err(format!("unsupported value type `{}`", other.type_str())),
107 }
108}
109
110fn secret_state(owner: &dyn SettingsOwner, key: &str) -> Result<SecretState> {
112 match std::fs::read(owner.secret_file(key)?) {
113 Ok(bytes) if !bytes.is_empty() => Ok(SecretState::Set),
114 Ok(_) => Ok(SecretState::Unset),
115 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(SecretState::Unset),
116 Err(e) => Err(e.into()),
117 }
118}
119
120fn resolve(def: &SettingDef, owner: &dyn SettingsOwner, cache: &mut Cache) -> Result<Entry> {
122 let entry = |value, origin: Origin| Entry {
123 key: def.key.clone(),
124 value,
125 note: match origin {
126 Origin::Scope(scope) => owner.scope_note(scope),
127 Origin::Default => None,
128 },
129 origin,
130 pending_restart: false,
131 };
132
133 if def.kind == Kind::Secret {
134 return Ok(match secret_state(owner, &def.key)? {
135 SecretState::Set => entry(
136 EntryValue::Secret(SecretState::Set),
137 Origin::Scope(Scope::Device),
138 ),
139 SecretState::Unset => entry(EntryValue::Secret(SecretState::Unset), Origin::Default),
140 });
141 }
142
143 let mut layers = Vec::new();
144 if def.overridable {
145 layers.push(Scope::Device);
146 }
147 if !layers.contains(&def.home()) {
148 layers.push(def.home());
149 }
150 for scope in layers {
151 if owner.file(scope).is_err() {
153 continue;
154 }
155 if let Some(value) = cache.value(owner, scope, &def.key)? {
156 return Ok(entry(EntryValue::Value(value), Origin::Scope(scope)));
157 }
158 }
159 Ok(match &def.default {
160 Some(value) => entry(EntryValue::Value(value.clone()), Origin::Default),
161 None => entry(EntryValue::Unset, Origin::Default),
162 })
163}
164
165fn mark_pending(def: &SettingDef, entry: &mut Entry, start: Option<&StartState>) {
167 if def.apply != Apply::Restart {
168 return;
169 }
170 if let Some(before) = start.and_then(|s| s.0.get(&def.key)) {
171 entry.pending_restart = *before != plain(&entry.value);
172 }
173}
174
175pub fn list(
178 reg: &Registry,
179 scope: Option<Scope>,
180 start: Option<&StartState>,
181) -> Result<Vec<Entry>> {
182 let mut cache = Cache::default();
183 let mut entries = Vec::new();
184 for (def, owner) in reg.entries() {
185 let mut entry = resolve(def, owner, &mut cache)?;
186 mark_pending(def, &mut entry, start);
187 let Some(scope) = scope else {
188 entries.push(entry);
189 continue;
190 };
191 if !def.allows(scope) {
194 continue;
195 }
196 if def.kind == Kind::Secret {
197 if scope == Scope::Device && entry.value == EntryValue::Secret(SecretState::Set) {
198 entries.push(entry);
199 }
200 continue;
201 }
202 if let Some(value) = cache.value(owner, scope, &def.key)? {
204 entry.value = EntryValue::Value(value);
205 entry.origin = Origin::Scope(scope);
206 entry.note = owner.scope_note(scope);
207 entries.push(entry);
208 }
209 }
210 Ok(entries)
211}
212
213pub fn get(reg: &Registry, key: &str) -> Result<Entry> {
215 let (def, owner) = reg.def(key)?;
216 resolve(def, owner, &mut Cache::default())
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use crate::owner::test_support::{TestOwner, def};
223 use crate::{Apply, Error, Kind, Registry, SettingsOwner};
224 use std::sync::Arc;
225
226 fn int() -> Kind {
227 Kind::Int { min: 0, max: 100 }
228 }
229
230 fn setup(d: SettingDef) -> (Arc<TestOwner>, Registry) {
231 let owner = Arc::new(TestOwner::new(vec![d]));
232 let reg = Registry::new(vec![owner.clone() as Arc<dyn SettingsOwner>], &[]).unwrap();
233 (owner, reg)
234 }
235
236 #[test]
237 fn the_home_scope_wins_over_the_default() {
238 let mut d = def("a.b", int());
239 d.default = Some(Value::Int(1));
240 let (o, reg) = setup(d);
241 o.write("wg.toml", "[a]\nb = 3\n");
242 let e = get(®, "a.b").unwrap();
243 assert_eq!(e.value, EntryValue::Value(Value::Int(3)));
244 assert_eq!(e.origin, Origin::Scope(Scope::Workgroup));
245 assert_eq!(e.note.as_deref(), Some("wg note"));
246 }
247
248 #[test]
249 fn a_device_value_overrides_only_when_overridable() {
250 let mut d = def("a.b", int());
251 let (o, reg) = setup(d.clone());
252 o.write("wg.toml", "[a]\nb = 3\n");
253 o.write("dev.toml", "[a]\nb = 9\n");
254 assert_eq!(
255 get(®, "a.b").unwrap().value,
256 EntryValue::Value(Value::Int(3))
257 );
258 d.overridable = true;
259 let (o, reg) = setup(d);
260 o.write("wg.toml", "[a]\nb = 3\n");
261 o.write("dev.toml", "[a]\nb = 9\n");
262 let e = get(®, "a.b").unwrap();
263 assert_eq!(e.value, EntryValue::Value(Value::Int(9)));
264 assert_eq!(e.origin, Origin::Scope(Scope::Device));
265 }
266
267 #[test]
268 fn unset_without_default_is_unset() {
269 let (_o, reg) = setup(def("a.b", int()));
270 let e = get(®, "a.b").unwrap();
271 assert_eq!(e.value, EntryValue::Unset);
272 assert_eq!(e.origin, Origin::Default);
273 }
274
275 #[test]
276 fn a_missing_scope_is_not_an_error_and_unknown_keys_are() {
277 let mut d = def("a.b", int());
278 d.scopes = vec![Scope::Workspace];
279 d.overridable = true;
280 let (o, reg) = setup(d);
281 o.write("dev.toml", "[a]\nb = 4\n");
282 assert_eq!(
284 get(®, "a.b").unwrap().value,
285 EntryValue::Value(Value::Int(4))
286 );
287 assert!(matches!(
288 get(®, "x").err().unwrap(),
289 Error::UnknownKey(_)
290 ));
291 assert!(list(®, Some(Scope::Workspace), None).is_err());
292 }
293
294 #[test]
295 fn secrets_report_only_whether_they_are_set() {
296 let mut d = def("net.token", Kind::Secret);
297 d.scopes = vec![Scope::Device];
298 let (o, reg) = setup(d);
299 let e = get(®, "net.token").unwrap();
300 assert_eq!(e.value, EntryValue::Secret(SecretState::Unset));
301 o.write("secret-net.token", "hunter2-sekrit");
302 let entries = list(®, None, None).unwrap();
303 assert_eq!(entries[0].value, EntryValue::Secret(SecretState::Set));
304 assert!(!format!("{entries:?}").contains("hunter2"));
305 }
306
307 #[test]
308 fn list_with_a_scope_shows_only_what_it_holds() {
309 let owner = Arc::new(TestOwner::new(vec![def("a.b", int()), def("a.c", int())]));
310 let reg = Registry::new(vec![owner.clone() as Arc<dyn SettingsOwner>], &[]).unwrap();
311 owner.write("wg.toml", "[a]\nb = 3\n");
312 let entries = list(®, Some(Scope::Workgroup), None).unwrap();
313 assert_eq!(entries.len(), 1);
314 assert_eq!(entries[0].key, "a.b");
315 assert_eq!(list(®, None, None).unwrap().len(), 2);
316 assert!(list(®, Some(Scope::Device), None).unwrap().is_empty());
317 }
318
319 #[test]
320 fn list_with_a_scope_shows_only_keys_the_scope_allows() {
321 let mut device_only = def("d.x", int());
324 device_only.scopes = vec![Scope::Device];
325 let workgroup_only = def("w.y", int());
326 let owner = Arc::new(TestOwner::new(vec![device_only, workgroup_only]));
327 let reg = Registry::new(vec![owner.clone() as Arc<dyn SettingsOwner>], &[]).unwrap();
328 let both = "[d]\nx = 1\n[w]\ny = 2\n";
329 owner.write("dev.toml", both);
330 owner.write("wg.toml", both);
331 let keys = |scope| {
332 list(®, Some(scope), None)
333 .unwrap()
334 .into_iter()
335 .map(|e| e.key)
336 .collect::<Vec<_>>()
337 };
338 assert_eq!(keys(Scope::Workgroup), vec!["w.y".to_owned()]);
339 assert_eq!(keys(Scope::Device), vec!["d.x".to_owned()]);
340 }
341
342 #[test]
343 fn lists_and_strings_convert_from_toml() {
344 let k = Kind::List {
345 item: Box::new(Kind::Url),
346 };
347 let (o, reg) = setup(def("a.urls", k));
348 o.write("wg.toml", "[a]\nurls = [\"https://x\", \"https://y\"]\n");
349 assert_eq!(
350 get(®, "a.urls").unwrap().value,
351 EntryValue::Value(Value::List(vec![
352 Value::String("https://x".into()),
353 Value::String("https://y".into())
354 ]))
355 );
356 }
357
358 #[test]
359 fn an_unparsable_file_is_an_error_naming_it() {
360 let (o, reg) = setup(def("a.b", int()));
361 o.write("wg.toml", "this is = = not toml");
362 match get(®, "a.b").err().unwrap() {
363 Error::Unparsable { file, .. } => assert_eq!(file, o.dir.path().join("wg.toml")),
364 other => panic!("unexpected {other:?}"),
365 }
366 }
367
368 #[test]
369 fn an_unparsable_file_is_named_by_line_not_quoted() {
370 let (o, reg) = setup(def("a.b", int()));
371 o.write("wg.toml", "a = 1\ntoken = \"hunter2\" x\n");
372 let err = get(®, "a.b").err().unwrap().to_string();
373 assert!(err.contains("line 2"), "{err}");
374 assert!(!err.contains("hunter2"), "{err}");
375 }
376
377 #[test]
378 fn a_value_of_an_unsupported_type_is_unparsable() {
379 let (o, reg) = setup(def("a.b", int()));
380 o.write("wg.toml", "[a]\nb = 1.5\n");
381 assert!(matches!(
382 get(®, "a.b").err().unwrap(),
383 Error::Unparsable { .. }
384 ));
385 }
386
387 #[test]
388 fn pending_restart_compares_with_the_start() {
389 let mut r = def("a.r", int());
390 r.apply = Apply::Restart;
391 let owner = Arc::new(TestOwner::new(vec![r, def("a.l", int())]));
392 let reg = Registry::new(vec![owner.clone() as Arc<dyn SettingsOwner>], &[]).unwrap();
393 owner.write("wg.toml", "[a]\nr = 1\nl = 1\n");
394 let start = StartState::capture(®).unwrap();
395 let pending = |reg: &Registry| {
396 list(reg, None, Some(&start))
397 .unwrap()
398 .into_iter()
399 .map(|e| (e.key, e.pending_restart))
400 .collect::<Vec<_>>()
401 };
402 assert_eq!(
403 pending(®),
404 vec![("a.r".to_string(), false), ("a.l".to_string(), false)]
405 );
406 owner.write("wg.toml", "[a]\nr = 2\nl = 2\n");
407 assert_eq!(
408 pending(®),
409 vec![("a.r".to_string(), true), ("a.l".to_string(), false)]
410 );
411 }
412}