use rho_protocol::{HookConfigChange, HookConfigEntry};
use serde_json::{Map, Value as Json};
use toml_edit::{ArrayOfTables, DocumentMut, Item, Table};
use crate::config::entries::{to_item, to_json};
const HOOK: &str = "hook";
const ID: &str = "id";
const ENABLED: &str = "enabled";
const NEW_FILE: &str = "version = 1\n";
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum HookEditError {
#[error("{0}")]
FileInvalid(String),
#[error("hook '{id}': the file holds no such hook")]
Missing { id: String },
#[error("hook '{id}': its value must be a table")]
NotTable { id: String },
#[error("hook '{id}': its value must not hold `id`; the change names the hook")]
HoldsId { id: String },
#[error("hook '{id}': field '{field}': {problem}")]
Field {
id: String,
field: String,
problem: String,
},
}
pub(crate) fn hook_entries(text: &str) -> Result<Vec<HookConfigEntry>, HookEditError> {
Ok(HooksDoc::parse(text)?.entries())
}
pub(crate) fn apply_hook_changes(
text: Option<&str>,
changes: &[HookConfigChange],
) -> Result<String, HookEditError> {
let text = text
.filter(|text| !text.trim().is_empty())
.unwrap_or(NEW_FILE);
let mut doc = HooksDoc::parse(text)?;
doc.apply(changes)?;
Ok(doc.0.to_string())
}
struct HooksDoc(DocumentMut);
impl HooksDoc {
fn parse(text: &str) -> Result<Self, HookEditError> {
let doc = text
.parse::<DocumentMut>()
.map_err(|error| HookEditError::FileInvalid(error.to_string().trim_end().to_owned()))?;
match doc.get(HOOK) {
None => {}
Some(Item::ArrayOfTables(hooks)) => {
if let Some(index) = hooks.iter().position(|hook| id_of(hook).is_none()) {
return Err(HookEditError::FileInvalid(format!(
"hook {} has no `id` string",
index + 1
)));
}
}
Some(_) => {
return Err(HookEditError::FileInvalid(
"`hook` is not an array of `[[hook]]` tables".to_owned(),
));
}
}
Ok(Self(doc))
}
fn entries(&self) -> Vec<HookConfigEntry> {
let Some(hooks) = self.0.get(HOOK).and_then(Item::as_array_of_tables) else {
return Vec::new();
};
hooks
.iter()
.map(|hook| {
let value = hook
.iter()
.filter(|(key, _)| *key != ID)
.map(|(key, item)| (key.to_owned(), to_json(item)))
.collect::<Map<_, _>>();
let id = id_of(hook).expect("`HooksDoc::parse` checked every hook's id");
HookConfigEntry::new(id.to_owned(), Json::Object(value))
})
.collect()
}
fn apply(&mut self, changes: &[HookConfigChange]) -> Result<(), HookEditError> {
for change in changes {
let hooks = self
.0
.entry(HOOK)
.or_insert(Item::ArrayOfTables(ArrayOfTables::new()))
.as_array_of_tables_mut()
.expect("`HooksDoc::parse` checked `hook` is an array of tables");
let found = hooks
.iter()
.position(|hook| id_of(hook) == Some(change.id()));
match change {
HookConfigChange::Put { id, value } => {
let fields = fields(id, value)?;
match found {
Some(index) => {
rewrite(hooks.get_mut(index).expect("`position` found it"), fields);
}
None => hooks.push(new_hook(id, fields)),
}
}
HookConfigChange::Remove { id } => {
let index = found.ok_or_else(|| HookEditError::Missing { id: id.clone() })?;
hooks.remove(index);
}
}
}
Ok(())
}
}
fn id_of(hook: &Table) -> Option<&str> {
hook.get(ID).and_then(Item::as_str)
}
fn fields(id: &str, value: &Json) -> Result<Vec<(String, Item)>, HookEditError> {
let Json::Object(fields) = value else {
return Err(HookEditError::NotTable { id: id.to_owned() });
};
if fields.contains_key(ID) {
return Err(HookEditError::HoldsId { id: id.to_owned() });
}
fields
.iter()
.filter(|(field, value)| !(field.as_str() == ENABLED && value.as_bool() == Some(true)))
.map(|(field, value)| {
to_item(value)
.map(|item| (field.clone(), item))
.map_err(|problem| HookEditError::Field {
id: id.to_owned(),
field: field.clone(),
problem,
})
})
.collect()
}
fn rewrite(hook: &mut Table, fields: Vec<(String, Item)>) {
let dropped: Vec<String> = hook
.iter()
.map(|(key, _)| key.to_owned())
.filter(|key| key != ID && !fields.iter().any(|(field, _)| field == key))
.collect();
for key in &dropped {
hook.remove(key);
}
for (field, item) in fields {
match hook.get_mut(&field) {
Some(slot) => replace_value(slot, item),
None => {
hook.insert(&field, item);
}
}
}
}
fn replace_value(slot: &mut Item, mut item: Item) {
if to_json(slot) == to_json(&item) {
return;
}
if let (Item::Value(old), Item::Value(new)) = (&*slot, &mut item) {
*new.decor_mut() = old.decor().clone();
}
*slot = item;
}
fn new_hook(id: &str, fields: Vec<(String, Item)>) -> Table {
let mut hook = Table::new();
hook.insert(ID, toml_edit::value(id));
for (field, item) in fields {
hook.insert(&field, item);
}
hook
}
#[cfg(test)]
#[path = "entries_tests.rs"]
mod tests;