rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A hooks file read and edited one `[[hook]]` at a time, for
//! `rho/hooks/config/*`: each hook as JSON by its `id` ([`hook_entries`]),
//! and changes that put or remove a hook ([`apply_hook_changes`]) while the
//! rest of the text, comments included, stays as it was, byte for byte.
//!
//! This only edits text. Whether the result loads is the caller's check, as
//! a session of the file's scope would load it (`check_user_hooks`,
//! `check_project_hooks`).

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};

/// The key of the file's hooks.
const HOOK: &str = "hook";
/// The key of a hook's id.
const ID: &str = "id";
/// The key that turns a hook off; rho before 3.10 refuses it.
const ENABLED: &str = "enabled";
/// What an absent or blank file starts as before a change.
const NEW_FILE: &str = "version = 1\n";

/// Why hooks text could not be read or edited.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum HookEditError {
    /// The text is not TOML, its `hook` is not an array of `[[hook]]`
    /// tables, or a hook has no string `id`, so its hooks cannot be told
    /// apart; only a hand edit fixes it.
    #[error("{0}")]
    FileInvalid(String),
    /// A remove names a hook the file does not hold.
    #[error("hook '{id}': the file holds no such hook")]
    Missing { id: String },
    /// A put's value is not a table.
    #[error("hook '{id}': its value must be a table")]
    NotTable { id: String },
    /// A put's value holds `id`, which the change names.
    #[error("hook '{id}': its value must not hold `id`; the change names the hook")]
    HoldsId { id: String },
    /// A field of a put's value TOML cannot hold, such as `null`.
    #[error("hook '{id}': field '{field}': {problem}")]
    Field {
        id: String,
        field: String,
        problem: String,
    },
}

/// The hooks `text` holds, in file order, each as JSON without its `id`.
pub(crate) fn hook_entries(text: &str) -> Result<Vec<HookConfigEntry>, HookEditError> {
    Ok(HooksDoc::parse(text)?.entries())
}

/// `text`, `None` for an absent file, with `changes` applied in order. An
/// absent or blank file starts as `version = 1`. Every change applies or
/// the first that cannot is the error.
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())
}

/// Hooks text whose hooks can be told apart: its `hook`, when set, is an
/// array of `[[hook]]` tables, each with a string `id`. Parsing checks it
/// once; a change keeps it so.
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))
    }

    /// Each hook, in file order, as JSON without its `id`.
    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()
    }

    /// Applies `changes` in order, stopping at the first that cannot apply.
    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(())
    }
}

/// The id of `hook`; `None` when it has no string `id`.
fn id_of(hook: &Table) -> Option<&str> {
    hook.get(ID).and_then(Item::as_str)
}

/// The fields a put of hook `id` writes, each as the TOML item it holds.
/// `enabled = true` is the default, so it is left out: rho before 3.10
/// refuses the key, and a file it refuses runs no hooks at all, so only a
/// hook that is off pays that.
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()
}

/// Writes `fields` over `hook` in place: a key they leave out is removed, a
/// key they keep is rewritten where it stands with the comments around it,
/// and a new one goes last. Its `id` stays as written.
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);
            }
        }
    }
}

/// Puts `item` in `slot`, keeping the whitespace and comment around the
/// value it replaces. An equal value stays as it was written.
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;
}

/// A new `[[hook]]` with `id`, then `fields` in order.
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;