rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! What the description says, held against what the diff does. Runs last, so it can see
//! what the other rules found.

use super::*;
use crate::review::diff::Status;

pub fn run(cx: &Cx, out: &mut Vec<Finding>) {
    let Some(d) = cx.desc else { return };
    if cx.diff.files.is_empty() {
        return;
    }
    unchecked(d, out);
    test_plan(d, out);
    unmentioned(cx, d, out);
    claimed_tests(cx, d, out);
    screenshots(cx, d, out);
    issues(d, out);
}

fn line_of(d: &Description, no: u32) -> &str {
    d.lines.get(no as usize - 1).map_or("", String::as_str)
}

fn unchecked(d: &Description, out: &mut Vec<Finding>) {
    let open: Vec<_> = d.checklist.iter().filter(|c| !c.done).collect();
    for c in open.iter().take(8) {
        out.push(
            Finding::new("PR001", Level::Note, format!("unchecked in the description: {}", c.text))
                .at_text(&d.source, c.line, line_of(d, c.line), c.col as usize - 1, c.text.chars().count(), "not ticked")
                .check("is it still to be done, or does it not apply?"),
        );
    }
    if open.len() > 8
        && let Some(last) = out.last_mut()
    {
        last.note.push(format!("{} more unchecked item(s)", open.len() - 8));
    }
}

fn test_plan(d: &Description, out: &mut Vec<Finding>) {
    let has_plan = d.test_section().is_some_and(|s| !s.body.is_empty()) || d.checklist.iter().any(|c| c.done && c.text.to_lowercase().contains("test"));
    if has_plan {
        return;
    }
    let level = if out.iter().any(|f| f.level == Level::Risk) { Level::Warn } else { Level::Note };
    out.push(
        Finding::new("PR002", level, format!("nothing in the {} says how this was tested", d.source))
            .note("a reviewer cannot tell what was tried, or repeat it")
            .help("add a \"Test plan\" section; the manual test plan below is a place to start"),
    );
}

/// Things a person deploying or reviewing must be told about, with the words that would tell them.
fn unmentioned(cx: &Cx, d: &Description, out: &mut Vec<Finding>) {
    let new_migration = cx.diff.files.iter().find(|f| f.status == Status::Added && f.path.starts_with("database/migrations/"));
    if let Some(m) = new_migration
        && !d.mentions(&["migrat", "schema", "database", "db "])
    {
        out.push(
            Finding::new("PR003", Level::Warn, "the description does not mention the new migration")
                .note(format!("`{}` is added: whoever deploys has to run it, and reviewers should know the schema changes", m.path))
                .help("say that it needs `migrate`, and whether it is safe to run while the old code is live"),
        );
    }
    let new_env: Vec<String> = out
        .iter()
        .filter(|f| f.code == "LAR009" && f.title.starts_with("new environment variable"))
        .filter_map(|f| f.title.split('`').nth(1).map(str::to_string))
        .collect();
    if !new_env.is_empty() && !d.mentions(&["env", "environment", "config", "variable"]) && !new_env.iter().any(|v| d.mentions(&[v.to_lowercase().as_str()])) {
        out.push(
            Finding::new("PR003", Level::Warn, "the description does not mention the new environment variables")
                .note(format!("{} must be set before deploying", new_env.iter().map(|v| format!("`{v}`")).collect::<Vec<_>>().join(", ")))
                .help("list them with an example value and where to get the real one"),
        );
    }
    if out.iter().any(|f| f.code == "TAU006") && !d.mentions(&["identifier", "productname", "product name", "rename"]) {
        out.push(
            Finding::new("PR003", Level::Warn, "the description does not mention the app rename")
                .note("changing the identifier or product name affects every existing install")
                .help("say why, and what happens to existing users' data"),
        );
    }
}

fn claimed_tests(cx: &Cx, d: &Description, out: &mut Vec<Finding>) {
    const CLAIMS: &[&str] = &["tests added", "added tests", "added a test", "added test", "adds tests", "adds a test", "with tests", "new tests"];
    // An unticked checklist item is a to-do, not a claim.
    let unticked: Vec<u32> = d.checklist.iter().filter(|c| !c.done).map(|c| c.line).collect();
    let Some((line, byte, word)) = d.find(CLAIMS).filter(|(l, ..)| !unticked.contains(l)) else { return };
    let touched = cx.diff.files.iter().any(|f| {
        f.status != Status::Deleted && (is_test_path(&f.path) || f.added().any(|a| a.text.contains("#[test]") || a.text.contains("#[cfg(test)]") || a.text.contains("::test]")))
    });
    if touched {
        return;
    }
    let text = line_of(d, line);
    // `byte` indexes the lowercased line; clamp in case lowercasing changed lengths.
    let col = text.to_lowercase().get(..byte).map_or(0, |p| p.chars().count());
    out.push(
        Finding::new("PR004", Level::Warn, "the description says tests were added, but none changed")
            .at_text(&d.source, line, text, col, word.chars().count(), "no test file is part of this diff")
            .help("check they were committed and pushed, or correct the description"),
    );
}

fn screenshots(cx: &Cx, d: &Description, out: &mut Vec<Finding>) {
    // Commit messages are not where screenshots go.
    if d.has_image || d.source == "commit messages" {
        return;
    }
    let ui = cx
        .diff
        .files
        .iter()
        .filter(|f| f.status != Status::Deleted && !is_test_path(&f.path) && f.added_count() > 0)
        .filter(|f| f.path.ends_with(".blade.php") || matches!(ext(&f.path).as_str(), "vue" | "svelte" | "tsx" | "jsx" | "css" | "scss" | "html"))
        .count();
    if ui > 0 {
        out.push(
            Finding::new("PR005", Level::Note, format!("{ui} UI file(s) changed and the description has no screenshot or recording"))
                .help("a before/after picture lets a reviewer spot layout problems without running the branch"),
        );
    }
}

fn issues(d: &Description, out: &mut Vec<Finding>) {
    let closes: Vec<&str> = d.issues.iter().filter(|i| i.closes).map(|i| i.target.as_str()).collect();
    if closes.is_empty() {
        return;
    }
    out.push(
        Finding::new("PR006", Level::Note, format!("says it closes {}", closes.join(", ")))
            .note("the issue text is not part of this review")
            .test(format!("open {} and walk through its steps or acceptance criteria yourself", closes.join(", "))),
    );
}

#[cfg(test)]
mod tests {
    use super::super::testing::*;
    use super::*;
    use crate::review::desc;
    use crate::review::project::Project;

    fn with(parts: &[String], text: &str) -> Vec<Finding> {
        let d = desc::parse(text, "PR description");
        review_with(parts, &Project::default(), Some(&d))
    }

    const MIG: &str = "database/migrations/2024_01_01_000000_add_x.php";

    #[test]
    fn unchecked_items_point_into_the_description() {
        let f = with(&[add("a.txt", &["x"])], "## Test plan\n- clicked it\n\n- [ ] Docs updated\n");
        let s = get(&f, "PR001").span.clone().unwrap();
        assert_eq!((s.file.as_str(), s.line, s.col, s.len), ("PR description", 4, 7, 12));
        assert!(!has(&f, "PR002"));
    }

    #[test]
    fn missing_test_plan() {
        assert!(has(&with(&[add("a.txt", &["x"])], "Fix a thing"), "PR002"));
        assert!(has(&with(&[add("a.txt", &["x"])], "## Test plan\n<!-- fill in -->\n"), "PR002"));
    }

    #[test]
    fn unmentioned_migration_and_env() {
        let parts = [add(MIG, &["Schema::create('x');"]), edit("config/a.php", &["+'k' => env('NEW_KEY'),"])];
        let f = with(&parts, "Adds a feature");
        assert_eq!(f.iter().filter(|f| f.code == "PR003").count(), 2);
        let g = with(&parts, "Run the migration. Set NEW_KEY in .env");
        assert!(!has(&g, "PR003"));
    }

    #[test]
    fn claimed_tests_that_are_not_there() {
        let f = with(&[add("src/a.rs", &["fn a() {}"])], "I added tests for this.");
        let s = get(&f, "PR004").span.clone().unwrap();
        assert_eq!((s.line, s.col), (1, 3));
        assert!(!has(&with(&[add("tests/a.rs", &["x"])], "I added tests"), "PR004"));
        assert!(!has(&with(&[add("src/a.rs", &["x"])], "- [ ] added tests"), "PR004"));
    }

    #[test]
    fn screenshots_and_issues() {
        let f = with(&[add("src/App.vue", &["<template/>"])], "Fixes #4");
        assert!(has(&f, "PR005"));
        assert!(get(&f, "PR006").title.contains("#4"));
        assert!(!has(&with(&[add("src/App.vue", &["<template/>"])], "![a](b.png)"), "PR005"));
    }
}