silcrow 0.2.0

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

use crate::workspace::Workspace;

/// One conflict block, by 0-based line: the `<<<<<<<` line, the lines of each side, the base
/// lines of a diff3 block, and the `>>>>>>>` line.
#[derive(Debug, PartialEq, Eq)]
pub struct Block {
    pub open: usize,
    pub ours: std::ops::Range<usize>,
    pub base: Option<std::ops::Range<usize>>,
    pub theirs: std::ops::Range<usize>,
    pub close: usize,
}

fn opens(line: &str, mark: &str) -> bool {
    let line = line.trim_end_matches('\r');
    line.strip_prefix(mark)
        .is_some_and(|rest| rest.is_empty() || rest.starts_with(' '))
}

/// Each complete conflict block of `lines`, in order. A block cut short is none.
pub fn blocks(lines: &[&str]) -> Vec<Block> {
    let mut out = Vec::new();
    let mut open: Option<usize> = None;
    let mut base: Option<usize> = None;
    let mut split: Option<usize> = None;
    for (idx, line) in lines.iter().enumerate() {
        if opens(line, "<<<<<<<") {
            (open, base, split) = (Some(idx), None, None);
        } else if let Some(start) = open {
            if split.is_none() && base.is_none() && opens(line, "|||||||") {
                base = Some(idx);
            } else if split.is_none() && opens(line, "=======") {
                split = Some(idx);
            } else if let Some(mid) = split.filter(|_| opens(line, ">>>>>>>")) {
                let ours_end = base.unwrap_or(mid);
                out.push(Block {
                    open: start,
                    ours: start + 1..ours_end,
                    base: base.map(|b| b + 1..mid),
                    theirs: mid + 1..idx,
                    close: idx,
                });
                (open, base, split) = (None, None, None);
            }
        }
    }
    out
}

/// The paths, relative to the git root, that git holds unmerged.
fn unmerged(root: &Path) -> Result<BTreeSet<PathBuf>> {
    let out = crate::workspace::git(root)
        .args(["diff", "--name-only", "--diff-filter=U"])
        .output()?;
    if !out.status.success() {
        bail!(
            "git diff --name-only --diff-filter=U: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout)
        .lines()
        .map(PathBuf::from)
        .collect())
}

/// Each text file of a project of `ws` that is not external with a line opening a conflict
/// block, by absolute path, as the walk reads git: tracked, or untracked and not ignored. It
/// reads git rather than the walk, which reads the block, so a conflict in `AGENTS.md` is named
/// too. Outside git none is.
fn opening_files(ws: &Workspace) -> Result<Vec<PathBuf>> {
    if !ws.root.join(".git").exists() {
        return Ok(Vec::new());
    }
    let out = crate::workspace::git(&ws.root)
        .args(["grep", "--untracked", "-I", "-l", "-E", "^<<<<<<<( |$)"])
        .output()?;
    // `git grep` exits 1 when no line matches.
    if !out.status.success() && !(out.status.code() == Some(1) && out.stdout.is_empty()) {
        bail!(
            "git grep for conflict blocks: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout)
        .lines()
        .map(|rel| ws.root.join(rel))
        .filter(|path| {
            path.parent()
                .and_then(|dir| ws.enclosing(dir))
                .is_some_and(|project| !project.external)
        })
        .collect())
}

/// The operation a stopped rebase, cherry-pick or merge records in the git directory.
fn operation(root: &Path) -> Result<Option<&'static str>> {
    // § fcknw57x1.b@76jc1
    for (head, name) in [
        ("REBASE_HEAD", "a rebase"),
        ("CHERRY_PICK_HEAD", "a cherry-pick"),
        ("MERGE_HEAD", "a merge"),
    ] {
        let out = crate::workspace::git(root)
            .args(["rev-parse", "--git-path", head])
            .output()?;
        if !out.status.success() {
            bail!(
                "git rev-parse --git-path {head}: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        let path = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
        if root.join(path).is_file() {
            return Ok(Some(name));
        }
    }
    Ok(None)
}

/// Fails, naming the operation and each conflicted file with its first conflict line, while git
/// holds a path unmerged or a file of a project of `ws` holds a conflict block. `texts` stands in
/// for the files it names, by absolute path, as a dry run of `fix` would leave them.
pub fn refuse(ws: &Workspace, texts: &BTreeMap<PathBuf, String>) -> Result<()> {
    // § fcknw57x1@yt134
    let git = ws.root.join(".git").exists();
    // § fcknw57x1.a@hf0wg
    let mut found: BTreeMap<PathBuf, Option<usize>> = BTreeMap::new();
    if git {
        for rel in unmerged(&ws.root)? {
            found.insert(rel, None);
        }
    }
    for path in opening_files(ws)? {
        let text = match texts.get(&path) {
            Some(text) => text.clone(),
            None => std::fs::read_to_string(&path)?,
        };
        let lines: Vec<&str> = text.lines().collect();
        if let Some(block) = blocks(&lines).first() {
            let rel = path.strip_prefix(&ws.root).unwrap_or(&path).to_path_buf();
            found.insert(rel, Some(block.open + 1));
        }
    }
    // § end fcknw57x1.a
    if found.is_empty() {
        return Ok(());
    }
    let during = match git.then(|| operation(&ws.root)).transpose()?.flatten() {
        Some(name) => format!("{name} is in progress and left conflicts"),
        None => "no merge, rebase or cherry-pick is in progress, and the tree holds conflicts"
            .to_string(),
    };
    let lines: Vec<String> = found
        .iter()
        .map(|(rel, line)| match line {
            Some(line) => format!("  {}:{line}: a conflict block opens here", rel.display()),
            None => format!(
                "  {}: git holds it unmerged with no conflict block left in it: `git add` it once it is resolved",
                rel.display()
            ),
        })
        .collect();
    bail!(
        "{during}, so Silcrow reads no tree:\n{}\nResolve these conflicts, then run `silcrow check`.",
        lines.join("\n")
    )
}

/// `line` without the digest of each marker whose position `keep` refuses, in the order the
/// line writes its markers.
fn without_digests(line: &str, keep: impl Fn(usize) -> bool) -> String {
    let mut out = line.to_string();
    for (at, written) in crate::marker::written(line).iter().enumerate().rev() {
        if let Some(digest) = written.digest.as_ref().filter(|_| !keep(at)) {
            out.replace_range(digest.start - 1..digest.end, "");
        }
    }
    out
}

/// The lines of `block` once its two sides are found equal but for marker digests, each marker
/// whose digest differs written bare, with the address of each and its 0-based line in the
/// block. `None` when the sides differ in anything else.
fn digest_only(lines: &[&str], block: &Block) -> Option<Vec<(String, Option<String>)>> {
    // § fcknw57x1.c@425js
    let ours = &lines[block.ours.clone()];
    let theirs = &lines[block.theirs.clone()];
    if ours.len() != theirs.len() {
        return None;
    }
    let mut out = Vec::new();
    for (mine, other) in ours.iter().zip(theirs) {
        if mine == other {
            out.push((mine.to_string(), None));
            continue;
        }
        if without_digests(mine, |_| false) != without_digests(other, |_| false) {
            return None;
        }
        let (a, b) = (crate::marker::written(mine), crate::marker::written(other));
        let same = |at: usize| {
            let digest = |w: &[crate::marker::Written], line: &str| {
                w.get(at)
                    .and_then(|w| w.digest.clone())
                    .map(|d| line[d].to_string())
            };
            digest(&a, mine) == digest(&b, other)
        };
        let bare: Vec<String> = a
            .iter()
            .enumerate()
            .filter(|(at, _)| !same(*at))
            .map(|(_, w)| {
                crate::marker::MarkerAddr {
                    digest: None,
                    ..w.addr.clone()
                }
                .display()
            })
            .collect();
        out.push((without_digests(mine, same), Some(bare.join(", "))));
    }
    Some(out)
}

/// `text` with each conflict block whose sides differ only in marker digests replaced by their
/// common text, and each address it left bare with its 1-based line. `None` when no block was.
fn resolve_text(text: &str) -> Option<(String, Vec<(usize, String)>)> {
    let lines: Vec<&str> = text.lines().collect();
    let mut out: Vec<String> = Vec::new();
    let mut bare = Vec::new();
    let mut next = 0;
    let mut resolved = false;
    for block in blocks(&lines) {
        let Some(common) = digest_only(&lines, &block) else {
            continue;
        };
        out.extend(lines[next..block.open].iter().map(|l| l.to_string()));
        for (line, addrs) in common {
            out.push(line);
            if let Some(addrs) = addrs {
                bare.push((out.len(), addrs));
            }
        }
        next = block.close + 1;
        resolved = true;
    }
    if !resolved {
        return None;
    }
    out.extend(lines[next..].iter().map(|l| l.to_string()));
    let mut joined = out.join("\n");
    if text.ends_with('\n') {
        joined.push('\n');
    }
    Some((joined, bare))
}

/// Resolves, in each file of `projects`, every conflict block whose sides differ only in marker
/// digests, writing it unless `dry_run`, and names each address it left bare for `accept`. The
/// text of each file it resolved, by absolute path.
pub fn resolve_digests(
    ws: &Workspace,
    projects: &[&crate::workspace::ProjectRef],
    dry_run: bool,
) -> Result<BTreeMap<PathBuf, String>> {
    // § fcknw57x1.c@xwccb
    let opening = opening_files(ws)?;
    let mut texts = BTreeMap::new();
    for project in projects {
        let mut addrs = BTreeSet::new();
        let mine = opening
            .iter()
            .filter(|path| path.parent().and_then(|dir| ws.enclosing(dir)) == Some(*project));
        for path in mine {
            let text = std::fs::read_to_string(path)?;
            let Some((next, bare)) = resolve_text(&text) else {
                continue;
            };
            let rel = path.strip_prefix(&project.dir).unwrap_or(path);
            for (line, addr) in &bare {
                println!(
                    "  {} {}:{line} § {addr}: the two sides of its conflict differ only in this digest, so the marker is written bare",
                    if dry_run { "would RESOLVE" } else { "RESOLVE" },
                    rel.display()
                );
                addrs.extend(addr.split(", ").map(str::to_string));
            }
            if !dry_run {
                std::fs::write(path, &next)?;
            }
            texts.insert(path.clone(), next);
        }
        if addrs.is_empty() {
            continue;
        }
        let run_in = match project.key.as_str() {
            "." => String::new(),
            key => format!("-C {key} "),
        };
        println!(
            "Read each against its law or clause with `silcrow diff`, then run `silcrow {run_in}accept {}`.",
            addrs.into_iter().collect::<Vec<_>>().join(" ")
        );
    }
    Ok(texts)
}

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

    #[test]
    fn a_block_that_differs_only_in_marker_digests_resolves_to_its_bare_markers() {
        let text = "fn f() {\n<<<<<<< HEAD\n    // § abcdefgh1.a@aaaaa\n    // § abcdefgh1.b@ccccc\n||||||| base\n    // § abcdefgh1.a@zzzzz\n    // § abcdefgh1.b@ccccc\n=======\n    // § abcdefgh1.a@bbbbb\n    // § abcdefgh1.b@ccccc\n>>>>>>> other\n    go();\n}\n";
        let (next, bare) = resolve_text(text).unwrap();
        assert_eq!(
            next,
            "fn f() {\n    // § abcdefgh1.a\n    // § abcdefgh1.b@ccccc\n    go();\n}\n"
        );
        assert_eq!(bare, vec![(2, "abcdefgh1.a".to_string())]);
        let one = "<<<<<<< HEAD\n// § one abcdefgh1.a@aaaaa, abcdefgh2@ddddd\n=======\n// § one abcdefgh1.a@bbbbb, abcdefgh2@ddddd\n>>>>>>> other\n";
        let (next, bare) = resolve_text(one).unwrap();
        assert_eq!(next, "// § one abcdefgh1.a, abcdefgh2@ddddd\n");
        assert_eq!(bare, vec![(1, "abcdefgh1.a".to_string())]);
    }

    #[test]
    fn a_block_that_differs_in_anything_but_a_digest_stays() {
        for text in [
            "<<<<<<< HEAD\n// § abcdefgh1@aaaaa\ngo();\n=======\n// § abcdefgh1@bbbbb\nstop();\n>>>>>>> other\n",
            "<<<<<<< HEAD\n// § abcdefgh1@aaaaa\n||||||| base\n// § abcdefgh1@aaaaa\n=======\n// § abcdefgh1@bbbbb\ngo();\n>>>>>>> other\n",
            "<<<<<<< HEAD\n// § abcdefgh1@aaaaa\n=======\n// § abcdefgh2@aaaaa\n>>>>>>> other\n",
            "<<<<<<< HEAD\nlet a = \"x@aaaaa\";\n=======\nlet a = \"x@bbbbb\";\n>>>>>>> other\n",
        ] {
            assert_eq!(resolve_text(text), None, "{text}");
        }
        let mixed = "<<<<<<< HEAD\n// § abcdefgh1@aaaaa\n=======\n// § abcdefgh1@bbbbb\n>>>>>>> other\nmid\n<<<<<<< HEAD\ngo();\n=======\nstop();\n>>>>>>> other\n";
        let (next, _) = resolve_text(mixed).unwrap();
        assert_eq!(
            next,
            "// § abcdefgh1\nmid\n<<<<<<< HEAD\ngo();\n=======\nstop();\n>>>>>>> other\n"
        );
    }

    #[test]
    fn a_block_runs_from_its_open_to_its_close_with_an_optional_base() {
        let text = "a\n<<<<<<< HEAD\nx\n||||||| base\ny\n=======\nz\n>>>>>>> other\nb\n";
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(
            blocks(&lines),
            vec![Block {
                open: 1,
                ours: 2..3,
                base: Some(4..5),
                theirs: 6..7,
                close: 7,
            }]
        );
        let plain = "<<<<<<< HEAD\nx\n=======\nz\n>>>>>>> other\n";
        let lines: Vec<&str> = plain.lines().collect();
        assert_eq!(blocks(&lines)[0].base, None);
        for cut in [
            "<<<<<<< HEAD\nx\n=======\nz\n",
            "Title\n=======\n>>>>>>> x\n",
            "<<<<<<<< wide\nx\n=======\n>>>>>>> x\n",
        ] {
            let lines: Vec<&str> = cut.lines().collect();
            assert!(blocks(&lines).is_empty(), "{cut}");
        }
    }
}