use anyhow::{bail, Result};
use regex::Regex;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use std::sync::LazyLock;
use crate::parse;
static ID_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(&format!(r"\b({})\b", crate::marker::ID)).expect("id regex"));
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StepKind {
Declare,
Accept,
Remint,
Retire,
}
struct Step {
commit: String,
id: String,
old: Option<String>,
new: Option<String>,
kind: StepKind,
author: String,
date: String,
time: i64,
}
pub fn run(root: &Path, id: &str, verbose: bool) -> Result<()> {
if id.len() != 9 {
bail!("log expects a 9-character law id");
}
let id = &crate::hash::normalise_id(id);
ensure_git(root)?;
let scan = parse::scan_root(root)?;
let current_law = scan
.laws
.iter()
.find(|law| law.id == *id || law.aliases.iter().any(|alias| alias == id));
let id = current_law.map_or(id.as_str(), |law| law.id.as_str());
let git = History::new(root);
let family = expand_family(&git, id)?;
let steps = collect_steps(&git, &family, verbose)?;
if current_law.is_none() && steps.is_empty() {
bail!("no law `{id}` in the tree or in its git history: check the id with `silcrow list`");
}
let current = current_law
.map(|law| law.name.as_str())
.unwrap_or("(unknown law)");
println!("[{id}] {current}");
if let Some(law) = current_law {
let drafts: Vec<String> =
std::iter::once((law.draft, law.id.clone()))
.chain(law.clauses.iter().filter(|c| !c.struck).filter_map(|c| {
Some((c.draft, format!("{}.{}", law.id, c.letter.as_deref()?)))
}))
.filter_map(|(draft, address)| draft.then_some(address))
.collect();
if !drafts.is_empty() {
println!(
" draft {} (not implemented, not pinned)",
drafts.join(", ")
);
}
if law.public {
println!(" public a promise of the public docs, owes a documentation marker");
}
}
let (meta, rewrites) = std::thread::scope(|s| {
let meta = s.spawn(|| crate::meta::for_id(root, &scan, id, false));
let rewrites = rewrites_in(&git, id);
let meta = meta
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
(meta, rewrites)
});
if let Some(date) = &meta.declared_on {
match &meta.age {
Some(age) => println!(" declared {date} ({age})"),
None => println!(" declared {date}"),
}
}
let rewrites = rewrites?;
println!(
" markers code {} doc {} remint {} accept {} re-pin {}",
meta.markers.code,
meta.markers.doc,
rewrites.remints,
rewrites.accepts,
rewrites.repins.len()
);
if verbose {
for repin in &rewrites.repins {
print!("{}", render_repin(repin));
}
}
if steps.is_empty() {
println!(" (no commits touching § {id})");
return Ok(());
}
for step in steps {
print!("{}", render_step(&step));
}
Ok(())
}
fn render_step(step: &Step) -> String {
let kind = match step.kind {
StepKind::Declare => "declare",
StepKind::Accept => "accept",
StepKind::Remint => "remint",
StepKind::Retire => "retire",
};
let mut out = format!("[{}] {kind}, {}, {}\n", step.id, step.author, step.date);
if let Some(old) = &step.old {
out.push_str(&format!(" - {old}\n"));
}
if let Some(new) = &step.new {
out.push_str(&format!(" + {new}\n"));
}
out
}
pub struct Rewrites {
pub remints: usize,
pub accepts: usize,
pub repins: Vec<Repin>,
}
fn render_repin(repin: &Repin) -> String {
format!(
" re-pin {} {}, {} {}\n",
repin.sha,
repin.author,
repin.date,
repin.addresses.join(", ")
)
}
pub fn rewrite_counts(root: &Path, id: &str) -> Result<Rewrites> {
rewrites_in(&History::new(root), id)
}
fn rewrites_in(git: &History<'_>, id: &str) -> Result<Rewrites> {
let family = expand_family(git, id)?;
let (steps, digests) = std::thread::scope(|s| {
let digests = crate::par::spawn(s, || digest_changes(git.root, &family));
let steps = collect_steps(git, &family, true);
let digests = digests
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
(steps, digests)
});
let steps = steps?;
let (repins, digest_remints) = digests?;
let remints: BTreeSet<&str> = steps
.iter()
.filter(|step| step.kind == StepKind::Remint)
.map(|step| step.commit.as_str())
.chain(digest_remints.iter().map(String::as_str))
.collect();
let accepts = steps
.iter()
.filter(|step| step.kind == StepKind::Accept)
.count();
Ok(Rewrites {
remints: remints.len(),
accepts,
repins,
})
}
#[derive(Clone)]
pub struct Repin {
pub sha: String,
pub author: String,
pub date: String,
pub addresses: Vec<String>,
}
fn digest_changes(root: &Path, family: &BTreeSet<String>) -> Result<(Vec<Repin>, Vec<String>)> {
let mut repins: BTreeMap<String, (i64, Repin)> = BTreeMap::new();
let mut remints = BTreeSet::new();
for id in family {
let (found, reminted) = id_digest_changes(root, id)?;
remints.extend(reminted);
for (time, full, repin) in found {
let entry = repins.entry(full).or_insert((
time,
Repin {
addresses: Vec::new(),
..repin.clone()
},
));
entry.1.addresses.extend(repin.addresses);
entry.1.addresses.sort();
entry.1.addresses.dedup();
}
}
let mut repins: Vec<(i64, Repin)> = repins.into_values().collect();
repins.sort_by_key(|(time, _)| *time);
Ok((
repins.into_iter().map(|(_, repin)| repin).collect(),
remints.into_iter().collect(),
))
}
type TimedRepin = (i64, String, Repin);
fn id_digest_changes(root: &Path, id: &str) -> Result<(Vec<TimedRepin>, Vec<String>)> {
let out = crate::workspace::git(root)
.args([
"-c",
"core.quotePath=false",
"log",
"-G",
id,
"--format=%x01%H%x00%h%x00%an%x00%ad%x00%at%x00%(trailers:key=Silcrow-Op,valueonly,separator=%x20)%x00%(trailers:key=Silcrow-Scheme,valueonly,separator=%x20)",
"--date=format:%-d %b %Y",
"-p",
"-U0",
"--no-color",
"--no-ext-diff",
"--no-renames",
"--src-prefix=a/",
"--dst-prefix=b/",
])
.output()?;
if !out.status.success() {
bail!(
"git log -G {id} failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
let stdout = String::from_utf8_lossy(&out.stdout);
let mut repins = Vec::new();
let mut remints = Vec::new();
for record in stdout.split('\u{1}').filter(|r| !r.is_empty()) {
let (head, patch) = record.split_once('\n').unwrap_or((record, ""));
let fields: Vec<&str> = head.split('\0').collect();
let [full, sha, author, date, time, op, scheme] = fields[..] else {
bail!("git log -G {id}: unexpected header `{head}`");
};
let addresses = repinned_addresses(patch, id, &|new, path| {
let rev = if new {
full.to_string()
} else {
format!("{full}^")
};
show(root, &rev, path)
})?;
if addresses.is_empty() {
continue;
}
if scheme_changed(root, full, op, scheme)? {
remints.push(full.to_string());
continue;
}
repins.push((
time.parse()?,
full.to_string(),
Repin {
sha: sha.to_string(),
author: author.to_string(),
date: date.to_string(),
addresses,
},
));
}
Ok((repins, remints))
}
fn repinned_addresses(
patch: &str,
id: &str,
file: &dyn Fn(bool, &str) -> Result<String>,
) -> Result<Vec<String>> {
let mut removed: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
let mut added: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
let mut rows: HashMap<(bool, String), BTreeSet<usize>> = HashMap::new();
let mut paths: [Option<String>; 2] = [None, None];
let mut at = [0usize; 2];
let mut header = false;
for line in patch.lines() {
if line.starts_with("diff --git ") {
header = true;
paths = [None, None];
continue;
}
if header {
if let Some(path) = line.strip_prefix("--- ") {
paths[0] = patch_path(path, "a/")?;
} else if let Some(path) = line.strip_prefix("+++ ") {
paths[1] = patch_path(path, "b/")?;
} else if let Some(range) = line.strip_prefix("@@ ") {
header = false;
at = hunk_starts(range)?;
}
continue;
}
if let Some(range) = line.strip_prefix("@@ ") {
at = hunk_starts(range)?;
continue;
}
let new = match line.as_bytes().first() {
Some(b'-') => false,
Some(b'+') => true,
_ => continue,
};
let side = usize::from(new);
let lineno = at[side];
at[side] += 1;
let markers: Vec<_> = crate::marker::markers_in_line(&line[1..])
.into_iter()
.filter(|m| m.id == id && m.digest.is_some())
.collect();
if markers.is_empty() {
continue;
}
let Some(path) = &paths[side] else {
bail!("git log -G {id}: a changed line outside any file: {line}");
};
let key = (new, path.clone());
if !rows.contains_key(&key) {
let text = file(new, path)?;
let lines = crate::span::marker_rows(Path::new(path), &text, None)
.into_iter()
.map(|row| row.idx + 1)
.collect();
rows.insert(key.clone(), lines);
}
if !rows[&key].contains(&lineno) {
continue;
}
let side = if new { &mut added } else { &mut removed };
for marker in markers {
let digest = marker.digest.clone().unwrap_or_default();
side.entry(marker.display()).or_default().insert(digest);
}
}
Ok(added
.into_iter()
.filter(|(addr, new)| {
removed
.get(addr)
.is_some_and(|old| new.iter().any(|digest| !old.contains(digest)))
})
.map(|(addr, _)| addr)
.collect())
}
pub fn patch_path(field: &str, prefix: &str) -> Result<Option<String>> {
if field == "/dev/null" {
return Ok(None);
}
match field
.strip_suffix('\t')
.unwrap_or(field)
.strip_prefix(prefix)
{
Some(path) => Ok(Some(path.to_string())),
None => bail!("git log: a patch names `{field}`, not a path under `{prefix}`"),
}
}
pub fn hunk_starts(range: &str) -> Result<[usize; 2]> {
let mut parts = range.split_whitespace();
let mut start = |sign: char| -> Result<usize> {
let part = parts.next().and_then(|p| p.strip_prefix(sign));
let first = part.and_then(|p| p.split(',').next());
match first.map(str::parse::<usize>) {
Some(Ok(n)) => Ok(n),
_ => bail!("git log: unreadable hunk header `@@ {range}`"),
}
};
Ok([start('-')?, start('+')?])
}
fn show(root: &Path, rev: &str, path: &str) -> Result<String> {
let out = crate::workspace::git(root)
.args(["cat-file", "blob", &format!("{rev}:{path}")])
.output()?;
if !out.status.success() {
bail!(
"git cat-file {rev}:{path} failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
pub fn scheme_changed(root: &Path, commit: &str, op: &str, scheme: &str) -> Result<bool> {
if is_scheme_remint(root, commit, op)? {
return Ok(true);
}
let Some(recorded) = scheme.split_whitespace().next_back() else {
return Ok(false);
};
let recorded: u32 = recorded.parse().map_err(|_| {
anyhow::anyhow!("Silcrow-Scheme trailer `{recorded}` is not a scheme number")
})?;
let parent = crate::hook::recorded_scheme_at(root, &format!("{commit}^"))?;
Ok(parent.is_some_and(|before| before != recorded) && moves_only_tokens(root, commit)?)
}
fn moves_only_tokens(root: &Path, commit: &str) -> Result<bool> {
let parent = format!("{commit}^1");
let born = crate::workspace::git(root)
.args(["rev-parse", "--verify", "--quiet", &parent])
.output()?;
if !born.status.success() {
return Ok(false);
}
let out = crate::workspace::git(root)
.args([
"diff",
"--no-color",
"--no-ext-diff",
"--no-renames",
"-U0",
&parent,
commit,
])
.output()?;
if !out.status.success() {
bail!(
"git diff {parent} {commit} failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(crate::hook::only_minted_tokens(&String::from_utf8_lossy(
&out.stdout,
)))
}
pub fn can_trace(root: &Path, id: &str) -> Result<bool> {
let out = crate::workspace::git(root)
.args(["log", "-S", id, "--format=%H", "-1", "--", "."])
.output()?;
if !out.status.success() {
bail!("git log -S failed");
}
Ok(!String::from_utf8_lossy(&out.stdout).trim().is_empty())
}
pub fn genealogy_check(
root: &Path,
ids: &[String],
existed_before: &BTreeSet<String>,
) -> (Vec<String>, Vec<String>) {
let mut errors = Vec::new();
let mut warnings = Vec::new();
for id in ids {
if !existed_before.contains(id) {
continue;
}
match can_trace(root, id) {
Ok(true) => {}
Ok(false) => errors.push(format!(
"genealogy: § {id} has no pickaxe history; post-rewrite may have broken `silcrow log`"
)),
Err(e) => warnings.push(format!("genealogy: § {id}: {e}")),
}
}
(errors, warnings)
}
fn expand_family(git: &History<'_>, start: &str) -> Result<BTreeSet<String>> {
let mut family = BTreeSet::from([start.to_string()]);
let mut changed = true;
while changed {
changed = false;
for id in family.clone() {
for (old, new) in accept_pairs(git, &id)? {
if family.insert(old) {
changed = true;
}
if family.insert(new) {
changed = true;
}
}
}
}
Ok(family)
}
fn accept_pairs(git: &History<'_>, id: &str) -> Result<Vec<(String, String)>> {
let mut pairs = Vec::new();
for hit in pickaxe_commits(git, id, true)? {
let commit = hit.hash;
let diff = git_show_decisions(git, &commit)?;
for (old, new) in pairs_in_diff(&diff) {
if old == *id || new == *id {
pairs.push((old, new));
}
}
}
pairs.sort();
pairs.dedup();
Ok(pairs)
}
fn collect_steps(git: &History<'_>, family: &BTreeSet<String>, verbose: bool) -> Result<Vec<Step>> {
let mut by_commit: BTreeMap<String, PickaxeHit> = BTreeMap::new();
for id in family {
for hit in pickaxe_commits(git, id, verbose)? {
by_commit.entry(hit.hash.clone()).or_insert(hit);
}
}
let mut steps = Vec::new();
for (hash, hit) in by_commit {
let diff = git_show_decisions(git, &hash)?;
let step = if hit.remint {
remint_step_from_diff(&diff, family, &hit.author, &hit.date)
} else {
step_from_diff(&diff, family, &hit.author, &hit.date)
};
if let Some(step) = step {
steps.push(Step {
commit: hash,
time: hit.time,
..step
});
}
}
steps.sort_by(|a, b| b.time.cmp(&a.time).then_with(|| b.id.cmp(&a.id)));
steps.dedup_by(|a, b| a.id == b.id && a.date == b.date && a.kind == b.kind);
Ok(steps)
}
fn remint_step_from_diff(
diff: &str,
family: &BTreeSet<String>,
author: &str,
date: &str,
) -> Option<Step> {
for (old, new) in pairs_in_diff(diff) {
if family.contains(&new) && family.contains(&old) {
return Some(Step {
commit: String::new(),
old: carrying_in(diff, '-', &old),
new: carrying_in(diff, '+', &new),
id: new,
kind: StepKind::Remint,
author: author.to_string(),
date: date.to_string(),
time: 0,
});
}
}
None
}
fn step_from_diff(diff: &str, family: &BTreeSet<String>, author: &str, date: &str) -> Option<Step> {
for id in family {
if struck_in(diff, '+', id) && !struck_in(diff, '-', id) {
return Some(Step {
commit: String::new(),
id: id.clone(),
old: carrying_in(diff, '-', id),
new: None,
kind: StepKind::Retire,
author: author.to_string(),
date: date.to_string(),
time: 0,
});
}
}
if diff.contains("**Retire §") {
for id in family {
if diff.contains(&format!("**Retire § {id}")) {
return Some(Step {
commit: String::new(),
id: id.clone(),
old: carrying_in(diff, '-', id),
new: None,
kind: StepKind::Retire,
author: author.to_string(),
date: date.to_string(),
time: 0,
});
}
}
}
for (old, new) in pairs_in_diff(diff) {
if family.contains(&new) && family.contains(&old) {
return Some(Step {
commit: String::new(),
old: carrying_in(diff, '-', &old),
new: carrying_in(diff, '+', &new),
id: new,
kind: StepKind::Accept,
author: author.to_string(),
date: date.to_string(),
time: 0,
});
}
}
for id in family {
let added = carrying_in(diff, '+', id);
let declared = diff.contains(&format!("+§ {id}"))
|| (added.is_some() && carrying_in(diff, '-', id).is_none());
if declared {
return Some(Step {
commit: String::new(),
id: id.clone(),
old: None,
new: added,
kind: StepKind::Declare,
author: author.to_string(),
date: date.to_string(),
time: 0,
});
}
}
None
}
fn struck_in(diff: &str, sign: char, id: &str) -> bool {
let anchored = format!("§ <a id=\"{id}\">{id}</a>");
diff.lines()
.filter(|line| line.starts_with(sign) && !line.starts_with(&sign.to_string().repeat(3)))
.find_map(|line| line.find(&anchored).map(|at| &line[at + anchored.len()..]))
.is_some_and(|after| crate::hash::strip_aliases(after).trim().starts_with("~~"))
}
fn carrying_in(diff: &str, sign: char, id: &str) -> Option<String> {
diff.lines()
.filter(|line| line.starts_with(sign) && !line.starts_with(&sign.to_string().repeat(3)))
.filter(|line| line.contains(id))
.find_map(|line| declare_sentence(line[1..].trim(), id))
}
fn declare_sentence(line: &str, id: &str) -> Option<String> {
let anchored = format!("§ <a id=\"{id}\">{id}</a>");
let bare = format!("§ {id}");
let (idx, len) = line
.find(&anchored)
.map(|i| (i, anchored.len()))
.or_else(|| line.find(&bare).map(|i| (i, bare.len())))?;
let before = line[..idx].trim();
let after = crate::hash::strip_aliases(&line[idx + len..]);
let after = after.trim();
let mut text = before.to_string();
if !after.is_empty() {
if !text.is_empty() {
text.push(' ');
}
text.push_str(after);
}
let text = text
.trim_matches(|c: char| c == '~' || c == '*' || c == '_' || c == '`')
.trim();
if text.is_empty() {
return None;
}
Some(text.to_string())
}
pub fn pairs_in_diff(diff: &str) -> Vec<(String, String)> {
let ids_on = |sign: char| -> BTreeSet<String> {
diff.lines()
.filter(|line| line.starts_with(sign) && !line.starts_with(&sign.to_string().repeat(3)))
.flat_map(|line| ids_in_line(&crate::hash::strip_aliases(&line[1..])))
.collect()
};
let (removed, added) = (ids_on('-'), ids_on('+'));
let mut pairs = Vec::new();
let mut hunk_minus: Vec<(String, String)> = Vec::new();
let mut hunk_plus: Vec<(String, String)> = Vec::new();
let mut flush = |minus: &mut Vec<(String, String)>, plus: &mut Vec<(String, String)>| {
pairs.extend(pairs_in_hunk(minus, plus));
minus.clear();
plus.clear();
};
for line in diff.lines() {
if line.starts_with("@@") {
flush(&mut hunk_minus, &mut hunk_plus);
continue;
}
if line.starts_with("---") || line.starts_with("+++") {
continue;
}
let sign = match line.chars().next() {
Some(sign @ ('-' | '+')) => sign,
_ => continue,
};
let Some((id, sentence)) = head_in(line[1..].trim()) else {
continue;
};
if sign == '-' {
hunk_minus.push((id, sentence));
} else {
hunk_plus.push((id, sentence));
}
}
flush(&mut hunk_minus, &mut hunk_plus);
pairs.retain(|(old, new)| !added.contains(old) && !removed.contains(new));
pairs
}
fn head_in(line: &str) -> Option<(String, String)> {
let rest = line.trim_start_matches('*').strip_prefix("§ ")?;
let id = ids_in_line(rest).into_iter().next()?;
let opens = rest.starts_with(&format!("<a id=\"{id}\">{id}</a>")) || rest.starts_with(&id);
if !opens || struck_after(rest, &id) {
return None;
}
Some((id.clone(), declare_sentence(line, &id)?))
}
fn struck_after(rest: &str, id: &str) -> bool {
let anchored = format!("<a id=\"{id}\">{id}</a>");
let after = rest
.strip_prefix(&anchored)
.or_else(|| rest.strip_prefix(id));
after.is_some_and(|after| crate::hash::strip_aliases(after).trim().starts_with("~~"))
}
fn pairs_in_hunk(minus: &[(String, String)], plus: &[(String, String)]) -> Vec<(String, String)> {
if minus.len() == 1 && plus.len() == 1 && minus[0].0 != plus[0].0 {
return vec![(minus[0].0.clone(), plus[0].0.clone())];
}
let mut pairs = Vec::new();
for (old, old_sent) in minus {
for (new, new_sent) in plus {
if old != new && old_sent == new_sent && !old_sent.is_empty() {
pairs.push((old.clone(), new.clone()));
}
}
}
pairs
}
fn ids_in_line(line: &str) -> Vec<String> {
ID_RE
.captures_iter(line)
.map(|c| c[1].to_string())
.collect()
}
struct PickaxeHit {
hash: String,
author: String,
date: String,
time: i64,
remint: bool,
}
fn pickaxe_commits(git: &History<'_>, id: &str, verbose: bool) -> Result<Vec<PickaxeHit>> {
let decisions = decisions_paths(git.root)?.join("\n");
let mut entries = Vec::new();
for (pickaxe, paths) in [("-S", "."), ("-G", decisions.as_str())] {
let out = git.read((pickaxe, id, paths), |root| {
let out = crate::workspace::git(root)
.args([
"log",
pickaxe,
id,
"--format=%H\t%an\t%ad\t%at\t%s\t%(trailers:key=Silcrow-Op,valueonly)",
"--date=format:%-d %b %Y",
"--",
])
.args(paths.lines())
.output()?;
if !out.status.success() {
bail!(
"git log {pickaxe} {id} failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
})?;
for line in out.lines() {
if line.is_empty() {
continue;
}
let parts: Vec<_> = line.split('\t').collect();
if parts.len() < 5 {
continue;
}
let op = parts.get(5).copied().unwrap_or("");
let remint = is_scheme_remint(git.root, parts[0], op)?;
if !verbose && remint {
continue;
}
entries.push(PickaxeHit {
hash: parts[0].to_string(),
author: parts[1].to_string(),
date: parts[2].to_string(),
time: parts[3].parse()?,
remint,
});
}
}
entries.sort_by_key(|hit| hit.time);
entries.dedup_by(|a, b| a.hash == b.hash);
Ok(entries)
}
fn decisions_paths(root: &Path) -> Result<Vec<String>> {
let project = crate::walk::Project::at(root)?;
Ok(project
.notes
.roots()
.iter()
.map(|dir| match dir.to_string_lossy().replace('\\', "/") {
dir if dir.is_empty() => ".".to_string(),
dir => dir,
})
.collect())
}
fn git_show_decisions(git: &History<'_>, commit: &str) -> Result<String> {
git.read(("show", commit, ""), |root| {
let project = crate::walk::Project::at(root)?;
let out = crate::workspace::git(root)
.args(["show", "--relative", commit, "-U0", "--"])
.args(decisions_paths(root)?)
.output()?;
if !out.status.success() {
return Ok(String::new());
}
let patch = notes_patch(&project, &String::from_utf8_lossy(&out.stdout));
Ok(parse::plain_heads(&patch))
})
}
fn notes_patch(project: &crate::walk::Project, patch: &str) -> String {
let mut out = String::new();
let mut keep = true;
for line in patch.split_inclusive('\n') {
if let Some(paths) = line.strip_prefix("diff --git ") {
keep = paths
.split_whitespace()
.filter_map(|p| p.strip_prefix("a/").or_else(|| p.strip_prefix("b/")))
.any(|rel| project.is_note(Path::new(rel)));
}
if keep {
out.push_str(line);
}
}
out
}
struct History<'a> {
root: &'a Path,
read: RefCell<HashMap<(String, String, String), String>>,
}
impl<'a> History<'a> {
fn new(root: &'a Path) -> Self {
Self {
root,
read: RefCell::default(),
}
}
fn read(
&self,
(verb, arg, path): (&str, &str, &str),
run: impl FnOnce(&Path) -> Result<String>,
) -> Result<String> {
let key = (verb.to_string(), arg.to_string(), path.to_string());
if let Some(out) = self.read.borrow().get(&key) {
return Ok(out.clone());
}
let out = run(self.root)?;
self.read.borrow_mut().insert(key, out.clone());
Ok(out)
}
}
fn is_scheme_remint(root: &Path, commit: &str, op: &str) -> Result<bool> {
Ok(op.trim().eq_ignore_ascii_case("remint") && moves_only_tokens(root, commit)?)
}
fn ensure_git(root: &Path) -> Result<()> {
let out = crate::workspace::git(root)
.args(["rev-parse", "--is-inside-work-tree"])
.output()?;
if !out.status.success() {
bail!("silcrow log needs a git repository");
}
crate::published::require_history(root)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn pairs_in_diff_finds_accept() {
let diff = "\
--- a/docs/decisions/x.md
+++ b/docs/decisions/x.md
-§ k7m2x9p4a The old sentence.
+§ s4w9k2nab The new sentence.
";
let pairs = pairs_in_diff(diff);
assert!(pairs.contains(&("k7m2x9p4a".into(), "s4w9k2nab".into())));
}
#[test]
fn pairs_in_diff_pairs_remint_by_sentence() {
let diff = "\
--- a/docs/decisions/x.md
+++ b/docs/decisions/x.md
@@ -1,2 +1,2 @@
-§ aaaaaaaa1 Same carrying sentence.
-§ bbbbbbbb2 Other carrying sentence.
+§ cccccccc3 Same carrying sentence.
+§ dddddddd4 Other carrying sentence.
";
let pairs = pairs_in_diff(diff);
assert!(pairs.contains(&("aaaaaaaa1".into(), "cccccccc3".into())));
assert!(pairs.contains(&("bbbbbbbb2".into(), "dddddddd4".into())));
assert!(!pairs.contains(&("aaaaaaaa1".into(), "dddddddd4".into())));
}
#[test]
fn only_a_head_that_leaves_for_another_is_a_rename() {
let cite = "\
@@ -3 +3 @@
-See [aaaaaaaa1](x.md#aaaaaaaa1).
+See [cccccccc3](x.md#cccccccc3).
";
assert!(pairs_in_diff(cite).is_empty());
let successor = "\
@@ -1 +1,3 @@
-**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> The graph fails open.**
+**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> ~~The graph fails open.~~**
+**§ <a id=\"cccccccc3\">cccccccc3</a> The graph fails closed.**
";
assert!(pairs_in_diff(successor).is_empty());
let accept = "\
@@ -1 +1 @@
-**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> The graph fail open.**
+**§ <a id=\"cccccccc3\">cccccccc3</a><a id=\"aaaaaaaa1\"></a> The graph fails open.**
";
assert_eq!(
pairs_in_diff(accept),
vec![("aaaaaaaa1".to_string(), "cccccccc3".to_string())]
);
}
#[test]
fn remint_mark_is_the_trailer_not_the_subject() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let init = crate::test_git()
.args(["init", "-q", "--template="])
.current_dir(root)
.status()
.unwrap();
assert!(init.success());
std::fs::write(root.join("a.rs"), "// § abcdefgh1@aaaaa\nfn f() {}\n").unwrap();
commit_all(root, 1, "pin");
std::fs::write(root.join("a.rs"), "// § abcdefgh1@bbbbb\nfn f() {}\n").unwrap();
commit_all(root, 2, "scheme remint of digests");
assert!(!is_scheme_remint(root, "HEAD", "").unwrap());
assert!(is_scheme_remint(root, "HEAD", "remint").unwrap());
assert!(!is_scheme_remint(root, "HEAD^", "remint").unwrap());
}
#[test]
fn declare_sentence_strips_marker() {
let s = declare_sentence("§ k7m2x9p4a The graph fails open.", "k7m2x9p4a").unwrap();
assert_eq!(s, "The graph fails open.");
}
#[test]
fn remint_step_is_not_accept() {
let diff = "\
--- a/docs/decisions/x.md
+++ b/docs/decisions/x.md
@@ -1 +1 @@
-§ aaaaaaaa1 Same carrying sentence.
+§ cccccccc3 Same carrying sentence.
";
let family = BTreeSet::from(["aaaaaaaa1".into(), "cccccccc3".into()]);
let remint = remint_step_from_diff(diff, &family, "Ada", "6 Sep 2026").unwrap();
assert_eq!(remint.kind, StepKind::Remint);
assert_eq!(remint.id, "cccccccc3");
let force = step_from_diff(diff, &family, "Ada", "6 Sep 2026").unwrap();
assert_eq!(force.kind, StepKind::Accept);
}
#[test]
fn accept_step_is_not_a_remint() {
let diff = "\
--- a/docs/decisions/x.md
+++ b/docs/decisions/x.md
-§ aaaaaaaa1 The graph fails open.
+§ cccccccc3 The graph fails closed.
";
let family = BTreeSet::from(["aaaaaaaa1".into(), "cccccccc3".into()]);
let step = step_from_diff(diff, &family, "Ada", "6 Sep 2026").unwrap();
assert_eq!(step.kind, StepKind::Accept);
assert_eq!(step.id, "cccccccc3");
}
#[test]
fn a_step_prints_the_old_and_new_sentence_in_full() {
let old = "Le système doit bloqué les accès hors des heures ouvrées, sauf pour les comptes de service.";
let new = "Le système doit bloquer les accès hors des heures ouvrées, sauf pour les comptes de service.";
let diff = format!(
"--- a/docs/decisions/x.md\n+++ b/docs/decisions/x.md\n@@ -1 +1 @@\n\
-**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> {old}**\n\
+**§ <a id=\"cccccccc3\">cccccccc3</a><a id=\"aaaaaaaa1\"></a> {new}**\n"
);
let family = BTreeSet::from(["aaaaaaaa1".into(), "cccccccc3".into()]);
let step = step_from_diff(&diff, &family, "Alice", "2 Sep 2026").unwrap();
assert_eq!(step.kind, StepKind::Accept);
assert_eq!(
render_step(&step),
format!("[cccccccc3] accept, Alice, 2 Sep 2026\n - {old}\n + {new}\n")
);
}
#[test]
fn a_declaration_prints_only_the_new_sentence() {
let diff = "--- a/docs/decisions/x.md\n+++ b/docs/decisions/x.md\n@@ -0,0 +1 @@\n\
+**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> The graph fails closed.**\n";
let family = BTreeSet::from(["aaaaaaaa1".into()]);
let step = step_from_diff(diff, &family, "Bob", "14 May 2026").unwrap();
assert_eq!(
render_step(&step),
"[aaaaaaaa1] declare, Bob, 14 May 2026\n + The graph fails closed.\n"
);
}
#[test]
fn can_trace_finds_id_after_commit() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let init = crate::test_git()
.args(["init", "-q", "--template="])
.current_dir(root)
.status()
.unwrap();
assert!(init.success());
std::fs::create_dir_all(root.join("docs/decisions")).unwrap();
std::fs::write(
root.join("docs/decisions/x.md"),
"**§ k7m2x9p4a The graph fails open.**\n",
)
.unwrap();
commit_all(root, 1, "declare");
assert!(can_trace(root, "k7m2x9p4a").unwrap());
assert!(!can_trace(root, &unhistoried_id()).unwrap());
}
#[test]
fn the_walk_reads_the_docs_base_and_code_outside_src() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let id = "abcdefgh1";
crate::meta::tests::notes_tree(root, id);
assert!(can_trace(root, id).unwrap());
let steps = collect_steps(
&History::new(root),
&BTreeSet::from([id.to_string()]),
false,
)
.unwrap();
let kinds: Vec<_> = steps.iter().map(|s| s.kind).collect();
assert_eq!(kinds, [StepKind::Declare]);
}
#[test]
fn a_strike_is_a_retire_step() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let id = "abcdefgh1";
crate::meta::tests::notes_tree(root, id);
let note = root.join(crate::meta::tests::NOTE);
let sentence = crate::meta::tests::SENTENCE;
let text = std::fs::read_to_string(¬e).unwrap();
std::fs::write(¬e, text.replace(sentence, &format!("~~{sentence}~~"))).unwrap();
crate::meta::tests::commit(root, "2026-01-14T12:00:00Z", "strike");
let steps = collect_steps(
&History::new(root),
&BTreeSet::from([id.to_string()]),
false,
)
.unwrap();
let rendered: String = steps.iter().map(render_step).collect();
assert_eq!(
rendered,
format!(
"[{id}] retire, t, 14 Jan 2026\n - {sentence}\n[{id}] declare, t, 2 Jan 2026\n + {sentence}\n"
)
);
}
#[test]
fn genealogy_check_flags_missing_history() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let id = unhistoried_id();
let ids = vec![id.clone()];
let existed = BTreeSet::from([id.clone()]);
let (errors, warnings) = genealogy_check(&root, &ids, &existed);
assert!(warnings.is_empty());
assert_eq!(errors.len(), 1);
assert!(errors[0].contains(&id));
}
#[test]
fn genealogy_check_skips_new_laws() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let ids = vec![unhistoried_id()];
let (errors, warnings) = genealogy_check(&root, &ids, &BTreeSet::new());
assert!(errors.is_empty());
assert!(warnings.is_empty());
}
fn commit_all(dir: &Path, day: u32, msg: &str) {
let date = format!("2026-01-{day:02}T12:00:00Z");
for args in [
vec!["add", "-A"],
vec!["commit", "-q", "--no-verify", "-m", msg],
] {
let out = crate::test_git()
.args([
"-c",
"commit.gpgsign=false",
"-c",
"core.hooksPath=/dev/null",
])
.args(&args)
.env("GIT_AUTHOR_NAME", "Ada")
.env("GIT_AUTHOR_EMAIL", "a@a")
.env("GIT_COMMITTER_NAME", "Ada")
.env("GIT_COMMITTER_EMAIL", "a@a")
.env("GIT_AUTHOR_DATE", &date)
.env("GIT_COMMITTER_DATE", &date)
.current_dir(dir)
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
}
}
#[test]
fn a_digest_change_is_a_repin_unless_the_scheme_changed() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let init = crate::test_git()
.args(["init", "-q", "--template="])
.current_dir(root)
.status()
.unwrap();
assert!(init.success());
std::fs::create_dir_all(root.join("src")).unwrap();
let write = |law: &str, a: &str, extra: &str| {
std::fs::write(
root.join("src/lib.rs"),
format!(
"fn run() {{\n // § abcdefgh1@{law}\n // § abcdefgh1.a@{a}\n{extra} // § zyxwvtsr1@{a}\n}}\n"
),
)
.unwrap();
};
write("bbbbb", "aaaaa", "");
commit_all(root, 1, "pin\n\nSilcrow-Scheme: 4");
write("bbbbb", "ccccc", "");
commit_all(root, 2, "re-pin a letter");
write("eeeee", "fffff", "");
commit_all(root, 3, "scheme\n\nSilcrow-Op: remint\nSilcrow-Scheme: 5");
write("ggggg", "fffff", "");
commit_all(root, 4, "re-pin the law\n\nSilcrow-Scheme: 5");
write("hhhhh", "fffff", "");
commit_all(root, 5, "scheme\n\nSilcrow-Scheme: 6");
write("hhhhh", "fffff", " // § abcdefgh1.b@ddddd\n");
commit_all(root, 6, "first pin of a new letter");
write("iiiii", "fffff", " // § abcdefgh1.b@ddddd\n go();\n");
commit_all(root, 7, "code\n\nSilcrow-Op: remint\nSilcrow-Scheme: 7");
let family = BTreeSet::from(["abcdefgh1".to_string()]);
let (repins, remints) = digest_changes(root, &family).unwrap();
let seen: Vec<_> = repins
.iter()
.map(|r| (r.date.as_str(), r.addresses.join(",")))
.collect();
assert_eq!(
seen,
vec![
("2 Jan 2026", "abcdefgh1.a".to_string()),
("4 Jan 2026", "abcdefgh1".to_string()),
("7 Jan 2026", "abcdefgh1".to_string())
]
);
assert_eq!(remints.len(), 2);
let counts = rewrite_counts(root, "abcdefgh1").unwrap();
assert_eq!((counts.remints, counts.repins.len()), (2, 3));
let line = render_repin(&repins[0]);
assert!(
line.starts_with(&format!(
" re-pin {} Ada, 2 Jan 2026 abcdefgh1.a",
repins[0].sha
)),
"{line}"
);
assert_eq!(repins[0].sha.len(), 7);
}
#[test]
fn a_repin_counts_only_a_line_its_file_reads_as_a_marker() {
let patch = "\ndiff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -3 +3 @@\n-// § abcdefgh1.a@aaaaa\n+// § abcdefgh1.a@bbbbb\ndiff --git a/q.sql b/q.sql\n--- a/q.sql\n+++ b/q.sql\n@@ -1 +1 @@\n--- § abcdefgh1.b@ccccc\n+-- § abcdefgh1.b@ddddd\n";
let files = |new: bool, path: &str| -> Result<String> {
Ok(match (path, new) {
("src/lib.rs", false) => "fn f() {\n r\"\n// § abcdefgh1.a@aaaaa\n\";\n}\n",
("src/lib.rs", true) => "fn f() {\n r\"\n// § abcdefgh1.a@bbbbb\n\";\n}\n",
("q.sql", false) => "-- § abcdefgh1.b@ccccc\nselect 1;\n",
("q.sql", true) => "-- § abcdefgh1.b@ddddd\nselect 1;\n",
_ => unreachable!("{path}"),
}
.to_string())
};
assert_eq!(
repinned_addresses(patch, "abcdefgh1", &files).unwrap(),
vec!["abcdefgh1.b"]
);
}
fn unhistoried_id() -> String {
"vv3".repeat(3)
}
}