silcrow 0.2.1

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

/// Each part of the hashing scheme and the version this binary hashes it with, in the order a
/// trailer names them.
pub const PARTS: [(&str, u32); 16] = [
    // ยง d1bc2zca5.h@0dk35
    ("core", 25),
    ("md", 25),
    ("rust", 26),
    ("js", 26),
    ("python", 26),
    ("html", 25),
    ("css", 25),
    ("hcl", 25),
    ("bash", 25),
    ("yaml", 26),
    ("helm", 25),
    ("cedar", 25),
    ("dockerfile", 25),
    ("prisma", 25),
    ("jsonc", 25),
    ("fallback", 25),
];
pub const SERIALIZATION: &str = "tree-ts-v23";

/// The version of each part of `PARTS`, as a binary hashes or a history records them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Scheme([u32; PARTS.len()]);

/// A part whose version moved: its name, the version it moved from and the one it moved to.
pub type Move = (&'static str, u32, u32);

impl Scheme {
    pub fn binary() -> Self {
        Scheme(PARTS.map(|(_, version)| version))
    }

    /// The scheme a `Silcrow-Scheme` trailer writes. A part this binary does not know concerns
    /// none of its pins and is passed over.
    pub fn parse(value: &str) -> anyhow::Result<Self> {
        // ยง k2xswz12t.d@7f0kh
        let bad = || {
            anyhow::anyhow!(
                "Silcrow-Scheme trailer `{value}` is not a scheme: a version, then `<part>=<version>` for each part at another"
            )
        };
        let mut words = value.split_whitespace();
        let base: u32 = words.next().ok_or_else(bad)?.parse().map_err(|_| bad())?;
        let mut out = Scheme([base; PARTS.len()]);
        for word in words {
            let (name, version) = word.split_once('=').ok_or_else(bad)?;
            let version: u32 = version.parse().map_err(|_| bad())?;
            if let Some(at) = PARTS.iter().position(|(part, _)| *part == name) {
                out.0[at] = version;
            }
        }
        Ok(out)
    }

    /// Each part of `parts` that `self` writes at another version than `to`, in table order.
    pub fn moved(&self, to: &Scheme, parts: &[&str]) -> Vec<Move> {
        PARTS
            .iter()
            .enumerate()
            .filter(|(at, (name, _))| parts.contains(name) && self.0[*at] != to.0[*at])
            .map(|(at, (name, _))| (*name, self.0[at], to.0[at]))
            .collect()
    }

    /// Each part that `self` writes at another version than `to`.
    pub fn moved_all(&self, to: &Scheme) -> Vec<Move> {
        self.moved(to, &PARTS.map(|(name, _)| name))
    }
}

impl std::fmt::Display for Scheme {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // ยง k2xswz12t.d@vskmk
        let share = |v: u32| self.0.iter().filter(|&&w| w == v).count();
        let base = self
            .0
            .iter()
            .copied()
            .max_by_key(|&v| (share(v), v))
            .expect("the scheme has parts");
        write!(f, "{base}")?;
        for ((name, _), version) in PARTS.iter().zip(self.0) {
            if version != base {
                write!(f, " {name}={version}")?;
            }
        }
        Ok(())
    }
}

/// The parts of the scheme a pin in the file at `path` reads.
pub fn parts_of(path: &Path) -> Vec<&'static str> {
    // ยง d1bc2zca5.h@7egmj
    let language: &[&'static str] = match crate::span_lang::lang_for_path(path) {
        None => &["fallback"],
        Some(lang) => match lang.id {
            "markdown" => &[],
            "javascript" | "typescript" | "tsx" => &["js"],
            "yaml" if lang.template => &["yaml", "helm"],
            _ => std::slice::from_ref(&lang.id),
        },
    };
    ["core", "md"]
        .into_iter()
        .chain(language.iter().copied())
        .collect()
}

/// `moved` in words, the parts that moved alike grouped: `yaml from 25 to 26`, or `every part
/// from 24 to 25`.
pub fn describe(moved: &[Move]) -> String {
    let mut groups: Vec<((u32, u32), Vec<&str>)> = Vec::new();
    for &(name, from, to) in moved {
        match groups.iter_mut().find(|(pair, _)| *pair == (from, to)) {
            Some((_, names)) => names.push(name),
            None => groups.push(((from, to), vec![name])),
        }
    }
    let phrases: Vec<String> = groups
        .iter()
        .map(|((from, to), names)| {
            let names = match names.len() == PARTS.len() {
                true => "every part".to_string(),
                false => join_and(names),
            };
            format!("{names} from {from} to {to}")
        })
        .collect();
    join_and(&phrases)
}

fn join_and<S: AsRef<str>>(items: &[S]) -> String {
    match items {
        [] => String::new(),
        [one] => one.as_ref().to_string(),
        [rest @ .., last] => format!(
            "{} and {}",
            rest.iter()
                .map(AsRef::as_ref)
                .collect::<Vec<_>>()
                .join(", "),
            last.as_ref()
        ),
    }
}

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@89vda
    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 a_trailer_reads_every_part_it_omits_at_its_first_version() {
        let old = Scheme::parse("24").unwrap();
        assert_eq!(old, Scheme([24; PARTS.len()]));
        assert_eq!(old.to_string(), "24");
        assert_eq!(Scheme::parse(" 24 \n").unwrap(), old);
        let mixed = Scheme::parse("25 yaml=26 core=24 zig=3").unwrap();
        assert_eq!(mixed.to_string(), "25 core=24 yaml=26");
        assert_eq!(Scheme::parse(&mixed.to_string()).unwrap(), mixed);
        // The first version is the one most parts share, the higher on a tie.
        let mut most = Scheme([30; PARTS.len()]);
        most.0[..7].fill(31);
        let written = most.to_string();
        assert!(written.starts_with("30 core=31 md=31 rust=31"), "{written}");
        assert_eq!(Scheme::parse(&written).unwrap(), most);
        most.0[7] = 31;
        let tie = most.to_string();
        assert!(tie.starts_with("31 bash=30 yaml=30"), "{tie}");
        assert_eq!(Scheme::parse(&tie).unwrap(), most);
        for bad in ["", "yaml=26", "25 yaml", "25 yaml=x", "x"] {
            assert!(Scheme::parse(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn this_binary_reads_back_the_trailer_it_writes() {
        let written = Scheme::binary().to_string();
        assert!(Scheme::binary()
            .moved_all(&Scheme::parse(&written).unwrap())
            .is_empty());
    }

    #[test]
    fn a_pin_reads_core_md_and_the_parts_of_its_language() {
        let parts = |path: &str| parts_of(Path::new(path));
        assert_eq!(parts("src/a.rs"), ["core", "md", "rust"]);
        assert_eq!(parts("web/a.tsx"), ["core", "md", "js"]);
        assert_eq!(parts("web/a.mjs"), ["core", "md", "js"]);
        assert_eq!(parts("docs/a.md"), ["core", "md"]);
        assert_eq!(parts("docs/a.mdx"), ["core", "md"]);
        assert_eq!(parts("ci/a.yaml"), ["core", "md", "yaml"]);
        assert_eq!(
            parts("chart/templates/a.yaml"),
            ["core", "md", "yaml", "helm"]
        );
        assert_eq!(parts("Dockerfile"), ["core", "md", "dockerfile"]);
        assert_eq!(parts("tsconfig.json"), ["core", "md", "jsonc"]);
        assert_eq!(parts("main.go"), ["core", "md", "fallback"]);
        // Every language maps to parts of the table, and every part is read by some pin.
        let names = PARTS.map(|(name, _)| name);
        let mut read: Vec<&str> = vec!["core", "md", "fallback", "helm"];
        for lang in crate::span_lang::PINNED {
            let path = format!("x.{}", lang.extensions[0]);
            let of = parts(&path);
            assert!(of.iter().all(|part| names.contains(part)), "{path}: {of:?}");
            read.extend(of);
        }
        for name in names {
            assert!(read.contains(&name), "no pin reads {name}");
        }
    }

    #[test]
    fn a_part_that_moved_alone_is_the_only_one_named() {
        let binary = Scheme::parse("25 yaml=26").unwrap();
        let recorded = Scheme::parse("25").unwrap();
        let rust = parts_of(Path::new("src/a.rs"));
        let yaml = parts_of(Path::new("ci/a.yml"));
        assert!(recorded.moved(&binary, &rust).is_empty());
        assert_eq!(recorded.moved(&binary, &yaml), [("yaml", 25, 26)]);
        assert_eq!(describe(&recorded.moved_all(&binary)), "yaml from 25 to 26");
        let md = Scheme::parse("25 md=24").unwrap();
        assert_eq!(md.moved(&binary, &rust), [("md", 24, 25)]);
        assert_eq!(
            describe(&md.moved_all(&binary)),
            "md from 24 to 25 and yaml from 25 to 26"
        );
        let old = Scheme::parse("24").unwrap();
        assert_eq!(
            describe(&old.moved(&binary, &rust)),
            "core, md and rust from 24 to 25"
        );
        assert_eq!(
            describe(&old.moved_all(&Scheme::parse("25").unwrap())),
            "every part from 24 to 25"
        );
    }

    #[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(_)));
    }
}