silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use anyhow::Result;

use crate::harness;
use crate::workspace::Workspace;

/// What a dry run of `install` names beside the files it would write.
fn dry_run_notes(ws: &Workspace) {
    if let Some(line) = published_rewrite(ws) {
        println!("{line}\n");
    }
    // § hqv22s05t.d@v2qqs
    let Some(home) = std::env::var_os("HOME") else {
        println!("HOME is unset, so no home skill directory was read.\n");
        return;
    };
    let shadows = harness::home_skills(std::path::Path::new(&home), &ws.root);
    if shadows.is_empty() {
        return;
    }
    for dir in &shadows {
        println!(
            "  {} is a home skill named silcrow, which may load in place of the repo pointer",
            dir.display()
        );
    }
    println!("\nRemove it unless you mean it to override the repo pointer.\n");
}

/// The change of `default-branch` that every comparison reads past, or why the default branch
/// cannot be read. Nothing before the first commit, or outside git.
fn published_rewrite(ws: &Workspace) -> Option<String> {
    // § f46qcnawn.d@65ecx
    let dirs: Vec<&std::path::Path> = ws.local().iter().map(|p| p.dir.as_path()).collect();
    let born = crate::workspace::git(&ws.root)
        .args(["rev-parse", "--verify", "--quiet", "HEAD"])
        .output()
        .is_ok_and(|out| out.status.success());
    if dirs.is_empty() || !born {
        return None;
    }
    match crate::published::held_branch(&ws.root, &dirs) {
        Ok(held) => held.rewritten.map(|(named, at)| {
            let name = held.name;
            format!(
                "The Silcrow block names `{named}` in `default-branch`, a change made at {at} while `{name}` was the default branch, and `{name}` does not hold it: every comparison reads `{name}` as the default branch until the change lands there. If `{name}` is no longer the default branch, let it hold the change and keep it, local or as `origin/{name}`: a branch this clone lacks holds no change."
            )
        }),
        Err(e) => Some(format!("The default branch cannot be read: {e}")),
    }
}

pub fn install(dry_run: bool) -> Result<()> {
    // § hqv22s05t@8gj8j
    let cwd = std::env::current_dir()?;
    let ws = Workspace::discover(&cwd)?;
    // § k3v7hb6mk.c@fq8c4
    if !ws.root.join(".git").exists() {
        anyhow::bail!("no git repository here. `silcrow install` writes into the git root.");
    }
    // § end k3v7hb6mk.c
    // § ave4h4m3g.b@172bd
    let project = ws
        .enclosing(&cwd)
        .map_or_else(|| cwd.clone(), |project| project.dir.clone());
    if let Some(enclosing) = ws.enclosing(&cwd).filter(|project| project.dir != cwd) {
        eprintln!(
            "install writes the block of project `{}`, the nearest that encloses this directory. A nested project starts as an `AGENTS.md` with a Silcrow block in its own directory.",
            enclosing.key
        );
    }
    // § end ave4h4m3g.b
    // § yymjgaqr0.i@1em43
    if let Err(e) = crate::policy::ProjectPolicy::from_root(&project) {
        anyhow::bail!("{e} `install` writes no file while the block reads otherwise.");
    }
    // § end yymjgaqr0.i
    // The notes come before the writes, since a hook another tool wrote fails the run.
    if dry_run {
        dry_run_notes(&ws);
    }
    harness::install_skill(&ws.root, dry_run)?;
    harness::install_block_and_hooks(&ws.root, &project, dry_run)
}