Skip to main content

Mountain/IPC/WindServiceHandlers/Utilities/RecentlyOpened/
Mutate.rs

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