agentmux_srv_core/backend/
json_keep.rs1use serde::de::DeserializeOwned;
13use serde::Serialize;
14use serde_json::Value;
15use std::collections::BTreeMap;
16use std::path::{Path, PathBuf};
17
18fn aside_path(path: &Path) -> PathBuf {
20 let mut name = path.file_name().map(|n| n.to_os_string()).unwrap_or_default();
21 name.push(".unreadable");
22 path.with_file_name(name)
23}
24
25pub fn set_aside_if_unreadable<T: DeserializeOwned>(path: &Path) {
28 let Ok(bytes) = std::fs::read(path) else { return };
29 if serde_json::from_slice::<T>(&bytes).is_ok() {
30 return;
31 }
32 let aside = aside_path(path);
33 match std::fs::write(&aside, &bytes) {
34 Ok(()) => tracing::warn!(file = %path.display(), copy = %aside.display(), "config file could not be read; it was copied aside before it is replaced"),
35 Err(e) => tracing::warn!(file = %path.display(), error = %e, "config file could not be read, and the copy aside failed"),
36 }
37}
38
39pub fn read_entries<T: DeserializeOwned>(path: &Path) -> BTreeMap<String, T> {
42 let Some(raw) = read_raw_object(path) else { return BTreeMap::new() };
43 raw.into_iter().filter_map(|(k, v)| serde_json::from_value::<T>(v).ok().map(|t| (k, t))).collect()
44}
45
46pub fn has_record(path: &Path, key: &str) -> bool {
48 read_raw_object(path).is_some_and(|map| map.contains_key(key))
49}
50
51fn read_raw_object(path: &Path) -> Option<serde_json::Map<String, Value>> {
52 match serde_json::from_slice::<Value>(&std::fs::read(path).ok()?).ok()? {
53 Value::Object(map) => Some(map),
54 _ => None,
55 }
56}
57
58pub fn write_entries<T: Serialize + DeserializeOwned>(path: &Path, entries: &BTreeMap<String, T>) -> Result<(), String> {
62 write_entries_removing(path, entries, &[])
63}
64
65pub fn write_entries_removing<T: Serialize + DeserializeOwned>(path: &Path, entries: &BTreeMap<String, T>, removed: &[&str]) -> Result<(), String> {
68 if let Some(dir) = path.parent() {
69 std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
70 }
71 let mut out = serde_json::Map::new();
72 match read_raw_object(path) {
73 Some(on_disk) => {
74 for (key, value) in on_disk {
75 if !entries.contains_key(&key) && !removed.contains(&key.as_str()) && serde_json::from_value::<T>(value.clone()).is_err() {
76 out.insert(key, value);
77 }
78 }
79 }
80 None => set_aside_if_unreadable::<serde_json::Map<String, Value>>(path),
81 }
82 for (key, entry) in entries {
83 out.insert(key.clone(), serde_json::to_value(entry).map_err(|e| e.to_string())?);
84 }
85 let tmp = path.with_extension("json.tmp");
86 std::fs::write(&tmp, serde_json::to_vec_pretty(&Value::Object(out)).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
87 std::fs::rename(&tmp, path).map_err(|e| e.to_string())
88}
89
90pub fn read_old(path: &Path) -> Option<Value> {
93 serde_json::from_slice(&std::fs::read(path).ok()?).ok()
94}
95
96pub fn carry_unknown_keys(old: &Value, new: &mut Value, known: &[&str]) {
99 let (Some(old), Some(new)) = (old.as_object(), new.as_object_mut()) else { return };
100 for (key, value) in old {
101 if !known.contains(&key.as_str()) && !new.contains_key(key) {
102 new.insert(key.clone(), value.clone());
103 }
104 }
105}
106
107pub fn carry_unknown_keys_in_list(old: &Value, new: &mut Value, id_key: &str, known: &[&str]) {
109 let (Some(old), Some(new)) = (old.as_array(), new.as_array_mut()) else { return };
110 for item in new {
111 let Some(id) = item.get(id_key).cloned() else { continue };
112 if let Some(before) = old.iter().find(|o| o.get(id_key) == Some(&id)) {
113 carry_unknown_keys(before, item, known);
114 }
115 }
116}
117
118#[cfg(test)]
119#[path = "json_keep_tests.rs"]
120mod tests;