use anyhow::{bail, Result};
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use crate::diff::{Moved, PinAt, Tree};
use crate::marker::MarkerAddr;
use crate::parse::{Clause, Law};
use crate::policy::TestPaths;
use crate::span::{self, CodeFile};
use crate::walk;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Cause {
Remint,
Span,
Prefix,
Callee,
Import,
Text,
Other,
Unread,
}
const CAUSES: [Cause; 8] = [
Cause::Remint,
Cause::Span,
Cause::Prefix,
Cause::Callee,
Cause::Import,
Cause::Text,
Cause::Other,
Cause::Unread,
];
impl Cause {
fn key(self) -> &'static str {
match self {
Cause::Remint => "remint",
Cause::Span => "span",
Cause::Prefix => "prefix",
Cause::Callee => "callee",
Cause::Import => "import",
Cause::Text => "text",
Cause::Other => "other",
Cause::Unread => "unread",
}
}
fn of(moved: Moved) -> Self {
[
(moved.span, Cause::Span),
(moved.prefix || moved.above, Cause::Prefix),
(moved.callee, Cause::Callee),
(moved.import, Cause::Import),
(moved.text, Cause::Text),
]
.into_iter()
.find_map(|(hit, cause)| hit.then_some(cause))
.unwrap_or(Cause::Other)
}
}
#[derive(Default, Clone, Copy)]
struct ByCause([usize; CAUSES.len()]);
impl ByCause {
fn add(&mut self, cause: Cause) {
self.0[cause as usize] += 1;
}
fn total(&self) -> usize {
self.0.iter().sum()
}
fn json(&self) -> Value {
CAUSES
.iter()
.map(|&cause| (cause.key().to_string(), json!(self.0[cause as usize])))
.collect::<serde_json::Map<_, _>>()
.into()
}
}
struct Commit {
sha: String,
parent: Option<String>,
week: String,
op: String,
scheme: String,
files: Vec<FilePatch>,
}
struct FilePatch {
paths: [Option<String>; 2],
lines: [BTreeSet<usize>; 2],
patch: String,
}
#[derive(Clone)]
struct Pin {
addr: MarkerAddr,
path: String,
line: usize,
bit: String,
test: bool,
}
struct Repin {
addr: MarkerAddr,
cause: Cause,
with_test: bool,
}
#[derive(Default)]
struct Week {
commits: usize,
governed: usize,
repins: ByCause,
laws_added: usize,
laws_struck: usize,
clauses_added: usize,
clauses_struck: usize,
markers_added: usize,
}
#[derive(Default)]
struct AddressCounts {
causes: ByCause,
with_test: usize,
neither: usize,
}
#[derive(Default)]
struct Overhead {
files: usize,
code: usize,
markers: usize,
ends: usize,
}
struct History {
rev: String,
since: Option<String>,
commits: usize,
addresses: BTreeMap<String, AddressCounts>,
weeks: BTreeMap<String, Week>,
never: Vec<String>,
overhead: BTreeMap<&'static str, Overhead>,
}
pub fn run(root: &Path, range: Option<&str>, since: Option<&str>, json: bool) -> Result<()> {
crate::published::require_history(root)?;
let rev = match range {
Some(range) => range.to_string(),
None => crate::published::tip(root, &[root])?,
};
let history = read(root, &rev, since)?;
if json {
println!("{}", serde_json::to_string_pretty(&history.json())?);
} else {
print!("{}", history.table());
}
Ok(())
}
fn read(root: &Path, rev: &str, since: Option<&str>) -> Result<History> {
let since_arg = since.map(|date| format!("--since={date}"));
let mut args = vec![
"--first-parent",
"--diff-merges=first-parent",
"--relative",
"--format=%x01%H%x00%P%x00%cd%x00%(trailers:key=Silcrow-Op,valueonly,separator=%x20)%x00%(trailers:key=Silcrow-Scheme,valueonly,separator=%x20)",
"--date=format:%G-W%V",
];
args.extend(since_arg.as_deref());
args.extend([rev, "--"]);
let commits = parse_walk(&crate::meta::patch_walk(root, &args)?)?;
let project = walk::Project::at(root)?;
let mut weeks: BTreeMap<String, Week> = BTreeMap::new();
let mut repins: Vec<Repin> = Vec::new();
let mut renamed: BTreeMap<String, String> = BTreeMap::new();
for (commit, facts) in
commits
.iter()
.zip(weigh_all(root, &project, &TestPaths::at(root)?, &commits)?)
{
let week = weeks.entry(commit.week.clone()).or_default();
week.commits += 1;
week.governed += usize::from(facts.governed);
week.laws_added += facts.laws_added;
week.laws_struck += facts.laws_struck;
week.clauses_added += facts.clauses_added;
week.clauses_struck += facts.clauses_struck;
week.markers_added += facts.markers_added;
for repin in &facts.repins {
week.repins.add(repin.cause);
}
renamed.extend(facts.renamed);
repins.extend(facts.repins);
}
let current = |addr: &MarkerAddr| {
let mut addr = addr.clone();
for _ in 0..=renamed.len() {
match renamed.get(&addr.id).filter(|_| addr.project.is_none()) {
Some(next) => addr.id = next.clone(),
None => break,
}
}
addr
};
let mut addresses: BTreeMap<String, AddressCounts> = BTreeMap::new();
let mut touched: BTreeSet<(String, Option<String>)> = BTreeSet::new();
for repin in &repins {
let addr = current(&repin.addr);
let counts = addresses.entry(addr.display()).or_default();
counts.causes.add(repin.cause);
counts.with_test += usize::from(repin.with_test);
let examined = matches!(repin.cause, Cause::Span | Cause::Remint | Cause::Unread);
counts.neither += usize::from(!examined && !repin.with_test);
if addr.project.is_none() {
touched.insert((addr.id.clone(), addr.letter.clone()));
}
}
let scan = crate::parse::scan_root(root)?;
Ok(History {
rev: rev.to_string(),
since: since.map(str::to_string),
commits: commits.len(),
addresses,
weeks,
never: never_repinned(&scan.laws, &touched),
overhead: overhead(&CodeFile::read_all(root)?),
})
}
fn parse_walk(out: &str) -> Result<Vec<Commit>> {
let mut commits = Vec::new();
for record in out.split('\u{1}').filter(|r| !r.is_empty()) {
let (head, patch) = record.split_once('\n').unwrap_or((record, ""));
let fields: Vec<&str> = head.split('\0').collect();
let [sha, parents, week, op, scheme] = fields[..] else {
bail!("git log: unexpected header `{head}`");
};
commits.push(Commit {
sha: sha.to_string(),
parent: parents.split_whitespace().next().map(str::to_string),
week: week.to_string(),
op: op.to_string(),
scheme: scheme.to_string(),
files: file_patches(patch)?,
});
}
Ok(commits)
}
fn file_patches(patch: &str) -> Result<Vec<FilePatch>> {
let mut out: Vec<FilePatch> = Vec::new();
let mut header = false;
let mut at = [0usize; 2];
for line in patch.lines() {
if line.starts_with("diff --git ") {
out.push(FilePatch {
paths: [None, None],
lines: Default::default(),
patch: String::new(),
});
header = true;
}
let Some(file) = out.last_mut() else {
continue;
};
file.patch.push_str(line);
file.patch.push('\n');
if header {
if let Some(path) = line.strip_prefix("--- ") {
file.paths[0] = crate::log::patch_path(path, "a/")?;
} else if let Some(path) = line.strip_prefix("+++ ") {
file.paths[1] = crate::log::patch_path(path, "b/")?;
} else if let Some(range) = line.strip_prefix("@@ ") {
header = false;
at = crate::log::hunk_starts(range)?;
}
continue;
}
if let Some(range) = line.strip_prefix("@@ ") {
at = crate::log::hunk_starts(range)?;
continue;
}
let side = match line.as_bytes().first() {
Some(b'-') => 0,
Some(b'+') => 1,
_ => continue,
};
file.lines[side].insert(at[side]);
at[side] += 1;
}
Ok(out)
}
#[derive(Default)]
struct Facts {
governed: bool,
repins: Vec<Repin>,
renamed: Vec<(String, String)>,
laws_added: usize,
laws_struck: usize,
clauses_added: usize,
clauses_struck: usize,
markers_added: usize,
}
struct Touched<'a> {
patch: &'a FilePatch,
texts: [Option<String>; 2],
files: [Option<CodeFile>; 2],
}
fn weigh_all(
root: &Path,
project: &walk::Project,
test_paths: &TestPaths,
commits: &[Commit],
) -> Result<Vec<Facts>> {
let workers = std::thread::available_parallelism()
.map_or(1, |n| n.get() / 4)
.clamp(1, commits.len().max(1));
let size = commits.len().div_ceil(workers).max(1);
let stretches: Vec<Result<Vec<Facts>>> = std::thread::scope(|s| {
let handles: Vec<_> = commits
.chunks(size)
.map(|stretch| {
crate::par::spawn(s, move || {
let mut last = None;
stretch
.iter()
.map(|commit| weigh(root, project, test_paths, commit, &mut last))
.collect()
})
})
.collect();
handles
.into_iter()
.map(|h| {
h.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
})
.collect()
});
let mut out = Vec::with_capacity(commits.len());
for stretch in stretches {
out.extend(stretch?);
}
Ok(out)
}
fn weigh(
root: &Path,
project: &walk::Project,
test_paths: &TestPaths,
commit: &Commit,
last: &mut Option<(String, Tree)>,
) -> Result<Facts> {
let mut facts = Facts::default();
let held = |rel: &str| {
let rel = Path::new(rel);
walk::walks_to(project, rel) || project.is_note(rel)
};
let patches: Vec<&FilePatch> = commit
.files
.iter()
.filter(|file| file.paths.iter().flatten().any(|p| held(p)))
.collect();
let mut texts: [Vec<Option<String>>; 2] = Default::default();
let revs = [commit.parent.as_deref(), Some(commit.sha.as_str())];
for (side, (texts, rev)) in texts.iter_mut().zip(revs).enumerate() {
let rels: Vec<PathBuf> = patches
.iter()
.map(|file| PathBuf::from(file.paths[side].as_deref().unwrap_or("")))
.collect();
*texts = match rev {
Some(rev) => crate::published::blobs_at(root, rev, &rels)?
.into_iter()
.zip(&patches)
.map(|(text, file)| text.filter(|_| file.paths[side].is_some()))
.collect(),
None => vec![None; patches.len()],
};
}
let [old_texts, new_texts] = texts;
let mut touched = Vec::new();
let mut notes: [Vec<Law>; 2] = Default::default();
let mut notes_patch = String::new();
for ((patch, old), new) in patches.into_iter().zip(old_texts).zip(new_texts) {
let note = patch
.paths
.iter()
.flatten()
.any(|p| project.is_note(Path::new(p)));
if note {
for (side, text) in [&old, &new].into_iter().enumerate() {
if let (Some(path), Some(text)) = (&patch.paths[side], text) {
notes[side].extend(crate::parse::scan_text(Path::new(path), text).laws);
}
}
notes_patch.push_str(&patch.patch);
continue;
}
let parse = |side: usize, text: &Option<String>| {
let path = patch.paths[side].as_ref()?;
let text = text.as_ref().filter(|t| t.contains('§'))?;
Some(CodeFile::new(PathBuf::from(path), text.clone()))
};
let files = [parse(0, &old), parse(1, &new)];
touched.push(Touched {
patch,
texts: [old, new],
files,
});
}
let pairs = crate::log::pairs_in_diff(&crate::parse::plain_heads(¬es_patch));
let renames: BTreeMap<&str, &str> = pairs
.iter()
.map(|(old, new)| (old.as_str(), new.as_str()))
.collect();
let (old_laws, new_laws) = (¬es[0], ¬es[1]);
note_facts(old_laws, new_laws, &renames, &mut facts);
facts.renamed = pairs.clone();
let key = |addr: &MarkerAddr| {
let mut addr = MarkerAddr {
digest: None,
..addr.clone()
};
if addr.project.is_none() {
if let Some(new) = renames.get(addr.id.as_str()) {
addr.id = new.to_string();
}
}
addr.display()
};
let mut changed: [BTreeMap<String, Vec<Pin>>; 2] = Default::default();
for file in &touched {
facts.governed |= governs(file);
for (side, changed) in changed.iter_mut().enumerate() {
let (Some(path), Some(code)) = (&file.patch.paths[side], &file.files[side]) else {
continue;
};
let tests = code.cfg_test_rows();
let in_tests = test_paths.holds(Path::new(path));
for row in span::marker_rows(&code.rel, &code.text, code.tree()) {
if !file.patch.lines[side].contains(&(row.idx + 1)) {
continue;
}
for addr in row.markers {
changed.entry(key(&addr)).or_default().push(Pin {
addr,
path: path.clone(),
line: row.idx + 1,
bit: row.line.trim().to_string(),
test: in_tests || tests.iter().any(|&(a, b)| a <= row.idx && row.idx <= b),
});
}
}
}
}
let [removed, added] = changed;
let digests = |pins: Option<&Vec<Pin>>| -> BTreeSet<String> {
pins.into_iter()
.flatten()
.filter_map(|pin| pin.addr.digest.clone())
.collect()
};
let mut moved: Vec<(&String, &Pin)> = Vec::new();
for (address, pins) in &added {
let before = removed.get(address).map_or(0, Vec::len);
facts.markers_added += pins.len().saturating_sub(before);
let old = digests(removed.get(address));
moved.extend(
pins.iter()
.filter(|pin| pin.addr.digest.as_ref().is_some_and(|d| !old.contains(d)))
.map(|pin| (address, pin)),
);
}
let repinned: Vec<(&Pin, &Pin)> = added
.keys()
.filter_map(|address| {
let olds = removed.get(address)?;
let (_, new) = moved
.iter()
.find(|(a, pin)| *a == address && !pin.test)
.or_else(|| moved.iter().find(|(a, _)| *a == address))?;
let old = olds
.iter()
.find(|pin| pin.path == new.path)
.or_else(|| olds.first())?;
olds.iter()
.any(|pin| pin.addr.digest.is_some())
.then_some((old, *new))
})
.collect();
if repinned.is_empty() {
return Ok(facts);
}
let scheme = crate::log::scheme_changed(root, &commit.sha, &commit.op, &commit.scheme)?;
let needs_trees = !scheme && repinned.iter().any(|(old, new)| old.addr.id == new.addr.id);
let trees = match (needs_trees, &commit.parent) {
(true, Some(parent)) => {
let old = match last.take() {
Some((sha, tree)) if sha == *parent => tree,
_ => Tree::at(root, parent)?,
};
let new = Tree::at_reusing(root, &commit.sha, Some(&old))?;
Some((old, new))
}
_ => None,
};
let text_of = |pin: &Pin, side: usize| {
touched
.iter()
.find(|file| file.patch.paths[side].as_deref() == Some(pin.path.as_str()))
.and_then(|file| file.texts[side].as_deref())
};
for (old, new) in repinned {
let cause = match &trees {
_ if scheme || old.addr.id != new.addr.id => Cause::Remint,
None => Cause::Unread,
Some((old_tree, new_tree)) => {
let address = key(&new.addr);
match (text_of(old, 0), text_of(new, 1)) {
(Some(then), Some(now)) => crate::diff::moved(
&address,
(old_tree, pin_at(old, then)),
(new_tree, pin_at(new, now)),
)
.map_or(Cause::Unread, Cause::of),
_ => Cause::Unread,
}
}
};
let with_test = !scheme && tested(&key(&new.addr), &new.addr, &moved, &removed, &key);
facts.repins.push(Repin {
addr: MarkerAddr {
digest: None,
..new.addr.clone()
},
cause,
with_test,
});
}
if let Some((_, tree)) = trees {
*last = Some((commit.sha.clone(), tree));
}
Ok(facts)
}
fn tested(
address: &str,
addr: &MarkerAddr,
moved: &[(&String, &Pin)],
removed: &BTreeMap<String, Vec<Pin>>,
key: &dyn Fn(&MarkerAddr) -> String,
) -> bool {
let law = |pin: &Pin| {
key(&MarkerAddr {
letter: None,
..pin.addr.clone()
})
};
moved.iter().any(|(other, pin)| {
let reminted = removed
.get(*other)
.is_some_and(|olds| olds.iter().any(|old| old.addr.id != pin.addr.id));
let ours = other.as_str() == address || (addr.letter.is_none() && law(pin) == address);
pin.test && ours && !reminted
})
}
fn pin_at<'a>(pin: &'a Pin, text: &'a str) -> PinAt<'a> {
PinAt {
path: &pin.path,
text,
line: pin.line,
bit: &pin.bit,
}
}
fn governs(file: &Touched) -> bool {
(0..2).any(|side| {
let Some(code) = &file.files[side] else {
return false;
};
let starts: Vec<usize> = std::iter::once(0)
.chain(code.text.match_indices('\n').map(|(at, _)| at + 1))
.collect();
let spans = code.span_markers();
file.patch.lines[side].iter().any(|&line| {
starts.get(line - 1).is_some_and(|&at| {
spans
.iter()
.any(|m| m.line == line || (m.start <= at && at < m.end))
})
})
})
}
fn note_facts(old: &[Law], new: &[Law], renames: &BTreeMap<&str, &str>, facts: &mut Facts) {
let mut before: BTreeMap<&str, &Law> = BTreeMap::new();
for law in old {
before.insert(&law.id, law);
for alias in &law.aliases {
before.entry(alias).or_insert(law);
}
if let Some(next) = renames.get(law.id.as_str()) {
before.entry(next).or_insert(law);
}
}
for law in new.iter().filter(|law| !law.id.starts_with('+')) {
let was = std::iter::once(&law.id)
.chain(&law.aliases)
.find_map(|id| before.get(id.as_str()));
let active = |c: &&Clause| c.letter.is_some() && !c.struck;
let Some(was) = was else {
if !law.struck {
facts.laws_added += 1;
facts.clauses_added += law.clauses.iter().filter(active).count();
}
continue;
};
if law.struck {
facts.laws_struck += usize::from(!was.struck);
continue;
}
for clause in &law.clauses {
let then = was.clauses.iter().find(|c| c.letter == clause.letter);
match then {
None => facts.clauses_added += usize::from(active(&clause)),
Some(then) => facts.clauses_struck += usize::from(clause.struck && !then.struck),
}
}
}
}
fn never_repinned(laws: &[Law], touched: &BTreeSet<(String, Option<String>)>) -> Vec<String> {
let hit = |id: &str, letter: Option<&String>| {
touched
.iter()
.any(|(t, l)| t == id && (letter.is_none() || l.as_ref() == letter))
};
let mut out = Vec::new();
for law in laws.iter().filter(|law| !law.struck && !law.draft) {
if !hit(&law.id, None) {
out.push(law.id.clone());
}
for clause in &law.clauses {
let Some(letter) = clause
.letter
.as_ref()
.filter(|_| !clause.struck && !clause.draft)
else {
continue;
};
if !hit(&law.id, Some(letter)) {
out.push(format!("{}.{letter}", law.id));
}
}
}
out
}
fn overhead(files: &[CodeFile]) -> BTreeMap<&'static str, Overhead> {
let mut out: BTreeMap<&'static str, Overhead> = BTreeMap::new();
for file in files {
let entry = out
.entry(file.lang.map_or("other", |lang| lang.id))
.or_default();
entry.files += 1;
let rows = span::marker_rows(&file.rel, &file.text, file.tree());
let markers = rows.iter().filter(|row| !row.markers.is_empty()).count();
let ends = rows.iter().filter(|row| row.end.is_some()).count();
let lines = file.text.lines().filter(|l| !l.trim().is_empty()).count();
entry.markers += markers;
entry.ends += ends;
entry.code += lines - markers - ends;
}
out
}
fn percent(part: usize, whole: usize) -> Option<f64> {
(whole > 0).then(|| (part as f64 / whole as f64 * 1000.0).round() / 10.0)
}
impl History {
fn total(&self) -> AddressCounts {
let mut total = AddressCounts::default();
for counts in self.addresses.values() {
for cause in CAUSES {
total.causes.0[cause as usize] += counts.causes.0[cause as usize];
}
total.with_test += counts.with_test;
total.neither += counts.neither;
}
total
}
fn by_repins(&self) -> Vec<(&String, &AddressCounts)> {
let mut out: Vec<_> = self.addresses.iter().collect();
out.sort_by_key(|(address, counts)| (std::cmp::Reverse(counts.causes.total()), *address));
out
}
fn json(&self) -> Value {
let counts = |counts: &AddressCounts| {
json!({
"repins": counts.causes.total(),
"causes": counts.causes.json(),
"with_test": counts.with_test,
"neither": counts.neither,
})
};
json!({
"range": {
"rev": self.rev,
"since": self.since,
"commits": self.commits,
},
"addresses": self.by_repins().iter().map(|(address, c)| {
let mut value = counts(c);
value["address"] = json!(address);
value
}).collect::<Vec<_>>(),
"total": counts(&self.total()),
"weeks": self.weeks.iter().map(|(week, w)| json!({
"week": week,
"commits": w.commits,
"governed_commits": w.governed,
"repins": w.repins.json(),
"laws_added": w.laws_added,
"laws_struck": w.laws_struck,
"clauses_added": w.clauses_added,
"clauses_struck": w.clauses_struck,
"markers_added": w.markers_added,
})).collect::<Vec<_>>(),
"never_repinned": self.never,
"overhead": self.overhead.iter().map(|(lang, o)| json!({
"language": lang,
"files": o.files,
"code_lines": o.code,
"marker_lines": o.markers,
"end_lines": o.ends,
"percent": percent(o.markers + o.ends, o.code),
})).collect::<Vec<_>>(),
})
}
fn table(&self) -> String {
let mut out = String::new();
let since = self
.since
.as_ref()
.map_or(String::new(), |since| format!(" since {since}"));
let _ = writeln!(
out,
"History of {}{since}: {} commit(s), first parents only",
self.rev, self.commits
);
let causes: Vec<&str> = CAUSES.iter().map(|c| c.key()).collect();
let total = self.total();
let rows = self.by_repins();
let width = rows
.iter()
.map(|(address, _)| address.len())
.fold("total".len(), usize::max);
let _ = writeln!(out, "\nRe-pins by address");
let head: Vec<String> = causes.iter().map(|c| format!("{c:>6}")).collect();
let _ = writeln!(
out,
" {:<width$} {:>7} {} {:>9} {:>7}",
"address",
"re-pins",
head.join(" "),
"with test",
"neither"
);
let total_key = "total".to_string();
for (address, counts) in rows.iter().copied().chain([(&total_key, &total)]) {
let cells: Vec<String> = counts.causes.0.iter().map(|n| format!("{n:>6}")).collect();
let _ = writeln!(
out,
" {:<width$} {:>7} {} {:>9} {:>7}",
address,
counts.causes.total(),
cells.join(" "),
counts.with_test,
counts.neither
);
}
let _ = writeln!(out, "\nWeeks");
let _ = writeln!(
out,
" {:<8} {:>7} {:>8} {:>7} {} {:>10} {:>11} {:>13} {:>14} {:>13}",
"week",
"commits",
"governed",
"re-pins",
head.join(" "),
"laws added",
"laws struck",
"clauses added",
"clauses struck",
"markers added"
);
for (week, w) in &self.weeks {
let cells: Vec<String> = w.repins.0.iter().map(|n| format!("{n:>6}")).collect();
let _ = writeln!(
out,
" {:<8} {:>7} {:>8} {:>7} {} {:>10} {:>11} {:>13} {:>14} {:>13}",
week,
w.commits,
w.governed,
w.repins.total(),
cells.join(" "),
w.laws_added,
w.laws_struck,
w.clauses_added,
w.clauses_struck,
w.markers_added
);
}
let _ = writeln!(
out,
"\nNever re-pinned: {} law(s) and clause(s)",
self.never.len()
);
for chunk in self.never.chunks(8) {
let _ = writeln!(out, " {}", chunk.join(" "));
}
let _ = writeln!(out, "\nMarker overhead");
let _ = writeln!(
out,
" {:<10} {:>5} {:>10} {:>12} {:>9} {:>7}",
"language", "files", "code lines", "marker lines", "end lines", "percent"
);
for (lang, o) in &self.overhead {
let _ = writeln!(
out,
" {:<10} {:>5} {:>10} {:>12} {:>9} {:>7}",
lang,
o.files,
o.code,
o.markers,
o.ends,
percent(o.markers + o.ends, o.code).map_or("-".to_string(), |p| format!("{p:.1}"))
);
}
out
}
}