rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! 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/")));
    }
}