rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The guided review: a change cut into stages in the order a person would go through it.
//! First what it claims, then getting it running, then one stage per part of the app it
//! touches (everything about invoices together, everything about settings together), then
//! what runs across the whole change, and last the verdict.
//!
//! The parts are named from the code itself: file and folder names, identifiers in the
//! findings (`load_invoice`, `/invoices/{invoice}`) and quoted strings on the lines they
//! point at. Words that say what kind of file something is (controller, view, src) are
//! ignored, so `InvoiceController.php`, `views/invoices/show.blade.php` and the
//! `load_invoice` command all land in "Invoice".

use super::diff::FileDiff;
use super::rules::{Finding, Level};
use super::session::{self, Item};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    /// What the change says it does, and whether the description holds up.
    Overview,
    /// Dependencies, settings and environment: before anything can be tried.
    Setup,
    Database,
    /// One part of the app.
    Area,
    /// Security, leftovers and tests: about the whole change.
    Across,
    Finish,
}

#[derive(Clone, Debug)]
pub struct Stage {
    pub kind: Kind,
    pub title: String,
    /// Indices into the change's files, to read.
    pub files: Vec<usize>,
    /// Indices into the items, to check and test.
    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() }
    }
}

/// Words that say what kind of file or code something is, not what it is about.
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()
    }
}

/// The words in a name: split on anything not a letter or digit and at camelCase humps,
/// lowercased and made singular, without the noise.
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
}

/// What a file is about: the nearest folder that says, so `settings/ThemePicker.tsx` is
/// about settings, or else its own name.
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())
}

/// The backticked parts of a text.
fn quoted(text: &str) -> impl Iterator<Item = &str> {
    text.split('`').skip(1).step_by(2)
}

/// The strings quoted on a line of code, such as the address in a route.
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
}

/// What a finding is about: of the words in what it names and where it is, the first that
/// is already a part of the app, or else the first.
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()
}

/// Where a finding belongs, by what kind of thing it is.
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,
    }
}

/// Where a file belongs if nothing names a part of the app it is in.
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()
}

/// Cut a change into stages. Every file and every item lands in exactly one.
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");
    // The parts of the app, in the order first met.
    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
    };

    // The parts the files are in come first; findings join them where they can.
    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() {
        // Its own part, or else the part of the first finding in it.
        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 {
            // The author's own step goes with the part it names first.
            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),
        }
    }

    // The parts the author talks about first, then the riskiest.
    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);
    // Inside a stage: what to look at, then what to try in the app (the author's steps
    // first), then what to run; each kind most serious first, as the items came.
    for s in &mut stages {
        s.items.sort_by_key(|&i| order(&items[i]));
    }
    stages
}

/// Where an item comes within its stage.
pub fn order(item: &Item) -> u8 {
    if item.check {
        0
    } else if item.described {
        1
    } else if runs_something(&item.text) {
        3
    } else {
        2
    }
}

/// Whether a step is mostly a command to run rather than something to do in the app.
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);
            }
        }
        // Every file and item is in exactly one stage.
        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/")));
    }
}