use anyhow::Result;
use serde_json::{json, Value};
use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use crate::check;
use crate::follow::FollowIndex;
use crate::graph::Graph;
use crate::marker::{self, MarkerAddr};
use crate::parse::{self, Scan};
use crate::policy::ProjectPolicy;
use crate::span::{self, CodeFile};
use crate::walk;
use crate::workspace::{ProjectRef, Workspace};
const TOP_CALLEES: usize = 10;
pub fn run(ws: &Workspace, project: &ProjectRef, json: bool) -> Result<()> {
let root = project.dir.as_path();
let scan = parse::scan_root(root)?;
let code = CodeFile::read_all(root)?;
let tests = crate::policy::TestPaths::at(root)?;
let follow = FollowIndex::from_files(&code, &tests);
let stats = Stats {
notes: note_stats(&scan),
pins: pin_stats(&scan, &code, &follow),
files: files_per_language(&code),
coverage: coverage(&code, &follow, &tests, &crate::walk::Project::at(root)?),
resolved: resolved_references(ws, project, &scan)?,
oldest_draft: oldest_draft(root, &scan),
};
if json || !crate::list_tty::is_tty_stdout() {
println!("{}", serde_json::to_string_pretty(&stats.json())?);
} else {
print!("{}", stats.table());
}
Ok(())
}
struct Stats {
notes: BTreeMap<String, NoteStats>,
pins: PinStats,
files: BTreeMap<&'static str, usize>,
coverage: BTreeMap<(&'static str, bool), Coverage>,
resolved: usize,
oldest_draft: Option<OldestDraft>,
}
struct OldestDraft {
address: String,
since: String,
age: String,
}
fn oldest_draft(root: &Path, scan: &Scan) -> Option<OldestDraft> {
let drafts = crate::list::drafts(&scan.laws);
let ages = crate::meta::draft_ages(root, &drafts)?;
drafts
.iter()
.zip(ages)
.filter_map(|(draft, age)| match age? {
(Some(since), Some(age)) => Some(OldestDraft {
address: draft.address(),
since,
age,
}),
_ => None,
})
.min_by(|a, b| a.since.cmp(&b.since))
}
#[derive(Default, Clone)]
struct Coverage {
lines: usize,
zoned: usize,
read: usize,
}
impl Coverage {
fn add(&mut self, other: &Coverage) {
self.lines += other.lines;
self.zoned += other.zoned;
self.read += other.read;
}
fn share(&self, n: usize) -> Option<f64> {
(self.lines > 0).then(|| (n as f64 * 1000.0 / self.lines as f64).round() / 10.0)
}
fn json(&self) -> Value {
json!({
"lines": self.lines,
"zoned": self.zoned,
"read": self.read,
"zoned_pct": self.share(self.zoned),
"read_pct": self.share(self.read),
})
}
}
#[derive(Default, Clone)]
struct NoteStats {
laws: usize,
active_laws: usize,
clauses: usize,
struck: usize,
active: usize,
drafts: usize,
public: usize,
words: usize,
words_max: usize,
longest: Option<String>,
over: usize,
bytes: usize,
}
impl NoteStats {
fn add(&mut self, other: &NoteStats) {
self.laws += other.laws;
self.active_laws += other.active_laws;
self.clauses += other.clauses;
self.struck += other.struck;
self.active += other.active;
self.drafts += other.drafts;
self.public += other.public;
self.words += other.words;
self.bytes += other.bytes;
self.over += other.over;
if other.words_max > self.words_max {
self.words_max = other.words_max;
self.longest = other.longest.clone();
}
}
fn words_mean(&self) -> Option<f64> {
mean(self.words, self.active)
}
fn json(&self) -> Value {
json!({
"laws": self.laws,
"clauses": self.clauses,
"struck_clauses": self.struck,
"active_clauses": self.active,
"drafts": self.drafts,
"public": self.public,
"words_mean": self.words_mean(),
"words_max": self.words_max,
"longest": self.longest,
"over_word_limit": self.over,
"bytes": self.bytes,
})
}
}
fn note_stats(scan: &Scan) -> BTreeMap<String, NoteStats> {
let mut out: BTreeMap<String, NoteStats> = BTreeMap::new();
for law in &scan.laws {
let note = out.entry(law.loc.path.display().to_string()).or_default();
note.laws += 1;
if !law.struck {
note.bytes += law.pin_text().len();
note.drafts += usize::from(law.draft);
note.public += usize::from(law.public);
note.active_laws += usize::from(!law.draft);
}
for clause in &law.clauses {
note.clauses += 1;
if law.struck || clause.struck {
note.struck += 1;
continue;
}
note.active += 1;
note.drafts += usize::from(clause.draft);
note.bytes += clause.body.len();
let words = clause.body.split_whitespace().count();
note.words += words;
if words > note.words_max {
note.words_max = words;
note.longest = Some(match &clause.letter {
Some(letter) => format!("{}.{letter}", law.id),
None => law.id.clone(),
});
}
}
}
for (_, loc, words) in check::text_lengths(scan) {
if words > check::WARN_WORDS {
out.entry(loc.path.display().to_string()).or_default().over += 1;
}
}
out
}
type Body = (String, PathBuf);
#[derive(Default)]
struct PinStats {
markers: usize,
pinned: usize,
laws: BTreeMap<String, LawPins>,
fan_in: BTreeMap<Body, (usize, usize)>,
}
#[derive(Default)]
struct LawPins {
markers: usize,
read: Vec<usize>,
callees: Vec<usize>,
}
impl LawPins {
fn json(&self, law: &str) -> Value {
json!({
"law": law,
"markers": self.markers,
"pins": self.read.len(),
"bytes_mean": mean(self.read.iter().sum(), self.read.len()),
"bytes_max": self.read.iter().max(),
"callees_mean": mean(self.callees.iter().sum(), self.callees.len()),
"callees_max": self.callees.iter().max(),
})
}
}
fn pin_stats(scan: &Scan, code: &[CodeFile], follow: &FollowIndex) -> PinStats {
let alias: HashMap<&str, &str> = scan
.laws
.iter()
.flat_map(|law| law.aliases.iter().map(|a| (a.as_str(), law.id.as_str())))
.collect();
let law_of = |addr: &MarkerAddr| {
let id = alias.get(addr.id.as_str()).copied().unwrap_or(&addr.id);
match &addr.project {
Some(project) => format!("{project}:{}", addr.id),
None => id.to_string(),
}
};
let texts: HashMap<&Path, &str> = code
.iter()
.map(|f| (f.rel.as_path(), f.text.as_str()))
.collect();
let mut out = PinStats::default();
for file in code {
for (_, line) in file.marker_lines() {
for addr in marker::markers_in_line(line) {
out.markers += 1;
out.pinned += usize::from(addr.digest.is_some());
out.laws.entry(law_of(&addr)).or_default().markers += 1;
}
}
let markers = file.span_markers();
for m in markers.iter().filter(|m| m.addr.digest.is_some()) {
let punch = span::punch_of(&markers, m.line);
let prefix = file.prefix(m.start, m.end);
let callees = follow.followed_callees(&file.rel, m.start, m.end, &punch, &prefix);
let mut bodies: BTreeMap<Body, Vec<(usize, usize)>> = BTreeMap::new();
for callee in callees {
bodies
.entry((callee.name, callee.path))
.or_default()
.push((callee.start, callee.end));
}
let mut read = (m.end - m.start) - covered(punch);
for (start, end, holes) in prefix {
read += (end - start) - covered(holes);
}
for ((name, path), stretches) in &bodies {
read += covered(stretches.clone());
let first = stretches
.iter()
.map(|s| s.0)
.min()
.expect("a body has a stretch");
let line = texts
.get(path.as_path())
.and_then(|t| t.get(..first))
.map_or(1, |before| before.matches('\n').count() + 1);
out.fan_in
.entry((name.clone(), path.clone()))
.or_insert((0, line))
.0 += 1;
}
let law = out.laws.entry(law_of(&m.addr)).or_default();
law.read.push(read);
law.callees.push(bodies.len());
}
}
out
}
fn covered(mut ranges: Vec<(usize, usize)>) -> usize {
ranges.sort();
let (mut total, mut reach) = (0, 0);
for (start, end) in ranges {
let start = start.max(reach);
if end > start {
total += end - start;
reach = end;
}
}
total
}
fn coverage(
code: &[CodeFile],
follow: &FollowIndex,
tests: &crate::policy::TestPaths,
project: &crate::walk::Project,
) -> BTreeMap<(&'static str, bool), Coverage> {
let mut zoned: HashMap<&Path, Vec<(usize, usize)>> = HashMap::new();
let mut read: HashMap<PathBuf, Vec<(usize, usize)>> = HashMap::new();
for file in code {
let markers = file.span_markers();
for m in &markers {
let punch = span::punch_of(&markers, m.line);
let prefix = file.prefix(m.start, m.end);
let span = outside_holes(m.start, m.end, &punch);
zoned.entry(&file.rel).or_default().extend(&span);
let own = read.entry(file.rel.clone()).or_default();
own.extend(span);
for (start, end, holes) in &prefix {
own.extend(outside_holes(*start, *end, holes));
}
own.extend(follow.pin_import_bytes(&file.rel, m.start, m.end, &punch, &prefix));
for callee in follow.followed_callees(&file.rel, m.start, m.end, &punch, &prefix) {
read.entry(callee.path)
.or_default()
.push((callee.start, callee.end));
}
}
}
let mut out: BTreeMap<(&'static str, bool), Coverage> = BTreeMap::new();
for file in code {
if project.is_note(&file.rel) || file.rel == Path::new("AGENTS.md") {
continue;
}
let zoned = union_stretches(zoned.remove(file.rel.as_path()).unwrap_or_default());
let read = union_stretches(read.remove(&file.rel).unwrap_or_default());
let in_tests = tests.holds(&file.rel);
let test_rows = file.cfg_test_rows();
let lang = file.lang.map_or("other", |lang| lang.id);
let mut start = 0;
for (row, piece) in file.text.split_inclusive('\n').enumerate() {
let line = (start, start + piece.len());
start += piece.len();
if piece.trim().is_empty() {
continue;
}
let test = in_tests || test_rows.iter().any(|&(a, b)| a <= row && row <= b);
let entry = out.entry((lang, test)).or_default();
entry.lines += 1;
entry.zoned += usize::from(touches_line(&zoned, line));
entry.read += usize::from(touches_line(&read, line));
}
}
out
}
fn outside_holes(start: usize, end: usize, holes: &[(usize, usize)]) -> Vec<(usize, usize)> {
let mut holes = holes.to_vec();
holes.sort();
let mut out = Vec::new();
let mut from = start;
for (hole_start, hole_end) in holes {
if hole_start > from {
out.push((from, hole_start.min(end)));
}
from = from.max(hole_end);
if from >= end {
break;
}
}
if from < end {
out.push((from, end));
}
out
}
fn union_stretches(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
ranges.sort();
let mut out: Vec<(usize, usize)> = Vec::new();
for (start, end) in ranges {
match out.last_mut() {
Some(last) if start <= last.1 => last.1 = last.1.max(end),
_ => out.push((start, end)),
}
}
out
}
fn touches_line(stretches: &[(usize, usize)], line: (usize, usize)) -> bool {
let at = stretches.partition_point(|&(_, end)| end <= line.0);
stretches.get(at).is_some_and(|&(start, _)| start < line.1)
}
fn files_per_language(code: &[CodeFile]) -> BTreeMap<&'static str, usize> {
let mut out = BTreeMap::new();
for file in code {
*out.entry(file.lang.map_or("other", |lang| lang.id))
.or_default() += 1;
}
out
}
fn resolved_references(ws: &Workspace, project: &ProjectRef, scan: &Scan) -> Result<usize> {
let root = project.dir.as_path();
let policy = ProjectPolicy::from_root(root).map_err(anyhow::Error::msg)?;
let scans = ws.law_scans(&project.key)?;
let report = check::evaluate(
scan,
&Graph::from_scan(scan),
0,
&policy,
&walk::Project::at(root)?.notes,
&check::Others::from_scans(&scans),
);
Ok(report.ok.len())
}
fn code_kind(test: bool) -> &'static str {
if test {
"test"
} else {
"source"
}
}
fn mean(sum: usize, n: usize) -> Option<f64> {
(n > 0).then(|| (sum as f64 / n as f64 * 10.0).round() / 10.0)
}
impl Stats {
fn total(&self) -> NoteStats {
let mut total = NoteStats::default();
for note in self.notes.values() {
total.add(note);
}
total
}
fn laws_by_read(&self) -> Vec<(&String, &LawPins)> {
let mut laws: Vec<_> = self.pins.laws.iter().collect();
laws.sort_by_key(|(law, pins)| (std::cmp::Reverse(pins.read.iter().max().copied()), *law));
laws
}
fn top_callees(&self) -> Vec<(&Body, &(usize, usize))> {
let mut callees: Vec<_> = self.pins.fan_in.iter().collect();
callees.sort_by_key(|(key, (pins, _))| (std::cmp::Reverse(*pins), *key));
callees.truncate(TOP_CALLEES);
callees
}
fn markers_per_law(&self) -> Option<f64> {
mean(self.pins.markers, self.total().active_laws)
}
fn coverage_rows(&self) -> Vec<(String, &'static str, Coverage)> {
let mut rows = Vec::new();
for test in [false, true] {
let mut total = Coverage::default();
for ((lang, t), c) in &self.coverage {
if *t == test && !matches!(*lang, "markdown" | "other") {
total.add(c);
}
}
rows.push(("code".to_string(), code_kind(test), total));
}
for ((lang, test), c) in &self.coverage {
rows.push(((*lang).to_string(), code_kind(*test), c.clone()));
}
rows
}
fn coverage_json(&self) -> Value {
let rows: Vec<Value> = self
.coverage_rows()
.into_iter()
.map(|(lang, kind, c)| {
let mut value = c.json();
value["language"] = json!(lang);
value["kind"] = json!(kind);
value
})
.collect();
json!({ "markers_per_law": self.markers_per_law(), "rows": rows })
}
fn json(&self) -> Value {
let notes: Vec<Value> = self
.notes
.iter()
.map(|(path, note)| {
let mut value = note.json();
value["path"] = json!(path);
value
})
.collect();
json!({
"laws": {
"notes": notes,
"total": self.total().json(),
"oldest_draft": self.oldest_draft.as_ref().map(|d| json!({
"address": d.address,
"since": d.since,
"age": d.age,
})),
},
"pins": {
"markers": self.pins.markers,
"pinned": self.pins.pinned,
"bare": self.pins.markers - self.pins.pinned,
"laws": self.laws_by_read().iter().map(|(law, pins)| pins.json(law)).collect::<Vec<_>>(),
"top_callees": self.top_callees().iter().map(|((name, path), (pins, line))| json!({
"name": name,
"path": path.display().to_string(),
"line": line,
"pins": pins,
})).collect::<Vec<_>>(),
},
"coverage": self.coverage_json(),
"project": {
"files": self.files,
"references_resolved": self.resolved,
},
})
}
fn table(&self) -> String {
let opt = |v: Option<f64>| v.map_or("-".to_string(), |v| format!("{v:.1}"));
let max = |v: Option<&usize>| v.map_or("-".to_string(), usize::to_string);
let mut out = String::new();
let total = self.total();
let width = self
.notes
.keys()
.map(String::len)
.fold("total".len(), usize::max);
let _ = writeln!(out, "Laws");
let _ = writeln!(
out,
" {:<width$} {:>5} {:>6} {:>7} {:>6} {:>6} {:>6} {:>10} {:>9} {:<12} {:>7} {:>7}",
"note",
"laws",
"public",
"clauses",
"struck",
"active",
"drafts",
"words mean",
"words max",
"longest",
format!("over {}", check::WARN_WORDS),
"bytes"
);
for (path, note) in self.notes.iter().chain([(&"total".to_string(), &total)]) {
let _ = writeln!(
out,
" {:<width$} {:>5} {:>6} {:>7} {:>6} {:>6} {:>6} {:>10} {:>9} {:<12} {:>7} {:>7}",
path,
note.laws,
note.public,
note.clauses,
note.struck,
note.active,
note.drafts,
opt(note.words_mean()),
note.words_max,
note.longest.as_deref().unwrap_or("-"),
note.over,
note.bytes
);
}
if let Some(d) = &self.oldest_draft {
let _ = writeln!(
out,
" oldest draft § {} since {}, {}",
d.address, d.since, d.age
);
}
let _ = writeln!(
out,
"\nPins\n {} marker(s), {} pinned, {} bare",
self.pins.markers,
self.pins.pinned,
self.pins.markers - self.pins.pinned
);
let laws = self.laws_by_read();
let width = laws
.iter()
.map(|(law, _)| law.len())
.fold("law".len(), usize::max);
let _ = writeln!(
out,
" {:<width$} {:>7} {:>4} {:>10} {:>9} {:>12} {:>11}",
"law", "markers", "pins", "bytes mean", "bytes max", "callees mean", "callees max"
);
for (law, pins) in &laws {
let _ = writeln!(
out,
" {:<width$} {:>7} {:>4} {:>10} {:>9} {:>12} {:>11}",
law,
pins.markers,
pins.read.len(),
opt(mean(pins.read.iter().sum(), pins.read.len())),
max(pins.read.iter().max()),
opt(mean(pins.callees.iter().sum(), pins.callees.len())),
max(pins.callees.iter().max())
);
}
let pct = |v: Option<f64>| v.map_or("-".to_string(), |v| format!("{v:.1}%"));
let _ = writeln!(
out,
"\nCoverage\n {} marker(s) per active law\n {:<12} {:<6} {:>8} {:>7} {:>7}",
opt(self.markers_per_law()),
"language",
"kind",
"lines",
"zoned",
"read"
);
for (lang, kind, c) in self.coverage_rows() {
let _ = writeln!(
out,
" {:<12} {:<6} {:>8} {:>7} {:>7}",
lang,
kind,
c.lines,
pct(c.share(c.zoned)),
pct(c.share(c.read))
);
}
let _ = writeln!(out, "\nCallees the most pins follow");
for ((name, path), (pins, line)) in self.top_callees() {
let _ = writeln!(out, " {pins:>5} {name} {}:{line}", path.display());
}
let files: Vec<String> = self
.files
.iter()
.map(|(lang, n)| format!("{lang} {n}"))
.collect();
let _ = writeln!(
out,
"\nProject\n files walked: {}\n {} reference(s) resolved",
files.join(", "),
self.resolved
);
out
}
}