silcrow 0.2.0

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

use crate::workspace::{ProjectRef, Workspace};

#[cfg(test)]
use std::collections::HashMap;

pub struct WritePlan {
    pub writes: Vec<(PathBuf, String)>,
}

/// A copy of every file the local projects of a workspace read, at the same paths under a
/// temporary root, and the workspace there. A write that chains steps, each reading what the
/// last one wrote, runs them here in a dry run, so the diff it shows is the one it would write.
pub struct Sandbox {
    _dir: tempfile::TempDir,
    pub ws: Workspace,
    /// Each copied file, by the key of its project and its path in that project.
    files: Vec<(String, PathBuf)>,
}

impl Sandbox {
    pub fn of(ws: &Workspace) -> anyhow::Result<Self> {
        // § z50y8eyxx.e@re7tt
        let dir = tempfile::tempdir()?;
        let mut files = Vec::new();
        let mut seen = std::collections::BTreeSet::new();
        for project in ws.local() {
            let mut paths = vec![project.dir.join("AGENTS.md")];
            paths.extend(crate::walk::decision_files(&project.dir)?);
            paths.extend(crate::walk::code_files(&project.dir)?);
            for path in paths {
                if !path.is_file() || !seen.insert(path.clone()) {
                    continue;
                }
                let dest = dir.path().join(path.strip_prefix(&ws.root)?);
                if let Some(parent) = dest.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                std::fs::copy(&path, &dest)?;
                files.push((
                    project.key.clone(),
                    path.strip_prefix(&project.dir)?.to_path_buf(),
                ));
            }
        }
        let ws = Workspace::at(dir.path().to_path_buf())?;
        Ok(Self {
            _dir: dir,
            ws,
            files,
        })
    }

    /// The project of the sandbox that stands for `project`.
    pub fn project(&self, project: &ProjectRef) -> anyhow::Result<&ProjectRef> {
        self.ws
            .get(&project.key)
            .ok_or_else(|| anyhow::anyhow!("the dry-run copy holds no project `{}`", project.key))
    }

    /// Shows each file the steps changed against the tree, as a dry run shows a write.
    pub fn show(&self, ws: &Workspace) -> anyhow::Result<()> {
        for (key, rel) in &self.files {
            let (Some(real), Some(copy)) = (ws.get(key), self.ws.get(key)) else {
                anyhow::bail!("the dry-run copy holds no project `{key}`");
            };
            let next = std::fs::read_to_string(copy.dir.join(rel))?;
            apply(
                &WritePlan {
                    writes: vec![(rel.clone(), next)],
                },
                &real.dir,
                true,
            )?;
        }
        Ok(())
    }
}

pub fn apply(plan: &WritePlan, root: &Path, dry_run: bool) -> std::io::Result<()> {
    // § z50y8eyxx.c@7atxf
    for (rel, new_body) in &plan.writes {
        let path = root.join(rel);
        let old = std::fs::read_to_string(&path).unwrap_or_default();
        let new_body = keep_line_endings(&old, new_body);
        if old == new_body {
            continue;
        }
        // § z50y8eyxx.d@z3tz7
        if dry_run {
            print_diff(rel, &old, &new_body);
        } else {
            crate::walk::forget();
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&path, new_body)?;
        }
        // § end z50y8eyxx.d
    }
    Ok(())
}

/// `new` with the line endings of `old`: a line the write kept keeps its own, and a line it
/// added takes the ending of the old line where it lands. Writers rebuild a file from its
/// lines with LF, which would rewrite every line of a CRLF file.
pub fn keep_line_endings(old: &str, new: &str) -> String {
    // § k6rfj5k37.a@6y9aq
    if !old.contains("\r\n") {
        return new.to_string();
    }
    let breaks: Vec<Option<bool>> = old
        .split_inclusive('\n')
        .map(|line| line.ends_with('\n').then(|| line.ends_with("\r\n")))
        .collect();
    let crlf_at = |at: usize| {
        breaks[..breaks.len().min(at + 1)]
            .iter()
            .rev()
            .find_map(|b| *b)
            .expect("the first line of a file that holds a CRLF ends in a line break")
    };
    let new = new.replace("\r\n", "\n");
    let old_lines: Vec<&str> = old.lines().collect();
    let new_lines: Vec<&str> = new.lines().collect();
    let mut crlf = Vec::with_capacity(new_lines.len());
    let mut at = 0;
    for entry in simple_diff(&old_lines, &new_lines) {
        match entry.as_bytes().first() {
            Some(b' ') => {
                crlf.push(crlf_at(at));
                at += 1;
            }
            Some(b'-') => at += 1,
            _ => crlf.push(crlf_at(at)),
        }
    }
    let mut out = String::with_capacity(new.len() + new_lines.len());
    for (line, crlf) in new.split_inclusive('\n').zip(crlf) {
        match line.strip_suffix('\n') {
            Some(body) if crlf => {
                out.push_str(body);
                out.push_str("\r\n");
            }
            _ => out.push_str(line),
        }
    }
    out
}

/// Deletes each file, or in a dry run shows it against an empty result.
pub fn remove(paths: &[PathBuf], root: &Path, dry_run: bool) -> std::io::Result<()> {
    // § z50y8eyxx.a@ebb05
    for rel in paths {
        let path = root.join(rel);
        if dry_run {
            print_diff(rel, &std::fs::read_to_string(&path)?, "");
        } else {
            crate::walk::forget();
            std::fs::remove_file(&path)?;
        }
    }
    Ok(())
}

pub fn print_diff(rel: &Path, old: &str, new: &str) {
    // § z50y8eyxx.b@191cw
    crate::say!("--- a/{}", rel.display());
    crate::say!("+++ b/{}", rel.display());
    // § z50y8eyxx.a@zcwhn
    let old_lines: Vec<&str> = if old.is_empty() {
        vec![]
    } else {
        old.lines().collect()
    };
    let new_lines: Vec<&str> = if new.is_empty() {
        vec![]
    } else {
        new.lines().collect()
    };
    // § end z50y8eyxx.a
    for line in hunks(&simple_diff(&old_lines, &new_lines)) {
        crate::say!("{line}");
    }
    crate::say!();
}

/// The changed lines of `diff`, each run with up to three unchanged lines around it, under the
/// `@@ -<old>,<count> +<new>,<count> @@` head of its hunk.
fn hunks(diff: &[String]) -> Vec<String> {
    // § z50y8eyxx.a@23qkq
    const CONTEXT: usize = 3;
    let changed: Vec<usize> = (0..diff.len())
        .filter(|&i| !diff[i].starts_with(' '))
        .collect();
    let side =
        |lines: &[String], other: char| lines.iter().filter(|l| !l.starts_with(other)).count();
    let head = |start: usize, count: usize| match count {
        0 => format!("{start},0"),
        _ => format!("{},{count}", start + 1),
    };
    let mut out = Vec::new();
    let mut at = 0;
    while at < changed.len() {
        let start = changed[at].saturating_sub(CONTEXT);
        while at + 1 < changed.len() && changed[at + 1] <= changed[at] + 2 * CONTEXT + 1 {
            at += 1;
        }
        let end = (changed[at] + CONTEXT + 1).min(diff.len());
        let (before, body) = (&diff[..start], &diff[start..end]);
        out.push(format!(
            "@@ -{} +{} @@",
            head(side(before, '+'), side(body, '+')),
            head(side(before, '-'), side(body, '-'))
        ));
        out.extend(body.iter().cloned());
        at += 1;
    }
    out
}

/// Every line of both sides, aligned on a longest common subsequence, so a line inserted or
/// removed shifts nothing after it into a change.
fn simple_diff(old: &[&str], new: &[&str]) -> Vec<String> {
    // § z50y8eyxx.f@znbwp
    let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
    let suffix = old[prefix..]
        .iter()
        .rev()
        .zip(new[prefix..].iter().rev())
        .take_while(|(a, b)| a == b)
        .count();
    let (a, b) = (
        &old[prefix..old.len() - suffix],
        &new[prefix..new.len() - suffix],
    );
    let mut out: Vec<String> = old[..prefix].iter().map(|l| format!(" {l}")).collect();
    // The table is quadratic: past this size the middle prints as one removal and one addition.
    if a.len().saturating_mul(b.len()) > 4_000_000 {
        out.extend(a.iter().map(|l| format!("-{l}")));
        out.extend(b.iter().map(|l| format!("+{l}")));
        out.extend(old[old.len() - suffix..].iter().map(|l| format!(" {l}")));
        return out;
    }
    // lcs[i][j] is the common subsequence length of a[i..] and b[j..].
    let mut lcs = vec![vec![0u32; b.len() + 1]; a.len() + 1];
    for i in (0..a.len()).rev() {
        for j in (0..b.len()).rev() {
            lcs[i][j] = if a[i] == b[j] {
                lcs[i + 1][j + 1] + 1
            } else {
                lcs[i + 1][j].max(lcs[i][j + 1])
            };
        }
    }
    let (mut i, mut j) = (0, 0);
    while i < a.len() || j < b.len() {
        if i < a.len() && j < b.len() && a[i] == b[j] {
            out.push(format!(" {}", a[i]));
            (i, j) = (i + 1, j + 1);
        } else if j == b.len() || (i < a.len() && lcs[i + 1][j] >= lcs[i][j + 1]) {
            out.push(format!("-{}", a[i]));
            i += 1;
        } else {
            out.push(format!("+{}", b[j]));
            j += 1;
        }
    }
    out.extend(old[old.len() - suffix..].iter().map(|l| format!(" {l}")));
    out
}

#[cfg(test)]
pub fn rewrite_files(
    root: &Path,
    paths: &[PathBuf],
    replace: &HashMap<String, String>,
) -> WritePlan {
    let mut writes = Vec::new();
    for rel in paths {
        let path = root.join(rel);
        let Ok(body) = std::fs::read_to_string(&path) else {
            continue;
        };
        let mut next = body.clone();
        for (from, to) in replace {
            next = next.replace(from, to);
        }
        if next != body {
            writes.push((rel.clone(), next));
        }
    }
    WritePlan { writes }
}

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

    #[test]
    fn a_dry_run_diff_shows_each_change_with_three_lines_around_it() {
        let old: Vec<String> = (1..=20).map(|n| format!("l{n}")).collect();
        let mut new = old.clone();
        new[1] = "two".into();
        new[15] = "sixteen".into();
        new.insert(17, "added".into());
        let old: Vec<&str> = old.iter().map(String::as_str).collect();
        let new: Vec<&str> = new.iter().map(String::as_str).collect();
        let out = hunks(&simple_diff(&old, &new)).join("\n");
        assert_eq!(
            out,
            "@@ -1,5 +1,5 @@\n l1\n-l2\n+two\n l3\n l4\n l5\n@@ -13,8 +13,9 @@\n l13\n l14\n l15\n-l16\n+sixteen\n l17\n+added\n l18\n l19\n l20"
        );
        let created = hunks(&simple_diff(&[], &["a", "b"])).join("\n");
        assert_eq!(created, "@@ -0,0 +1,2 @@\n+a\n+b");
        assert!(hunks(&simple_diff(&old, &old)).is_empty());
    }
    use std::collections::HashMap;

    #[test]
    fn a_dry_run_diff_aligns_lines_after_an_insertion() {
        assert_eq!(
            simple_diff(&["a", "b", "c"], &["a", "x", "b", "c"]),
            [" a", "+x", " b", " c"]
        );
        assert_eq!(
            simple_diff(&["a", "b", "c", "d"], &["a", "c", "d", "e"]),
            [" a", "-b", " c", " d", "+e"]
        );
        assert_eq!(simple_diff(&["a"], &["b"]), ["-a", "+b"]);
    }

    #[test]
    fn a_write_keeps_the_line_endings_of_the_file() {
        let old = "a\r\n// § x\r\nb\r\nc\n";
        assert_eq!(
            keep_line_endings(old, "a\n// § x@aaaaa\nb\nc\n"),
            "a\r\n// § x@aaaaa\r\nb\r\nc\n"
        );
        assert_eq!(
            keep_line_endings(old, "a\nb\nnew\nc\n"),
            "a\r\nb\r\nnew\nc\n"
        );
        assert_eq!(keep_line_endings("a\r\nb", "z\na\nb"), "z\r\na\r\nb");
        assert_eq!(keep_line_endings("a\nb\n", "a\nc\n"), "a\nc\n");
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("f.py"), "x = 1\r\n# § a\r\n").unwrap();
        let plan = WritePlan {
            writes: vec![(PathBuf::from("f.py"), "x = 1\n# § a@bbbbb\n".into())],
        };
        apply(&plan, dir.path(), false).unwrap();
        assert_eq!(
            std::fs::read_to_string(dir.path().join("f.py")).unwrap(),
            "x = 1\r\n# § a@bbbbb\r\n"
        );
    }

    #[test]
    fn rewrite_substitutes_text() {
        let dir = tempfile::tempdir().unwrap();
        let rel = PathBuf::from("docs/decisions/t.md");
        let path = dir.path().join(&rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "§ +foo\n").unwrap();
        let mut map = HashMap::new();
        map.insert("§ +foo".into(), "§ abcdefgh1".into());
        let plan = rewrite_files(dir.path(), &[rel], &map);
        assert_eq!(plan.writes.len(), 1);
        assert!(plan.writes[0].1.contains("abcdefgh1"));
    }
}