use super::diff::FileDiff;
use super::rules::{Finding, Level};
use super::session::{self, Item};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Overview,
Setup,
Database,
Area,
Across,
Finish,
}
#[derive(Clone, Debug)]
pub struct Stage {
pub kind: Kind,
pub title: String,
pub files: Vec<usize>,
pub items: Vec<usize>,
}
impl Stage {
fn new(kind: Kind, title: &str) -> Stage {
Stage { kind, title: title.to_string(), files: Vec::new(), items: Vec::new() }
}
}
const NOISE: &[&str] = &[
"about",
"action",
"actions",
"apps",
"backend",
"check",
"client",
"crates",
"frontend",
"generate",
"handle",
"internal",
"packages",
"pkg",
"process",
"send",
"server",
"sync",
"add",
"admin",
"and",
"api",
"app",
"artisan",
"asset",
"assets",
"auth",
"base",
"blade",
"bootstrap",
"build",
"cmd",
"command",
"commands",
"common",
"component",
"components",
"composable",
"composables",
"config",
"console",
"context",
"controller",
"controllers",
"core",
"create",
"css",
"data",
"database",
"default",
"delete",
"destroy",
"detail",
"details",
"dist",
"docs",
"edit",
"event",
"events",
"factory",
"factories",
"feature",
"features",
"fetch",
"for",
"form",
"forms",
"from",
"get",
"handler",
"handlers",
"helper",
"helpers",
"hook",
"hooks",
"html",
"http",
"index",
"item",
"items",
"job",
"jobs",
"js",
"json",
"jsx",
"kernel",
"layout",
"layouts",
"lib",
"list",
"listener",
"listeners",
"load",
"mail",
"main",
"manager",
"middleware",
"migration",
"migrations",
"mod",
"model",
"models",
"module",
"modules",
"new",
"notification",
"notifications",
"observer",
"page",
"pages",
"partial",
"partials",
"patch",
"php",
"policies",
"policy",
"post",
"provider",
"providers",
"public",
"put",
"readme",
"remove",
"repository",
"request",
"requests",
"resource",
"resources",
"route",
"routes",
"rs",
"run",
"save",
"scss",
"seeder",
"seeders",
"service",
"services",
"set",
"shared",
"show",
"spec",
"src",
"state",
"store",
"stores",
"style",
"styles",
"svelte",
"table",
"tauri",
"test",
"tests",
"the",
"toml",
"ts",
"tsx",
"type",
"types",
"update",
"util",
"utils",
"value",
"vendor",
"view",
"views",
"vue",
"web",
"with",
"yaml",
"yml",
];
fn singular(word: &str) -> String {
if let Some(stem) = word.strip_suffix("ies").filter(|s| s.len() >= 3) {
format!("{stem}y")
} else if word.len() > 4 && word.ends_with('s') && !word.ends_with("ss") && !word.ends_with("us") {
word[..word.len() - 1].to_string()
} else {
word.to_string()
}
}
pub fn words(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut word = String::new();
let mut prev_lower = false;
let flush = |word: &mut String, out: &mut Vec<String>| {
let w = singular(&word.to_lowercase());
if w.len() >= 3 && !w.chars().all(|c| c.is_ascii_digit()) && !NOISE.contains(&w.as_str()) {
out.push(w);
}
word.clear();
};
for c in text.chars() {
if c.is_alphanumeric() {
if c.is_uppercase() && prev_lower {
flush(&mut word, &mut out);
}
prev_lower = c.is_lowercase() || c.is_ascii_digit();
word.push(c);
} else {
flush(&mut word, &mut out);
prev_lower = false;
}
}
flush(&mut word, &mut out);
out
}
pub fn file_topic(path: &str) -> Option<String> {
let mut parts: Vec<&str> = path.split('/').collect();
let name = parts.pop().unwrap_or("");
let stem = name.split('.').next().unwrap_or(name);
parts.into_iter().rev().chain(std::iter::once(stem)).find_map(|p| words(p).into_iter().next())
}
fn quoted(text: &str) -> impl Iterator<Item = &str> {
text.split('`').skip(1).step_by(2)
}
fn literals(line: &str) -> Vec<&str> {
let mut out = Vec::new();
for q in ['\'', '"'] {
out.extend(line.split(q).skip(1).step_by(2));
}
out
}
fn finding_topic(f: &Finding, known: &[String]) -> Option<String> {
let span = f.span.as_ref().filter(|s| !matches!(s.file.as_str(), "PR description" | "commit messages"));
let mut candidates: Vec<String> = quoted(&f.title).flat_map(words).collect();
candidates.extend(span.and_then(|s| file_topic(&s.file)));
candidates.extend(span.into_iter().flat_map(|s| literals(&s.text)).flat_map(words));
candidates.iter().find(|w| known.contains(w)).or(candidates.first()).cloned()
}
fn place(code: &str) -> Kind {
match code {
"LAR009" | "LAR013" | "GEN005" | "TAU007" => Kind::Setup,
"LAR001" | "LAR002" | "LAR003" => Kind::Database,
"PR001" | "PR003" | "PR004" | "PR005" | "PR006" => Kind::Overview,
"GEN001" | "GEN002" | "GEN003" | "GEN004" | "GEN006" | "GEN007" | "TAU001" | "TAU002" | "TAU006" | "TAU008" => {
Kind::Across
}
_ => Kind::Area,
}
}
fn file_place(f: &FileDiff) -> Kind {
let name = f.path.rsplit('/').next().unwrap_or(&f.path).to_ascii_lowercase();
let deps = [
"composer.json",
"composer.lock",
"package.json",
"package-lock.json",
"pnpm-lock.yaml",
"yarn.lock",
"bun.lockb",
"cargo.toml",
"cargo.lock",
];
if f.path.contains("migrations/") || f.path.contains("seeders/") {
Kind::Database
} else if deps.contains(&name.as_str()) || name.starts_with(".env") || f.path.starts_with("config/") {
Kind::Setup
} else {
Kind::Across
}
}
fn title_case(word: &str) -> String {
let mut c = word.chars();
c.next().map(|f| f.to_uppercase().chain(c).collect()).unwrap_or_default()
}
pub fn build(files: &[FileDiff], findings: &[Finding], items: &[Item]) -> Vec<Stage> {
let mut overview = Stage::new(Kind::Overview, "What it claims");
let mut setup = Stage::new(Kind::Setup, "Get it running");
let mut database = Stage::new(Kind::Database, "Database");
let mut across = Stage::new(Kind::Across, "Across the change");
let finish = Stage::new(Kind::Finish, "Finish");
let mut areas: Vec<(String, Stage)> = Vec::new();
let area = |topic: &str, areas: &mut Vec<(String, Stage)>| -> usize {
if let Some(i) = areas.iter().position(|(t, _)| t == topic) {
return i;
}
let title = title_case(topic);
areas.push((topic.to_string(), Stage::new(Kind::Area, &title)));
areas.len() - 1
};
let topics: Vec<Option<String>> =
files.iter().map(|f| if file_place(f) == Kind::Across { file_topic(&f.path) } else { None }).collect();
let known: Vec<String> = topics.iter().flatten().cloned().collect();
let homes: Vec<(Kind, Option<usize>)> = findings
.iter()
.map(|f| match (place(f.code), finding_topic(f, &known)) {
(Kind::Area, Some(t)) => (Kind::Area, Some(area(&t, &mut areas))),
(Kind::Area, None) => (Kind::Across, None),
(k, _) => (k, None),
})
.collect();
for (i, f) in files.iter().enumerate() {
let pointed = || {
findings.iter().zip(&homes).find_map(|(finding, home)| {
(finding.span.as_ref().is_some_and(|s| s.file == f.path) && home.0 == Kind::Area)
.then_some(home.1)
.flatten()
})
};
match topics[i].as_deref().map(|t| area(t, &mut areas)).or_else(pointed) {
Some(a) => areas[a].1.files.push(i),
None => match file_place(f) {
Kind::Database => database.files.push(i),
Kind::Setup => setup.files.push(i),
_ => across.files.push(i),
},
}
}
for (i, item) in items.iter().enumerate() {
if item.described {
let named = words(&item.text).into_iter().find_map(|w| areas.iter().position(|(t, _)| *t == w));
match named {
Some(a) => areas[a].1.items.push(i),
None => overview.items.push(i),
}
continue;
}
let home = item.findings.first().map(|&f| homes[f]).unwrap_or((Kind::Across, None));
match home {
(Kind::Area, Some(a)) => areas[a].1.items.push(i),
(Kind::Overview, _) => overview.items.push(i),
(Kind::Setup, _) => setup.items.push(i),
(Kind::Database, _) => database.items.push(i),
_ => across.items.push(i),
}
}
let worst = |s: &Stage| s.items.iter().filter_map(|&i| items[i].level).min().unwrap_or(Level::Note);
let described = |s: &Stage| s.items.iter().any(|&i| items[i].described);
let mut areas: Vec<Stage> =
areas.into_iter().map(|(_, s)| s).filter(|s| !s.files.is_empty() || !s.items.is_empty()).collect();
areas.sort_by_key(|s| (!described(s), worst(s), std::cmp::Reverse(s.files.len() + s.items.len())));
let mut stages = vec![overview];
stages.extend([setup, database].into_iter().filter(|s| !s.files.is_empty() || !s.items.is_empty()));
stages.extend(areas);
if !across.files.is_empty() || !across.items.is_empty() {
stages.push(across);
}
stages.push(finish);
for s in &mut stages {
s.items.sort_by_key(|&i| order(&items[i]));
}
stages
}
pub fn order(item: &Item) -> u8 {
if item.check {
0
} else if item.described {
1
} else if runs_something(&item.text) {
3
} else {
2
}
}
pub fn runs_something(text: &str) -> bool {
text.trim_start().starts_with('`') && session::quoted(text).first().is_some_and(|q| session::is_command(q))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_come_from_the_code_not_its_kind() {
assert_eq!(words("InvoiceController"), ["invoice"]);
assert_eq!(words("load_invoice"), ["invoice"]);
assert_eq!(words("exportPdf"), ["export", "pdf"]);
assert_eq!(words("/invoices/{invoice}"), ["invoice", "invoice"]);
assert_eq!(words("categories"), ["category"]);
assert_eq!(words("2026_11_25_000000_drop_legacy_total"), ["drop", "legacy", "total"]);
assert_eq!(file_topic("resources/views/settings/show.blade.php").as_deref(), Some("setting"));
assert_eq!(file_topic("src/components/settings/ThemePicker.tsx").as_deref(), Some("setting"));
assert_eq!(file_topic("src/components/ThemePicker.tsx").as_deref(), Some("theme"));
assert_eq!(file_topic("frontend/src/pages/Billing.vue").as_deref(), Some("billing"));
assert_eq!(file_topic("app/Http/Controllers/SettingsController.php").as_deref(), Some("setting"));
assert_eq!(file_topic("src-tauri/src/lib.rs"), None);
}
}
#[cfg(test)]
mod demo_tests {
use super::*;
use crate::review::source::{self, Loaded};
use crate::review::{Parsed, parse_args, session};
#[test]
fn the_demo_is_cut_into_stages_by_what_it_is_about() {
let Ok(Parsed::Review(o)) = parse_args(&["demo".to_string()]) else { panic!() };
let Ok(Loaded::Change(change)) = source::load(&std::env::temp_dir(), &o) else { panic!() };
let items = session::items(&change.report);
let stages = build(&change.files, &change.report.findings, &items);
for s in &stages {
eprintln!("== {:?} {}", s.kind, s.title);
for &f in &s.files {
eprintln!(" file {}", change.files[f].path);
}
for &i in &s.items {
eprintln!(" {} {}", if items[i].check { "look" } else { "test" }, items[i].text);
}
}
let mut files: Vec<usize> = stages.iter().flat_map(|s| s.files.clone()).collect();
files.sort();
assert_eq!(files, (0..change.files.len()).collect::<Vec<_>>());
let mut all: Vec<usize> = stages.iter().flat_map(|s| s.items.clone()).collect();
all.sort();
assert_eq!(all, (0..items.len()).collect::<Vec<_>>());
let titles: Vec<&str> = stages.iter().map(|s| s.title.as_str()).collect();
assert_eq!(titles.first(), Some(&"What it claims"));
assert_eq!(titles.last(), Some(&"Finish"));
let invoice = stages.iter().find(|s| s.title == "Invoice").expect("an Invoice stage");
let paths: Vec<&str> = invoice.files.iter().map(|&f| change.files[f].path.as_str()).collect();
assert!(
paths.iter().any(|p| p.ends_with("InvoiceController.php"))
&& paths.iter().any(|p| p.ends_with("invoice.blade.php")),
"{paths:?}"
);
assert!(
invoice.items.iter().any(|&i| items[i].described),
"the author's invoice steps are tested with the invoice code"
);
let db = stages.iter().find(|s| s.kind == Kind::Database).expect("a Database stage");
assert!(db.files.iter().any(|&f| change.files[f].path.contains("migrations/")));
}
}