use anyhow::{bail, Context, Result};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use crate::check;
use crate::hash;
use crate::log;
use crate::parse;
use crate::resolve;
use crate::workspace::Workspace;
pub fn run(ws: &Workspace, event: &str, args: &[String]) -> Result<()> {
match event {
"pre-commit" => pre_commit(ws),
"post-merge" => post_merge(ws),
"post-rewrite" => post_rewrite(ws, args),
"commit-msg" => commit_msg(&ws.root, args),
other => bail!("unknown hook event `{other}`"),
}
}
fn pre_commit(ws: &Workspace) -> Result<()> {
let staged = staged_paths(&ws.root)?;
let index = IndexTree::export(&ws.root)?;
let outcome = fix_and_check_index(ws, &index, &staged);
index.remove()?;
if !outcome? {
std::process::exit(1);
}
Ok(())
}
fn fix_and_check_index(ws: &Workspace, index: &IndexTree, staged: &[PathBuf]) -> Result<bool> {
let copy = index_workspace(ws, index)?;
let unstaged = unstaged_projects(ws, ©);
if !unstaged.is_empty() {
println!(
" ERR {} carries a Silcrow block in the worktree but not in the index, so the commit would be checked without its project. Stage it, then commit.",
unstaged.join(", ")
);
return Ok(false);
}
let mut rewritten = Vec::new();
for project in copy.local() {
let rel = project.dir.strip_prefix(&index.dir).unwrap_or(&project.dir);
let mine: Vec<PathBuf> = staged
.iter()
.filter_map(|path| path.strip_prefix(rel).ok().map(Path::to_path_buf))
.collect();
if let Some(paths) = resolve::resolve_staged(©, project, &mine, false)? {
rewritten.extend(paths.into_iter().map(|path| rel.join(path)));
}
}
rewritten.sort();
rewritten.dedup();
let partial: Vec<String> = rewritten
.iter()
.filter(|rel| differs_from_index(&ws.root, rel))
.map(|rel| rel.display().to_string())
.collect();
if !partial.is_empty() {
println!(
" ERR {} is partially staged and `silcrow fix` would rewrite it, so the hook writes nothing. Stage each whole, or run `silcrow fix` and stage what it wrote, then commit.",
partial.join(", ")
);
return Ok(false);
}
let mut report = check::validate(©, ©.local(), true)?;
report.harness = staged_harness(ws, ©)?;
report.errors.extend(stray_markers(©)?);
if !check::print_report(&report, false) {
return Ok(false);
}
for rel in &rewritten {
std::fs::copy(index.dir.join(rel), ws.root.join(rel))?;
}
restage(&ws.root, &rewritten)?;
Ok(true)
}
fn index_workspace(ws: &Workspace, index: &IndexTree) -> Result<Workspace> {
let mut copy = Workspace::discover(&index.dir)?;
for project in ws.projects.iter().filter(|project| project.external) {
if copy.get(&project.key).is_none() {
copy.projects.push(project.clone());
}
}
copy.projects.sort_by(|a, b| a.key.cmp(&b.key));
Ok(copy)
}
fn unstaged_projects(ws: &Workspace, copy: &Workspace) -> Vec<String> {
ws.local()
.into_iter()
.filter(|project| copy.get(&project.key).is_none_or(|staged| staged.external))
.map(|project| {
crate::workspace::in_workspace(&project.key, Path::new("AGENTS.md"))
.display()
.to_string()
})
.collect()
}
fn staged_harness(ws: &Workspace, copy: &Workspace) -> Result<Vec<String>> {
let versioned =
|root: &Path, projects: Vec<&crate::workspace::ProjectRef>| -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
for d in crate::harness::workspace_drift(root)? {
if d.versioned {
out.push(d.path);
}
}
for project in projects {
if let Some(d) = crate::harness::project_drift(&project.dir)? {
out.push(d.path);
}
}
Ok(out
.into_iter()
.map(|path| path.strip_prefix(root).unwrap_or(&path).to_path_buf())
.collect())
};
let worktree = versioned(&ws.root, ws.local())?;
Ok(versioned(©.root, copy.local())?
.into_iter()
.map(|rel| {
if !worktree.contains(&rel) {
format!(
"{} is not staged as `silcrow install` wrote it. Stage it, with `git add -f` when git ignores it.",
rel.display()
)
} else if copy.root.join(&rel).exists() {
format!(
"{} differs from this binary. Run `silcrow install`, then stage it.",
rel.display()
)
} else {
format!(
"{} is missing. Run `silcrow install`, then stage it.",
rel.display()
)
}
})
.collect())
}
pub fn stray_markers(ws: &Workspace) -> Result<Vec<String>> {
let mut out = Vec::new();
if ws.projects.is_empty() {
return Ok(out);
}
for path in crate::walk::files_outside_projects(&ws.root)? {
let text =
std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
if !text.contains('§') {
continue;
}
let dialect = crate::marker::Dialect::of(&path);
let fenced = crate::marker::fenced_lines(dialect.is_markdown(), &text);
let rel = path.strip_prefix(&ws.root).unwrap_or(&path);
for (idx, line) in text.lines().enumerate() {
let line = line.trim();
if fenced[idx] || !crate::marker::opens_like_a_marker(line) || !dialect.opens_with(line)
{
continue;
}
out.push(format!(
"{}:{}: `{line}` is in a file outside every project, so no project checks it. Move it into a project, or give its directory, or one above it, an `AGENTS.md` with a Silcrow block.",
rel.display(),
idx + 1
));
}
}
Ok(out)
}
fn differs_from_index(root: &Path, rel: &Path) -> bool {
!crate::workspace::git(root)
.args(["diff", "--quiet", "--"])
.arg(rel)
.status()
.is_ok_and(|status| status.success())
}
struct IndexTree {
dir: PathBuf,
}
impl IndexTree {
fn export(root: &Path) -> Result<Self> {
let git_dir = git_line(root, &["rev-parse", "--absolute-git-dir"])?;
let dir = PathBuf::from(&git_dir).join("silcrow-index");
if dir.exists() {
std::fs::remove_dir_all(&dir)?;
}
std::fs::create_dir_all(&dir)?;
let prefix = format!("{}/", dir.display());
let status = crate::workspace::git(root)
.args(["checkout-index", "--all", "--force"])
.arg(format!("--prefix={prefix}"))
.status()?;
if !status.success() {
bail!(
"git checkout-index could not write the index to {}",
dir.display()
);
}
std::fs::write(dir.join(".git"), format!("gitdir: {git_dir}\n"))?;
Ok(Self { dir })
}
fn remove(&self) -> Result<()> {
Ok(std::fs::remove_dir_all(&self.dir)?)
}
}
fn git_line(root: &Path, args: &[&str]) -> Result<String> {
let out = crate::workspace::git(root).args(args).output()?;
if !out.status.success() {
bail!(
"git {}: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
fn staged_paths(root: &Path) -> Result<Vec<PathBuf>> {
let out = crate::workspace::git(root)
.args(["diff", "--cached", "--name-only"])
.output()?;
if !out.status.success() {
return Ok(Vec::new());
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.filter(|line| !line.is_empty())
.map(PathBuf::from)
.collect())
}
fn restage(root: &Path, paths: &[PathBuf]) -> Result<()> {
for rel in paths {
let Some(path) = rel.to_str() else {
continue;
};
let status = crate::workspace::git(root)
.args(["add", "--", path])
.status()?;
if !status.success() {
bail!("git add failed for {}", rel.display());
}
}
Ok(())
}
fn post_merge(ws: &Workspace) -> Result<()> {
eprintln!("silcrow: post-merge semantic collision check");
let mut report = check::validate(ws, &ws.local(), true)?;
report.errors.extend(stray_markers(ws)?);
let merge_report = crate::merge::parent_conflicts(ws)?;
report.errors.extend(merge_report.errors);
report.warnings.extend(merge_report.warnings);
if !check::print_report(&report, false) {
std::process::exit(1);
}
Ok(())
}
fn post_rewrite(ws: &Workspace, args: &[String]) -> Result<()> {
let before = rewritten_commit(
&ws.root,
args.first().map(String::as_str),
&mut std::io::stdin().lock(),
)?;
let mut report = check::validate(ws, &ws.local(), true)?;
report.errors.extend(stray_markers(ws)?);
for project in ws.local() {
let (genealogy_errors, genealogy_warnings) =
verify_rewrite_genealogy(&project.dir, before.as_deref())?;
report.errors.extend(genealogy_errors);
report.warnings.extend(genealogy_warnings);
}
if !check::print_report(&report, false) {
std::process::exit(1);
}
Ok(())
}
fn rewritten_commit(
root: &Path,
kind: Option<&str>,
stdin: &mut dyn std::io::BufRead,
) -> Result<Option<String>> {
if kind == Some("amend") {
let mut line = String::new();
stdin.read_line(&mut line)?;
let Some(old) = line.split_whitespace().next() else {
bail!("post-rewrite after an amend got no `<old> <new>` line on stdin");
};
return Ok(Some(old.to_string()));
}
let out = crate::workspace::git(root)
.args(["rev-parse", "--verify", "-q", "ORIG_HEAD"])
.output()?;
Ok(out
.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()))
}
const GENEALOGY_CAP: usize = 50;
fn verify_rewrite_genealogy(
root: &Path,
before: Option<&str>,
) -> Result<(Vec<String>, Vec<String>)> {
let scan = parse::scan_root(root)?;
let live: Vec<(String, PathBuf)> = scan
.laws
.iter()
.filter(|law| !hash::is_provisional_id(&law.id))
.map(|law| (law.id.clone(), law.loc.path.clone()))
.collect();
let (changed, existed_before) = match before {
Some(before) => (
rewrite_changed_paths(root, before)?,
pre_rewrite_law_ids(root, before)?,
),
None => (BTreeSet::new(), BTreeSet::new()),
};
let (ids, capped) = select_genealogy_ids(&live, &changed, GENEALOGY_CAP);
let (errors, mut warnings) = if ids.is_empty() {
(Vec::new(), Vec::new())
} else {
log::genealogy_check(root, &ids, &existed_before)
};
warnings.extend(capped);
Ok((errors, warnings))
}
fn rewrite_changed_paths(root: &Path, before: &str) -> Result<BTreeSet<PathBuf>> {
let out = crate::workspace::git(root)
.args(["diff", "--relative", "--name-only", before, "HEAD"])
.output()?;
if !out.status.success() {
return Ok(BTreeSet::new());
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.filter(|line| !line.is_empty())
.map(PathBuf::from)
.collect())
}
fn pre_rewrite_law_ids(root: &Path, before: &str) -> Result<BTreeSet<String>> {
let mut ids = BTreeSet::new();
let project = crate::walk::Project::at(root)?;
let out = crate::workspace::git(root)
.args(["ls-tree", "-r", "--name-only", before, "--"])
.args(
project
.notes
.roots()
.iter()
.map(|dir| match dir.as_os_str().is_empty() {
true => Path::new("."),
false => dir.as_path(),
}),
)
.output()?;
if !out.status.success() {
return Ok(ids);
}
for rel in String::from_utf8_lossy(&out.stdout).lines() {
if rel.is_empty() || !project.is_note(Path::new(rel)) {
continue;
}
let scan = scan_at_rev(root, before, &PathBuf::from(rel));
for law in scan.laws {
if !hash::is_provisional_id(&law.id) {
ids.insert(law.id);
}
}
}
Ok(ids)
}
fn scan_at_rev(root: &Path, rev: &str, rel: &Path) -> parse::Scan {
let spec = format!("{}:./{}", rev, rel.to_string_lossy());
let out = crate::workspace::git(root)
.args(["show", &spec])
.output()
.ok();
let Some(out) = out else {
return parse::Scan::default();
};
if !out.status.success() {
return parse::Scan::default();
}
let Ok(text) = String::from_utf8(out.stdout) else {
return parse::Scan::default();
};
parse::scan_text(rel, &text)
}
fn select_genealogy_ids(
live: &[(String, PathBuf)],
changed: &BTreeSet<PathBuf>,
cap: usize,
) -> (Vec<String>, Option<String>) {
if live.len() < cap {
return (live.iter().map(|(id, _)| id.clone()).collect(), None);
}
let ids: Vec<String> = live
.iter()
.filter(|(_, path)| changed.contains(path))
.map(|(id, _)| id.clone())
.collect();
let skipped = live.len() - ids.len();
let warning = (skipped > 0).then(|| {
format!(
"genealogy: {} live laws reach GENEALOGY_CAP ({cap}): verified the {} in changed notes, skipped {skipped}",
live.len(),
ids.len()
)
});
(ids, warning)
}
fn commit_msg(root: &Path, args: &[String]) -> Result<()> {
let Some(msg_path) = args.first() else {
return Ok(());
};
let path = PathBuf::from(msg_path);
let mut body = std::fs::read_to_string(&path)?;
let staged = staged_paths(root)?;
if staged.is_empty() {
return Ok(());
}
let index = IndexTree::export(root)?;
let named = staged_law_ids(&index.dir, &staged).and_then(|ids| declared_only(&index.dir, ids));
index.remove()?;
if named?.is_empty() {
return Ok(());
}
let recorded = recorded_scheme(root)?;
let current = crate::scheme::BINARY_VERSION;
let alone = match recorded {
Some(scheme) if scheme != current => {
let alone = only_minted_tokens_staged(root)?;
if !alone {
eprintln!(
"silcrow: the scheme moves from {scheme} to {current} in a change that moves more than digests, ids and alias anchors. A scheme remint travels alone, so this commit records the scheme without `Silcrow-Op: remint`."
);
}
alone
}
_ => false,
};
let trailers = scheme_trailers(recorded, current, alone, &body);
if trailers.is_empty() {
return Ok(());
}
if !body.ends_with('\n') {
body.push('\n');
}
body.push_str(&format!("\n{}\n", trailers.join("\n")));
std::fs::write(path, body)?;
Ok(())
}
fn scheme_trailers(recorded: Option<u32>, current: u32, remint: bool, body: &str) -> Vec<String> {
if body.contains("Silcrow-Scheme:") || recorded == Some(current) {
return Vec::new();
}
let mut out = Vec::new();
if recorded.is_some() && remint && !body.contains("Silcrow-Op:") {
out.push("Silcrow-Op: remint".to_string());
}
out.push(format!("Silcrow-Scheme: {current}"));
out
}
fn only_minted_tokens_staged(root: &Path) -> Result<bool> {
let diff = git_line(
root,
&["diff", "--cached", "--no-color", "--no-ext-diff", "-U0"],
)?;
Ok(only_minted_tokens(&diff))
}
pub fn only_minted_tokens(diff: &str) -> bool {
static TOKEN_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(&format!(
r#"<a id="{id}"></a>|@{digest}(?:{digest})?|\b{id}\b"#,
id = crate::marker::ID,
digest = crate::marker::DIGEST
))
.expect("minted token regex")
});
let blank = |line: &str| {
TOKEN_RE
.replace_all(
line,
|caps: ®ex::Captures| {
if caps[0].starts_with('<') {
""
} else {
"~"
}
},
)
.into_owned()
};
let (mut gone, mut came) = (Vec::new(), Vec::new());
for line in diff.lines() {
if line.starts_with("---") || line.starts_with("+++") {
continue;
}
if let Some(rest) = line.strip_prefix('-') {
gone.push(blank(rest));
} else if let Some(rest) = line.strip_prefix('+') {
came.push(blank(rest));
}
}
gone.sort();
came.sort();
gone == came
}
fn recorded_scheme(root: &Path) -> Result<Option<u32>> {
recorded_scheme_at(root, "HEAD")
}
pub fn recorded_scheme_at(root: &Path, rev: &str) -> Result<Option<u32>> {
let born = crate::workspace::git(root)
.args(["rev-parse", "--verify", "-q", rev])
.output()?;
if !born.status.success() {
return Ok(None);
}
let out = crate::workspace::git(root)
.args([
"log",
"-1",
"-E",
"--grep=^Silcrow-Scheme: ",
"--format=%B",
rev,
])
.output()?;
if !out.status.success() {
bail!("git log failed while reading Silcrow-Scheme");
}
let text = String::from_utf8_lossy(&out.stdout);
let Some(value) = text
.lines()
.filter_map(|line| line.strip_prefix("Silcrow-Scheme:"))
.next_back()
else {
return Ok(None);
};
let value = value.trim();
match value.parse() {
Ok(n) => Ok(Some(n)),
Err(_) => bail!("Silcrow-Scheme trailer `{value}` is not a scheme number"),
}
}
fn staged_law_ids(index: &Path, staged: &[PathBuf]) -> Result<Vec<String>> {
let mut ids = Vec::new();
for rel in staged {
let Ok(text) = std::fs::read_to_string(index.join(rel)) else {
continue;
};
let mut scan = parse::Scan::default();
if crate::walk::is_note_in(index, rel)? {
parse::parse_note_text(rel, &text, &mut scan);
for law in &scan.laws {
ids.push(law.id.clone());
}
}
for row in crate::span::marker_rows(rel, &text, None) {
ids.extend(row.markers.into_iter().map(|marker| marker.id));
}
}
ids.sort();
ids.dedup();
Ok(ids)
}
fn declared_only(root: &Path, ids: Vec<String>) -> Result<Vec<String>> {
if ids.is_empty() {
return Ok(ids);
}
let mut declared = BTreeSet::new();
for project in Workspace::discover(root)?.local() {
for law in parse::scan_root(&project.dir)?.laws {
declared.extend(law.aliases);
declared.insert(law.id);
}
}
Ok(ids.into_iter().filter(|id| declared.contains(id)).collect())
}
pub fn script(root: &Path, event: &str) -> String {
if is_silcrow_repo(root) {
format!("#!/bin/sh\nset -e\nexec cargo run -q -- hook {event} \"$@\"\n")
} else {
format!("#!/bin/sh\nset -e\nexec silcrow hook {} \"$@\"\n", event)
}
}
pub fn hooks_dir(root: &Path) -> Result<Option<PathBuf>> {
let dot_git = root.join(".git");
if !dot_git.exists() {
return Ok(None);
}
if dot_git.is_file() {
let link = std::fs::read_to_string(&dot_git)?;
let Some(git_dir) = link.trim().strip_prefix("gitdir: ") else {
bail!(
"{} is a file that names no `gitdir:`, so its hooks cannot be found",
dot_git.display()
);
};
if root.starts_with(git_dir) {
return Ok(None);
}
let path = PathBuf::from(git_line(root, &["rev-parse", "--git-path", "hooks"])?);
return Ok(Some(if path.is_absolute() {
path
} else {
root.join(path)
}));
}
let out = crate::workspace::git(root)
.args(["config", "--get", "core.hooksPath"])
.output()?;
let configured = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !out.status.success() || configured.is_empty() {
return Ok(Some(dot_git.join("hooks")));
}
let path = PathBuf::from(configured);
Ok(Some(if path.is_absolute() {
path
} else {
root.join(path)
}))
}
const EVENTS: [&str; 4] = ["pre-commit", "post-merge", "post-rewrite", "commit-msg"];
fn call_line(root: &Path, event: &str) -> String {
let script = script(root, event);
let exec = script.lines().last().unwrap_or_default();
exec.replacen("exec ", "", 1)
}
fn is_ours(text: &str, event: &str) -> bool {
let event = regex::escape(event);
regex::Regex::new(&format!(
r#"^#!/bin/sh\nset -e\n(?:cd '[^'\n]*' && )?exec (?:silcrow|cargo run -q --) hook {event} "\$@"\n$"#
))
.expect("hook script regex")
.is_match(text)
}
enum HookState {
Current,
Write(Option<String>),
Foreign,
}
fn executable(path: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
{
let _ = path;
true
}
}
fn hook_state(root: &Path, path: &Path, event: &str) -> HookState {
match std::fs::read(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => HookState::Write(None),
Ok(bytes) => match String::from_utf8(bytes) {
Ok(old) if old == script(root, event) && executable(path) => HookState::Current,
Ok(old) if is_ours(&old, event) => HookState::Write(Some(old)),
_ => HookState::Foreign,
},
Err(_) => HookState::Foreign,
}
}
pub fn drift(root: &Path) -> Result<Vec<(PathBuf, Option<String>)>> {
let Some(dir) = hooks_dir(root)? else {
return Ok(Vec::new());
};
Ok(EVENTS
.iter()
.filter_map(|event| {
let path = dir.join(event);
match hook_state(root, &path, event) {
HookState::Current => None,
HookState::Write(_) => Some((path, None)),
HookState::Foreign => Some((path, Some(call_line(root, event)))),
}
})
.collect())
}
pub fn installed(root: &Path) -> Result<Vec<PathBuf>> {
let Some(dir) = hooks_dir(root)? else {
return Ok(Vec::new());
};
Ok(EVENTS
.iter()
.map(|event| (dir.join(event), script(root, event)))
.filter(|(path, body)| std::fs::read_to_string(path).ok().as_deref() == Some(body.as_str()))
.map(|(path, _)| path)
.collect())
}
pub fn foreign_origin(root: &Path, path: &Path) -> Option<String> {
let text = std::fs::read(path).ok()?;
let event = path.file_name()?.to_str()?;
if let Some(dir) = template_dir(root) {
if std::fs::read(dir.join("hooks").join(event)).ok().as_deref() == Some(text.as_slice()) {
return Some(format!(
"it is the copy of `{}` that `git init` made from your git template, not a hook of this repository: delete it and run `silcrow install` again to write Silcrow's, or add the line to keep both",
dir.join("hooks").join(event).display()
));
}
}
let text = String::from_utf8_lossy(&text);
let tool = [
("husky", "husky"),
("lefthook", "lefthook"),
("pre-commit.com", "pre-commit"),
("pre_commit", "pre-commit"),
]
.into_iter()
.find(|(needle, _)| text.contains(needle))?
.1;
Some(format!(
"{tool} wrote it: add the line where {tool} runs your hooks"
))
}
fn template_dir(root: &Path) -> Option<PathBuf> {
let dir = match std::env::var("GIT_TEMPLATE_DIR") {
Ok(dir) if !dir.is_empty() => dir,
_ => git_line(root, &["config", "--get", "init.templateDir"])
.ok()
.filter(|dir| !dir.is_empty())?,
};
Some(match dir.strip_prefix("~/") {
Some(rest) => PathBuf::from(std::env::var_os("HOME")?).join(rest),
None => PathBuf::from(dir),
})
}
fn refuse_foreign(root: &Path) -> Result<()> {
let foreign: Vec<String> = drift(root)?
.into_iter()
.filter_map(|(path, line)| {
let line = line?;
Some(match foreign_origin(root, &path) {
Some(origin) => format!(" {}: {origin}, `{line}`", path.display()),
None => format!(" {}: add `{line}` to it", path.display()),
})
})
.collect();
if !foreign.is_empty() {
bail!(
"another tool wrote these git hooks, so `silcrow install` leaves them, writes the others, and does not count them as installed. Silcrow does not read them: add the line to each to run Silcrow there, and let `silcrow check --all` in CI be the gate:\n{}",
foreign.join("\n")
);
}
Ok(())
}
pub fn install(root: &Path, dry_run: bool) -> Result<()> {
let Some(dir) = hooks_dir(root)? else {
return Ok(());
};
for event in EVENTS {
let path = dir.join(event);
let HookState::Write(old) = hook_state(root, &path, event) else {
continue;
};
let body = script(root, event);
crate::harness::write_file(
root,
&path,
old.as_deref().unwrap_or_default(),
&body,
dry_run,
)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if !dry_run {
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?;
}
}
}
refuse_foreign(root)
}
pub fn is_silcrow_repo(root: &Path) -> bool {
std::fs::read_to_string(root.join("Cargo.toml"))
.is_ok_and(|t| t.lines().any(|line| line.trim() == "name = \"silcrow\""))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dev_hook_script_uses_cargo_run() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("Cargo.toml"), "name = \"silcrow\"\n").unwrap();
let s = script(dir.path(), "pre-commit");
assert!(s.contains("cargo run -q -- hook pre-commit"));
}
#[test]
fn a_marker_line_inside_a_string_names_no_staged_id() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("src")).unwrap();
std::fs::write(
dir.path().join("src/a.rs"),
"fn f() {\n // § abcdefgh1.a\n let s = r\"\n// § abcdefgh2.a@aaaaa\n\";\n}\n",
)
.unwrap();
let ids = staged_law_ids(dir.path(), &[PathBuf::from("src/a.rs")]).unwrap();
assert_eq!(ids, vec!["abcdefgh1"]);
}
#[test]
fn a_pointer_counts_only_for_a_declared_id() {
let dir = tempfile::tempdir().unwrap();
assert!(crate::test_git()
.args(["init", "-q"])
.current_dir(dir.path())
.status()
.unwrap()
.success());
std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(
dir.path().join("docs/decisions/a.md"),
"**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
)
.unwrap();
let ids = vec!["wxsgf68fh".to_string(), "abcdefgh1".to_string()];
assert_eq!(declared_only(dir.path(), ids).unwrap(), vec!["wxsgf68fh"]);
}
#[test]
fn remint_trailer_is_not_rewritten_when_already_present() {
let dir = tempfile::tempdir().unwrap();
let msg = dir.path().join("COMMIT_EDITMSG");
std::fs::write(&msg, "upgrade\n\nSilcrow-Op: remint\n").unwrap();
commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
let body = std::fs::read_to_string(&msg).unwrap();
assert_eq!(body.matches("Silcrow-Op: remint").count(), 1);
}
#[test]
fn commit_msg_records_the_scheme_and_no_impact_trailer() {
let dir = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
let out = crate::test_git()
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.current_dir(dir.path())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
};
git(&["init", "-q"]);
std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(
dir.path().join("docs/decisions/a.md"),
"**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
)
.unwrap();
git(&["add", "."]);
let msg = dir.path().join("COMMIT_EDITMSG");
std::fs::write(&msg, "law\n").unwrap();
commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
assert_eq!(
std::fs::read_to_string(&msg).unwrap(),
format!("law\n\nSilcrow-Scheme: {}\n", crate::scheme::BINARY_VERSION)
);
}
#[test]
fn commit_msg_reads_the_index_and_marks_a_remint_only_when_it_travels_alone() {
let dir = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
let out = crate::test_git()
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args([
"-c",
"commit.gpgsign=false",
"-c",
"core.hooksPath=/dev/null",
])
.args(args)
.current_dir(dir.path())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
};
let write = |rel: &str, text: &str| {
let path = dir.path().join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
let trailers = |msg: &str| {
let path = dir.path().join(".git/COMMIT_EDITMSG");
std::fs::write(&path, msg).unwrap();
commit_msg(dir.path(), &[path.to_string_lossy().into_owned()]).unwrap();
std::fs::read_to_string(&path).unwrap()[msg.len()..].to_string()
};
git(&["init", "-q"]);
write(
"AGENTS.md",
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
);
write(
"docs/decisions/a.md",
"**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
);
git(&["add", "."]);
git(&["commit", "-q", "-m", "law"]);
write(
"src/lib.rs",
"fn f() {\n // § wxsgf68fh@aaaaa\n go();\n}\n",
);
git(&["add", "."]);
write("src/lib.rs", "fn f() {\n go();\n}\n");
let current = crate::scheme::BINARY_VERSION;
assert_eq!(trailers("code\n"), format!("\nSilcrow-Scheme: {current}\n"));
write(
"src/lib.rs",
"fn f() {\n // § wxsgf68fh@aaaaa\n go();\n}\n",
);
git(&["commit", "-q", "-m", "code\n\nSilcrow-Scheme: 1"]);
write(
"src/lib.rs",
"fn f() {\n // § wxsgf68fh@bbbbb\n go();\n}\n",
);
git(&["add", "."]);
assert_eq!(
trailers("remint\n"),
format!("\nSilcrow-Op: remint\nSilcrow-Scheme: {current}\n")
);
write(
"src/lib.rs",
"fn f() {\n // § wxsgf68fh@bbbbb\n stop();\n}\n",
);
git(&["add", "."]);
assert_eq!(trailers("edit\n"), format!("\nSilcrow-Scheme: {current}\n"));
}
#[test]
fn a_scheme_that_differs_from_the_record_is_a_remint() {
assert_eq!(
scheme_trailers(Some(4), 5, true, "upgrade\n"),
vec!["Silcrow-Op: remint", "Silcrow-Scheme: 5"]
);
assert_eq!(
scheme_trailers(Some(4), 5, false, "upgrade and edit\n"),
vec!["Silcrow-Scheme: 5"]
);
assert!(scheme_trailers(Some(5), 5, true, "edit\n").is_empty());
assert_eq!(
scheme_trailers(None, 5, false, "first\n"),
vec!["Silcrow-Scheme: 5"]
);
assert_eq!(
scheme_trailers(Some(4), 5, true, "upgrade\n\nSilcrow-Op: remint\n"),
vec!["Silcrow-Scheme: 5"]
);
assert!(scheme_trailers(Some(4), 5, true, "x\n\nSilcrow-Scheme: 4\n").is_empty());
}
#[test]
fn recorded_scheme_is_the_last_trailer_in_history() {
let dir = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
let out = crate::test_git()
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args([
"-c",
"commit.gpgsign=false",
"-c",
"core.hooksPath=/dev/null",
])
.args(args)
.current_dir(dir.path())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
};
git(&["init", "-q"]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
git(&["commit", "-q", "--allow-empty", "-m", "start"]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
git(&[
"commit",
"-q",
"--allow-empty",
"-m",
"remint\n\nSilcrow-Op: remint\nSilcrow-Scheme: 4",
]);
git(&["commit", "-q", "--allow-empty", "-m", "edit"]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), Some(4));
git(&[
"commit",
"-q",
"--allow-empty",
"-m",
"remint\n\nSilcrow-Scheme: 5",
]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), Some(5));
}
fn scratch_git(dir: &Path) -> impl Fn(&[&str]) -> String + '_ {
move |args: &[&str]| {
let out = crate::test_git()
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args([
"-c",
"commit.gpgsign=false",
"-c",
"core.hooksPath=/dev/null",
])
.args(args)
.current_dir(dir)
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
}
#[test]
fn commit_msg_writes_nothing_on_a_first_commit_that_names_no_law() {
let dir = tempfile::tempdir().unwrap();
let git = scratch_git(dir.path());
git(&["init", "-q"]);
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
git(&["add", "."]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
let msg = dir.path().join("COMMIT_EDITMSG");
std::fs::write(&msg, "first\n").unwrap();
commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
assert_eq!(std::fs::read_to_string(&msg).unwrap(), "first\n");
}
#[test]
fn an_amend_is_compared_against_the_commit_it_replaced_not_a_stale_orig_head() {
let dir = tempfile::tempdir().unwrap();
let git = scratch_git(dir.path());
let write = |rel: &str, text: &str| {
let path = dir.path().join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
git(&["init", "-q"]);
write("a.md", "a\n");
git(&["add", "."]);
git(&["commit", "-q", "-m", "a"]);
write("b.md", "b\n");
git(&["add", "."]);
git(&["commit", "-q", "-m", "b"]);
git(&["reset", "-q", "--soft", "HEAD~1"]);
git(&["commit", "-q", "-m", "b again"]);
let replaced = git(&["rev-parse", "HEAD"]);
write("c.md", "c\n");
git(&["add", "."]);
git(&["commit", "-q", "--amend", "-m", "b and c"]);
let stale = git(&["rev-parse", "ORIG_HEAD"]);
assert_ne!(stale, replaced);
let new = git(&["rev-parse", "HEAD"]);
let stdin = format!("{replaced} {new}\n");
let before = rewritten_commit(dir.path(), Some("amend"), &mut stdin.as_bytes())
.unwrap()
.unwrap();
assert_eq!(before, replaced);
assert_eq!(
rewrite_changed_paths(dir.path(), &before).unwrap(),
BTreeSet::from([PathBuf::from("c.md")])
);
assert_eq!(
rewritten_commit(dir.path(), Some("rebase"), &mut "".as_bytes()).unwrap(),
Some(stale)
);
assert!(rewritten_commit(dir.path(), Some("amend"), &mut "".as_bytes()).is_err());
}
#[test]
fn a_script_silcrow_writes_is_ours_in_every_build_and_path() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let ours = script(root, "pre-commit");
assert!(is_ours(&ours, "pre-commit"));
assert!(!is_ours(&ours, "post-merge"));
assert!(is_ours(
"#!/bin/sh\nset -e\ncd '/x y' && exec cargo run -q -- hook pre-commit \"$@\"\n",
"pre-commit"
));
assert!(!is_ours(
"#!/bin/sh\nset -e\nexec silcrow hook pre-commit \"$@\"\nnpx lint-staged\n",
"pre-commit"
));
}
#[test]
fn select_genealogy_ids_uses_all_when_small() {
let live = vec![
("aaaaaaaab".into(), PathBuf::from("docs/decisions/a.md")),
("bbbbbbbbc".into(), PathBuf::from("docs/decisions/b.md")),
];
let changed = BTreeSet::from([PathBuf::from("docs/decisions/a.md")]);
let (ids, capped) = select_genealogy_ids(&live, &changed, 50);
assert_eq!(ids.len(), 2);
assert!(capped.is_none());
}
#[test]
fn select_genealogy_ids_samples_changed_when_large() {
let mut live = Vec::new();
for i in 0..60 {
live.push((
format!("id{i:07}"),
PathBuf::from(format!("docs/decisions/f{i}.md")),
));
}
let changed = BTreeSet::from([
PathBuf::from("docs/decisions/f0.md"),
PathBuf::from("docs/decisions/f59.md"),
]);
let (ids, capped) = select_genealogy_ids(&live, &changed, 50);
assert_eq!(ids.len(), 2);
assert!(ids.contains(&"id0000000".to_string()));
assert!(ids.contains(&"id0000059".to_string()));
let warning = capped.expect("a capped run warns");
assert!(warning.contains("GENEALOGY_CAP (50)"), "{warning}");
assert!(warning.contains("skipped 58"), "{warning}");
}
}