use super::{
edit::Edit,
files::{self, FIX, Failure},
naming::NEW,
targets::Target,
};
use serde_json::{Value, json};
use std::path::Path;
pub fn blank(path: &Path) -> bool {
std::fs::read_to_string(path).is_ok_and(|text| text.trim().is_empty())
}
pub fn load(path: &Path) -> Result<(Option<String>, Value), Failure> {
if blank(path) {
return Ok((std::fs::read_to_string(path).ok(), json!({})));
}
files::load_text(path)
}
pub fn with_entry(target: &Target, entry: &Value) -> Result<(Edit, Value), Failure> {
let (prior, mut document) = load(&target.path)?;
if document.get(target.key).is_none() {
document[target.key] = json!({});
}
let Some(servers) = document[target.key].as_object_mut() else {
return Err(Failure::new(
format!(
"{} in {} is not a JSON object; refusing to rewrite it",
target.key,
target.path.display()
),
FIX,
));
};
let written = match servers.get(NEW).and_then(Value::as_object) {
Some(present) => {
let mut kept = present.clone();
for key in ["command", "args"] {
kept.insert(key.into(), entry[key].clone());
}
Value::Object(kept)
}
None => entry.clone(),
};
servers.insert(NEW.into(), written.clone());
let text = files::pretty(&document);
let path = target.path.clone();
Ok((
Edit {
path,
read: prior,
text,
},
written,
))
}
pub fn without(target: &Target) -> Result<Option<Edit>, Failure> {
let (prior, mut document) = load(&target.path)?;
let removed = document
.get_mut(target.key)
.and_then(Value::as_object_mut)
.and_then(|servers| servers.shift_remove(NEW));
let path = target.path.clone();
Ok(removed.map(|_| Edit {
path,
read: prior,
text: files::pretty(&document),
}))
}