silcrow 0.2.1

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

use crate::model::Scan;
use crate::parse;
use crate::walk;

static PROJECTPATH_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!("^{}$", crate::marker::PROJECTPATH)).expect("project path regex")
});

/// The git toplevel and every project at or below it.
pub struct Workspace {
    pub root: PathBuf,
    pub projects: Vec<ProjectRef>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectRef {
    /// The project directory relative to the workspace root, `/`-separated; `.` for the root.
    pub key: String,
    pub dir: PathBuf,
    /// Behind a nested `.git`: read for resolution, never checked or written.
    pub external: bool,
}

/// The notes of every project but one, scanned for the laws they declare.
pub struct LawScans {
    pub own: String,
    pub scans: BTreeMap<String, Scan>,
}

/// The variables `git rev-parse --local-env-vars` names: each binds a command to one
/// repository, which a hook sets for its own.
const LOCAL_GIT_ENV: [&str; 15] = [
    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
    "GIT_CONFIG",
    "GIT_CONFIG_PARAMETERS",
    "GIT_CONFIG_COUNT",
    "GIT_OBJECT_DIRECTORY",
    "GIT_DIR",
    "GIT_WORK_TREE",
    "GIT_IMPLICIT_WORK_TREE",
    "GIT_GRAFT_FILE",
    "GIT_INDEX_FILE",
    "GIT_NO_REPLACE_OBJECTS",
    "GIT_REPLACE_REF_BASE",
    "GIT_PREFIX",
    "GIT_SHALLOW_FILE",
    "GIT_COMMON_DIR",
];

/// The repository the process runs in, which the git variables it inherits are for.
static OWN_REPO: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
    let cwd = std::env::current_dir().ok()?;
    std::fs::canonicalize(root_of(&cwd)).ok()
});

/// The id git names a blob of `bytes` by in a repository whose objects are named by SHA-1.
pub fn blob_id(bytes: &[u8]) -> String {
    let mut sha = sha1_smol::Sha1::new();
    sha.update(format!("blob {}\0", bytes.len()).as_bytes());
    sha.update(bytes);
    sha.digest().to_string()
}

/// A `git` command run in `dir`. In another repository than the process's own, a submodule or
/// a nested clone, it drops the variables that bind git to one repository, as git does for a
/// submodule: a hook's `GIT_INDEX_FILE` names the index of its own repository.
pub fn git(dir: &Path) -> std::process::Command {
    // ยง gyhzk1qye.d@ffaxs
    let mut cmd = std::process::Command::new("git");
    cmd.current_dir(dir);
    let repo = std::fs::canonicalize(root_of(dir)).ok();
    if repo.is_none() || repo != *OWN_REPO {
        for var in LOCAL_GIT_ENV {
            cmd.env_remove(var);
        }
    }
    cmd
}

/// The workspace root above `start`: the git toplevel, or `start` outside git.
pub fn root_of(start: &Path) -> PathBuf {
    start
        .ancestors()
        .find(|dir| dir.join(".git").exists())
        .unwrap_or(start)
        .to_path_buf()
}

impl Workspace {
    pub fn discover(start: &Path) -> Result<Self> {
        // ยง r4dndth75.a@zsf9j
        Self::at(root_of(start))
    }

    /// The workspace whose root is `root`, whether or not git holds it.
    pub fn at(root: PathBuf) -> Result<Self> {
        let mut projects = Vec::new();
        collect_projects(&root, &root, false, &mut projects)?;
        projects.sort_by(|a, b| a.key.cmp(&b.key));
        Ok(Self { root, projects })
    }

    pub fn get(&self, key: &str) -> Option<&ProjectRef> {
        self.projects.iter().find(|project| project.key == key)
    }

    /// The nearest project at or above `dir`, never above the workspace root.
    pub fn enclosing(&self, dir: &Path) -> Option<&ProjectRef> {
        dir.ancestors()
            .take_while(|d| d.starts_with(&self.root))
            .find_map(|d| self.projects.iter().find(|project| project.dir == d))
    }

    /// The project a verb acts on from `dir`.
    pub fn require(&self, dir: &Path) -> Result<&ProjectRef> {
        // ยง egfcsmhyg.a@4mhrc
        let Some(project) = self.enclosing(dir) else {
            bail!(
                "{} is in no Silcrow project. Projects: {}. Run from a project, or pass `--all` where the verb takes it.",
                dir.display(),
                self.list()
            );
        };
        if project.external {
            bail!(
                "project `{}` is behind a nested `.git`: it is read for resolution, never checked or written",
                project.key
            );
        }
        Ok(project)
    }

    /// Every project a verb may check or write.
    pub fn local(&self) -> Vec<&ProjectRef> {
        // ยง r4dndth75.d@6q4t8
        self.projects
            .iter()
            .filter(|project| !project.external)
            .collect()
    }

    /// The published base, held to the branch the local projects name in `default-branch`.
    pub fn base_ref(&self, on_integration: &str) -> Result<Option<String>> {
        let dirs: Vec<&Path> = self.local().iter().map(|p| p.dir.as_path()).collect();
        crate::published::base_ref(&self.root, &dirs, on_integration)
    }

    /// The ids of `ids` that a removed law of the project at `dir` carried.
    pub fn frozen(&self, dir: &Path, ids: &BTreeSet<String>) -> Result<BTreeSet<String>> {
        let dirs: Vec<&Path> = self.local().iter().map(|p| p.dir.as_path()).collect();
        crate::published::frozen(&self.root, &dirs, dir, ids)
    }

    /// Every letter the first-parent history of the default branch wrote for a law of the
    /// project at `dir`, by each id and alias anchor its head carried.
    pub fn held_letters(&self, dir: &Path) -> Result<BTreeMap<String, BTreeSet<String>>> {
        let dirs: Vec<&Path> = self.local().iter().map(|p| p.dir.as_path()).collect();
        let tip = crate::published::tip(&self.root, &dirs)?;
        crate::published::held_letters(dir, &tip)
    }

    pub fn list(&self) -> String {
        if self.projects.is_empty() {
            return "none".to_string();
        }
        self.projects
            .iter()
            .map(|project| format!("`{}`", project.key))
            .collect::<Vec<_>>()
            .join(", ")
    }

    pub fn law_scans(&self, own: &str) -> Result<LawScans> {
        self.law_scans_of(own, |_| true)
    }

    /// The scans `law_scans` reads, of the projects `read` keeps alone: every other project
    /// keeps its key with an empty scan, so its notes are never read.
    pub fn law_scans_of(&self, own: &str, read: impl Fn(&str) -> bool) -> Result<LawScans> {
        let mut scans = BTreeMap::new();
        for project in self.projects.iter().filter(|project| project.key != own) {
            let scan = match read(&project.key) {
                true => scan_laws(&project.dir)?,
                false => Scan::default(),
            };
            scans.insert(project.key.clone(), scan);
        }
        Ok(LawScans {
            own: own.to_string(),
            scans,
        })
    }
}

/// A path relative to the workspace root, from one relative to a project.
pub fn in_workspace(key: &str, rel: &Path) -> PathBuf {
    if key == "." {
        rel.to_path_buf()
    } else {
        Path::new(key).join(rel)
    }
}

fn scan_laws(dir: &Path) -> Result<Scan> {
    let mut notes = Vec::new();
    for path in walk::decision_files(dir)? {
        let text =
            std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
        notes.push((PathBuf::from(parse::display_path(&path, dir)), text));
    }
    Ok(parse::scan_notes(&notes))
}

fn collect_projects(
    root: &Path,
    dir: &Path,
    external: bool,
    out: &mut Vec<ProjectRef>,
) -> Result<()> {
    if walk::is_project(dir) {
        out.push(ProjectRef {
            key: project_key(root, dir)?,
            dir: dir.to_path_buf(),
            external,
        });
    }
    for entry in std::fs::read_dir(dir)? {
        // ยง r4dndth75.g@q94k5
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let path = entry.path();
        if walk::skips_dir(&path)? {
            continue;
        }
        let nested_repo = path.join(".git").exists();
        if nested_repo && !PROJECTPATH_RE.is_match(&relative_key(root, &path)?) {
            continue;
        }
        collect_projects(root, &path, external || nested_repo, out)?;
    }
    Ok(())
}

fn project_key(root: &Path, dir: &Path) -> Result<String> {
    // ยง as48vtffh.a@yteyj
    let key = relative_key(root, dir)?;
    if !PROJECTPATH_RE.is_match(&key) {
        bail!(
            "project `{key}` has a path a qualified reference cannot name: segments are `[A-Za-z0-9_-][A-Za-z0-9._-]*`"
        );
    }
    Ok(key)
}

/// The `/`-separated path of `dir` from the workspace root, `.` for the root.
fn relative_key(root: &Path, dir: &Path) -> Result<String> {
    let rel = dir.strip_prefix(root).unwrap_or(dir);
    let mut parts = Vec::new();
    for comp in rel.components() {
        match comp {
            Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
            _ => bail!("project {} is not below the workspace root", dir.display()),
        }
    }
    Ok(if parts.is_empty() {
        ".".to_string()
    } else {
        parts.join("/")
    })
}

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

    const BLOCK: &str = "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n";

    #[test]
    fn projects_are_keyed_by_path_and_external_behind_a_nested_repository() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::write(root.join("AGENTS.md"), BLOCK).unwrap();
        std::fs::create_dir_all(root.join("packages/billing/async")).unwrap();
        std::fs::write(root.join("packages/billing/AGENTS.md"), BLOCK).unwrap();
        std::fs::write(root.join("packages/billing/async/AGENTS.md"), BLOCK).unwrap();
        std::fs::create_dir_all(root.join("vendor/lib/.git")).unwrap();
        std::fs::write(root.join("vendor/lib/AGENTS.md"), BLOCK).unwrap();
        let ws = Workspace::discover(&root.join("packages/billing/async")).unwrap();
        assert_eq!(ws.root, root);
        let keys: Vec<_> = ws
            .projects
            .iter()
            .map(|h| (h.key.as_str(), h.external))
            .collect();
        assert_eq!(
            keys,
            vec![
                (".", false),
                ("packages/billing", false),
                ("packages/billing/async", false),
                ("vendor/lib", true),
            ]
        );
        let near = ws.enclosing(&root.join("packages/billing/src")).unwrap();
        assert_eq!(near.key, "packages/billing");
        assert!(ws.require(&root.join("vendor/lib")).is_err());
    }

    #[test]
    fn a_dir_in_no_project_lists_the_projects() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::create_dir_all(root.join("a")).unwrap();
        std::fs::write(root.join("a/AGENTS.md"), BLOCK).unwrap();
        let ws = Workspace::discover(root).unwrap();
        let err = ws.require(root).unwrap_err().to_string();
        assert!(err.contains("`a`"), "{err}");
    }
}