silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use anyhow::{bail, Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use crate::workspace::{in_workspace, ProjectRef, Workspace};
use crate::write::{self, WritePlan};
use crate::{follow, harness, hook, marker, parse, walk};

/// Every change, keyed by the path from the workspace root.
#[derive(Default)]
struct Plan {
    texts: BTreeMap<PathBuf, String>,
    removes: BTreeSet<PathBuf>,
    /// Skill copies whose emptied parent directories go with them.
    prune: Vec<PathBuf>,
}

impl Plan {
    fn current(&self, root: &Path, rel: &Path) -> Result<String> {
        match self.texts.get(rel) {
            Some(text) => Ok(text.clone()),
            None => read(&root.join(rel)),
        }
    }

    fn set(&mut self, rel: PathBuf, original: &str, next: String) {
        if next != original {
            self.texts.insert(rel, next);
        }
    }

    fn remove(&mut self, rel: PathBuf) {
        self.texts.remove(&rel);
        self.removes.insert(rel);
    }
}

pub fn run(ws: &Workspace, projects: &[&ProjectRef], dry_run: bool) -> Result<()> {
    // § qeka6zh48.i@eqevz
    refuse_dangling(ws, projects)?;
    let mut plan = Plan::default();
    for project in projects {
        plan_project(ws, project, &mut plan)?;
    }
    if ws.local().iter().all(|project| projects.contains(project)) {
        plan_workspace(&ws.root, &mut plan)?;
    }
    if plan.texts.is_empty() && plan.removes.is_empty() {
        println!("✓ Nothing to eject.");
        return Ok(());
    }
    for rel in plan.texts.keys() {
        println!("  EJECT {}", rel.display());
    }
    for rel in &plan.removes {
        println!("  DELETE {}", rel.display());
    }
    let writes = WritePlan {
        writes: plan.texts.into_iter().collect(),
    };
    write::apply(&writes, &ws.root, dry_run)?;
    let removes: Vec<PathBuf> = plan.removes.into_iter().collect();
    write::remove(&removes, &ws.root, dry_run)?;
    if dry_run {
        println!("\nRun with --write to apply.");
        return Ok(());
    }
    for rel in &plan.prune {
        prune_empty(&ws.root, rel)?;
    }
    println!("\n✓ Silcrow ejected.");
    Ok(())
}

/// A project left in place must not point into a project that is ejected.
fn refuse_dangling(ws: &Workspace, projects: &[&ProjectRef]) -> Result<()> {
    // § qeka6zh48.h@8ncyw
    let ejected: BTreeSet<&str> = projects
        .iter()
        .map(|project| project.key.as_str())
        .collect();
    let mut refs = Vec::new();
    for project in ws.local() {
        if ejected.contains(project.key.as_str()) {
            continue;
        }
        let scan = parse::scan_root(&project.dir)?;
        let named = scan
            .pointers
            .iter()
            .filter_map(|p| p.project.as_deref().map(|key| (key, &p.name, &p.loc)))
            .chain(
                scan.adoptions
                    .iter()
                    .map(|a| (a.project.as_str(), &a.id, &a.loc)),
            );
        for (key, id, loc) in named {
            if ejected.contains(key) {
                refs.push(format!(
                    "[{}] {}:{}: § {key}:{id}",
                    project.key,
                    loc.path.display(),
                    loc.line
                ));
            }
        }
    }
    if !refs.is_empty() {
        bail!(
            "eject would leave references into an ejected project. Remove them, or eject that project too:\n  {}",
            refs.join("\n  ")
        );
    }
    Ok(())
}

fn plan_project(ws: &Workspace, project: &ProjectRef, plan: &mut Plan) -> Result<()> {
    for path in walk::decision_files(&project.dir)? {
        let text = read(&path)?;
        let rel = PathBuf::from(parse::display_path(&path, &project.dir));
        let next = demark_note(&rel, &text);
        plan.set(in_workspace(&project.key, &rel), &text, next);
    }
    let mut files: BTreeSet<PathBuf> = walk::code_files(&project.dir)?.into_iter().collect();
    files.extend(walk::doc_files(&project.dir)?);
    for path in files {
        let text = read(&path)?;
        let rel = PathBuf::from(parse::display_path(&path, &project.dir));
        plan.set(
            in_workspace(&project.key, &rel),
            &text,
            strip_marks(&rel, &text),
        );
    }
    plan_agents(ws, project, plan)
}

fn plan_agents(ws: &Workspace, project: &ProjectRef, plan: &mut Plan) -> Result<()> {
    // § qeka6zh48.f@6p456
    let rel = in_workspace(&project.key, Path::new("AGENTS.md"));
    let text = plan.current(&ws.root, &rel)?;
    let next = harness::strip_block(&text)
        .with_context(|| format!("{} carries no Silcrow block", rel.display()))?;
    if next.trim().is_empty() {
        plan.remove(rel);
    } else {
        plan.texts.insert(rel, next);
    }
    Ok(())
}

/// The skill pointer and the hooks belong to the workspace, so they go with its last project.
fn plan_workspace(root: &Path, plan: &mut Plan) -> Result<()> {
    // § qeka6zh48.g@cb2e8
    for path in harness::skill_copies(root)? {
        let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
        plan.prune.push(rel.clone());
        plan.remove(rel);
    }
    for path in hook::installed(root)? {
        plan.remove(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
    }
    Ok(())
}

/// Removes the directories above `rel` that the removal left empty, up to the root.
fn prune_empty(root: &Path, rel: &Path) -> Result<()> {
    for dir in rel.ancestors().skip(1) {
        if dir.as_os_str().is_empty() {
            break;
        }
        let path = root.join(dir);
        if std::fs::read_dir(&path)?.next().is_some() {
            break;
        }
        std::fs::remove_dir(&path)?;
    }
    Ok(())
}

fn strip_marks(rel: &Path, text: &str) -> String {
    // § qeka6zh48.b@7kkq1
    // A follow mark holds no `§`, so the lines that open in a string are read from the
    // literals themselves, not from `span::unmarked_lines`.
    let unmarked = marker::unmarked_lines(marker::Dialect::of(rel), text);
    let literal = crate::span::lines_opening_in(text, &crate::span::literal_ranges(rel, text));
    text.split_inclusive('\n')
        .enumerate()
        .filter(|&(idx, line)| {
            unmarked.get(idx).copied().unwrap_or(false)
                || literal.get(idx).copied().unwrap_or(false)
                || !is_mark(line.trim_end_matches(['\n', '\r']))
        })
        .map(|(_, line)| line)
        .collect()
}

fn is_mark(line: &str) -> bool {
    marker::is_pointer_line(line)
        || follow::parse_decl_mark(line).is_some()
        || follow::parse_call_mark(line).is_some()
}

/// The note as plain prose: the lines the parser places in a removed clause go, a live head
/// loses its marker, and a cite keeps only its text.
fn demark_note(rel: &Path, text: &str) -> String {
    // § qeka6zh48.d@fx4nj
    let scan = parse::scan_text(rel, text);
    let mut cut = Cut::default();
    let mut heads = BTreeSet::new();
    for law in &scan.laws {
        if law.struck {
            cut.lines(law.loc.line, law.end);
        } else {
            heads.insert(law.loc.line);
        }
        for al in law.clauses.iter().filter(|al| law.struck || al.struck) {
            cut.lines(al.loc.line, al.end);
        }
    }
    for adoption in &scan.adoptions {
        cut.lines(adoption.loc.line, adoption.loc.line);
    }
    let fence = parse::fenced(text);
    let mut out: Vec<String> = Vec::new();
    for (idx, line) in text.lines().enumerate() {
        let n = idx + 1;
        if cut.lines.contains(&n) {
            if cut.starts.contains(&n) {
                pop_blank(&mut out);
            }
            continue;
        }
        if fence[idx] {
            out.push(line.to_string());
            continue;
        }
        // § qeka6zh48.c@h055x
        let head = if heads.contains(&n) {
            parse::demark_head(line)
        } else {
            line.to_string()
        };
        // § end qeka6zh48.c
        // § qeka6zh48.e@dmzw7
        let next = parse::uncite(&head);
        if next == head {
            out.push(head);
        } else if next.trim().is_empty() {
            pop_blank(&mut out);
        } else {
            out.push(next.trim_end().to_string());
        }
        // § end qeka6zh48.e
    }
    let mut joined = out.join("\n");
    if text.ends_with('\n') && !joined.is_empty() {
        joined.push('\n');
    }
    joined
}

/// Lines to delete, 1-based. Each span also takes the blank line above it, the separator
/// every law and clause carries.
#[derive(Default)]
struct Cut {
    lines: BTreeSet<usize>,
    starts: BTreeSet<usize>,
}

impl Cut {
    fn lines(&mut self, start: usize, end: usize) {
        self.starts.insert(start);
        self.lines.extend(start..=end);
    }
}

fn pop_blank(out: &mut Vec<String>) {
    if out.last().is_some_and(|line| line.trim().is_empty()) {
        out.pop();
    }
}

fn read(path: &Path) -> Result<String> {
    std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))
}

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

    #[test]
    fn strips_every_mark_line_and_nothing_else() {
        let text = "fn a() {\n    // § abcdefgh1.a@k3n7q\n    # § packages/billing:abcdefgh2\n    let x = 1; // § abcdefgh1\n    // § end abcdefgh1.a\n    // silcrow:skip\n    -- silcrow:technical\n}\n<!-- § abcdefgh1 -->\n<!-- § end abcdefgh1 -->\n";
        assert_eq!(
            strip_marks(Path::new("a.txt"), text),
            "fn a() {\n    let x = 1; // § abcdefgh1\n}\n"
        );
    }

    #[test]
    fn keeps_a_mark_line_inside_a_string() {
        let text = "fn a() {\n    // § abcdefgh1.a@k3n7q\n    let s = r\"\n// § abcdefgh1.a@k3n7q\n// silcrow:skip\n\";\n}\n";
        assert_eq!(
            strip_marks(Path::new("src/a.rs"), text),
            "fn a() {\n    let s = r\"\n// § abcdefgh1.a@k3n7q\n// silcrow:skip\n\";\n}\n"
        );
        let doc = "# § abcdefgh1.a\n\n<!-- § abcdefgh1.a@k3n7q -->\nProse.\n";
        assert_eq!(
            strip_marks(Path::new("docs/guide.md"), doc),
            "# § abcdefgh1.a\n\nProse.\n"
        );
    }

    #[test]
    fn demarks_a_note() {
        let text = "# N\n\nWhy, see [abcdefgh3.a](o.md#abcdefgh3) and `[x](o.md#abcdefgh3)`.\n\n**§ <a id=\"abcdefgh1\">abcdefgh1</a><a id=\"abcdefgh2\"></a> Live law.**\n\n| A | B |\n| - | - |\n\n- (a) Kept.\n\n- (b) ~~Struck.~~\n\n  ```text\n  attached\n  ```\n\n- (c) **Retired.**\n\n- (d) Kept too.\n\nContext stays.\n\n**§ abcdefgh4 ~~Struck law.~~**\n\n- (a) Its letter.\n\n**§ packages/billing:abcdefgh5**\n\nEnd.\n";
        assert_eq!(
            demark_note(Path::new("docs/decisions/n.md"), text),
            "# N\n\nWhy, see abcdefgh3.a and `[x](o.md#abcdefgh3)`.\n\n**Live law.**\n\n| A | B |\n| - | - |\n\n- (a) Kept.\n\n- (d) Kept too.\n\nContext stays.\n\nEnd.\n"
        );
    }

    #[test]
    fn strips_the_block_and_its_separator() {
        let text = "<silcrow notes=\"docs/decisions/**/*.md\">\nx\n</silcrow>\n\n# Mine\n";
        assert_eq!(harness::strip_block(text).as_deref(), Some("# Mine\n"));
        assert_eq!(
            harness::strip_block("<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n")
                .as_deref(),
            Some("")
        );
    }
}