use anyhow::{bail, Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use crate::follow::FollowIndex;
use crate::list_tty;
use crate::marker;
use crate::parse::{self, PointerKind, Scan, Target};
use crate::policy::TestPaths;
use crate::span;
use crate::span_lang;
use crate::walk;
mod review;
mod structure;
mod ungoverned;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Form {
Json,
Markdown,
Tty,
}
impl Form {
pub fn chosen(json: bool, markdown: bool) -> Self {
match (json, markdown) {
(true, _) => Form::Json,
(_, true) => Form::Markdown,
_ => Form::Tty,
}
}
}
pub fn run(
ws: &crate::workspace::Workspace,
projects: &[&crate::workspace::ProjectRef],
all: bool,
rev: Option<String>,
laws: &[String],
verbose: bool,
form: Form,
) -> Result<()> {
let history = (form == Form::Json).then(|| crate::meta::History::start(&ws.root));
let review = gather(ws, projects, all, rev, laws, verbose)?;
match (form, history) {
(_, Some(history)) => {
let ids: Vec<&str> = review.rules.iter().map(|rule| local_id(&rule.id)).collect();
print!("{}", review::review_json(&review, &history.declared(&ids)));
Ok(())
}
(Form::Tty, None) if !review.holds_nothing() => {
emit_diff_stream(&review::review_tty(&review))
}
_ => {
print!("{}", review::review_markdown(&review));
Ok(())
}
}
}
pub fn packet(
ws: &crate::workspace::Workspace,
projects: &[&crate::workspace::ProjectRef],
base: &str,
) -> Result<(String, bool, String)> {
let review = gather(ws, projects, true, Some(base.to_string()), &[], false)?;
let holds = !review.rules.is_empty() || !review.block.is_empty();
Ok((
review::review_markdown(&review),
holds,
review::shared_summary(&review),
))
}
fn gather(
ws: &crate::workspace::Workspace,
projects: &[&crate::workspace::ProjectRef],
all: bool,
rev: Option<String>,
laws: &[String],
verbose: bool,
) -> Result<review::Review> {
let Some(first) = projects.first() else {
bail!("silcrow diff found no project to read");
};
let base_ref = resolve_base(ws, &first.dir, rev)?;
let mut pieces = Vec::new();
for project in projects {
pieces.push(project_piece(ws, project, &base_ref, laws, verbose)?);
}
let declared: BTreeSet<&String> = pieces.iter().flat_map(|piece| &piece.declared).collect();
let unknown: Vec<&String> = laws.iter().filter(|law| !declared.contains(law)).collect();
if !unknown.is_empty() {
let names: Vec<String> = unknown.iter().map(|law| format!("`{law}`")).collect();
bail!(
"--law {} names no law or clause that either side of the comparison against {base_ref} declares",
names.join(", ")
);
}
if !all {
let unread: BTreeSet<&String> = pieces.iter().flat_map(|piece| &piece.unread).collect();
if !unread.is_empty() {
let names: Vec<String> = unread.iter().map(|key| format!("`{key}`")).collect();
eprintln!(
"Nested project(s) {} differ from {base_ref} and this diff does not read them. Run `silcrow diff --all` to read every project.",
names.join(", ")
);
}
}
let folded: usize = pieces.iter().map(|piece| piece.folded).sum();
let block: Vec<BlockRow> = pieces
.iter()
.flat_map(|piece| {
piece.block.iter().map(|(attr, old, new)| BlockRow {
path: format!("{}AGENTS.md", piece.shown),
attr,
old: old.clone(),
new: new.clone(),
})
})
.collect();
let mut rules = Vec::new();
let mut ungoverned = Vec::new();
for mut piece in pieces {
ungoverned.append(&mut piece.ungoverned);
if piece.changes.is_empty() {
continue;
}
let root = piece.root.as_path();
let new_rev = diff_ends(root, &base_ref)?.new_rev;
let stable = collect_stable_markers(root, new_rev.as_deref(), &piece.changes)?;
piece.changes.extend(stable);
piece.changes.sort();
piece.changes.dedup();
fill_file_map(root, new_rev.as_deref(), &piece.changes, &mut piece.files);
let follow = match piece.follow {
Some(follow) => follow,
None => new_side_follow(root, &base_ref)?,
};
let callers = drift_callers(&piece.changes, &follow);
let docs = crate::walk::Project::at(root)?.docs;
let shown = Shown {
prefix: &piece.shown,
key: &piece.key,
docs: &docs,
};
rules.extend(review::law_entries(
&piece.changes,
&piece.files,
&follow,
&callers,
&shown,
));
}
Ok(review::Review::gather(
base_ref,
laws.to_vec(),
folded,
block,
rules,
ungoverned,
))
}
struct BlockRow {
path: String,
attr: &'static str,
old: Option<String>,
new: Option<String>,
}
const BLOCK_HEADING: &str = "Silcrow block changed";
struct Piece {
root: PathBuf,
changes: Vec<Change>,
folded: usize,
files: FileMap,
follow: Option<FollowIndex>,
shown: String,
key: Option<String>,
unread: BTreeSet<String>,
block: Vec<(&'static str, Option<String>, Option<String>)>,
ungoverned: Vec<ungoverned::FileHunks>,
declared: BTreeSet<String>,
}
fn project_piece(
ws: &crate::workspace::Workspace,
project: &crate::workspace::ProjectRef,
base_ref: &str,
laws: &[String],
verbose: bool,
) -> Result<Piece> {
let root = project.dir.as_path();
let key = (project.key != ".").then(|| project.key.clone());
let kept = |change: &Change| {
let address = qualify(&key, &change.address);
laws.is_empty()
|| laws.iter().any(|want| {
keep_address(&address, want)
|| (change.kind == Kind::Reminted && split_address(want).0 == address)
})
};
let paths = changed_paths(root, base_ref)?;
let (old, new, markers, files) = scan_sides(ws, root, base_ref, &paths)?;
let declared: BTreeSet<String> = [&old, &new]
.into_iter()
.flat_map(|scan| &scan.laws)
.flat_map(|law| {
let letters = law.clauses.iter().filter_map(|c| c.letter.as_ref());
std::iter::once(law.id.clone()).chain(letters.map(|l| format!("{}.{l}", law.id)))
})
.map(|address| qualify(&key, &address))
.collect();
let mut changes = collect_law_changes(&old, &new);
changes.extend(collect_deleted(&old, &new));
changes.extend(collect_pointer_changes(&old, &new));
changes.extend(markers);
changes.retain(|change| kept(change));
changes.sort();
changes.dedup();
let (folded, sides);
(changes, folded, sides) = sort_markers(ws, root, base_ref, changes, &files, verbose)?;
let marked: BTreeSet<String> = changes
.iter()
.flat_map(|change| [change.address.clone(), split_address(&change.address).0])
.collect();
let recalled = recalls(&new, &marked, &changes);
changes.extend(recalled);
changes.retain(|change| kept(change));
changes.sort();
changes.dedup();
let ends = diff_ends(root, base_ref)?;
let block = match laws.is_empty() {
false => Vec::new(),
true => {
let old = crate::published::agents_at(root, &ends.old_rev)?;
let new = match &ends.new_rev {
Some(rev) => crate::published::agents_at(root, rev)?,
None => read_worktree(root, Path::new("AGENTS.md")),
};
crate::published::block_changes(old.as_deref(), new.as_deref())
}
};
let owners = Owners::read(ws, root, &ends)?;
let unread = nested_touched(project, &paths, &owners);
let shown = shown_prefix(ws, root);
let ungoverned = match laws.is_empty() {
false => Vec::new(),
true => {
let renamed: BTreeMap<String, String> = paths
.iter()
.filter(|t| t.old != t.new)
.map(|t| (path_of(&t.old), path_of(&t.new)))
.collect();
let notes = [
ungoverned::note_lines(&old, &renamed),
ungoverned::note_lines(&new, &BTreeMap::new()),
];
let governed = ungoverned::governed(&files, sides.as_ref(), notes, &renamed);
let held: BTreeSet<String> = paths
.iter()
.filter(|t| {
owners.of(&t.old, false) != Owner::Other
|| owners.of(&t.new, true) != Owner::Other
})
.map(|t| path_of(&t.new))
.collect();
let mut hunks = ungoverned::ungoverned(
root,
base_ref,
ends.new_rev.is_none(),
|file| held.contains(&file.path),
&governed,
)?;
for file in &mut hunks {
for path in [&mut file.old_path, &mut file.new_path]
.into_iter()
.flatten()
{
*path = format!("{shown}{path}");
}
file.path = format!("{shown}{}", file.path);
}
hunks
}
};
Ok(Piece {
root: root.to_path_buf(),
changes,
folded: folded.len(),
files,
follow: sides.map(|[_, new]| new.follow),
shown,
key,
unread,
block,
ungoverned,
declared,
})
}
fn nested_touched(
project: &crate::workspace::ProjectRef,
paths: &[Touched],
owners: &Owners,
) -> BTreeSet<String> {
paths
.iter()
.flat_map(|touched| {
[
owners.other_of(&touched.old, false),
owners.other_of(&touched.new, true),
]
})
.flatten()
.map(|dir| path_of(&crate::workspace::in_workspace(&project.key, &dir)))
.collect()
}
fn qualify(key: &Option<String>, address: &str) -> String {
match (address.split_once(':'), key) {
(Some((".", local)), _) => local.to_string(),
(Some(_), _) | (None, None) => address.to_string(),
(None, Some(key)) => format!("{key}:{address}"),
}
}
fn shown_prefix(ws: &crate::workspace::Workspace, root: &Path) -> String {
match root.strip_prefix(&ws.root) {
Ok(rel) if !rel.as_os_str().is_empty() => format!("{}/", path_of(rel)),
_ => String::new(),
}
}
pub fn folded_pins(
ws: &crate::workspace::Workspace,
root: &Path,
base: &str,
) -> Result<BTreeMap<(PathBuf, usize), String>> {
let paths = changed_paths(root, base)?;
let (_, _, markers, files) = scan_sides(ws, root, base, &paths)?;
let (_, folded, _) = sort_markers(ws, root, base, markers, &files, false)?;
let mut out = BTreeMap::new();
for change in folded {
let (Some(path), Some(line), Some(old)) =
(change.new_path, change.lines[1], change.old_text.as_deref())
else {
continue;
};
let digest = crate::marker::entry_for(old, &change.address).and_then(|pin| pin.digest);
if let Some(digest) = digest {
out.insert((PathBuf::from(path), line), digest);
}
}
Ok(out)
}
fn remint_line(pinned: usize) -> String {
format!(" scheme span digest remint ({pinned} pinned markers)")
}
fn nest_changes(changes: &[Change]) -> BTreeMap<String, NestedLaw> {
let mut laws: BTreeMap<String, NestedLaw> = BTreeMap::new();
for change in changes {
let (id, letter) = split_address(&change.address);
let law = laws.entry(id).or_default();
match (change.kind, letter) {
(Kind::Marker | Kind::Drift | Kind::Accepted, Some(letter)) => {
law.clauses
.entry(letter)
.or_default()
.markers
.push(change.clone());
}
(Kind::Marker | Kind::Drift | Kind::Accepted, None) => law.markers.push(change.clone()),
(_, Some(letter)) => {
law.clauses
.entry(letter)
.or_default()
.changes
.push(change.clone());
}
(_, None) => law.changes.push(change.clone()),
}
}
laws
}
fn collect_stable_markers(
root: &Path,
new_rev: Option<&str>,
changes: &[Change],
) -> Result<Vec<Change>> {
let addresses: BTreeSet<String> = changes
.iter()
.filter(|c| c.kind != Kind::Recall)
.map(|c| c.address.clone())
.collect();
if addresses.is_empty() {
return Ok(Vec::new());
}
let mut out = Vec::new();
let rels = new_side_paths(root, new_rev)?;
for (rel, text) in rels.iter().zip(read_new_sides(root, new_rev, &rels)) {
let rel_s = path_of(rel);
let Some(text) = text else {
continue;
};
for row in span::marker_rows(rel, &text, None) {
for marker in row.markers {
let addr = marker.display();
if !addresses.contains(&addr) || marker_listed(changes, &addr, &rel_s) {
continue;
}
let bit = row.line.trim().to_string();
out.push(Change {
address: addr,
kind: Kind::Marker,
old_path: Some(rel_s.clone()),
new_path: Some(rel_s.clone()),
old_text: Some(bit.clone()),
new_text: Some(bit),
callees: Vec::new(),
lines: [None, None],
why: None,
});
}
}
}
Ok(out)
}
fn new_side_follow(root: &Path, base_ref: &str) -> Result<FollowIndex> {
let new_rev = diff_ends(root, base_ref)?.new_rev;
let sources = side_sources(&new_side_paths(root, new_rev.as_deref())?, |rels| {
read_new_sides(root, new_rev.as_deref(), rels)
});
Ok(FollowIndex::from_sources(
&sources,
&crate::policy::TestPaths::at(root)?,
))
}
fn side_sources(
paths: &[PathBuf],
read: impl Fn(&[PathBuf]) -> Vec<Option<String>>,
) -> Vec<(PathBuf, String)> {
let rels: Vec<PathBuf> = paths
.iter()
.filter(|rel| crate::follow::reads_path(rel))
.cloned()
.collect();
let texts = read(&rels);
rels.into_iter()
.zip(texts)
.filter_map(|(rel, text)| Some((rel, text?)))
.collect()
}
fn new_side_paths(root: &Path, new_rev: Option<&str>) -> Result<Vec<PathBuf>> {
let Some(rev) = new_rev else {
return Ok(walk::code_files(root)?
.iter()
.map(|path| path.strip_prefix(root).unwrap_or(path).to_path_buf())
.collect());
};
let project = walk::Project::at(root)?;
let listed = git_lines(root, &["ls-tree", "-r", "--name-only", rev, "--", "."])?;
Ok(listed
.into_iter()
.filter(|rel| walk::walks_to(&project, rel))
.collect())
}
fn fill_file_map(root: &Path, new_rev: Option<&str>, changes: &[Change], files: &mut FileMap) {
let missing: BTreeSet<&String> = changes
.iter()
.filter(|change| change.is_marker())
.flat_map(|change| [&change.old_path, &change.new_path].into_iter().flatten())
.filter(|path| !files.contains_key(*path))
.collect();
let rels: Vec<PathBuf> = missing
.iter()
.map(|path| PathBuf::from(path.as_str()))
.collect();
for (path, text) in missing
.into_iter()
.zip(read_new_sides(root, new_rev, &rels))
{
files.insert(path.clone(), (text.clone(), text));
}
}
fn marker_listed(changes: &[Change], address: &str, path: &str) -> bool {
changes.iter().any(|change| {
change.is_marker()
&& change.address == address
&& (change.new_path.as_deref() == Some(path)
|| change.old_path.as_deref() == Some(path))
})
}
type Callers = BTreeMap<(String, usize), Vec<String>>;
fn drift_callers(changes: &[Change], follow: &FollowIndex) -> Callers {
changes
.iter()
.filter(|c| matches!(c.kind, Kind::Drift | Kind::Accepted))
.filter_map(|c| Some((c.new_path.as_deref()?, c.lines[1]?)))
.filter_map(|(path, line)| {
let callers = follow.caller_laws(Path::new(path), line);
(!callers.is_empty()).then(|| ((path.to_string(), line), callers))
})
.collect()
}
fn lost_pin(change: &Change) -> bool {
let pinned = |text: &Option<String>| text.as_deref().is_some_and(|t| t.lines().any(is_pinned));
pinned(&change.old_text) && !pinned(&change.new_text)
}
#[derive(Default)]
struct NestedLaw {
changes: Vec<Change>,
clauses: BTreeMap<String, NestedClause>,
markers: Vec<Change>,
}
#[derive(Default)]
struct NestedClause {
changes: Vec<Change>,
markers: Vec<Change>,
}
fn local_id(id: &str) -> &str {
id.rsplit_once(':').map_or(id, |(_, local)| local)
}
fn split_address(address: &str) -> (String, Option<String>) {
let local = address.rfind(':').map_or(0, |at| at + 1);
match address[local..].split_once('.') {
Some((id, letter)) => (
format!("{}{id}", &address[..local]),
Some(letter.to_string()),
),
None => (address.to_string(), None),
}
}
fn json_escape(value: &str) -> String {
serde_json::Value::from(value).to_string()
}
pub fn range_end(rev: Option<&str>) -> Option<String> {
let rev = rev?;
let at = rev
.find("...")
.map(|at| at + 3)
.or(rev.find("..").map(|at| at + 2))?;
Some(match rev[at..].trim() {
"" => "HEAD".to_string(),
end => end.to_string(),
})
}
pub fn revision(revs: &[String]) -> Result<Option<String>> {
match revs {
[] => Ok(None),
[rev] => Ok(Some(rev.clone())),
[a, b] if a.contains("..") || b.contains("..") => {
bail!("silcrow diff takes one range or two revisions, not `{a}` and `{b}`")
}
[a, b] => Ok(Some(format!("{a}..{b}"))),
_ => bail!("silcrow diff takes at most two revisions"),
}
}
pub fn refuse_unresolved(root: &Path, rev: Option<&str>) -> Result<()> {
if !git_ok(root, &["rev-parse", "--is-inside-work-tree"]) {
return Ok(());
}
for end in rev.into_iter().flat_map(|r| r.split("..")) {
let end = end.trim_start_matches('.');
let commit = format!("{end}^{{commit}}");
if end.is_empty() || git_ok(root, &["rev-parse", "--verify", "--quiet", &commit]) {
continue;
}
let id = end.split_once('.').map_or(end, |(id, _)| id);
if crate::hash::is_crockford_id(id) {
bail!(
"`{end}` names no revision, and reads as a law address: run `silcrow diff --law {end}` to keep one law or clause"
);
}
let out = crate::workspace::git(root)
.args(["log", "-1", "--format=", end, "--"])
.output()
.context("git log")?;
bail!(
"{}\n`silcrow diff` takes revisions as `git diff` does: none, `<rev>`, `<a> <b>`, `<a>..<b>` or `<a>...<b>`.",
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(())
}
fn keep_address(address: &str, want: &str) -> bool {
if address == want {
return true;
}
if want.contains('.') {
return false;
}
split_address(address).0 == want
}
fn resolve_base(
ws: &crate::workspace::Workspace,
root: &Path,
explicit: Option<String>,
) -> Result<String> {
if let Some(r) = explicit {
ensure_git(root)?;
return Ok(r);
}
ensure_git(root)?;
Ok(ws.base_ref("HEAD")?.unwrap_or_else(|| "HEAD".to_string()))
}
fn ensure_git(root: &Path) -> Result<()> {
if !git_ok(root, &["rev-parse", "--is-inside-work-tree"]) {
bail!("silcrow diff needs a git repository");
}
crate::published::require_history(root)
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Touched {
old: PathBuf,
new: PathBuf,
}
fn changed_paths(root: &Path, base: &str) -> Result<Vec<Touched>> {
let status = git_stdout(
root,
&[
"diff",
"--relative",
"--name-status",
"--find-renames",
"--diff-filter=ACDMR",
base,
],
)?;
let mut paths = Vec::new();
for line in status.lines().filter(|l| !l.is_empty()) {
let fields: Vec<&str> = line.split('\t').collect();
match fields[..] {
[kind, old, new] if kind.starts_with('R') || kind.starts_with('C') => {
paths.push(Touched {
old: PathBuf::from(old),
new: PathBuf::from(new),
})
}
[_, path] => paths.push(Touched {
old: PathBuf::from(path),
new: PathBuf::from(path),
}),
_ => bail!("git diff --name-status: malformed line {line:?}"),
}
}
for path in git_lines(root, &["ls-files", "--others", "--exclude-standard"])? {
paths.push(Touched {
old: path.clone(),
new: path,
});
}
paths.sort();
paths.dedup();
Ok(paths)
}
pub fn touched(root: &Path, base: &str) -> Result<BTreeMap<PathBuf, PathBuf>> {
Ok(changed_paths(root, base)?
.into_iter()
.map(|touched| (touched.old, touched.new))
.collect())
}
type FileMap = BTreeMap<String, (Option<String>, Option<String>)>;
struct Owners {
old: Vec<PathBuf>,
new: Vec<PathBuf>,
own_key: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Owner {
Own,
Vanished(PathBuf, String),
Other,
}
impl Owners {
fn read(ws: &crate::workspace::Workspace, root: &Path, ends: &DiffEnds) -> Result<Self> {
let old = crate::published::projects_at(root, &ends.old_rev)?;
let new = match &ends.new_rev {
Some(rev) => crate::published::projects_at(root, rev)?,
None => ws
.projects
.iter()
.filter_map(|project| project.dir.strip_prefix(root).ok())
.filter(|rel| !rel.as_os_str().is_empty())
.map(Path::to_path_buf)
.collect(),
};
let own_key = ws
.projects
.iter()
.find(|project| project.dir == root)
.map(|project| project.key.clone())
.with_context(|| format!("{} is no project of the workspace", root.display()))?;
Ok(Self { old, new, own_key })
}
fn of(&self, rel: &Path, new: bool) -> Owner {
let nested = if new { &self.new } else { &self.old };
let deepest = nested
.iter()
.filter(|dir| rel.starts_with(dir))
.max_by_key(|dir| dir.components().count());
match deepest {
None => Owner::Own,
Some(dir) if new || self.new.contains(dir) => Owner::Other,
Some(dir) => {
let key = crate::workspace::in_workspace(&self.own_key, dir);
Owner::Vanished(dir.clone(), path_of(&key))
}
}
}
fn other_of(&self, rel: &Path, new: bool) -> Option<PathBuf> {
let nested = if new { &self.new } else { &self.old };
match self.of(rel, new) {
Owner::Other => nested
.iter()
.filter(|dir| rel.starts_with(dir))
.max_by_key(|dir| dir.components().count())
.cloned(),
_ => None,
}
}
fn vanished(&self) -> Vec<PathBuf> {
self.old
.iter()
.filter(|dir| {
!dir.ancestors()
.any(|up| self.new.iter().any(|kept| kept == up))
})
.cloned()
.collect()
}
}
fn side_notes(root: &Path, rev: Option<&str>, dir: &Path) -> Result<Vec<(PathBuf, String)>> {
let read = |rels: &[PathBuf]| match rev {
Some(rev) => git_show_all(root, rev, rels),
None => rels.iter().map(|rel| read_worktree(root, rel)).collect(),
};
let agents = read(&[dir.join("AGENTS.md")]).pop().flatten();
let notes = match rev {
Some(_) => walk::Notes::at_commit(agents.as_deref()),
None => walk::Notes::from_agents(agents.as_deref()),
}
.map_err(|e| anyhow::anyhow!("{}: {e}", dir.join("AGENTS.md").display()))?;
let dir: PathBuf = dir
.components()
.filter(|c| !matches!(c, std::path::Component::CurDir))
.collect();
let listed: Vec<PathBuf> = match rev {
Some(rev) => {
let spec = if dir.as_os_str().is_empty() {
".".to_string()
} else {
path_of(&dir)
};
let listed = git_lines(root, &["ls-tree", "-r", "--name-only", rev, "--", &spec])?;
let own = dir.join("AGENTS.md");
let agents: Vec<PathBuf> = listed
.iter()
.filter(|rel| rel.file_name().is_some_and(|n| n == "AGENTS.md") && **rel != own)
.cloned()
.collect();
let nested: Vec<PathBuf> = agents
.iter()
.zip(read(&agents))
.filter(|(_, text)| text.as_deref().is_some_and(crate::scheme::has_block))
.filter_map(|(rel, _)| rel.parent().map(Path::to_path_buf))
.collect();
listed
.into_iter()
.filter(|rel| !nested.iter().any(|n| rel.starts_with(n)))
.collect()
}
None => walk::decision_files(&root.join(&dir))?
.into_iter()
.map(|path| path.strip_prefix(root).unwrap_or(&path).to_path_buf())
.collect(),
};
let rels: Vec<PathBuf> = listed
.into_iter()
.filter(|rel| rel.strip_prefix(&dir).is_ok_and(|rel| notes.holds(rel)))
.collect();
let texts = read(&rels);
Ok(rels
.into_iter()
.zip(texts)
.filter_map(|(rel, text)| Some((rel, text?)))
.collect())
}
fn scan_owned(
notes: &[(PathBuf, String)],
owner: &Owner,
owner_of: impl Fn(&Path) -> Owner,
) -> Scan {
let mut scan = Scan::default();
for (rel, text) in notes.iter().filter(|(rel, _)| owner_of(rel) == *owner) {
merge_scan(&mut scan, parse::scan_text(rel, text));
}
if let Owner::Vanished(_, key) = owner {
for law in &mut scan.laws {
law.id = format!("{key}:{}", law.id);
for alias in &mut law.aliases {
*alias = format!("{key}:{alias}");
}
}
for ptr in &mut scan.pointers {
ptr.project.get_or_insert_with(|| key.clone());
}
}
scan
}
fn scan_sides(
ws: &crate::workspace::Workspace,
root: &Path,
base: &str,
paths: &[Touched],
) -> Result<(Scan, Scan, Vec<Change>, FileMap)> {
let ends = diff_ends(root, base)?;
let owners = Owners::read(ws, root, &ends)?;
let mut old = Scan::default();
let mut new = Scan::default();
let mut old_notes = BTreeSet::new();
let mut new_notes = BTreeSet::new();
let mut read_side = |rev: Option<&str>, dir: &Path, owner: Owner, is_new: bool| -> Result<()> {
let notes = side_notes(root, rev, dir)?;
let scan = scan_owned(¬es, &owner, |rel| owners.of(rel, is_new));
let (into, seen) = if is_new {
(&mut new, &mut new_notes)
} else {
(&mut old, &mut old_notes)
};
seen.extend(notes.into_iter().map(|(rel, _)| rel));
merge_scan(into, scan);
Ok(())
};
read_side(Some(&ends.old_rev), Path::new(""), Owner::Own, false)?;
for dir in owners.vanished() {
let owner = owners.of(&dir.join("AGENTS.md"), false);
read_side(Some(&ends.old_rev), &dir, owner, false)?;
}
read_side(ends.new_rev.as_deref(), Path::new(""), Owner::Own, true)?;
let remint = reminted(&old, &new);
let mut marker_changes = Vec::new();
let mut files = FileMap::new();
let old_paths: Vec<PathBuf> = paths.iter().map(|touched| touched.old.clone()).collect();
let new_paths: Vec<PathBuf> = paths.iter().map(|touched| touched.new.clone()).collect();
let olds = git_show_all(root, &ends.old_rev, &old_paths);
let news = read_new_sides(root, ends.new_rev.as_deref(), &new_paths);
for ((touched, old_text), new_text) in paths.iter().zip(olds).zip(news) {
let old_owner = owners.of(&touched.old, false);
let new_owner = owners.of(&touched.new, true);
let old_text = old_text
.filter(|_| old_owner != Owner::Other && !old_notes.contains(&touched.old))
.map(|text| match &old_owner {
Owner::Own => as_reminted(&touched.old, text, &remint),
_ => text,
});
let new_text =
new_text.filter(|_| new_owner != Owner::Other && !new_notes.contains(&touched.new));
if old_text.is_none() && new_text.is_none() {
continue;
}
let keys = [qualifier(&old_owner), qualifier(&new_owner)];
let rel = &touched.new;
marker_changes.extend(marker_diff(
rel,
[old_text.as_deref(), new_text.as_deref()],
keys,
));
files.insert(path_of(rel), (old_text, new_text));
}
Ok((old, new, marker_changes, files))
}
fn qualifier(owner: &Owner) -> Option<&str> {
match owner {
Owner::Vanished(_, key) => Some(key),
_ => None,
}
}
struct DiffEnds {
old_rev: String,
new_rev: Option<String>,
}
fn diff_ends(root: &Path, base: &str) -> Result<DiffEnds> {
let end = |side: &str| match side.trim() {
"" => "HEAD".to_string(),
side => side.to_string(),
};
if let Some(pos) = base.find("...") {
let (left, right) = (end(&base[..pos]), end(&base[pos + 3..]));
let old_rev = git_stdout(root, &["merge-base", &left, &right])?;
return Ok(DiffEnds {
old_rev,
new_rev: Some(right),
});
}
if let Some(pos) = base.find("..") {
return Ok(DiffEnds {
old_rev: end(&base[..pos]),
new_rev: Some(end(&base[pos + 2..])),
});
}
Ok(DiffEnds {
old_rev: base.to_string(),
new_rev: None,
})
}
fn read_new_sides(root: &Path, rev: Option<&str>, rels: &[PathBuf]) -> Vec<Option<String>> {
match rev {
None => rels.iter().map(|rel| read_worktree(root, rel)).collect(),
Some(rev) => git_show_all(root, rev, rels),
}
}
fn merge_scan(into: &mut Scan, from: Scan) {
into.laws.extend(from.laws);
into.pointers.extend(from.pointers);
into.form_errors.extend(from.form_errors);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Kind {
Declared,
Retired,
Reminted,
Removed,
Deleted,
Moved,
Amended,
Clause,
Reused,
Cite,
Marker,
Drift,
Accepted,
Recall,
Draft,
Public,
Context,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Change {
address: String,
kind: Kind,
old_path: Option<String>,
new_path: Option<String>,
old_text: Option<String>,
new_text: Option<String>,
callees: Vec<CalleeDiff>,
lines: [Option<usize>; 2],
why: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct CalleeDiff {
name: String,
path: String,
old: Option<String>,
new: Option<String>,
why: Option<String>,
read: Option<span_lang::Read>,
}
impl Change {
fn kind_name(&self) -> &'static str {
match self.kind {
Kind::Declared => "declared",
Kind::Retired => "retired",
Kind::Reminted => "reminted",
Kind::Removed => "removed",
Kind::Deleted => "deleted",
Kind::Moved => "moved",
Kind::Amended => "amended",
Kind::Clause => "clause",
Kind::Reused => "reused",
Kind::Cite => "cite",
Kind::Marker => "marker",
Kind::Drift => "drift",
Kind::Accepted => "accepted",
Kind::Recall => "recall",
Kind::Draft => "draft",
Kind::Public => "public",
Kind::Context => "context",
}
}
fn is_marker(&self) -> bool {
matches!(self.kind, Kind::Marker | Kind::Drift | Kind::Accepted)
}
}
fn collect_law_changes<'a>(old: &'a Scan, new: &'a Scan) -> Vec<Change> {
let old_laws = index_laws(old);
let new_laws = index_laws(new);
let carried = carried_ids(new);
let remint = reminted(old, new);
let mut ids: BTreeSet<&str> = BTreeSet::new();
ids.extend(old_laws.keys().copied());
ids.extend(new_laws.keys().copied());
let mut out = Vec::new();
for id in ids {
let live =
|laws: &BTreeMap<&str, &'a parse::Law>| laws.get(id).copied().filter(|l| !l.struck);
let was = remint
.iter()
.find(|(_, now)| now.as_str() == id)
.and_then(|(was, _)| Some((was, *old_laws.get(was.as_str())?)));
match (live(&old_laws), live(&new_laws), was) {
(Some(_), None, _) if remint.contains_key(id) => {}
(None, Some(n), Some((was, o))) => {
let shown = |law: &parse::Law| match attached_moved(&o.body, &n.body) {
true => law.pin_text(),
false => law.name.clone(),
};
out.push(Change {
address: id.to_string(),
kind: Kind::Reminted,
old_path: Some(path_of(&o.loc.path)),
new_path: Some(path_of(&n.loc.path)),
old_text: Some(shown(o)),
new_text: Some(shown(n)),
callees: Vec::new(),
lines: [None, None],
why: Some(format!("{REMINTED_FROM}{was}.")),
});
out.extend(clause_changes(id, o, n));
out.extend(draft_changes(id, Some(o), n));
out.extend(public_change(id, o, n));
out.extend(context_change(id, Some(o), n, false));
}
(None, Some(n), None) => {
let mut law = whole_law(id, n, None);
if let Some(struck) = old_laws.get(id) {
law[0] = Change {
kind: Kind::Reused,
old_path: Some(path_of(&struck.loc.path)),
old_text: Some(format!("~~{}~~", struck.name)),
new_text: Some(format!(
"{}\nRevives ยง {id}, struck at the comparison point: a marker or a cite of the retired law now names it again.",
n.name
)),
..law[0].clone()
};
let (held, now) = (index_clauses(struck), index_clauses(n));
for change in law.iter_mut().skip(1) {
let letter = change.address.rsplit('.').next().unwrap_or_default();
let (Some(was), Some(is)) =
(held.get(letter).filter(|c| !c.struck), now.get(letter))
else {
continue;
};
let canon = |c: &parse::Clause| crate::hash::pin_canon(&c.pin_body());
if canon(was) != canon(is) {
change.old_path = Some(path_of(&was.loc.path));
change.old_text = Some(was.text.clone());
}
}
}
out.extend(law);
out.extend(draft_changes(id, old_laws.get(id).copied(), n));
out.extend(context_change(id, old_laws.get(id).copied(), n, false));
}
(Some(o), None, _) if carried.contains(id) => {
out.extend(whole_law(id, o, Some(Kind::Retired)))
}
(Some(o), None, _) => out.extend(whole_law(id, o, Some(Kind::Deleted))),
(Some(o), Some(n), _) => {
let op = path_of(&o.loc.path);
let np = path_of(&n.loc.path);
let head_shown = op != np || o.name != n.name || attached_moved(&o.body, &n.body);
out.extend(context_change(id, Some(o), n, !head_shown));
if op != np {
out.push(Change {
address: id.to_string(),
kind: Kind::Moved,
old_path: Some(op.clone()),
new_path: Some(np.clone()),
old_text: Some(o.name.clone()),
new_text: Some(n.name.clone()),
callees: Vec::new(),
lines: [None, None],
why: None,
});
} else if o.name != n.name || attached_moved(&o.body, &n.body) {
let shown = |law: &parse::Law| match attached_moved(&o.body, &n.body) {
true => law.pin_text(),
false => law.name.clone(),
};
out.push(Change {
address: id.to_string(),
kind: Kind::Amended,
old_path: Some(op.clone()),
new_path: Some(np.clone()),
old_text: Some(shown(o)),
new_text: Some(shown(n)),
callees: Vec::new(),
lines: [None, None],
why: None,
});
}
out.extend(clause_changes(id, o, n));
out.extend(draft_changes(id, Some(o), n));
out.extend(public_change(id, o, n));
}
(None, None, _) => {}
}
}
out
}
fn draft_changes(id: &str, old: Option<&parse::Law>, new: &parse::Law) -> Vec<Change> {
let old = old.filter(|law| !law.struck);
let change = |address: String, was: Option<(bool, &str)>, is: (bool, &str), path: &Path| {
let why = match (was.map(|w| w.0), is.0) {
(Some(false), true) => DRAFT_MADE,
(Some(true), false) => DRAFT_DROPPED,
(None, true) => DRAFT_NEW,
_ => return None,
};
Some(Change {
address,
kind: Kind::Draft,
old_path: was.map(|_| path_of(path)),
new_path: Some(path_of(path)),
old_text: was.map(|w| w.1.to_string()),
new_text: Some(is.1.to_string()),
callees: Vec::new(),
lines: [None, None],
why: Some(why.to_string()),
})
};
fn head(law: &parse::Law) -> (bool, &str) {
(law.draft, law.name.as_str())
}
let mut out: Vec<Change> = change(id.to_string(), old.map(head), head(new), &new.loc.path)
.into_iter()
.collect();
for clause in new.clauses.iter().filter(|c| !c.struck) {
let Some(letter) = &clause.letter else {
continue;
};
let was = old.and_then(|law| {
law.clauses
.iter()
.find(|c| c.letter.as_ref() == Some(letter) && !c.struck)
.map(|c| (c.draft, c.text.as_str()))
});
out.extend(change(
format!("{id}.{letter}"),
was,
(clause.draft, clause.text.as_str()),
&clause.loc.path,
));
}
out
}
fn public_change(id: &str, old: &parse::Law, new: &parse::Law) -> Option<Change> {
let why = match (old.public, new.public) {
(false, true) => PUBLIC_MADE,
(true, false) => PUBLIC_DROPPED,
_ => return None,
};
Some(Change {
address: id.to_string(),
kind: Kind::Public,
old_path: Some(path_of(&old.loc.path)),
new_path: Some(path_of(&new.loc.path)),
old_text: Some(old.name.clone()),
new_text: Some(new.name.clone()),
callees: Vec::new(),
lines: [None, None],
why: Some(why.to_string()),
})
}
fn context_change(
id: &str,
old: Option<&parse::Law>,
new: &parse::Law,
recall: bool,
) -> Vec<Change> {
let was = old.map_or("", |law| law.context.as_str());
if !attached_moved(was, &new.context) {
return Vec::new();
}
let text = |context: &str| (!context.is_empty()).then(|| context.to_string());
let mut out = vec![Change {
address: id.to_string(),
kind: Kind::Context,
old_path: old.map(|law| path_of(&law.loc.path)),
new_path: Some(path_of(&new.loc.path)),
old_text: text(was),
new_text: text(&new.context),
callees: Vec::new(),
lines: [None, None],
why: Some(CONTEXT_MOVED.to_string()),
}];
if recall {
out.push(Change {
kind: Kind::Recall,
old_text: Some(new.pin_text()),
new_text: Some(new.pin_text()),
why: None,
..out[0].clone()
});
}
out
}
pub(crate) const CONTEXT_MOVED: &str =
"Its context changed: the prose between its head and its clauses, which binds nothing and no pin hashes, reads otherwise.";
pub(crate) const PUBLIC_MADE: &str =
"Made a public promise: it owes a documentation marker in a file the `docs` list matches.";
pub(crate) const PUBLIC_DROPPED: &str = "Made plain: it owes no documentation marker.";
pub(crate) const DRAFT_MADE: &str = "Made a draft: it owes no marker and is not pinned.";
pub(crate) const DRAFT_DROPPED: &str = "No longer a draft: it owes its markers.";
pub(crate) const DRAFT_NEW: &str = "A draft: it owes no marker and is not pinned.";
fn carried_ids(scan: &Scan) -> BTreeSet<&str> {
scan.laws
.iter()
.flat_map(|law| std::iter::once(&law.id).chain(&law.aliases))
.map(String::as_str)
.collect()
}
pub(crate) const REMINTED_FROM: &str = "Reminted from ยง ";
fn reminted(old: &Scan, new: &Scan) -> BTreeMap<String, String> {
let old_ids: BTreeSet<&str> = old.laws.iter().map(|law| law.id.as_str()).collect();
let old_live: BTreeSet<&str> = old
.laws
.iter()
.filter(|law| !law.struck)
.map(|law| law.id.as_str())
.collect();
let new_ids: BTreeSet<&str> = new.laws.iter().map(|law| law.id.as_str()).collect();
let mut out = BTreeMap::new();
for law in new.laws.iter().filter(|law| !law.struck) {
if old_ids.contains(law.id.as_str()) {
continue;
}
let was: Vec<&String> = law
.aliases
.iter()
.filter(|alias| old_live.contains(alias.as_str()) && !new_ids.contains(alias.as_str()))
.collect();
if let [was] = was.as_slice() {
out.insert((*was).clone(), law.id.clone());
}
}
out
}
fn as_reminted(rel: &Path, text: String, remint: &BTreeMap<String, String>) -> String {
let rows: BTreeSet<usize> = span::marker_rows(rel, &text, None)
.into_iter()
.filter(|row| {
row.markers
.iter()
.chain(&row.end)
.any(|m| m.project.is_none() && remint.contains_key(&m.id))
})
.map(|row| row.idx)
.collect();
if rows.is_empty() {
return text;
}
let token = |c: char| c.is_ascii_alphanumeric() || c == ':' || c == '/';
text.split_inclusive('\n')
.enumerate()
.map(|(idx, line)| {
if !rows.contains(&idx) {
return line.to_string();
}
let mut line = line.to_string();
for (was, now) in remint {
let mut at = 0;
while let Some(found) = line[at..].find(was.as_str()).map(|i| i + at) {
let end = found + was.len();
let alone = !line[..found].ends_with(token) && !line[end..].starts_with(token);
if alone {
line.replace_range(found..end, now);
}
at = found + 1;
}
}
line
})
.collect()
}
fn whole_law(id: &str, law: &parse::Law, gone: Option<Kind>) -> Vec<Change> {
let side = |path: &Path, text: &str| {
let (path, text) = (Some(path_of(path)), Some(text.to_string()));
if gone.is_some() {
(path, None, text, None)
} else {
(None, path, None, text)
}
};
let deleted = gone == Some(Kind::Deleted);
let text = if deleted {
last_text(law)
} else {
law.name.clone()
};
let (old_path, new_path, old_text, new_text) = side(&law.loc.path, &text);
let mut out = vec![Change {
address: id.to_string(),
kind: gone.unwrap_or(Kind::Declared),
old_path,
new_path,
old_text,
new_text,
callees: Vec::new(),
lines: [None, None],
why: None,
}];
for clause in law
.clauses
.iter()
.filter(|clause| deleted || !clause.struck)
{
let Some(letter) = &clause.letter else {
continue;
};
let text = if deleted {
clause_last_text(clause)
} else {
clause.text.clone()
};
let (old_path, new_path, old_text, new_text) = side(&clause.loc.path, &text);
out.push(Change {
address: format!("{id}.{letter}"),
kind: gone.unwrap_or(Kind::Clause),
old_path,
new_path,
old_text,
new_text,
callees: Vec::new(),
lines: [None, None],
why: None,
});
}
out
}
fn last_text(law: &parse::Law) -> String {
let head = if law.struck {
format!("~~{}~~", law.name)
} else {
law.name.clone()
};
if law.body.is_empty() {
head
} else {
format!("{head}\n{}", law.body)
}
}
fn clause_last_text(clause: &parse::Clause) -> String {
if clause.body.is_empty() {
clause.text.clone()
} else {
clause.body.clone()
}
}
fn collect_deleted(old: &Scan, new: &Scan) -> Vec<Change> {
let new_laws = index_laws(new);
let carried = carried_ids(new);
let remint = reminted(old, new);
let gone_as = |kind: Kind, address: String, path: &Path, text: String| Change {
address,
kind,
old_path: Some(path_of(path)),
new_path: None,
old_text: Some(text),
new_text: None,
callees: Vec::new(),
lines: [None, None],
why: None,
};
let mut out = Vec::new();
for law in &old.laws {
let alias_kind = if law.struck {
Kind::Removed
} else {
Kind::Deleted
};
for alias in law.aliases.iter().filter(|a| !carried.contains(a.as_str())) {
let text = format!("Alias anchor of ยง {}.", law.id);
out.push(gone_as(alias_kind, alias.clone(), &law.loc.path, text));
}
let id = remint.get(&law.id).unwrap_or(&law.id);
let Some(now) = new_laws.get(id.as_str()) else {
if law.struck {
out.push(gone_as(
Kind::Removed,
law.id.clone(),
&law.loc.path,
last_text(law),
));
}
let kind = if law.struck {
Kind::Removed
} else if carried.contains(law.id.as_str()) {
Kind::Retired
} else {
continue;
};
for clause in law.clauses.iter().filter(|c| law.struck || c.struck) {
if let Some(letter) = &clause.letter {
let address = format!("{}.{letter}", law.id);
let text = if kind == Kind::Retired {
clause.text.clone()
} else {
clause_last_text(clause)
};
out.push(gone_as(kind, address, &clause.loc.path, text));
}
}
continue;
};
for clause in &law.clauses {
let Some(letter) = &clause.letter else {
continue;
};
let gone = !now
.clauses
.iter()
.any(|c| c.letter.as_ref() == Some(letter));
if gone && (law.struck || clause.struck) {
let address = format!("{id}.{letter}");
let text = clause_last_text(clause);
out.push(gone_as(Kind::Removed, address, &clause.loc.path, text));
}
}
}
out
}
fn clause_changes<'a>(id: &str, old: &'a parse::Law, new: &'a parse::Law) -> Vec<Change> {
let old_map = index_clauses(old);
let new_map = index_clauses(new);
let mut letters: BTreeSet<&str> = BTreeSet::new();
letters.extend(old_map.keys().copied());
letters.extend(new_map.keys().copied());
let mut out = Vec::new();
for letter in letters {
let address = format!("{id}.{letter}");
let live = |clauses: &BTreeMap<&str, &'a parse::Clause>| {
clauses.get(letter).copied().filter(|c| !c.struck)
};
match (live(&old_map), live(&new_map)) {
(None, Some(n)) if old_map.contains_key(letter) => out.push(Change {
address,
kind: Kind::Reused,
old_path: Some(path_of(&old_map[letter].loc.path)),
new_path: Some(path_of(&n.loc.path)),
old_text: Some(format!("~~{}~~", old_map[letter].text)),
new_text: Some(format!(
"{}\nReuses ({letter}), burned at the comparison point: a marker of the struck clause now names this one.",
n.text
)),
callees: Vec::new(),
lines: [None, None],
why: None,
}),
(None, Some(n)) => out.push(Change {
address,
kind: Kind::Clause,
old_path: None,
new_path: Some(path_of(&n.loc.path)),
old_text: None,
new_text: Some(n.text.clone()),
callees: Vec::new(),
lines: [None, None],
why: None,
}),
(Some(o), None) if !new_map.contains_key(letter) => out.push(Change {
address,
kind: Kind::Deleted,
old_path: Some(path_of(&o.loc.path)),
new_path: None,
old_text: Some(clause_last_text(o)),
new_text: None,
callees: Vec::new(),
lines: [None, None],
why: None,
}),
(Some(o), None) => out.push(Change {
address,
kind: Kind::Retired,
old_path: Some(path_of(&o.loc.path)),
new_path: None,
old_text: Some(o.text.clone()),
new_text: None,
callees: Vec::new(),
lines: [None, None],
why: None,
}),
(Some(o), Some(n))
if o.text != n.text || attached_moved(&o.pin_body(), &n.pin_body()) =>
{
let shown = |clause: &parse::Clause| {
match attached_moved(&o.pin_body(), &n.pin_body()) {
true if !clause.header.is_empty() => {
format!("{}\n{}", clause.header, clause.text)
}
true => clause.pin_body(),
false => clause.text.clone(),
}
};
out.push(Change {
address,
kind: Kind::Clause,
old_path: Some(path_of(&o.loc.path)),
new_path: Some(path_of(&n.loc.path)),
old_text: Some(shown(o)),
new_text: Some(shown(n)),
callees: Vec::new(),
lines: [None, None],
why: None,
})
}
_ => {}
}
}
out
}
fn attached_moved(old: &str, new: &str) -> bool {
crate::hash::pin_canon(old) != crate::hash::pin_canon(new)
}
fn collect_pointer_changes(old: &Scan, new: &Scan) -> Vec<Change> {
let remint = reminted(old, new);
let old_set: BTreeSet<PointerKey> = pointer_keys(old)
.into_iter()
.map(|mut key| {
let (id, letter) = split_address(&key.address);
if let Some(now) = remint.get(&id) {
key.line = key.line.replace(&id, now);
key.address = match letter {
Some(letter) => format!("{now}.{letter}"),
None => now.clone(),
};
}
key
})
.collect();
let new_set = pointer_keys(new);
let mut out = Vec::new();
for key in old_set.difference(&new_set) {
out.push(Change {
address: key.address.clone(),
kind: pointer_kind(key.kind),
old_path: Some(key.path.clone()),
new_path: None,
old_text: Some(key.line.clone()),
new_text: None,
callees: Vec::new(),
lines: [None, None],
why: None,
});
}
for key in new_set.difference(&old_set) {
out.push(Change {
address: key.address.clone(),
kind: pointer_kind(key.kind),
old_path: None,
new_path: Some(key.path.clone()),
old_text: None,
new_text: Some(key.line.clone()),
callees: Vec::new(),
lines: [None, None],
why: None,
});
}
out
}
fn pointer_kind(kind: PointerKind) -> Kind {
match kind {
PointerKind::Implements => Kind::Marker,
PointerKind::Cite => Kind::Cite,
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct PointerKey {
kind: PointerKind,
address: String,
path: String,
line: String,
}
fn pointer_keys(scan: &Scan) -> BTreeSet<PointerKey> {
scan.pointers
.iter()
.map(|ptr| {
let local = match &ptr.target {
Target::Stable {
id,
letter: Some(letter),
} => format!("{id}.{letter}"),
Target::Stable { id, letter: None } => id.clone(),
Target::Display { clause, .. } => match clause {
Some(letter) => format!("{}.{}", ptr.name, letter),
None => ptr.name.clone(),
},
};
let address = match &ptr.project {
Some(project) => format!("{project}:{local}"),
None => local,
};
PointerKey {
kind: ptr.kind,
address,
path: path_of(&ptr.loc.path),
line: format!("{:?} ยง {}", ptr.kind, ptr.name),
}
})
.collect()
}
fn marker_diff(
path: &Path,
[old, new]: [Option<&str>; 2],
[old_key, new_key]: [Option<&str>; 2],
) -> Vec<Change> {
let old_map = marker_pins(path, old.unwrap_or(""), old_key);
let new_map = marker_pins(path, new.unwrap_or(""), new_key);
let rel = path_of(path);
let mut keys = BTreeSet::new();
keys.extend(old_map.keys().cloned());
keys.extend(new_map.keys().cloned());
let parsed = [std::cell::OnceCell::new(), std::cell::OnceCell::new()];
let punched = |side: usize, line: usize| -> Option<String> {
let text = [old, new][side]?;
if span_lang::lang_for_path(path).is_none() {
return extract_punched(path, text, line);
}
let markers = parsed[side].get_or_init(|| {
span::CodeFile::new(path.to_path_buf(), text.to_string()).span_markers()
});
punched_in(text, markers, line).map(|(span, _, _)| span)
};
let mut out = Vec::new();
let change = |key: &str, old: Option<(usize, &str)>, new: Option<(usize, &str)>| Change {
address: key.to_string(),
kind: Kind::Marker,
old_path: old.map(|_| rel.clone()),
new_path: new.map(|_| rel.clone()),
old_text: old.map(|(_, text)| text.to_string()),
new_text: new.map(|(_, text)| text.to_string()),
callees: Vec::new(),
lines: [old.map(|(line, _)| line), new.map(|(line, _)| line)],
why: None,
};
for key in keys {
let mut old_left = old_map.get(&key).cloned().unwrap_or_default();
let mut new_left = new_map.get(&key).cloned().unwrap_or_default();
let mut shared = Vec::new();
old_left.retain(|(line, text)| {
match new_left.iter().position(|(_, other)| other == text) {
Some(at) => {
shared.push((*line, new_left.remove(at).0, text.clone()));
false
}
None => true,
}
});
for (old_line, new_line, text) in shared {
if is_pinned(&text) || span_moved(path, old, new, old_line, new_line) {
out.push(change(
&key,
Some((old_line, &text)),
Some((new_line, &text)),
));
}
}
let choice = !old_left.is_empty()
&& !new_left.is_empty()
&& (old_left.len(), new_left.len()) != (1, 1);
let spans = |side: usize, left: &[(usize, String)]| -> Vec<Option<String>> {
left.iter()
.map(|(line, _)| choice.then(|| punched(side, *line)).flatten())
.collect()
};
let (old_spans, new_spans) = (spans(0, &old_left), spans(1, &new_left));
for (o, n) in pair_spans(&old_spans, &new_spans) {
out.push(change(
&key,
o.map(|i| (old_left[i].0, old_left[i].1.as_str())),
n.map(|j| (new_left[j].0, new_left[j].1.as_str())),
));
}
}
out
}
fn pair_spans(
old: &[Option<String>],
new: &[Option<String>],
) -> Vec<(Option<usize>, Option<usize>)> {
let mut pairs = Vec::new();
let mut new_free: Vec<usize> = (0..new.len()).collect();
let mut old_free = Vec::new();
for (i, span) in old.iter().enumerate() {
let same = span.as_ref().and_then(|span| {
let span = strip_digests(span);
new_free
.iter()
.position(|&j| new[j].as_ref().is_some_and(|n| strip_digests(n) == span))
});
match same {
Some(at) => pairs.push((Some(i), Some(new_free.remove(at)))),
None => old_free.push(i),
}
}
if old_free.len() == new_free.len() {
pairs.extend(
old_free
.into_iter()
.zip(new_free)
.map(|(i, j)| (Some(i), Some(j))),
);
} else {
pairs.extend(old_free.into_iter().map(|i| (Some(i), None)));
pairs.extend(new_free.into_iter().map(|j| (None, Some(j))));
}
pairs.sort_by_key(|&(i, j)| (j, i));
pairs
}
fn span_moved(
path: &Path,
old: Option<&str>,
new: Option<&str>,
old_line: usize,
new_line: usize,
) -> bool {
let (Some(old), Some(new)) = (old, new) else {
return false;
};
let old_span = extract_punched(path, old, old_line);
old_span.is_some() && old_span != extract_punched(path, new, new_line)
}
fn is_pinned(line: &str) -> bool {
marker::markers_in_line(line)
.iter()
.any(|marker| marker.digest.is_some())
}
fn marker_pins(
path: &Path,
text: &str,
key: Option<&str>,
) -> BTreeMap<String, Vec<(usize, String)>> {
let mut out: BTreeMap<String, Vec<(usize, String)>> = BTreeMap::new();
for row in span::marker_rows(path, text, None) {
for marker in row.markers {
out.entry(qualified(marker, key))
.or_default()
.push((row.idx + 1, row.line.trim().to_string()));
}
}
out
}
fn qualified(mut marker: marker::MarkerAddr, key: Option<&str>) -> String {
if marker.project.is_none() {
marker.project = key.map(str::to_string);
}
marker.display()
}
fn index_laws(scan: &Scan) -> BTreeMap<&str, &parse::Law> {
let mut out = BTreeMap::new();
for law in &scan.laws {
out.insert(law.id.as_str(), law);
}
out
}
fn index_clauses(art: &parse::Law) -> BTreeMap<&str, &parse::Clause> {
let mut out = BTreeMap::new();
for al in &art.clauses {
if let Some(letter) = &al.letter {
out.insert(letter.as_str(), al);
}
}
out
}
fn path_of(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
struct Shown<'a> {
prefix: &'a str,
key: &'a Option<String>,
docs: &'a crate::walk::Patterns,
}
#[cfg(test)]
fn review_of(
changes: &[Change],
files: &FileMap,
follow: &FollowIndex,
shown: &str,
) -> review::Review {
let shown = Shown {
prefix: shown,
key: &None,
docs: &crate::walk::Patterns::default(),
};
let rules = review::law_entries(changes, files, follow, &Callers::new(), &shown);
review::Review::gather("HEAD".into(), Vec::new(), 0, Vec::new(), rules, Vec::new())
}
#[cfg(test)]
fn render_diff(changes: &[Change]) -> String {
render_diff_with(changes, &BTreeMap::new())
}
#[cfg(test)]
fn render_diff_with(changes: &[Change], files: &FileMap) -> String {
render_diff_follow(changes, files, &FollowIndex::default(), "")
}
#[cfg(test)]
fn render_diff_follow(
changes: &[Change],
files: &FileMap,
follow: &FollowIndex,
shown: &str,
) -> String {
review::review_markdown(&review_of(changes, files, follow, shown))
}
#[cfg(test)]
fn diff_json(root: &Path, changes: &[Change], folded: usize) -> String {
let mut review = review_of(changes, &FileMap::new(), &FollowIndex::default(), "");
review.folded = folded;
let ids: Vec<&str> = review.rules.iter().map(|rule| local_id(&rule.id)).collect();
review::review_json(&review, &crate::meta::declared(root, &ids))
}
type ParsedMap = BTreeMap<String, [Option<Vec<span::SpanMarker>>; 2]>;
fn parse_files(files: &FileMap) -> ParsedMap {
let mut jobs = Vec::new();
for (path, (old, new)) in files {
if span_lang::lang_for_path(Path::new(path)).is_none() {
continue;
}
for (side, text) in [old, new].into_iter().enumerate() {
if let Some(text) = text {
jobs.push((path.clone(), side, text.clone()));
}
}
}
let done = crate::par::map(
jobs,
|(_, _, text)| text.len(),
|(path, side, text)| {
let markers = span::CodeFile::new(PathBuf::from(&path), text).span_markers();
(path, side, markers)
},
);
let mut out = ParsedMap::new();
for (path, side, markers) in done {
out.entry(path).or_default()[side] = Some(markers);
}
out
}
fn joined_notes(first: Option<String>, second: Option<String>) -> Option<String> {
match (first, second) {
(Some(first), Some(second)) => Some(format!("{first}\n{second}")),
(first, second) => first.or(second),
}
}
fn pin_lines(rel: &Path, text: &str, address: &str) -> Vec<usize> {
let own = address.rsplit_once(':').and_then(|(key, local)| {
rel.ancestors()
.skip(1)
.any(|dir| !dir.as_os_str().is_empty() && Path::new(key).ends_with(dir))
.then_some(local)
});
span::pinned_in_text(rel, text, None)
.into_iter()
.filter(|pin| {
let shown = pin.addr.display();
shown == address || (pin.addr.project.is_none() && Some(shown.as_str()) == own)
})
.map(|pin| pin.line)
.collect()
}
fn extract_punched(path: &Path, text: &str, marker_line: usize) -> Option<String> {
let keep = punched_lines(path, text, marker_line)?;
let mut out = String::new();
for (idx, line) in text.lines().enumerate() {
if keep.contains(&(idx + 1)) {
out.push_str(line);
out.push('\n');
}
}
Some(out)
}
fn punched_lines(path: &Path, text: &str, marker_line: usize) -> Option<BTreeSet<usize>> {
let (start, end) = line_span(path, text, marker_line)?;
let outer = nest_extent(path, text, marker_line)?;
let mut keep: BTreeSet<usize> = (start..=end).collect();
for pin in span::pinned_in_text(path, text, None) {
if pin.line == marker_line {
continue;
}
let (Some((inner_start, inner_end)), Some(inner)) = (
line_span(path, text, pin.line),
nest_extent(path, text, pin.line),
) else {
continue;
};
if span::nests_in(inner, outer) {
for line in inner_start..=inner_end {
keep.remove(&line);
}
}
}
keep.insert(marker_line);
Some(keep)
}
fn nest_extent(path: &Path, source: &str, marker_line: usize) -> Option<(usize, usize)> {
match span_lang::lang_for_path(path) {
Some(lang) => span_lang::span_bytes(lang, path, source, marker_line),
None => line_span(path, source, marker_line),
}
}
fn line_span(path: &Path, source: &str, marker_line: usize) -> Option<(usize, usize)> {
match span_lang::lang_for_path(path) {
Some(lang) => {
let (start, end) = span_lang::span_bytes(lang, path, source, marker_line)?;
if end <= start {
return None;
}
Some((byte_line(source, start), byte_line(source, end - 1)))
}
None => {
let ends = span::file_ends(path, source);
if let Some(&end_idx) = ends.pairs.get(&marker_line.checked_sub(1)?) {
return Some((marker_line + 1, end_idx + 1));
}
let last = source.lines().count();
if marker_line >= last {
return None;
}
Some((marker_line + 1, last))
}
}
}
fn byte_line(source: &str, byte: usize) -> usize {
let byte = byte.min(source.len());
source.as_bytes()[..byte]
.iter()
.filter(|b| **b == b'\n')
.count()
+ 1
}
fn aligned_lines(old_lines: &[String], new_lines: &[String]) -> Vec<String> {
let mut out = Vec::new();
let mut i = 0;
let mut j = 0;
while i < old_lines.len() || j < new_lines.len() {
if i < old_lines.len() && j < new_lines.len() && old_lines[i] == new_lines[j] {
out.push(format!(" {}", old_lines[i]));
i += 1;
j += 1;
continue;
}
let mut removed = Vec::new();
let mut added = Vec::new();
while i < old_lines.len() && (j >= new_lines.len() || old_lines[i] != new_lines[j]) {
if let Some(pos) = new_lines[j..].iter().position(|l| l == &old_lines[i]) {
added.extend(new_lines[j..j + pos].iter().map(|l| format!("+{l}")));
j += pos;
break;
}
removed.push(format!("-{}", old_lines[i]));
i += 1;
}
while j < new_lines.len() && (i >= old_lines.len() || old_lines[i] != new_lines[j]) {
if let Some(pos) = old_lines[i..].iter().position(|l| l == &new_lines[j]) {
removed.extend(old_lines[i..i + pos].iter().map(|l| format!("-{l}")));
i += pos;
break;
}
added.push(format!("+{}", new_lines[j]));
j += 1;
}
if removed.is_empty() && added.is_empty() {
break;
}
out.extend(removed);
out.extend(added);
}
out
}
fn delta_available() -> bool {
Command::new("delta")
.arg("--version")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn emit_diff_stream(diff: &str) -> Result<()> {
if diff.is_empty() {
return Ok(());
}
if list_tty::is_tty_stdout() && delta_available() {
return emit_delta(diff);
}
if list_tty::is_tty_stdout() {
return list_tty::page(diff);
}
print!("{diff}");
Ok(())
}
fn emit_delta(diff: &str) -> Result<()> {
match Command::new("delta")
.arg("--side-by-side")
.stdin(Stdio::piped())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.spawn()
{
Ok(mut child) => {
if let Some(mut stdin) = child.stdin.take() {
stdin.write_all(diff.as_bytes())?;
}
let status = child.wait()?;
if !status.success() {
print!("{diff}");
}
Ok(())
}
Err(_) => {
print!("{diff}");
Ok(())
}
}
}
fn read_worktree(root: &Path, rel: &Path) -> Option<String> {
if walk::behind_nested_repo(root, rel) {
return None;
}
std::fs::read_to_string(root.join(rel)).ok()
}
fn git_show(root: &Path, base: &str, rel: &Path) -> Option<String> {
let spec = format!("{}:./{}", base, rel.to_string_lossy());
let out = crate::workspace::git(root)
.args(["show", &spec])
.output()
.ok()?;
if !out.status.success() {
return None;
}
String::from_utf8(out.stdout).ok()
}
fn git_show_all(root: &Path, rev: &str, rels: &[PathBuf]) -> Vec<Option<String>> {
let specs: Vec<String> = rels
.iter()
.map(|rel| format!("{}:./{}", rev, rel.to_string_lossy()))
.collect();
if rels.is_empty() || specs.iter().any(|spec| spec.contains('\n')) {
return rels.iter().map(|rel| git_show(root, rev, rel)).collect();
}
let batch = crate::workspace::git(root)
.args(["cat-file", "--batch"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn();
let Ok(mut child) = batch else {
return rels.iter().map(|rel| git_show(root, rev, rel)).collect();
};
let input: String = specs.iter().map(|spec| format!("{spec}\n")).collect();
let mut stdin = child.stdin.take().expect("piped stdin");
let writer = std::thread::spawn(move || stdin.write_all(input.as_bytes()));
let out = child.wait_with_output();
let wrote = writer.join().is_ok_and(|wrote| wrote.is_ok());
let out = match out {
Ok(out) if wrote && out.status.success() => out.stdout,
_ => return rels.iter().map(|rel| git_show(root, rev, rel)).collect(),
};
let mut rest = out.as_slice();
rels.iter()
.map(|rel| {
let nl = rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len());
let header = String::from_utf8_lossy(&rest[..nl]).into_owned();
rest = rest.get(nl + 1..).unwrap_or_default();
let mut fields = header.rsplitn(3, ' ');
let size: usize = fields.next()?.parse().ok()?;
let kind = fields.next()?;
let body = rest.get(..size)?;
rest = rest.get(size + 1..).unwrap_or_default();
if kind != "blob" {
return git_show(root, rev, rel);
}
String::from_utf8(body.to_vec()).ok()
})
.collect()
}
fn git_ok(root: &Path, args: &[&str]) -> bool {
crate::workspace::git(root)
.args(args)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn git_stdout(root: &Path, args: &[&str]) -> Result<String> {
let out = crate::workspace::git(root)
.args(args)
.output()
.with_context(|| format!("git {}", args.join(" ")))?;
if !out.status.success() {
bail!(
"git {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr)
);
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
fn git_lines(root: &Path, args: &[&str]) -> Result<Vec<PathBuf>> {
let text = git_stdout(root, args)?;
Ok(text
.lines()
.filter(|l| !l.is_empty())
.map(PathBuf::from)
.collect())
}
type Sorted = (Vec<Change>, Vec<Change>, Option<[Side; 2]>);
fn sort_markers(
ws: &crate::workspace::Workspace,
root: &Path,
base_ref: &str,
changes: Vec<Change>,
files: &FileMap,
verbose: bool,
) -> Result<Sorted> {
let reworded = changes
.iter()
.any(|change| matches!(change.kind, Kind::Amended | Kind::Clause));
if files.is_empty() && !reworded {
return Ok((changes, Vec::new(), None));
}
let ends = diff_ends(root, base_ref)?;
let paths = new_side_paths(root, ends.new_rev.as_deref())?;
let tests = TestPaths::at(root)?;
let new = Side::of(
side_sources(&paths, |rels| {
read_new_sides(root, ends.new_rev.as_deref(), rels)
}),
&tests,
None,
);
let moved_away: BTreeMap<PathBuf, PathBuf> = changed_paths(root, base_ref)?
.into_iter()
.filter(|t| t.old != t.new && crate::follow::reads_path(&t.old))
.filter(|t| {
files
.get(&path_of(&t.new))
.and_then(|(old, _)| old.as_deref())
.is_some_and(|text| !text.contains('ยง'))
})
.map(|t| (t.new, t.old))
.collect();
let mut old_sources = side_sources(&paths, |rels| {
rels.iter()
.map(|rel| match files.get(&path_of(rel)) {
_ if moved_away.contains_key(rel) => None,
Some((old, _)) => old.clone(),
None => new.files.get(rel).map(|file| file.text.clone()),
})
.collect()
});
for (now, then) in &moved_away {
if let Some(text) = files.get(&path_of(now)).and_then(|(old, _)| old.clone()) {
old_sources.push((then.clone(), text));
}
}
let held: BTreeSet<&PathBuf> = paths.iter().collect();
for (path, (old, new)) in files {
let rel = PathBuf::from(path);
let deleted = new.is_none() && !held.contains(&rel) && crate::follow::reads_path(&rel);
if let Some(text) = old.clone().filter(|_| deleted) {
old_sources.push((rel, text));
}
}
let old = Side::of(old_sources, &tests, Some(&new));
let texts = AddressTexts::new(root, &ends);
let scheme = SchemeReads::new(ws, root, &ends)?;
let mut kept = Vec::new();
let mut folded = Vec::new();
for change in changes {
if !weighed_pin(&change) {
kept.push(change);
continue;
}
let digest_moved = change.old_text != change.new_text;
let text_moved = match digest_moved {
true => !texts.unchanged(&change.address)?,
false => texts.changed(&change.address)?,
};
let drift = match drift_of(&change, files, &old, &new, text_moved)? {
None if digest_moved && !scheme.same(&change)? => {
drift_of(&change, files, &old, &new, true)?.map(|drift| Change {
why: Some(UNSHOWN_MOVE.to_string()),
..drift
})
}
None if digest_moved && !scheme.held(&change)? => {
drift_of(&change, files, &old, &new, true)?.map(|drift| Change {
why: Some(RED_AT_BASE.to_string()),
..drift
})
}
drift => drift,
};
match drift {
Some(mut drift) => {
if text_moved && drift.why.is_none() && unshown(&drift) {
drift.why = Some(TEXT_MOVE.to_string());
}
kept.push(drift);
}
None if digest_moved => {
if verbose {
kept.push(change.clone());
}
folded.push(change);
}
None => {}
}
}
kept.extend(callee_drifts(files, &old, &new, &texts)?);
Ok((kept, folded, Some([old, new])))
}
const REBOUND: &str =
"A call of the span that reads alike now names another body, or what binds it changed.";
const CALLEE_EDIT: &str = "A callee changed: its patch is below.";
const UNSHOWN_MOVE: &str = "The span, the stretches it reads around it and its followed callees read alike, and the digest moved: it also reads the constants it follows, the definitions its links name and the project path, and one of them changed.";
const RED_AT_BASE: &str = "The span and its followed callees read alike, and the digest the comparison point wrote did not hold there: what it binds changed there without an accept, and this side re-pins it.";
const TEXT_MOVE: &str =
"The span and its followed callees read alike: the law or clause text it is pinned to changed.";
fn unshown(change: &Change) -> bool {
change.callees.is_empty()
&& change.old_text.as_deref().map(strip_digests)
== change.new_text.as_deref().map(strip_digests)
}
struct SchemeReads<'a> {
ws_root: &'a Path,
root_rel: PathBuf,
own_key: String,
ends: &'a DiffEnds,
sides: std::cell::RefCell<[Option<SideTokens>; 2]>,
files: std::cell::RefCell<BTreeMap<(usize, PathBuf), span::PinTokens>>,
recorded: std::cell::OnceCell<Option<crate::scheme::Scheme>>,
}
struct SideTokens {
_tree: Option<tempfile::TempDir>,
dir: PathBuf,
tokens: span::TreeTokens,
}
impl<'a> SchemeReads<'a> {
fn new(ws: &'a crate::workspace::Workspace, root: &Path, ends: &'a DiffEnds) -> Result<Self> {
let own_key = ws
.projects
.iter()
.find(|project| project.dir == root)
.map(|project| project.key.clone())
.with_context(|| format!("{} is no project of the workspace", root.display()))?;
Ok(Self {
ws_root: &ws.root,
root_rel: root.strip_prefix(&ws.root)?.to_path_buf(),
own_key,
ends,
sides: Default::default(),
files: Default::default(),
recorded: Default::default(),
})
}
fn load(&self, side: usize) -> Result<SideTokens> {
let rev = [
Some(self.ends.old_rev.as_str()),
self.ends.new_rev.as_deref(),
][side];
let (tree, top) = match rev {
Some(rev) => {
let tree = tempfile::tempdir()?;
crate::published::write_tree(self.ws_root, rev, tree.path())?;
let top = tree.path().to_path_buf();
(Some(tree), top)
}
None => (None, self.ws_root.to_path_buf()),
};
let dir = top.join(&self.root_rel);
let scans = crate::workspace::Workspace::at(top)?.law_scans(&self.own_key)?;
let texts = span::PinTexts::for_project(&parse::scan_root(&dir)?, &scans);
let tokens = span::TreeTokens::new(&dir, texts)?;
Ok(SideTokens {
_tree: tree,
dir,
tokens,
})
}
fn token(
&self,
side: usize,
rel: &Path,
line: usize,
(bit, address): (&str, &str),
) -> Result<Option<String>> {
if self.sides.borrow()[side].is_none() {
let loaded = self.load(side)?;
self.sides.borrow_mut()[side] = Some(loaded);
}
let Some(addr) = marker::entry_for(bit, address)
.and_then(|pin| pin.split_digest())
.map(|(addr, _)| addr.display())
else {
return Ok(None);
};
let key = (side, rel.to_path_buf());
if !self.files.borrow().contains_key(&key) {
let sides = self.sides.borrow();
let side = sides[side].as_ref().expect("loaded above");
let tokens = match std::fs::read_to_string(side.dir.join(rel)) {
Ok(text) => side.tokens.tokens(rel, &text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => span::PinTokens::new(),
Err(e) => return Err(e.into()),
};
self.files.borrow_mut().insert(key.clone(), tokens);
}
Ok(self.files.borrow()[&key].get(&(line - 1, addr)).cloned())
}
fn same(&self, change: &Change) -> Result<bool> {
let (
Some(old_path),
Some(new_path),
Some(old_bit),
Some(new_bit),
[Some(old_line), Some(new_line)],
) = (
change.old_path.as_deref(),
change.new_path.as_deref(),
change.old_text.as_deref(),
change.new_text.as_deref(),
change.lines,
)
else {
return Ok(false);
};
let address = change.address.as_str();
let written = marker::entry_for(new_bit, address).and_then(|pin| pin.digest);
let old = self.token(0, Path::new(old_path), old_line, (old_bit, address))?;
let new = self.token(1, Path::new(new_path), new_line, (new_bit, address))?;
Ok(old.is_some() && old == new && new == written)
}
fn held(&self, change: &Change) -> Result<bool> {
let (Some(old_path), Some(old_bit), Some(old_line)) = (
change.old_path.as_deref(),
change.old_text.as_deref(),
change.lines[0],
) else {
return Ok(false);
};
if self.recorded.get().is_none() {
let read = crate::hook::recorded_scheme_at(self.ws_root, &self.ends.old_rev)?;
let _ = self.recorded.set(read);
}
let recorded = self.recorded.get().and_then(Option::as_ref);
let parts = crate::scheme::parts_of(Path::new(old_path));
if recorded.is_some_and(|scheme| {
!scheme
.moved(&crate::scheme::Scheme::binary(), &parts)
.is_empty()
}) {
return Ok(true);
}
let address = change.address.as_str();
let written = marker::entry_for(old_bit, address).and_then(|pin| pin.digest);
let read = self.token(0, Path::new(old_path), old_line, (old_bit, address))?;
Ok(read.is_some() && read == written)
}
}
struct AddressTexts<'a> {
root: &'a Path,
ends: &'a DiffEnds,
read: std::cell::RefCell<BTreeMap<String, [BTreeMap<String, String>; 2]>>,
}
impl<'a> AddressTexts<'a> {
fn new(root: &'a Path, ends: &'a DiffEnds) -> Self {
Self {
root,
ends,
read: Default::default(),
}
}
fn texts(laws: &[parse::Law]) -> BTreeMap<String, String> {
let mut out = BTreeMap::new();
for law in laws {
out.insert(law.id.clone(), law.pin_text());
for al in &law.clauses {
if let Some(letter) = &al.letter {
out.insert(
format!("{}.{letter}", law.id),
format!("{}\n{}", law.pin_text(), al.pin_body()),
);
}
}
}
out
}
fn unchanged(&self, address: &str) -> Result<bool> {
let (project, local) = match address.rsplit_once(':') {
Some((project, local)) => (project, local),
None => ("", address),
};
let mut read = self.read.borrow_mut();
if !read.contains_key(project) {
let dir = match project {
"" => self.root.to_path_buf(),
project => {
let top =
PathBuf::from(git_stdout(self.root, &["rev-parse", "--show-toplevel"])?);
if project == "." {
top
} else {
top.join(project)
}
}
};
let then = crate::published::at(&dir, &self.ends.old_rev)?;
let now = match &self.ends.new_rev {
Some(rev) => crate::published::at(&dir, rev)?.laws().to_vec(),
None => parse::scan_root(&dir)?.laws,
};
read.insert(
project.to_string(),
[Self::texts(then.laws()), Self::texts(&now)],
);
}
let [then, now] = &read[project];
Ok(then
.get(local)
.is_some_and(|text| now.get(local) == Some(text)))
}
fn changed(&self, address: &str) -> Result<bool> {
self.unchanged(address)?;
let (project, local) = address.rsplit_once(':').unwrap_or(("", address));
let [then, now] = &self.read.borrow()[project];
Ok(then
.get(local)
.zip(now.get(local))
.is_some_and(|(then, now)| attached_moved(then, now)))
}
}
struct Side {
files: BTreeMap<PathBuf, span::CodeFile>,
markers: BTreeMap<PathBuf, Vec<span::SpanMarker>>,
follow: FollowIndex,
}
impl Side {
fn of(sources: Vec<(PathBuf, String)>, tests: &TestPaths, reuse: Option<&Side>) -> Self {
let parsed = crate::par::map(
sources,
|(_, text)| text.len(),
|(rel, text)| match reuse.and_then(|side| side.files.get(&rel)) {
Some(file) if file.text == text => file.clone(),
_ => span::CodeFile::new(rel, text),
},
);
let follow = FollowIndex::from_files(&parsed, tests);
let markers = parsed
.iter()
.map(|f| (f.rel.clone(), f.span_markers()))
.collect();
let files = parsed.into_iter().map(|f| (f.rel.clone(), f)).collect();
Self {
files,
markers,
follow,
}
}
}
pub struct Tree {
side: Side,
texts: BTreeMap<String, String>,
}
impl Tree {
pub fn at(root: &Path, rev: &str) -> Result<Self> {
Self::at_reusing(root, rev, None)
}
pub fn at_reusing(root: &Path, rev: &str, now: Option<&Tree>) -> Result<Self> {
let project = walk::Project::at(root)?;
let entries: Vec<(String, PathBuf)> = git_lines(root, &["ls-tree", "-r", rev, "--", "."])?
.into_iter()
.filter_map(|line| {
let text = line.to_string_lossy().into_owned();
let (meta, path) = text.split_once('\t')?;
let mut fields = meta.split(' ');
let (mode, blob) = (fields.next()?, fields.nth(1)?);
let blob = matches!(mode, "100644" | "100755").then(|| blob.to_string());
Some((blob.unwrap_or_default(), PathBuf::from(path)))
})
.collect();
let blobs: BTreeMap<&Path, &str> = entries
.iter()
.map(|(blob, rel)| (rel.as_path(), blob.as_str()))
.collect();
let listed: Vec<PathBuf> = entries.iter().map(|(_, rel)| rel.clone()).collect();
let code: Vec<PathBuf> = listed
.iter()
.filter(|rel| walk::walks_to(&project, rel))
.cloned()
.collect();
let held = |rel: &Path| {
let text = now?.side.files.get(rel)?.text.as_str();
let blob = blobs.get(rel).filter(|blob| !blob.is_empty())?;
(crate::workspace::blob_id(text.as_bytes()) == *blob).then(|| text.to_string())
};
let sources = side_sources(&code, |rels| {
let mut texts: Vec<Option<String>> = rels.iter().map(|rel| held(rel)).collect();
let missing: Vec<PathBuf> = rels
.iter()
.zip(&texts)
.filter(|(_, text)| text.is_none())
.map(|(rel, _)| rel.clone())
.collect();
let mut read = git_show_all(root, rev, &missing).into_iter();
for text in texts.iter_mut().filter(|text| text.is_none()) {
*text = read.next().flatten();
}
texts
});
let notes: Vec<PathBuf> = listed
.into_iter()
.filter(|rel| project.is_note(rel))
.collect();
let read = git_show_all(root, rev, ¬es);
let notes: Vec<(PathBuf, String)> = notes
.into_iter()
.zip(read)
.filter_map(|(rel, text)| Some((rel, text?)))
.collect();
Ok(Self {
side: Side::of(sources, &TestPaths::at(root)?, now.map(|tree| &tree.side)),
texts: AddressTexts::texts(&parse::scan_notes(¬es).laws),
})
}
}
impl Tree {
pub fn of(files: Vec<span::CodeFile>, follow: FollowIndex, laws: &[parse::Law]) -> Self {
let markers = files
.iter()
.map(|f| (f.rel.clone(), f.span_markers()))
.collect();
let files = files.into_iter().map(|f| (f.rel.clone(), f)).collect();
Self {
side: Side {
files,
markers,
follow,
},
texts: AddressTexts::texts(laws),
}
}
pub fn text(&self, rel: &Path) -> Option<&str> {
self.side.files.get(rel).map(|f| f.text.as_str())
}
pub fn pin(&self, pin: &marker::MarkerAddr, prefer: &Path) -> Option<(PathBuf, usize, String)> {
let at = |rel: &PathBuf| {
let hits: Vec<usize> = self
.side
.markers
.get(rel)?
.iter()
.filter(|m| &m.addr == pin)
.map(|m| m.line)
.collect();
match hits.as_slice() {
[line] => Some(*line),
_ => None,
}
};
let rel = match at(&prefer.to_path_buf()) {
Some(_) => prefer.to_path_buf(),
None => {
let found: Vec<&PathBuf> = self
.side
.markers
.keys()
.filter(|rel| at(rel).is_some())
.collect();
match found.as_slice() {
[rel] => (*rel).clone(),
_ => return None,
}
}
};
let line = at(&rel)?;
let bit = self.text(&rel)?.lines().nth(line - 1)?.trim().to_string();
Some((rel, line, bit))
}
}
pub struct PinAt<'a> {
pub path: &'a str,
pub text: &'a str,
pub line: usize,
pub bit: &'a str,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Moved {
pub span: bool,
pub prefix: bool,
pub above: bool,
pub callee: bool,
pub import: bool,
pub text: bool,
pub callees: Vec<(String, String)>,
pub left: Vec<(String, String)>,
}
pub fn fallback_moved(
address: &str,
(then, old): (&Tree, &str),
(now, new): (&Tree, PinAt),
) -> Option<(bool, bool)> {
let rel = Path::new(new.path);
let old_line = 1 + old.lines().position(|line| line.trim() == new.bit)?;
let span =
|text: &str, line: usize| extract_punched(rel, text, line).map(|s| strip_digests(&s));
let text = |tree: &Tree| tree.texts.get(address).map(|t| crate::hash::pin_canon(t));
Some((
span(old, old_line)? != span(new.text, new.line)?,
text(then) != text(now),
))
}
pub fn moved(address: &str, old: (&Tree, PinAt), new: (&Tree, PinAt)) -> Result<Moved> {
let side = |(tree, pin): &(&Tree, PinAt)| {
span_side(pin.path, pin.text, (Some(pin.line), pin.bit), &tree.side)
};
let (then, now) = (side(&old)?, side(&new)?);
let imports = |span: &SpanSide| -> BTreeSet<String> {
span.blob
.lines()
.filter(|line| line.starts_with("ยงimport "))
.map(str::to_string)
.collect()
};
let text = |tree: &Tree| tree.texts.get(address).map(|t| crate::hash::pin_canon(t));
let (left, callees): (Vec<CalleeDiff>, Vec<CalleeDiff>) =
callee_diffs(&then, &now, new.1.path, &new.0.side.follow)
.into_iter()
.partition(|c| c.new.is_none() && now.left.contains_key(&c.name));
let reads = read_diffs(new.1.path, &then.reads, &now.reads).0;
let is_above = |d: &CalleeDiff| d.read == Some(span_lang::Read::Above);
let span = strip_digests(&then.span) != strip_digests(&now.span);
let prefix = reads.iter().any(|d| !is_above(d));
let above = reads.iter().any(is_above);
let import = imports(&then) != imports(&now);
let text = text(old.0) != text(new.0);
Ok(Moved {
span,
prefix,
above,
callee: !callees.is_empty() || !left.is_empty(),
import,
text,
callees: callees.into_iter().map(|c| (c.name, c.path)).collect(),
left: left
.into_iter()
.map(|c| (c.name.clone(), now.left[&c.name].clone()))
.collect(),
})
}
fn drift_of(
change: &Change,
files: &FileMap,
old: &Side,
new: &Side,
text_moved: bool,
) -> Result<Option<Change>> {
let (Some(old_path), Some(new_path), Some(old_bit), Some(new_bit)) = (
change.old_path.as_deref(),
change.new_path.as_deref(),
change.old_text.as_deref(),
change.new_text.as_deref(),
) else {
bail!("ยง {} cannot be weighed: a side has no pin", change.address);
};
let old_span = span_side(
old_path,
side_text(files, old, old_path, true)?,
(change.lines[0], old_bit),
old,
)?;
let new_span = span_side(
new_path,
side_text(files, new, new_path, false)?,
(change.lines[1], new_bit),
new,
)?;
let (mut reads, reads_why) = read_diffs(new_path, &old_span.reads, &new_span.reads);
let callees = callee_diffs(&old_span, &new_span, new_path, &new.follow);
let same_span = strip_digests(&old_span.span) == strip_digests(&new_span.span);
let renamed = if !callees.is_empty() {
same_span.then(|| CALLEE_EDIT.to_string())
} else {
(same_span && reads.is_empty() && old_span.names != new_span.names)
.then(|| REBOUND.to_string())
};
if same_span
&& old_span.blob == new_span.blob
&& old_span.binding == new_span.binding
&& callees.is_empty()
&& reads.is_empty()
&& renamed.is_none()
&& !text_moved
{
return Ok(None);
}
reads.extend(callees);
let moved = match (&old_span.binding, &new_span.binding) {
(Some(then), Some(now)) if then != now => Some(format!(
"The marker moved from `{}` to `{}`, a construct that reads alike, or that construct was renamed: a comparing `check` pairs a pin only within the constructs that held it.",
then.join("::"),
now.join("::")
)),
_ => None,
};
let kind = if change.old_text == change.new_text && moved.is_none() {
Kind::Drift
} else {
Kind::Accepted
};
Ok(Some(Change {
kind,
old_text: Some(old_span.span),
new_text: Some(new_span.span),
callees: reads,
why: joined_notes(
joined_notes(moved.or(change.why.clone()), reads_why),
renamed,
),
..change.clone()
}))
}
fn callee_drifts(
files: &FileMap,
old: &Side,
new: &Side,
texts: &AddressTexts,
) -> Result<Vec<Change>> {
let mut out = Vec::new();
for (rel, file) in &new.files {
let path = path_of(rel);
if files.contains_key(&path) {
continue;
}
let markers = file.span_markers();
for marker in &markers {
if marker.addr.digest.is_none() {
continue;
}
let punch = span::punch_of(&markers, marker.line);
let text_moved = texts.changed(&marker.addr.display())?;
let prefix = file.prefix(marker.start, marker.end);
if !text_moved
&& old
.follow
.pin_blob(rel, marker.start, marker.end, &punch, &prefix)
== new
.follow
.pin_blob(rel, marker.start, marker.end, &punch, &prefix)
{
continue;
}
let bit = file
.text
.lines()
.nth(marker.line - 1)
.map(|line| line.trim().to_string());
let change = Change {
address: marker.addr.display(),
kind: Kind::Marker,
old_path: Some(path.clone()),
new_path: Some(path.clone()),
old_text: bit.clone(),
new_text: bit,
callees: Vec::new(),
lines: [Some(marker.line), Some(marker.line)],
why: None,
};
out.extend(
drift_of(&change, files, old, new, text_moved)?.map(|mut drift| {
if text_moved && drift.why.is_none() && unshown(&drift) {
drift.why = Some(TEXT_MOVE.to_string());
}
drift
}),
);
}
}
Ok(out)
}
fn side_text<'a>(files: &'a FileMap, side: &'a Side, path: &str, old: bool) -> Result<&'a str> {
let text = match files.get(path) {
Some((before, after)) => if old { before } else { after }.as_deref(),
None => side
.files
.get(Path::new(path))
.map(|file| file.text.as_str()),
};
text.with_context(|| format!("{path} cannot be read on the {} side", side_name(old)))
}
fn side_name(old: bool) -> &'static str {
if old {
"comparison"
} else {
"compared"
}
}
struct SpanSide {
span: String,
blob: String,
names: Vec<String>,
callees: Vec<(String, String, usize, String)>,
binding: Option<Vec<String>>,
reads: Vec<(span_lang::Read, String, String)>,
left: BTreeMap<String, String>,
}
fn read_stretches(
file: &span::CodeFile,
start: usize,
end: usize,
) -> Vec<(span_lang::Read, String, String)> {
if !file.parsed() {
return Vec::new();
}
file.memo(&("read stretches", start, end), || {
read_stretches_of(file, start, end)
})
}
fn read_stretches_of(
file: &span::CodeFile,
start: usize,
end: usize,
) -> Vec<(span_lang::Read, String, String)> {
let (Some(lang), Some(tree)) = (file.lang, file.tree()) else {
return Vec::new();
};
let text = file.text.as_str();
span_lang::read_stretches(lang, text, tree, start, end)
.into_iter()
.map(|(read, (from, to, punch))| {
let punched = |at: usize| punch.iter().any(|&(s, e)| s <= at && at < e);
let mut read_text = String::new();
for (at, c) in text[from..to].char_indices() {
if !punched(from + at) {
read_text.push(c);
}
}
let mut shown = String::new();
let mut at = text[..from].rfind('\n').map_or(0, |nl| nl + 1);
for line in text[at..].split_inclusive('\n') {
if at >= to {
break;
}
let kept = line.char_indices().any(|(i, c)| {
!c.is_whitespace() && (from..to).contains(&(at + i)) && !punched(at + i)
});
if kept {
shown.push_str(line.trim_end_matches(['\n', '\r']));
shown.push('\n');
}
at += line.len();
}
let read_text = strip_digests(&read_text)
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
(read, shown, read_text)
})
.collect()
}
fn read_diffs(
path: &str,
old: &[(span_lang::Read, String, String)],
new: &[(span_lang::Read, String, String)],
) -> (Vec<CalleeDiff>, Option<String>) {
let by_read = |side: &[(span_lang::Read, String, String)]| {
let mut out: BTreeMap<span_lang::Read, (String, Vec<String>)> = BTreeMap::new();
for (read, shown, text) in side {
let entry = out.entry(*read).or_default();
entry.0.push_str(shown);
entry.1.push(text.clone());
}
out
};
let (old, new) = (by_read(old), by_read(new));
let reads: BTreeSet<&span_lang::Read> = old.keys().chain(new.keys()).collect();
let diffs: Vec<CalleeDiff> = reads
.into_iter()
.filter(|read| old.get(*read).map(|o| &o.1) != new.get(*read).map(|n| &n.1))
.map(|read| CalleeDiff {
name: read_label(*read).to_string(),
path: path.to_string(),
old: old.get(read).map(|o| o.0.clone()),
new: new.get(read).map(|n| n.0.clone()),
why: None,
read: Some(*read),
})
.collect();
let why = (!diffs.is_empty()).then(|| {
let names: Vec<&str> = diffs.iter().map(|d| d.name.as_str()).collect();
format!(
"Beyond the span, the digest reads the {}, which changed.",
names.join(" and the ")
)
});
(diffs, why)
}
fn read_key(read: span_lang::Read) -> &'static str {
use span_lang::Read;
match read {
Read::Prefix => "prefix",
Read::Attribute => "attribute",
Read::Above => "above",
}
}
fn read_label(read: span_lang::Read) -> &'static str {
use span_lang::Read;
match read {
Read::Prefix => "code before the span in its function",
Read::Attribute => "attributes that govern the span",
Read::Above => "keys and entries above the span",
}
}
fn span_side(
path: &str,
text: &str,
(at, bit): (Option<usize>, &str),
side: &Side,
) -> Result<SpanSide> {
let rel = Path::new(path);
let written = |idx: usize| text.lines().nth(idx).is_some_and(|line| line.trim() == bit);
let line = match at {
Some(line) => line.checked_sub(1).filter(|&idx| written(idx)),
None => text.lines().position(|line| line.trim() == bit),
}
.with_context(|| format!("{path}: the pin `{bit}` is not in the file"))?
+ 1;
let unreadable = || format!("{path}:{line}: the span of `{bit}` cannot be read");
if span_lang::lang_for_path(rel).is_none() {
return Ok(SpanSide {
span: extract_punched(rel, text, line).with_context(unreadable)?,
blob: String::new(),
names: Vec::new(),
callees: Vec::new(),
binding: None,
reads: Vec::new(),
left: BTreeMap::new(),
});
}
let markers = side.markers.get(rel).with_context(unreadable)?;
let (span, (start, end), punch) = punched_in(text, markers, line).with_context(unreadable)?;
let file = side.files.get(rel);
let prefix = file.map_or_else(Vec::new, |file| file.prefix(start, end));
let followed = side
.follow
.followed_callees(rel, start, end, &punch, &prefix);
let callees = followed
.into_iter()
.map(|callee| {
let text = side.files.get(&callee.path).map(|file| file.text.as_str());
let at = text
.and_then(|t| t.get(..callee.start))
.map_or(1, |before| before.matches('\n').count() + 1);
let body = text
.and_then(|t| t.get(callee.start..callee.end))
.with_context(|| {
format!(
"{path}:{line}: the callee {} in {} cannot be read",
callee.name,
callee.path.display()
)
})?;
Ok((callee.name, path_of(&callee.path), at, body.to_string()))
})
.collect::<Result<_>>()?;
Ok(SpanSide {
span,
blob: side.follow.pin_blob(rel, start, end, &punch, &prefix),
names: side
.follow
.name_tokens(rel, start, end, &punch, &prefix)
.into_iter()
.collect::<BTreeMap<_, _>>()
.into_values()
.collect(),
callees,
binding: file.and_then(|file| file.binding(start, end)),
reads: file.map_or_else(Vec::new, |file| read_stretches(file, start, end)),
left: side
.follow
.outside_cone(rel, start, end, &punch)
.into_iter()
.map(|(name, decl)| (name, path_of(&decl)))
.collect(),
})
}
type Extent = (usize, usize);
fn punched_in(
text: &str,
markers: &[span::SpanMarker],
marker_line: usize,
) -> Option<(String, Extent, Vec<Extent>)> {
let lines = |(start, end): (usize, usize)| {
(end > start).then(|| (byte_line(text, start), byte_line(text, end - 1)))
};
let outer = markers.iter().find(|l| l.line == marker_line)?;
let (start, end) = lines((outer.start, outer.end))?;
let mut keep: BTreeSet<usize> = (start..=end).collect();
let punch = span::punch_of(markers, marker_line);
for &inner in &punch {
if let Some((inner_start, inner_end)) = lines(inner) {
for line in inner_start..=inner_end {
keep.remove(&line);
}
}
}
keep.insert(marker_line);
let mut span = String::new();
for (idx, line) in text.lines().enumerate() {
if keep.contains(&(idx + 1)) {
span.push_str(line);
span.push('\n');
}
}
Some((span, (outer.start, outer.end), punch))
}
fn callee_diffs(
old_span: &SpanSide,
new_span: &SpanSide,
caller: &str,
follow: &FollowIndex,
) -> Vec<CalleeDiff> {
let (old, new) = (&old_span.callees[..], &new_span.callees[..]);
let index = |side: &[(String, String, usize, String)]| {
let mut bodies: BTreeMap<(String, String), Vec<(usize, &str)>> = BTreeMap::new();
for (name, path, at, body) in side {
bodies
.entry((path.clone(), name.clone()))
.or_default()
.push((*at, body));
}
let out: BTreeMap<(String, String), String> = bodies
.into_iter()
.map(|(key, bodies)| {
let text = match bodies.as_slice() {
[(_, body)] => body.to_string(),
_ => bodies
.iter()
.map(|(at, body)| format!("{at}: {body}"))
.collect::<Vec<_>>()
.join("\n"),
};
(key, text)
})
.collect();
out
};
let (mut old, new) = (index(old), index(new));
let only = |a: &BTreeMap<(String, String), String>, b: &BTreeMap<(String, String), String>| {
let mut by_name: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
for key in a.keys().filter(|k| !b.contains_key(*k)) {
by_name.entry(key.1.clone()).or_default().push(key.clone());
}
by_name
};
let (gone, came) = (only(&old, &new), only(&new, &old));
for (name, from) in gone {
let to = came.get(&name).map_or(&[][..], Vec::as_slice);
if let ([from], [to]) = (from.as_slice(), to) {
if let Some(body) = old.remove(from) {
old.insert(to.clone(), body);
}
}
}
let keys: BTreeSet<&(String, String)> = old.keys().chain(new.keys()).collect();
let read = |bodies: &BTreeMap<(String, String), String>, key: &(String, String)| {
bodies.get(key).map(|body| strip_digests(body))
};
keys.into_iter()
.filter(|key| read(&old, key) != read(&new, key))
.map(|(path, name)| CalleeDiff {
name: name.clone(),
path: path.clone(),
old: old.get(&(path.clone(), name.clone())).cloned(),
new: new.get(&(path.clone(), name.clone())).cloned(),
why: (!new.contains_key(&(path.clone(), name.clone()))).then(|| {
match new_span.left.get(name) {
Some(decl) => left_cone(name, decl, caller),
None => unfollowed(name, follow),
}
}),
read: None,
})
.collect()
}
fn left_cone(name: &str, decl: &str, caller: &str) -> String {
format!(
"No longer followed: the one declaration of `{name}`, in {decl}, lies outside the directory of {caller} and its subdirectories, where a call follows a declaration with no mark, and no `follow` or `functional` mark pulls it in."
)
}
fn unfollowed(name: &str, follow: &FollowIndex) -> String {
let mut paths: Vec<String> = follow
.declarations_of(name)
.iter()
.map(|p| path_of(p))
.collect();
paths.sort();
paths.dedup();
if paths.is_empty() {
if let Some((path, line)) = follow.swallowing(name) {
return format!(
"No longer followed: {} does not parse with the tree-sitter grammar at line {line}, where error recovery may have swallowed a declaration of `{name}`.",
path_of(path)
);
}
return format!("No longer followed: the compared side declares no `{name}`.");
}
format!(
"No longer followed: `{name}` is still declared in {}, and the span no longer reaches it through a followed call: the name has more than one candidate, the declaration left the cone of the caller, or a follow mark, a marker over its whole body or the call changed.",
paths.join(", ")
)
}
fn recalls(scan: &Scan, marked: &BTreeSet<String>, changes: &[Change]) -> Vec<Change> {
let recalled: BTreeSet<&str> = changes
.iter()
.filter(|c| !c.is_marker())
.map(|c| c.address.as_str())
.collect();
let mut out = Vec::new();
for law in &scan.laws {
let mut recall = |address: String, path: &Path, text: &str| {
if marked.contains(&address) && !recalled.contains(address.as_str()) {
out.push(Change {
address,
kind: Kind::Recall,
old_path: Some(path_of(path)),
new_path: Some(path_of(path)),
old_text: Some(text.to_string()),
new_text: Some(text.to_string()),
callees: Vec::new(),
lines: [None, None],
why: None,
});
}
};
recall(law.id.clone(), &law.loc.path, &law.pin_text());
for al in &law.clauses {
if let Some(letter) = &al.letter {
let text = match al.header.is_empty() {
true => al.text.clone(),
false => format!("{}\n{}", al.header, al.text),
};
recall(format!("{}.{letter}", law.id), &al.loc.path, &text);
}
}
}
out
}
fn weighed_pin(change: &Change) -> bool {
change.kind == Kind::Marker
&& change
.old_text
.as_deref()
.zip(change.new_text.as_deref())
.is_some_and(|(old, new)| {
is_pinned(old) && is_pinned(new) && strip_digests(old) == strip_digests(new)
})
}
fn strip_digests(text: &str) -> String {
static DIGEST_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(&format!("@{}", crate::marker::DIGEST)).expect("digest token")
});
DIGEST_RE.replace_all(text, "@DIGEST").to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_callee_hidden_by_a_parse_error_is_named_as_such_not_as_undeclared() {
let helpers = "def other(x):\n return [x,\n\n\ndef cap(charge):\n return charge\n";
let follow = FollowIndex::from_sources(
&[(PathBuf::from("src/helpers.py"), helpers.to_string())],
&crate::policy::TestPaths::conventions(),
);
assert_eq!(
unfollowed("cap", &follow),
"No longer followed: src/helpers.py does not parse with the tree-sitter grammar at line 2, where error recovery may have swallowed a declaration of `cap`."
);
assert_eq!(
unfollowed("gone", &follow),
"No longer followed: the compared side declares no `gone`."
);
}
#[test]
fn the_stretches_a_drift_reads_print_in_the_order_the_law_lists_their_kinds() {
let read = |kind: span_lang::Read| CalleeDiff {
name: read_label(kind).to_string(),
path: "src/lib.rs".into(),
old: Some("a".into()),
new: Some("b".into()),
why: None,
read: Some(kind),
};
let mut drift = change(
"abcdefgh1.a",
Kind::Drift,
Some("// ยง abcdefgh1.a@aaaaa"),
Some("// ยง abcdefgh1.a@aaaaa"),
);
drift.callees = vec![
read(span_lang::Read::Attribute),
read(span_lang::Read::Prefix),
];
let out = render_diff(&[drift]);
let at = |kind| {
out.find(&format!("@@ {}\n", read_label(kind)))
.unwrap_or_else(|| panic!("{out}"))
};
assert!(
at(span_lang::Read::Prefix) < at(span_lang::Read::Attribute),
"{out}"
);
}
fn statuses(changes: &[Change]) -> Vec<(String, review::Status)> {
review_of(changes, &FileMap::new(), &FollowIndex::default(), "")
.rules
.into_iter()
.map(|rule| (rule.id, rule.status))
.collect()
}
#[test]
fn json_strings_escape_every_control_character() {
let raw = "a\u{1}b\tc\"d\\e\nf\u{1f}";
let parsed: String = serde_json::from_str(&json_escape(raw)).unwrap();
assert_eq!(parsed, raw);
}
#[test]
fn the_review_opens_with_the_block_as_each_side_writes_it() {
let rows = vec![BlockRow {
path: "AGENTS.md".to_string(),
attr: "default-branch",
old: Some("main".to_string()),
new: Some("evil".to_string()),
}];
let review =
review::Review::gather("HEAD".into(), Vec::new(), 0, rows, Vec::new(), Vec::new());
let out = review::review_markdown(&review);
assert!(out.contains("\n## Silcrow block changed\n"), "{out}");
assert!(out.contains("--- a/AGENTS.md\n"), "{out}");
assert!(out.contains("\n-default-branch=\"main\"\n"), "{out}");
assert!(out.contains("\n+default-branch=\"evil\"\n"), "{out}");
let json: serde_json::Value =
serde_json::from_str(&review::review_json(&review, &BTreeMap::new())).unwrap();
assert_eq!(json["block"][0]["new"], "evil", "{json}");
}
use std::path::Path;
#[test]
fn a_marker_or_an_end_inside_a_string_is_neither_to_diff() {
let rs = "fn f() {\n // ยง abcdefgh1.a@aaaaa\n let s = r\"\n// ยง abcdefgh1.a@bbbbb\n// ยง end abcdefgh1.a\n\";\n go();\n}\n";
let pins = marker_pins(Path::new("src/a.rs"), rs, None);
assert_eq!(
pins["abcdefgh1.a"],
vec![(2, "// ยง abcdefgh1.a@aaaaa".into())]
);
assert_eq!(pin_lines(Path::new("src/a.rs"), rs, "abcdefgh1.a"), vec![2]);
assert_eq!(
line_span(Path::new("src/a.rs"), rs, 2).map(|s| s.1),
Some(8)
);
let kt =
"// ยง abcdefgh1.a@aaaaa\nval x = \"\"\"\n// ยง end abcdefgh1.a\n\"\"\"\nval y = 1\n";
assert_eq!(line_span(Path::new("src/a.kt"), kt, 1), Some((2, 5)));
}
#[test]
fn declared_law_and_clause_are_changes() {
let old = Scan::default();
let new = parse::scan_text(
Path::new("docs/decisions/n.md"),
"## T\n\n**ยง abcdefgh1 Binding sentence.**\n- (a) First clause.\n",
);
let changes = collect_law_changes(&old, &new);
assert!(changes
.iter()
.any(|c| c.address == "abcdefgh1" && c.kind == Kind::Declared));
assert!(changes
.iter()
.any(|c| c.address == "abcdefgh1.a" && c.kind == Kind::Clause));
}
#[test]
fn a_struck_law_active_again_reads_as_revived() {
let path = Path::new("docs/decisions/n.md");
let old = parse::scan_text(
path,
"## T\n\n**ยง abcdefgh1 ~~Binding sentence.~~**\n\n- (a) Retry twice.\n",
);
let new = parse::scan_text(
path,
"## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) Retry twice.\n",
);
let changes = collect_law_changes(&old, &new);
let revived = changes.iter().find(|c| c.address == "abcdefgh1").unwrap();
assert_eq!(revived.kind, Kind::Reused, "{changes:?}");
assert_eq!(revived.old_text.as_deref(), Some("~~Binding sentence.~~"));
assert!(revived.new_text.as_deref().unwrap().contains("Revives"));
assert_eq!(statuses(&changes)[0].1, review::Status::New);
}
#[test]
fn a_draft_mark_added_or_dropped_reads_as_its_transition_and_no_text_change() {
let path = Path::new("docs/decisions/n.md");
let owed = "## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) One.\n\n- (b) Two.\n";
let draft = "## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) One.\n\n- (b)? Two.\n";
let (o, d) = (parse::scan_text(path, owed), parse::scan_text(path, draft));
let made = collect_law_changes(&o, &d);
assert_eq!(made.len(), 1, "{made:?}");
assert_eq!(made[0].kind, Kind::Draft);
assert_eq!(made[0].address, "abcdefgh1.b");
assert_eq!(
[made[0].old_text.as_deref(), made[0].new_text.as_deref()],
[Some("Two."), Some("Two.")]
);
assert_eq!(statuses(&made)[0].1, review::Status::Drafted);
let dropped = collect_law_changes(&d, &o);
assert_eq!(dropped.len(), 1, "{dropped:?}");
assert_eq!(statuses(&dropped)[0].1, review::Status::New);
assert!(render_diff(&made).contains(DRAFT_MADE));
let tty = review::review_tty(&review_of(
&made,
&BTreeMap::new(),
&FollowIndex::default(),
"",
));
assert!(tty.contains("+(b)? Two."), "{tty}");
assert!(tty.contains("-(b) Two."), "{tty}");
}
#[test]
fn a_burned_letter_declared_again_reads_as_reused() {
let path = Path::new("docs/decisions/n.md");
let old = parse::scan_text(
path,
"## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) ~~Retry twice.~~\n",
);
let new = parse::scan_text(
path,
"## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) Never retry.\n",
);
let changes = collect_law_changes(&old, &new);
let reused = changes.iter().find(|c| c.address == "abcdefgh1.a").unwrap();
assert_eq!(reused.kind, Kind::Reused, "{changes:?}");
assert_eq!(reused.old_text.as_deref(), Some("~~Retry twice.~~"));
assert!(reused.new_text.as_deref().unwrap().contains("burned"));
assert_eq!(statuses(&changes)[0].1, review::Status::New);
}
#[test]
fn amended_clause_keeps_law_quiet() {
let old = parse::scan_text(
Path::new("docs/decisions/n.md"),
"## T\n\n**ยง abcdefgh1 Binding sentence.**\n- (a) First clause.\n",
);
let new = parse::scan_text(
Path::new("docs/decisions/n.md"),
"## T\n\n**ยง abcdefgh1 Binding sentence.**\n- (a) First clause, narrowed.\n",
);
let changes = collect_law_changes(&old, &new);
assert!(changes
.iter()
.all(|c| c.address != "abcdefgh1" || c.kind == Kind::Clause));
assert_eq!(changes.len(), 1);
assert!(changes.iter().any(|c| c.address == "abcdefgh1.a"));
}
fn note_changes(old: &str, new: &str) -> Vec<Change> {
let path = Path::new("docs/decisions/n.md");
collect_law_changes(&parse::scan_text(path, old), &parse::scan_text(path, new))
}
#[test]
fn a_remint_reads_the_old_markers_under_the_new_id_and_leaves_a_qualified_one() {
let remint = BTreeMap::from([("abcdefgh4".to_string(), "abcdefgh5".to_string())]);
let text = "fn f() {\n // ยง abcdefgh4.a@aaaaa\n go();\n // ยง end abcdefgh4.a\n // ยง libs/x:abcdefgh4@bbbbb\n let s = \"abcdefgh4\";\n}\n";
assert_eq!(
as_reminted(Path::new("src/f.rs"), text.to_string(), &remint),
"fn f() {\n // ยง abcdefgh5.a@aaaaa\n go();\n // ยง end abcdefgh5.a\n // ยง libs/x:abcdefgh4@bbbbb\n let s = \"abcdefgh4\";\n}\n"
);
let path = Path::new("docs/decisions/n.md");
let old = parse::scan_text(path, "**ยง abcdefgh1 One.**\n\n**ยง abcdefgh2 Two.**\n");
let new = parse::scan_text(
path,
"**ยง abcdefgh3<a id=\"abcdefgh1\"></a><a id=\"abcdefgh2\"></a> Both.**\n",
);
assert!(reminted(&old, &new).is_empty());
}
#[test]
fn a_struck_law_retires_it_and_its_active_clauses() {
let changes = note_changes(
"**ยง abcdefgh1 Binding sentence.**\n- (a) First.\n- (b) ~~Gone.~~\n",
"**ยง abcdefgh1 ~~Binding sentence.~~**\n- (a) First.\n- (b) ~~Gone.~~\n",
);
let retired: Vec<_> = changes
.iter()
.filter(|c| c.kind == Kind::Retired)
.map(|c| (c.address.as_str(), c.old_text.as_deref()))
.collect();
assert_eq!(
retired,
[
("abcdefgh1", Some("Binding sentence.")),
("abcdefgh1.a", Some("First."))
],
"{changes:?}"
);
}
#[test]
fn a_struck_clause_is_retired_a_deleted_one_deleted_and_a_revived_one_reuses_its_letter() {
let changes = note_changes(
"**ยง abcdefgh1 Law.**\n- (a) First.\n- (b) Second.\n- (c) ~~Third.~~\n",
"**ยง abcdefgh1 Law.**\n- (a) ~~First.~~\n- (c) Third.\n",
);
let kinds: Vec<_> = changes
.iter()
.map(|c| (c.address.as_str(), c.kind, c.old_text.is_some()))
.collect();
assert_eq!(
kinds,
[
("abcdefgh1.a", Kind::Retired, true),
("abcdefgh1.b", Kind::Deleted, true),
("abcdefgh1.c", Kind::Reused, true),
]
);
}
#[test]
fn a_strike_a_reword_a_removal_and_a_deletion_each_read_apart() {
let old = "**ยง abcdefgh1 Struck now.**\n- (a) One.\n\n**ยง abcdefgh2 ~~Struck before.~~**\n- (a) ~~Two.~~\n | t |\n\n**ยง abcdefgh3 Deleted.**\n- (a) Three.\n- (b) **Retired.**\n\n**ยง abcdefgh4 Reworded.**\n";
let new = "**ยง abcdefgh1 ~~Struck now.~~**\n- (a) One.\n\n**ยง abcdefgh5<a id=\"abcdefgh4\"></a> Reworded again.**\n";
let path = Path::new("docs/decisions/n.md");
let (old, new) = (parse::scan_text(path, old), parse::scan_text(path, new));
let mut changes = collect_law_changes(&old, &new);
changes.extend(collect_deleted(&old, &new));
changes.sort();
changes.dedup();
let kinds: Vec<_> = changes
.iter()
.map(|c| {
(
c.address.as_str(),
c.kind,
c.old_text.as_deref().unwrap_or(""),
)
})
.collect();
assert_eq!(
kinds,
[
("abcdefgh1", Kind::Retired, "Struck now."),
("abcdefgh1.a", Kind::Retired, "One."),
("abcdefgh2", Kind::Removed, "~~Struck before.~~"),
("abcdefgh2.a", Kind::Removed, "~~Two.~~\n | t |"),
("abcdefgh3", Kind::Deleted, "Deleted."),
("abcdefgh3.a", Kind::Deleted, "Three."),
("abcdefgh3.b", Kind::Deleted, "**Retired.**"),
("abcdefgh5", Kind::Reminted, "Reworded."),
]
);
let order: Vec<(String, &str)> = statuses(&changes)
.into_iter()
.map(|(id, status)| (id, status.status_key()))
.collect();
let want = [
("abcdefgh3", "deleted"),
("abcdefgh1", "retired"),
("abcdefgh2", "removed"),
("abcdefgh5", "reminted"),
]
.map(|(id, key)| (id.to_string(), key));
assert_eq!(order, want);
let tty = render_diff(&changes);
let at = |heading: &str| {
tty.find(heading)
.unwrap_or_else(|| panic!("{heading}\n{tty}"))
};
assert!(at("## ยง abcdefgh3: deleted without a strike") < at("## ยง abcdefgh1: retired"));
assert!(
at("## ยง abcdefgh2: removed after a published strike")
< at("## ยง abcdefgh5: reminted from abcdefgh4 to abcdefgh5")
);
assert!(tty.contains("-~~Struck before.~~"), "{tty}");
}
#[test]
fn a_law_never_active_is_not_new() {
let changes = note_changes("", "**ยง abcdefgh1 ~~Born dead.~~**\n- (a) First.\n");
assert!(changes.is_empty(), "{changes:?}");
}
fn change(address: &str, kind: Kind, old: Option<&str>, new: Option<&str>) -> Change {
let path = if matches!(kind, Kind::Marker | Kind::Drift | Kind::Accepted) {
"src/x.rs"
} else {
"docs/decisions/n.md"
};
Change {
address: address.into(),
kind,
old_path: old.map(|_| path.into()),
new_path: new.map(|_| path.into()),
old_text: old.map(Into::into),
new_text: new.map(Into::into),
callees: Vec::new(),
lines: [None, None],
why: None,
}
}
fn grouped_sample() -> Vec<Change> {
vec![
change("abcdefgh1", Kind::Amended, Some("Old."), Some("New.")),
change("abcdefgh2.a", Kind::Clause, None, Some("Fresh clause.")),
change("abcdefgh3.a", Kind::Recall, Some("Kept."), Some("Kept.")),
change(
"abcdefgh3.a",
Kind::Accepted,
Some("save();\n"),
Some("drop();\n"),
),
change("abcdefgh4.a", Kind::Retired, Some("Struck clause."), None),
change(
"abcdefgh4.a",
Kind::Marker,
Some("// ยง abcdefgh4.a@aaaaa"),
None,
),
]
}
#[test]
fn the_tty_review_is_patches_alone_with_each_law_as_one_hunk_of_its_note() {
let tty = review::review_tty(&review_of(
&grouped_sample(),
&BTreeMap::new(),
&FollowIndex::default(),
"",
));
for prose in ["# Silcrow review", "Check:", "## ", "* `", "ยง", "```"] {
assert!(!tty.contains(prose), "{prose}\n{tty}");
}
assert!(
tty.lines().all(|l| l.is_empty()
|| l.starts_with(['@', ' ', '-', '+'])
|| l.starts_with("diff --git ")),
"{tty}"
);
assert!(tty.contains(" (a) Kept.\n"), "{tty}");
}
#[test]
fn the_review_is_one_entry_per_law_in_order_of_risk() {
let diff = render_diff(&grouped_sample());
let at = |needle: &str| {
diff.find(needle)
.unwrap_or_else(|| panic!("{needle}\n{diff}"))
};
let order = [
at("## ยง abcdefgh4: retired\n"),
at("### abcdefgh4.a: retired\n"),
at("-Struck clause."),
at("## ยง abcdefgh3: behaviour change accepted\n"),
at("### abcdefgh3.a: behaviour change accepted\n"),
at("\n> Kept.\n"),
at("-save();"),
at("+drop();"),
at("## ยง abcdefgh2: new\n"),
at("+Fresh clause."),
at("## ยง abcdefgh1: text changed\n"),
at("-Old."),
at("+New."),
];
assert!(order.windows(2).all(|w| w[0] < w[1]), "{diff}");
assert_eq!(diff.matches("## ยง abcdefgh4").count(), 1, "{diff}");
assert!(
diff.contains("Check: does the code below still do what abcdefgh3.a says?"),
"{diff}"
);
}
#[test]
fn the_json_review_holds_the_same_laws_in_the_same_order() {
let json: serde_json::Value =
serde_json::from_str(&diff_json(Path::new("."), &grouped_sample(), 0)).unwrap();
let laws: Vec<(&str, &str)> = json["laws"]
.as_array()
.unwrap()
.iter()
.map(|law| (law["id"].as_str().unwrap(), law["status"].as_str().unwrap()))
.collect();
assert_eq!(
laws,
[
("abcdefgh4", "retired"),
("abcdefgh3", "accepted"),
("abcdefgh2", "new"),
("abcdefgh1", "text-changed"),
]
);
let clause = &json["laws"][1]["clauses"][0];
assert_eq!(clause["address"], "abcdefgh3.a", "{json}");
assert_eq!(clause["text"]["new"], "Kept.", "{json}");
assert_eq!(
clause["locations"][0]["pins"][0]["kind"], "accepted",
"{json}"
);
assert_eq!(json["laws"][3]["sentence"]["text"]["new"], "New.", "{json}");
assert_eq!(
json["laws"][0]["sentence"]["status"],
serde_json::Value::Null,
"{json}"
);
assert_eq!(json["ungoverned"], serde_json::json!([]), "{json}");
}
#[test]
fn diff_ends_parses_two_dot_range() {
let ends = diff_ends(Path::new("."), "main..HEAD").unwrap();
assert_eq!(ends.old_rev, "main");
assert_eq!(ends.new_rev.as_deref(), Some("HEAD"));
}
#[test]
fn diff_ends_single_ref_uses_worktree() {
let ends = diff_ends(Path::new("."), "HEAD~3").unwrap();
assert_eq!(ends.old_rev, "HEAD~3");
assert!(ends.new_rev.is_none());
}
#[test]
fn an_open_range_reads_head_at_its_missing_end() {
let ends = diff_ends(Path::new("."), "main..").unwrap();
assert_eq!(
(ends.old_rev.as_str(), ends.new_rev.as_deref()),
("main", Some("HEAD"))
);
let ends = diff_ends(Path::new("."), "..main").unwrap();
assert_eq!(
(ends.old_rev.as_str(), ends.new_rev.as_deref()),
("HEAD", Some("main"))
);
}
#[test]
fn an_accept_its_span_does_not_show_prints_why() {
let mut accepted = change(
"abcdefgh1",
Kind::Accepted,
Some("// ยง abcdefgh1@aaaaa\nf();\n"),
Some("// ยง abcdefgh1@bbbbb\nf();\n"),
);
accepted.why = Some(UNSHOWN_MOVE.to_string());
let recall = change("abcdefgh1", Kind::Recall, Some("Law."), Some("Law."));
let diff = render_diff(&[accepted, recall]);
assert!(diff.contains(&format!(" {UNSHOWN_MOVE}")), "{diff}");
}
#[test]
fn diff_all_qualifies_a_nested_project_and_prints_each_law_once() {
let lib = Some("lib".to_string());
assert_eq!(qualify(&lib, "abcdefgh1.a"), "lib:abcdefgh1.a");
assert_eq!(qualify(&lib, ".:abcdefgh1"), "abcdefgh1");
assert_eq!(qualify(&lib, "svc:abcdefgh1"), "svc:abcdefgh1");
assert_eq!(qualify(&None, "abcdefgh1"), "abcdefgh1");
let declared = [change("abcdefgh1", Kind::Declared, None, Some("Law."))];
let none = None;
let mut rules = Vec::new();
for (prefix, key) in [("lib/", &lib), ("", &none)] {
let docs = crate::walk::Patterns::default();
let shown = Shown {
prefix,
key,
docs: &docs,
};
rules.extend(review::law_entries(
&declared,
&FileMap::new(),
&FollowIndex::default(),
&Callers::new(),
&shown,
));
}
let review =
review::Review::gather("HEAD".into(), Vec::new(), 0, Vec::new(), rules, Vec::new());
let diff = review::review_markdown(&review);
assert_eq!(diff.matches("## ยง abcdefgh1: new").count(), 1, "{diff}");
assert_eq!(diff.matches("## ยง lib:abcdefgh1: new").count(), 1, "{diff}");
assert!(
diff.contains("Decision note `lib/docs/decisions/n.md`."),
"{diff}"
);
assert!(
diff.contains("Decision note `docs/decisions/n.md`."),
"{diff}"
);
}
#[test]
fn split_address_keeps_a_dotted_project_path() {
assert_eq!(
split_address("pkg.v2:abcdefgh1.a"),
("pkg.v2:abcdefgh1".to_string(), Some("a".to_string()))
);
assert_eq!(split_address("abcdefgh1"), ("abcdefgh1".to_string(), None));
}
#[test]
fn move_same_text_is_moved() {
let old = parse::scan_text(
Path::new("docs/decisions/old.md"),
"**ยง abcdefgh1 Binding sentence.**\n",
);
let new = parse::scan_text(
Path::new("docs/decisions/new.md"),
"**ยง abcdefgh1 Binding sentence.**\n",
);
let changes = collect_law_changes(&old, &new);
assert_eq!(changes[0].kind, Kind::Moved);
assert_eq!(changes[0].address, "abcdefgh1");
}
fn sample_diff_changes() -> Vec<Change> {
vec![
Change {
address: "abcdefgh1".into(),
kind: Kind::Declared,
old_path: None,
new_path: Some("docs/decisions/cli/cli.md".into()),
old_text: None,
new_text: Some("Binding sentence.".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "abcdefgh1.a".into(),
kind: Kind::Clause,
old_path: None,
new_path: Some("docs/decisions/cli/cli.md".into()),
old_text: None,
new_text: Some("First clause.".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "abcdefgh1.a".into(),
kind: Kind::Marker,
old_path: None,
new_path: Some("src/main.rs".into()),
old_text: None,
new_text: Some("// ยง abcdefgh1.a".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "abcdefgh1.a".into(),
kind: Kind::Marker,
old_path: Some("src/keep.rs".into()),
new_path: Some("src/keep.rs".into()),
old_text: Some("// ยง abcdefgh1.a".into()),
new_text: Some("// ยง abcdefgh1.a".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
]
}
#[test]
fn each_place_is_named_by_its_own_file_under_its_law() {
let diff = render_diff(&sample_diff_changes());
assert!(
diff.contains("diff --git a/src/main.rs b/src/main.rs\n"),
"{diff}"
);
assert!(
diff.contains("diff --git a/src/keep.rs b/src/keep.rs\n"),
"{diff}"
);
assert!(!diff.contains("cli.md#"), "{diff}");
assert!(
diff.contains("Decision note `docs/decisions/cli/cli.md`."),
"{diff}"
);
}
#[test]
fn diff_opens_with_recall_then_markers() {
let diff = render_diff(&sample_diff_changes());
let law_at = diff.find("+Binding sentence.").expect("law recall");
let clause_at = diff.find("+First clause.").expect("clause recall");
let keep_at = diff.find("`src/keep.rs`").expect("unchanged path");
let added_at = diff.find("`src/main.rs`").expect("changed path");
assert!(law_at < clause_at);
assert!(clause_at < keep_at);
assert!(clause_at < added_at);
assert!(!diff.contains("// ยง abcdefgh1.a"), "{diff}");
}
#[test]
fn unchanged_marker_is_context_not_a_minus_plus() {
let diff = render_diff(&sample_diff_changes());
assert!(
diff.contains("`src/keep.rs`: span of abcdefgh1.a, unchanged."),
"{diff}"
);
assert!(!diff.contains("// ยง abcdefgh1.a"), "{diff}");
assert!(
diff.contains("`src/main.rs`: span of abcdefgh1.a, added."),
"{diff}"
);
}
#[test]
fn one_entry_per_law_with_its_clauses_under_it() {
let diff = render_diff(&sample_diff_changes());
assert_eq!(diff.matches("## ยง abcdefgh1: new\n").count(), 1, "{diff}");
assert_eq!(diff.matches("### abcdefgh1.a: new\n").count(), 1, "{diff}");
assert!(diff.find("## ยง abcdefgh1").unwrap() < diff.find("### abcdefgh1.a").unwrap());
}
fn rust_outer(inner: bool, outer_body: &str, inner_body: &str) -> String {
let pin = format!("{} abcdefgh1@aaaaa", "// ยง");
let nested = if inner {
let inner_pin = format!("{} abcdefgh2@bbbbb", "// ยง");
format!(" {{\n {inner_pin}\n {inner_body}\n }}\n")
} else {
String::new()
};
format!("fn outer() {{\n {pin}\n {outer_body}\n{nested}}}\n")
}
#[test]
fn a_removed_pin_carries_its_pin_comment_and_a_vanished_project_finds_its_pins() {
let pin = format!("{} abcdefgh1@aaaaa", "# ยง");
let text = format!("def total(xs):\n {pin}\n return sum(xs)\n");
let path = "libs/money/src/sum.py";
let files: FileMap = BTreeMap::from([(
path.into(),
(
Some(text.clone()),
Some("def total(xs):\n return sum(xs)\n".into()),
),
)]);
let removed = Change {
address: "libs/money:abcdefgh1".into(),
kind: Kind::Marker,
old_path: Some(path.into()),
new_path: None,
old_text: Some(pin.clone()),
new_text: None,
callees: Vec::new(),
lines: [Some(2), None],
why: None,
};
let review = review_of(&[removed], &files, &FollowIndex::default(), "");
let shown = format!(" {pin}\n return sum(xs)\n");
let pin_of = &review.rules[0].head.locations[0].pins[0];
assert_eq!(pin_of.old.as_deref(), Some(shown.as_str()));
assert_eq!(pin_of.kind, "removed");
assert_eq!(
pin_lines(Path::new(path), &text, "libs/money:abcdefgh1"),
[2]
);
assert!(pin_lines(Path::new("src/sum.py"), &text, "libs/money:abcdefgh1").is_empty());
}
fn span_files(old: &str, new: &str) -> FileMap {
BTreeMap::from([(
"src/x.rs".into(),
(Some(old.to_string()), Some(new.to_string())),
)])
}
fn span_changes() -> Vec<Change> {
vec![
Change {
address: "abcdefgh1".into(),
kind: Kind::Amended,
old_path: Some("docs/decisions/n.md".into()),
new_path: Some("docs/decisions/n.md".into()),
old_text: Some("Outer law.".into()),
new_text: Some("Outer law, amended.".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "abcdefgh1".into(),
kind: Kind::Marker,
old_path: Some("src/x.rs".into()),
new_path: Some("src/x.rs".into()),
old_text: Some("// ยง abcdefgh1@aaaaa".into()),
new_text: Some("// ยง abcdefgh1@aaaaa".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
]
}
#[test]
fn span_diff_keeps_change_inside_pin() {
let old = rust_outer(false, "silcrow();", "");
let new = rust_outer(false, "silcrow(x);", "");
let diff = render_diff_with(&span_changes(), &span_files(&old, &new));
assert!(diff.contains("- silcrow();") || diff.contains("-silcrow();"));
assert!(diff.contains("+ silcrow(x);") || diff.contains("+silcrow(x);"));
assert!(diff.contains(" silcrow") || diff.contains("fn outer"));
}
#[test]
fn span_diff_drops_change_outside_pin() {
let old = format!(
"fn other() {{ a(); }}\n{}",
rust_outer(false, "silcrow();", "")
);
let new = format!(
"fn other() {{ b(); }}\n{}",
rust_outer(false, "silcrow();", "")
);
let diff = render_diff_with(&span_changes(), &span_files(&old, &new));
assert!(!diff.contains("b();"), "{diff}");
assert!(
!diff.contains("-fn other") && !diff.contains("+fn other"),
"{diff}"
);
}
#[test]
fn span_diff_punches_nested_inner() {
let old = rust_outer(true, "silcrow();", "lade();");
let new = rust_outer(true, "silcrow();", "lade(x);");
let diff = render_diff_with(&span_changes(), &span_files(&old, &new));
assert!(!diff.contains("lade(x);"), "{diff}");
assert!(diff.contains("silcrow();"), "{diff}");
}
#[test]
fn parsed_spans_punch_as_extract_punched_does() {
let text = rust_outer(true, "silcrow();", "lade();");
let (old, _) = sides(&span_files(&text, &text));
let markers = &old.markers[Path::new("src/x.rs")];
for line in [2, 5] {
let (span, _, _) = punched_in(&text, markers, line).expect("span");
assert_eq!(
Some(span),
extract_punched(Path::new("src/x.rs"), &text, line)
);
}
}
#[test]
fn boundary_drift_lists_caller_laws() {
let pin = format!("{} abcdefgh1@aaaaa", "// ยง");
let caller_pin = format!("{} abcdefgh2@aaaaa", "// ยง");
let tax = |body: &str| format!("fn vat() {{\n {pin}\n {body}\n}}\n");
let invoice = format!("fn total() {{\n {caller_pin}\n vat();\n}}\n");
let (old, new) = (tax("save(1);"), tax("save(2);"));
let follow = FollowIndex::from_sources(
&[
(PathBuf::from("src/tax.rs"), new.clone()),
(PathBuf::from("src/invoice.rs"), invoice),
],
&crate::policy::TestPaths::conventions(),
);
let mut changes = span_changes();
for change in &mut changes {
for path in [&mut change.old_path, &mut change.new_path] {
if path.as_deref() == Some("src/x.rs") {
*path = Some("src/tax.rs".into());
}
}
}
let files = BTreeMap::from([("src/tax.rs".into(), (Some(old), Some(new)))]);
let diff = render_diff_follow(&changes, &files, &follow, "");
assert!(
diff.contains(
" src/tax.rs:2: ยง abcdefgh1 drifted; callers carry ยง abcdefgh2 (src/invoice.rs:2). Re-read them."
),
"{diff}"
);
}
#[test]
fn boundary_drift_through_a_followed_callee_lists_caller_laws() {
let pin = format!("{} abcdefgh1@aaaaa", "// ยง");
let caller_pin = format!("{} abcdefgh2@aaaaa", "// ยง");
let tax = format!("fn vat() {{\n {pin}\n rate();\n}}\n");
let invoice = format!("fn total() {{\n {caller_pin}\n vat();\n}}\n");
let follow = FollowIndex::from_sources(
&[
(PathBuf::from("src/tax.rs"), tax.clone()),
(PathBuf::from("src/invoice.rs"), invoice),
(
PathBuf::from("src/rate.rs"),
"fn rate() {\n two();\n}\n".into(),
),
],
&crate::policy::TestPaths::conventions(),
);
let mut changes = span_changes();
for change in &mut changes {
if change.kind == Kind::Marker {
change.kind = Kind::Drift;
change.old_path = Some("src/tax.rs".into());
change.new_path = Some("src/tax.rs".into());
change.lines = [Some(2), Some(2)];
change.callees = vec![CalleeDiff {
name: "rate".into(),
path: "src/rate.rs".into(),
old: Some("fn rate() {\n one();\n}".into()),
new: Some("fn rate() {\n two();\n}".into()),
why: None,
read: None,
}];
}
}
let untouched = render_diff_follow(&changes, &FileMap::new(), &follow, "");
let touched = render_diff_follow(
&changes,
&BTreeMap::from([("src/tax.rs".into(), (Some(tax.clone()), Some(tax)))]),
&follow,
"",
);
for diff in [untouched, touched] {
assert!(
diff.contains(
"src/tax.rs:2: ยง abcdefgh1 drifted; callers carry ยง abcdefgh2 (src/invoice.rs:2). Re-read them."
),
"{diff}"
);
}
}
fn declared_with_marker(marker: &str) -> Vec<Change> {
vec![
Change {
address: "abcdefgh1".into(),
kind: Kind::Declared,
old_path: None,
new_path: Some("docs/decisions/n.md".into()),
old_text: None,
new_text: Some("New law.".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "abcdefgh1".into(),
kind: Kind::Marker,
old_path: Some("src/x.rs".into()),
new_path: Some("src/x.rs".into()),
old_text: Some(marker.to_string()),
new_text: Some(marker.to_string()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
]
}
#[test]
fn new_recall_does_not_paint_unchanged_span() {
let src = rust_outer(false, "silcrow();", "");
let marker = format!("{} abcdefgh1@aaaaa", "// ยง");
let diff = render_diff_with(&declared_with_marker(&marker), &span_files(&src, &src));
assert!(diff.contains("+New law."), "{diff}");
assert!(!diff.contains("// ยง abcdefgh1"), "{diff}");
assert!(
diff.contains(" silcrow();\n") || diff.contains(" silcrow();"),
"{diff}"
);
assert!(!diff.contains("+ silcrow();"), "{diff}");
assert!(!diff.contains("- silcrow();"), "{diff}");
assert!(!diff.contains("+fn outer"), "{diff}");
assert!(!diff.contains("-fn outer"), "{diff}");
}
#[test]
fn amended_recall_does_not_paint_unchanged_span() {
let src = rust_outer(false, "silcrow();", "");
let mut changes = span_changes();
changes[0].old_text = Some("Old law.".into());
changes[0].new_text = Some("New law.".into());
let diff = render_diff_with(&changes, &span_files(&src, &src));
assert!(diff.contains("-Old law."), "{diff}");
assert!(diff.contains("+New law."), "{diff}");
assert!(!diff.contains("+ silcrow();"), "{diff}");
assert!(!diff.contains("- silcrow();"), "{diff}");
assert!(!diff.contains("// ยง abcdefgh1"), "{diff}");
}
#[test]
fn bare_marker_is_comment_only() {
let pin = format!("{} abcdefgh1", "// ยง");
let src = format!("fn outer() {{\n {pin}\n silcrow();\n}}\n");
let diff = render_diff_with(&declared_with_marker(&pin), &span_files(&src, &src));
assert!(diff.contains("+New law."), "{diff}");
assert!(!diff.contains("// ยง abcdefgh1"), "{diff}");
assert!(!diff.contains("silcrow();"), "{diff}");
assert!(!diff.contains("fn outer"), "{diff}");
}
#[test]
fn retired_recall_is_all_minus() {
let changes = vec![Change {
address: "abcdefgh1".into(),
kind: Kind::Retired,
old_path: Some("docs/decisions/n.md".into()),
new_path: None,
old_text: Some("Gone law.".into()),
new_text: None,
callees: Vec::new(),
lines: [None, None],
why: None,
}];
let diff = render_diff(&changes);
assert!(diff.contains("-Gone law."), "{diff}");
assert!(!diff.contains("+Gone law."), "{diff}");
}
#[test]
fn install_span_is_install_not_run() {
let src = include_str!("plane.rs");
let pin = src
.split("hqv22s05t@")
.nth(1)
.map(|rest| &rest[..5])
.expect("plane.rs pins hqv22s05t");
let files = BTreeMap::from([("src/plane.rs".into(), (None, Some(src.to_string())))]);
let changes = vec![
Change {
address: "hqv22s05t".into(),
kind: Kind::Declared,
old_path: None,
new_path: Some("docs/decisions/harness.md".into()),
old_text: None,
new_text: Some("`silcrow install` writes the skill pointer, and without `--user` also the `AGENTS.md` block and the hooks.".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "hqv22s05t".into(),
kind: Kind::Marker,
old_path: None,
new_path: Some("src/plane.rs".into()),
old_text: None,
new_text: Some(format!("{} hqv22s05t@{pin}", "// ยง")),
callees: Vec::new(),
lines: [None, None],
why: None,
},
];
let diff = render_diff_with(&changes, &files);
assert!(diff.contains("+pub fn install"), "{diff}");
assert!(!diff.contains("// ยง hqv22s05t"), "{diff}");
assert!(diff.contains("install_skill"), "{diff}");
assert!(!diff.contains("pub fn run"), "{diff}");
}
#[test]
fn two_pins_same_law_are_two_spans() {
let pin = format!("{} a2d8n8r1q@dnfcm", "// ยง");
let src = format!(
"\
fn silcrow() {{
{pin}
let _ = r#\"name: \"silcrow\"\"#;
}}
fn skill_state() {{
let leftover = true;
}}
fn lade() {{
{pin}
let _ = r#\"name: \"lade\"\"#;
}}
"
);
let files = BTreeMap::from([(
"src/plane.rs".into(),
(Some(src.to_string()), Some(src.to_string())),
)]);
let changes = vec![
Change {
address: "a2d8n8r1q".into(),
kind: Kind::Amended,
old_path: Some("docs/decisions/plane.md".into()),
new_path: Some("docs/decisions/plane.md".into()),
old_text: Some("Plane.".into()),
new_text: Some("Plane, amended.".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "a2d8n8r1q".into(),
kind: Kind::Marker,
old_path: Some("src/plane.rs".into()),
new_path: Some("src/plane.rs".into()),
old_text: Some(format!("{} a2d8n8r1q@dnfcm", "// ยง")),
new_text: Some(format!("{} a2d8n8r1q@dnfcm", "// ยง")),
callees: Vec::new(),
lines: [None, None],
why: None,
},
];
let diff = render_diff_with(&changes, &files);
assert!(diff.contains("name: \"silcrow\""), "{diff}");
assert!(diff.contains("name: \"lade\""), "{diff}");
assert!(!diff.contains("skill_state"), "{diff}");
}
#[test]
fn declared_change_renders_note_path() {
let old = Scan::default();
let new = parse::scan_text(
Path::new("docs/decisions/n.md"),
"**ยง abcdefgh1 Binding sentence.**\n",
);
let changes = collect_law_changes(&old, &new);
let diff = render_diff(&changes);
assert!(
diff.contains("diff --git a/docs/decisions/n.md b/docs/decisions/n.md\n"),
"{diff}"
);
assert!(
diff.contains(" @@ text of abcdefgh1\n+Binding sentence"),
"{diff}"
);
}
fn sides(files: &FileMap) -> (Side, Side) {
let side = |old: bool| {
Side::of(
files
.iter()
.filter_map(|(path, (before, after))| {
let text = if old { before } else { after };
Some((PathBuf::from(path), text.clone()?))
})
.collect(),
&TestPaths::conventions(),
None,
)
};
(side(true), side(false))
}
fn repin_change(old: &str, new: &str) -> (Change, FileMap) {
let mut files = FileMap::new();
files.insert("src/x.rs".into(), (Some(old.into()), Some(new.into())));
let changes = marker_diff(Path::new("src/x.rs"), [Some(old), Some(new)], [None, None]);
assert_eq!(changes.len(), 1, "{changes:?}");
(changes[0].clone(), files)
}
#[test]
fn repin_over_the_same_span_folds() {
let (change, files) = repin_change(
"fn f() {\n // ยง abcdefgh1@aaaaa\n save();\n}\n",
"fn f() {\n // ยง abcdefgh1@bbbbb\n save();\n}\n",
);
assert!(weighed_pin(&change));
let (old, new) = sides(&files);
assert!(drift_of(&change, &files, &old, &new, false)
.unwrap()
.is_none());
}
#[test]
fn two_pins_written_alike_are_each_weighed_at_their_own_span() {
let src = |second: &str| {
format!("fn f() {{\n // ยง abcdefgh1@aaaaa\n save();\n}}\n\nfn g() {{\n // ยง abcdefgh1@aaaaa\n {second}\n}}\n")
};
let (old, new) = (src("load();"), src("drop();"));
let mut files = FileMap::new();
files.insert("src/x.rs".into(), (Some(old.clone()), Some(new.clone())));
let changes = marker_diff(
Path::new("src/x.rs"),
[Some(&old), Some(&new)],
[None, None],
);
assert_eq!(changes.len(), 2, "{changes:?}");
let (old_side, new_side) = sides(&files);
let drifts: Vec<Change> = changes
.iter()
.filter_map(|c| drift_of(c, &files, &old_side, &new_side, false).unwrap())
.collect();
assert_eq!(drifts.len(), 1, "{drifts:?}");
assert!(drifts[0].new_text.as_deref().unwrap().contains("drop();"));
}
#[test]
fn repin_over_a_changed_span_is_accepted() {
let (change, files) = repin_change(
"fn f() {\n // ยง abcdefgh1@aaaaa\n save();\n}\n",
"fn f() {\n // ยง abcdefgh1@bbbbb\n drop();\n}\n",
);
let (old, new) = sides(&files);
let drift = drift_of(&change, &files, &old, &new, false)
.unwrap()
.expect("drift");
assert_eq!(drift.kind, Kind::Accepted);
assert!(drift.old_text.unwrap().contains("save();"));
assert!(drift.new_text.unwrap().contains("drop();"));
}
#[test]
fn an_accept_shows_each_changed_stretch_it_reads_beside_the_span_and_names_it() {
let src = |guard: &str, digest: &str, body: &str| {
format!("fn f(a: u32) -> u32 {{\n if a > {guard} {{\n return 0;\n }}\n // ยง abcdefgh1@{digest}\n let r = a + {body};\n // ยง end abcdefgh1\n r\n}}\n")
};
for (body, span_moved) in [("1", false), ("2", true)] {
let (change, files) = repin_change(&src("10", "aaaaa", "1"), &src("99", "bbbbb", body));
let (old, new) = sides(&files);
let drift = drift_of(&change, &files, &old, &new, false)
.unwrap()
.expect("drift");
assert_eq!(drift.kind, Kind::Accepted);
assert_eq!(
strip_digests(drift.old_text.as_deref().unwrap())
!= strip_digests(drift.new_text.as_deref().unwrap()),
span_moved
);
assert_eq!(drift.callees.len(), 1, "{:?}", drift.callees);
let read = &drift.callees[0];
assert_eq!(read.read, Some(span_lang::Read::Prefix));
assert!(
read.old.as_deref().unwrap().contains("if a > 10 {"),
"{read:?}"
);
assert!(
read.new.as_deref().unwrap().contains("if a > 99 {"),
"{read:?}"
);
assert!(
drift
.why
.as_deref()
.unwrap()
.contains("code before the span in its function"),
"{:?}",
drift.why
);
let json: serde_json::Value =
serde_json::from_str(&diff_json(Path::new("."), std::slice::from_ref(&drift), 0))
.unwrap();
let location = &json["laws"][0]["sentence"]["locations"][0];
assert_eq!(location["reads"][0]["read"], "prefix", "{json}");
let tty = render_diff_with(std::slice::from_ref(&drift), &FileMap::new());
assert!(
tty.contains(" @@ code before the span in its function\n"),
"{tty}"
);
assert!(tty.contains("+ if a > 99 {"), "{tty}");
}
}
#[test]
fn a_drift_shows_the_signature_and_the_call_that_receives_its_closure_as_one_prefix() {
let src = |ty: &str, adapter: &str| {
format!("fn f(xs: &[{ty}]) -> usize {{\n xs.iter().{adapter}(|x| {{\n // ยง abcdefgh1@aaaaa\n **x > 1\n }}).count()\n}}\n")
};
let (change, files) = (
Change {
address: "abcdefgh1".into(),
kind: Kind::Marker,
old_path: Some("src/x.rs".into()),
new_path: Some("src/x.rs".into()),
old_text: Some("// ยง abcdefgh1@aaaaa".into()),
new_text: Some("// ยง abcdefgh1@aaaaa".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
span_files(&src("u32", "filter"), &src("u64", "take_while")),
);
let (old, new) = sides(&files);
let drift = drift_of(&change, &files, &old, &new, false)
.unwrap()
.expect("drift");
assert_eq!(drift.kind, Kind::Drift);
let reads: Vec<_> = drift.callees.iter().map(|c| c.read).collect();
assert_eq!(
reads,
[Some(span_lang::Read::Prefix)],
"{:?}",
drift.callees
);
let prefix = drift.callees[0].new.as_deref().unwrap();
assert!(
prefix.contains("u64") && prefix.contains("take_while"),
"{prefix}"
);
let why = drift.why.unwrap();
assert!(
why.contains("the code before the span in its function, which changed"),
"{why}"
);
}
#[test]
fn a_kept_pin_over_a_moved_callee_is_a_drift_naming_it() {
let src = |body: &str| {
format!("fn f() {{\n // ยง abcdefgh1@aaaaa\n save();\n}}\n\nfn save() {{\n {body}\n}}\n")
};
let (change, files) = (
Change {
address: "abcdefgh1".into(),
kind: Kind::Marker,
old_path: Some("src/x.rs".into()),
new_path: Some("src/x.rs".into()),
old_text: Some("// ยง abcdefgh1@aaaaa".into()),
new_text: Some("// ยง abcdefgh1@aaaaa".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
span_files(&src("write();"), &src("write_twice();")),
);
let (old, new) = sides(&files);
let drift = drift_of(&change, &files, &old, &new, false)
.unwrap()
.expect("drift");
assert_eq!(drift.kind, Kind::Drift);
assert_eq!(drift.old_text, drift.new_text);
assert_eq!(drift.callees.len(), 1, "{:?}", drift.callees);
let callee = &drift.callees[0];
assert_eq!(
(callee.name.as_str(), callee.path.as_str()),
("save", "src/x.rs")
);
assert!(callee.old.as_deref().unwrap().contains("write();"));
assert!(callee.new.as_deref().unwrap().contains("write_twice();"));
let diff = render_diff_with(std::slice::from_ref(&drift), &files);
assert!(diff.contains(" @@ followed callee save\n"), "{diff}");
assert!(diff.contains("- write();"), "{diff}");
assert!(diff.contains("+ write_twice();"), "{diff}");
let json: serde_json::Value =
serde_json::from_str(&diff_json(Path::new("."), std::slice::from_ref(&drift), 0))
.unwrap();
let location = &json["laws"][0]["sentence"]["locations"][0];
assert_eq!(location["callees"][0]["name"], "save", "{json}");
assert_eq!(location["pins"][0]["kind"], "drift", "{json}");
}
fn drift_between(files: &[(&str, &str, &str)]) -> Option<Change> {
let files: FileMap = files
.iter()
.map(|(path, old, new)| {
(
path.to_string(),
(Some(old.to_string()), Some(new.to_string())),
)
})
.collect();
let change = Change {
address: "abcdefgh1".into(),
kind: Kind::Marker,
old_path: Some("src/x.rs".into()),
new_path: Some("src/x.rs".into()),
old_text: Some("// ยง abcdefgh1@aaaaa".into()),
new_text: Some("// ยง abcdefgh1@aaaaa".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
};
let (old, new) = sides(&files);
drift_of(&change, &files, &old, &new, false).unwrap()
}
#[test]
fn a_call_rebound_by_an_import_is_a_drift() {
let main = |a: &str, b: &str| {
format!("mod a;\nmod b;\nuse {a}::step as first;\nuse {b}::step as second;\nfn f(x: u32) -> u32 {{\n // ยง abcdefgh1@aaaaa\n first(x) - second(x)\n}}\n")
};
let (old, new) = (main("a", "b"), main("b", "a"));
let rebound = drift_between(&[
("src/x.rs", &old, &new),
(
"src/a.rs",
"pub fn step(x: u32) -> u32 { x * 2 }\n",
"pub fn step(x: u32) -> u32 { x * 2 }\n",
),
(
"src/b.rs",
"pub fn step(x: u32) -> u32 { x + 9 }\n",
"pub fn step(x: u32) -> u32 { x + 9 }\n",
),
])
.expect("two swapped imports are a drift");
assert_ne!(rebound.why.as_deref(), Some(CALLEE_EDIT), "{rebound:?}");
let same = "mod m1;\nuse m1::helper;\nfn f(x: u32) -> u32 {\n // ยง abcdefgh1@aaaaa\n helper(x)\n}\n";
assert!(drift_between(&[
("src/x.rs", same, same),
(
"src/m1.rs",
"pub fn helper(x: u32) -> u32 { x }\n",
"pub fn helper(x: u32) -> u32 { x }\n"
),
])
.is_none());
}
#[test]
fn an_edited_callee_says_a_callee_changed_and_names_no_rebinding() {
let main = "mod m;\nuse m::helper;\nfn f(x: u32) -> u32 {\n // ยง abcdefgh1@aaaaa\n helper(x)\n}\n";
let drift = drift_between(&[
("src/x.rs", main, main),
(
"src/m.rs",
"pub fn helper(x: u32) -> u32 { x * 7 }\n",
"pub fn helper(x: u32) -> u32 { x * 8 }\n",
),
])
.expect("an edited callee is a drift");
assert_eq!(drift.callees.len(), 1, "{drift:?}");
assert_eq!(drift.why.as_deref(), Some(CALLEE_EDIT), "{drift:?}");
}
#[test]
fn an_unreadable_span_fails_instead_of_folding() {
let (mut change, files) = repin_change(
"fn f() {\n // ยง abcdefgh1@aaaaa\n save();\n}\n",
"fn f() {\n // ยง abcdefgh1@bbbbb\n save();\n}\n",
);
change.new_text = Some("// ยง abcdefgh1@ccccc".into());
let (old, new) = sides(&files);
let err = drift_of(&change, &files, &old, &new, false).unwrap_err();
assert!(err.to_string().contains("is not in the file"), "{err}");
change.new_path = Some("src/gone.rs".into());
assert!(drift_of(&change, &files, &old, &new, false).is_err());
}
#[test]
fn a_subject_word_is_not_a_remint_mark() {
let change = Change {
address: "abcdefgh1".into(),
kind: Kind::Marker,
old_path: Some("src/x.rs".into()),
new_path: Some("src/x.rs".into()),
old_text: Some("ยง abcdefgh1 The graph fails open.".into()),
new_text: Some("ยง abcdefgh1 The graph fails closed.".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
};
assert!(!weighed_pin(&change));
}
#[test]
fn path_hash_in_source_is_not_a_marker() {
let changes = marker_diff(
Path::new("src/diff.rs"),
[
Some("fn x() {}\n"),
Some("assert!(diff.contains(\"docs/decisions/cli/cli.md#abcdefgh1.a\"));\n"),
],
[None, None],
);
assert!(changes.is_empty(), "{changes:?}");
}
#[test]
fn a_marker_in_a_markdown_fence_is_no_marker_change() {
let fenced = "Text.\n\n```ts\nfunction f() {\n // ยง abcdefgh1@aaaaa\n go();\n}\n```\n";
let changes = marker_diff(
Path::new("README.md"),
[Some(fenced), Some(&fenced.replace("go();", "stop();"))],
[None, None],
);
assert!(changes.is_empty(), "{changes:?}");
}
#[test]
fn pin_only_digest_is_one_marker_change() {
let changes = marker_diff(
Path::new("src/x.rs"),
[
Some("// ยง abcdefgh1@aaaaa\n"),
Some("// ยง abcdefgh1@bbbbb\n"),
],
[None, None],
);
assert_eq!(changes.len(), 1);
assert!(weighed_pin(&changes[0]));
}
#[test]
fn a_remint_keeps_every_group_in_json() {
let json: serde_json::Value =
serde_json::from_str(&diff_json(Path::new("."), &[], 3)).unwrap();
assert_eq!(
(json["remint"].clone(), json["pinned"].clone()),
(true.into(), 3.into())
);
for key in ["block", "laws", "ungoverned"] {
assert!(json[key].is_array(), "{key}: {json}");
}
let empty = review::Review::gather(
"HEAD".into(),
Vec::new(),
3,
Vec::new(),
Vec::new(),
Vec::new(),
);
assert!(review::review_markdown(&empty)
.contains("scheme span digest remint (3 pinned markers)"));
}
#[test]
fn diff_json_nests_law_clause_marker() {
let changes = vec![
Change {
address: "abcdefgh1".into(),
kind: Kind::Declared,
old_path: None,
new_path: Some("docs/decisions/n.md".into()),
old_text: None,
new_text: Some("Binding sentence".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "abcdefgh1.a".into(),
kind: Kind::Clause,
old_path: None,
new_path: Some("docs/decisions/n.md".into()),
old_text: None,
new_text: Some("First".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
Change {
address: "abcdefgh1.a".into(),
kind: Kind::Marker,
old_path: None,
new_path: Some("src/x.rs".into()),
old_text: None,
new_text: Some("ยง abcdefgh1.a".into()),
callees: Vec::new(),
lines: [None, None],
why: None,
},
];
let json: serde_json::Value = serde_json::from_str(&diff_json(
Path::new(env!("CARGO_MANIFEST_DIR")),
&changes,
0,
))
.unwrap();
let law = &json["laws"][0];
assert_eq!(
(&law["id"], &law["status"]),
(&"abcdefgh1".into(), &"new".into())
);
assert_eq!(law["sentence"]["text"]["new"], "Binding sentence", "{json}");
let clause = &law["clauses"][0];
assert_eq!(clause["letter"], "a", "{json}");
let location = &clause["locations"][0];
assert_eq!(location["path"], "src/x.rs", "{json}");
assert_eq!(location["doc"], false, "{json}");
assert_eq!(location["pins"][0]["kind"], "added", "{json}");
}
#[test]
fn empty_diff_stream_is_silent() {
emit_diff_stream("").unwrap();
}
#[test]
fn the_arguments_are_revisions_alone_and_two_are_a_range() {
let revs =
|args: &[&str]| revision(&args.iter().map(|a| a.to_string()).collect::<Vec<_>>());
assert_eq!(revs(&[]).unwrap(), None);
assert_eq!(revs(&["9a823256a"]).unwrap().as_deref(), Some("9a823256a"));
assert_eq!(
revs(&["main", "HEAD"]).unwrap().as_deref(),
Some("main..HEAD")
);
assert_eq!(
revs(&["main...HEAD"]).unwrap().as_deref(),
Some("main...HEAD")
);
assert!(revs(&["main..HEAD", "x"]).is_err());
assert_eq!(range_end(Some("main...")).as_deref(), Some("HEAD"));
assert_eq!(range_end(Some("main..topic")).as_deref(), Some("topic"));
assert_eq!(range_end(Some("main")), None);
}
#[test]
fn law_id_keeps_its_clauses() {
assert!(keep_address("k7m2x9p4a.v", "k7m2x9p4a"));
assert!(!keep_address("k7m2x9p4a.v", "k7m2x9p4a.u"));
}
}