silcrow 0.1.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use std::borrow::Cow;

pub const BINARY_VERSION: u32 = 24;
pub const SERIALIZATION: &str = "tree-ts-v23";

pub fn has_block(text: &str) -> bool {
    opening_tag(text).is_some()
}

/// The name of each attribute the opening tag of the block writes, in its order.
pub fn attr_names(text: &str) -> Vec<String> {
    let Some(open) = opening_tag(text) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    let mut rest = &open["<silcrow".len()..];
    while let Some(eq) = rest.find("=\"") {
        let name = rest[..eq]
            .rsplit(char::is_whitespace)
            .next()
            .unwrap_or_default();
        out.push(name.to_string());
        let after = &rest[eq + 2..];
        rest = after.find('"').map_or("", |end| &after[end + 1..]);
    }
    out
}

pub fn attr_from_agents(text: &str, key: &str) -> Option<String> {
    let open = opening_tag(text)?;
    attr_in_tag(open, key)
}

/// Each attribute renamed since a block could write it, by its old name.
const RENAMED: [(&str, &str); 2] = [("decisions", "notes"), ("published", "default-branch")];

/// `text`, an `AGENTS.md` that a commit holds, with its block in the names and values this
/// binary reads: a renamed attribute under its new name, unless the block writes that one too,
/// and `test-markers="true"` as `allow`. The block held its commit to the names of its time.
pub fn at_commit(text: &str) -> Cow<'_, str> {
    // § yymjgaqr0.g@96b2y
    let (Some(open), Some(start)) = (opening_tag(text), text.find("<silcrow")) else {
        return Cow::Borrowed(text);
    };
    let names = attr_names(text);
    let mut tag = open.to_string();
    for (old, new) in RENAMED {
        if names.iter().any(|n| n == old) && !names.iter().any(|n| n == new) {
            tag = rename_attr(&tag, old, new);
        }
    }
    if attr_in_tag(&tag, "test-markers").as_deref() == Some("true") {
        tag = tag.replacen("test-markers=\"true\"", "test-markers=\"allow\"", 1);
    }
    if tag == open {
        return Cow::Borrowed(text);
    }
    Cow::Owned(format!(
        "{}{tag}{}",
        &text[..start],
        &text[start + open.len()..]
    ))
}

/// `tag` with the attribute `old`, a name after whitespace, written `new`.
fn rename_attr(tag: &str, old: &str, new: &str) -> String {
    let needle = format!("{old}=\"");
    let at = tag.match_indices(&needle).find(|(at, _)| {
        tag[..*at]
            .chars()
            .next_back()
            .is_some_and(char::is_whitespace)
    });
    match at {
        Some((at, _)) => format!("{}{new}{}", &tag[..at], &tag[at + old.len()..]),
        None => tag.to_string(),
    }
}

fn opening_tag(text: &str) -> Option<&str> {
    // § yymjgaqr0.a@kj88y
    let start = text.find("<silcrow")?;
    text[start..].find("</silcrow>")?;
    let end = text[start..].find('>')? + start;
    Some(&text[start..=end])
}

fn attr_in_tag(open: &str, key: &str) -> Option<String> {
    let needle = format!("{key}=\"");
    let idx = open.find(&needle)?;
    let rest = &open[idx + needle.len()..];
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn attr_names_lists_each_attribute_of_the_opening_tag() {
        let text = "<silcrow notes=\"docs/**/*.md !docs/a/**\" default-branch=\"main\" pin=\"optional\">\nx=\"y\"\n</silcrow>\n";
        assert_eq!(attr_names(text), ["notes", "default-branch", "pin"]);
        assert_eq!(
            attr_from_agents(text, "notes").as_deref(),
            Some("docs/**/*.md !docs/a/**")
        );
        assert!(attr_names("<silcrow>\n</silcrow>\n").is_empty());
    }

    #[test]
    fn a_block_of_a_commit_is_read_in_the_names_and_values_of_its_time() {
        let old = "# A\n\n<silcrow decisions=\"notes/**/*.md\"\n  published=\"trunk\" test-markers=\"true\">\nKeep published=\"x\" decisions=\"y\".\n</silcrow>\n";
        let now = at_commit(old);
        assert_eq!(
            attr_names(&now),
            ["notes", "default-branch", "test-markers"]
        );
        assert_eq!(
            attr_from_agents(&now, "notes").as_deref(),
            Some("notes/**/*.md")
        );
        assert_eq!(
            attr_from_agents(&now, "default-branch").as_deref(),
            Some("trunk")
        );
        assert_eq!(
            attr_from_agents(&now, "test-markers").as_deref(),
            Some("allow")
        );
        assert!(now.starts_with("# A\n\n<silcrow notes="), "{now}");
        assert!(
            now.ends_with("\nKeep published=\"x\" decisions=\"y\".\n</silcrow>\n"),
            "{now}"
        );
        let both = "<silcrow notes=\"a/*.md\" decisions=\"b/*.md\" default-branch=\"main\" published=\"evil\">\n</silcrow>\n";
        let read = at_commit(both);
        assert_eq!(attr_from_agents(&read, "notes").as_deref(), Some("a/*.md"));
        assert_eq!(
            attr_from_agents(&read, "default-branch").as_deref(),
            Some("main")
        );
        let value = "<silcrow code=\"src/** !src/xdecisions=\" tests=\"t/**\">\n</silcrow>\n";
        assert_eq!(at_commit(value), value);
        let current = "<silcrow notes=\"docs/**/*.md\" test-markers=\"warn\">\n</silcrow>\n";
        assert!(matches!(at_commit(current), Cow::Borrowed(_)));
    }
}