Mountain/IPC/WindServiceHandlers/Utilities/RecentlyOpened/Mutate.rs
1//! Reads, mutates, and writes back RecentlyOpened.json atomically.
2
3use serde_json::{Value, json};
4
5pub fn Fn<F:FnOnce(&mut serde_json::Map<String, Value>)>(Apply:F) {
6 let Path = super::Path::Fn();
7
8 let mut Parsed:serde_json::Map<String, Value> = std::fs::read_to_string(&Path)
9 .ok()
10 .and_then(|Contents| serde_json::from_str::<Value>(&Contents).ok())
11 .and_then(|V| V.as_object().cloned())
12 .unwrap_or_default();
13
14 if !Parsed.contains_key("workspaces") {
15 Parsed.insert("workspaces".into(), json!([]));
16 }
17
18 if !Parsed.contains_key("files") {
19 Parsed.insert("files".into(), json!([]));
20 }
21
22 Apply(&mut Parsed);
23
24 if let Some(Parent) = Path.parent() {
25 let _ = std::fs::create_dir_all(Parent);
26 }
27
28 if let Ok(Serialised) = serde_json::to_vec_pretty(&Value::Object(Parsed)) {
29 let _ = std::fs::write(&Path, Serialised);
30 }
31}