rustimal 0.6.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
//! Guided testing: the steps to go through for a change, what became of each one, and where
//! that is kept. A result remembers which version of the change it was for, so after new
//! commits it is shown as needing another look rather than as done.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::diff::{Diff, FileDiff, Kind};
use super::render::Report;
use super::rules::Level;

/// A hash that stays the same between versions of rustimal (FNV-1a).
pub fn fingerprint(parts: &[&str]) -> String {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    for part in parts {
        for byte in part.bytes().chain([0]) {
            hash = (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3);
        }
    }
    format!("{hash:016x}")
}

fn diff_text(text: &mut String, f: &FileDiff) {
    text.push_str(&f.path);
    for l in f.lines() {
        text.push(match l.kind {
            Kind::Added => '+',
            Kind::Removed => '-',
            Kind::Context => ' ',
        });
        text.push_str(&l.text);
        text.push('\n');
    }
}

pub fn fingerprint_diff(diff: &Diff) -> String {
    let mut text = String::new();
    for f in &diff.files {
        diff_text(&mut text, f);
    }
    fingerprint(&[&text])
}

/// What a file's change is, so a tick stays put until that file changes again.
pub fn fingerprint_file(f: &FileDiff) -> String {
    let mut text = format!("{:?} {}\n", f.status, f.old_path.as_deref().unwrap_or(""));
    diff_text(&mut text, f);
    fingerprint(&[&text])
}

/// Whether a changed file has been read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Seen {
    No,
    Yes,
    /// Ticked, but the file has changed since.
    Changed,
}

/// One thing to test.
#[derive(Clone, Debug)]
pub struct Item {
    /// From the text, so a result stays with its step when others come and go.
    pub id: String,
    pub text: String,
    /// The author's own step, from the description.
    pub described: bool,
    /// Something to look at rather than to try: a finding that comes with no test.
    pub check: bool,
    /// The most serious of the findings behind it.
    pub level: Option<Level>,
    /// Indices into the report's findings.
    pub findings: Vec<usize>,
}

/// The author's steps first (does it do what it says?), then the ones from the findings,
/// most serious first, then the findings with no test of their own, to be looked at.
pub fn items(report: &Report) -> Vec<Item> {
    let mut out: Vec<Item> = Vec::new();
    for text in &report.described_steps {
        let id = fingerprint(&["described", text]);
        if !out.iter().any(|i| i.id == id) {
            out.push(Item { id, text: text.clone(), described: true, check: false, level: None, findings: Vec::new() });
        }
    }
    for step in &report.plan {
        let findings: Vec<usize> =
            report.findings.iter().enumerate().filter(|(_, f)| f.test.contains(&step.text)).map(|(i, _)| i).collect();
        let level = findings.iter().map(|&i| report.findings[i].level).min();
        out.push(Item { id: fingerprint(&["plan", &step.text]), text: step.text.clone(), described: false, check: false, level, findings });
    }
    for (i, f) in report.findings.iter().enumerate().filter(|(_, f)| f.test.is_empty()) {
        let place = f.span.as_ref().map(|s| format!("{}:{}", s.file, s.line)).unwrap_or_default();
        let id = fingerprint(&["check", f.code, &f.title, &place]);
        if !out.iter().any(|o| o.id == id) {
            out.push(Item { id, text: f.title.clone(), described: false, check: true, level: Some(f.level), findings: vec![i] });
        }
    }
    out
}

/// The commands and snippets a step quotes in backticks.
pub fn quoted(text: &str) -> Vec<String> {
    let mut parts = text.split('`');
    parts.next();
    let mut out = Vec::new();
    // Pairs only: a lone backtick quotes nothing.
    while let (Some(inside), Some(_)) = (parts.next(), parts.next()) {
        if !inside.trim().is_empty() && !out.iter().any(|o| o == inside) {
            out.push(inside.to_string());
        }
    }
    out
}

/// Whether a quoted snippet is something to run in the shell, rather than code or a name.
pub fn is_command(snippet: &str) -> bool {
    const PROGRAMS: &[&str] = &[
        "artisan", "bun", "bunx", "cargo", "composer", "curl", "docker", "git", "grep", "make", "node", "npm", "npx", "php", "pnpm",
        "rustimal", "yarn",
    ];
    let mut words = snippet.split_whitespace();
    let first = words.next().unwrap_or("");
    words.next().is_some() && (PROGRAMS.contains(&first) || first.starts_with("./vendor/bin/"))
}

/// A command made safe to type at a prompt. It can hold text from someone else's pull
/// request, and a line break or other control character would run it or worse.
pub fn typeable(command: &str) -> String {
    command.chars().filter(|c| !c.is_control()).collect()
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Verdict {
    Passed,
    Failed,
    Skipped,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Record {
    pub verdict: Verdict,
    #[serde(default)]
    pub note: String,
    /// The version of the change that was tested.
    pub revision: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
    Untested,
    Done(Verdict),
    /// Tested, but the change has moved on since.
    Stale(Verdict),
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Counts {
    pub passed: usize,
    pub failed: usize,
    pub skipped: usize,
    pub stale: usize,
    /// Not tested at all.
    pub left: usize,
}

#[derive(Default, Serialize, Deserialize)]
struct Saved {
    #[serde(default)]
    change: String,
    #[serde(default)]
    results: BTreeMap<String, Record>,
    /// Files ticked as read: path to the fingerprint of the file's change when it was.
    #[serde(default)]
    files: BTreeMap<String, String>,
    /// The version of the change that was approved from here.
    #[serde(default)]
    approved: Option<String>,
}

/// Which items a group of the results holds.
type Belongs = fn(&Item) -> bool;

pub struct Session {
    /// Where results are kept; none means they last only as long as the view.
    file: Option<PathBuf>,
    revision: String,
    saved: Saved,
}

impl Session {
    /// The results for a change in a repository, from `dir`.
    pub fn open(dir: Option<&Path>, root: &Path, change: &str, revision: &str) -> Session {
        let root = root.to_string_lossy().replace('\\', "/").to_lowercase();
        let file = dir.map(|d| d.join(format!("{}.json", fingerprint(&[&root, change]))));
        let saved = file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()).and_then(|s| serde_json::from_str(&s).ok());
        let mut saved: Saved = saved.unwrap_or_default();
        saved.change = change.to_string();
        Session { file, revision: revision.to_string(), saved }
    }

    pub fn record(&self, id: &str) -> Option<&Record> {
        self.saved.results.get(id)
    }

    pub fn state(&self, id: &str) -> State {
        match self.record(id) {
            None => State::Untested,
            Some(r) if r.revision == self.revision => State::Done(r.verdict),
            Some(r) => State::Stale(r.verdict),
        }
    }

    /// Record a verdict for this version, keeping any note.
    pub fn set(&mut self, id: &str, verdict: Verdict) -> Result<(), String> {
        let note = self.record(id).filter(|r| r.revision == self.revision).map(|r| r.note.clone()).unwrap_or_default();
        self.saved.results.insert(id.to_string(), Record { verdict, note, revision: self.revision.clone() });
        self.save()
    }

    pub fn set_note(&mut self, id: &str, note: &str) -> Result<(), String> {
        match self.saved.results.get_mut(id) {
            Some(r) => r.note = note.trim().to_string(),
            None => return Ok(()),
        }
        self.save()
    }

    pub fn clear(&mut self, id: &str) -> Result<(), String> {
        self.saved.results.remove(id);
        self.save()
    }

    pub fn reset(&mut self, items: &[Item]) -> Result<(), String> {
        for i in items {
            self.saved.results.remove(&i.id);
        }
        self.saved.files.clear();
        self.save()
    }

    pub fn seen(&self, file: &FileDiff) -> Seen {
        match self.saved.files.get(&file.path) {
            None => Seen::No,
            Some(print) if *print == fingerprint_file(file) => Seen::Yes,
            Some(_) => Seen::Changed,
        }
    }

    /// Tick a file as read, or untick it. Returns whether it is ticked now.
    pub fn toggle_seen(&mut self, file: &FileDiff) -> Result<bool, String> {
        let now = self.seen(file) != Seen::Yes;
        if now {
            self.saved.files.insert(file.path.clone(), fingerprint_file(file));
        } else {
            self.saved.files.remove(&file.path);
        }
        self.save().map(|()| now)
    }

    /// How many of the files are ticked, for the version they are now.
    pub fn seen_count(&self, files: &[FileDiff]) -> usize {
        files.iter().filter(|f| self.seen(f) == Seen::Yes).count()
    }

    /// Whether this version of the change was approved from here.
    pub fn approved(&self) -> bool {
        self.saved.approved.as_deref() == Some(self.revision.as_str())
    }

    pub fn set_approved(&mut self) -> Result<(), String> {
        self.saved.approved = Some(self.revision.clone());
        self.save()
    }

    pub fn counts(&self, items: &[Item]) -> Counts {
        let mut c = Counts::default();
        for i in items {
            *match self.state(&i.id) {
                State::Untested => &mut c.left,
                State::Stale(_) => &mut c.stale,
                State::Done(Verdict::Passed) => &mut c.passed,
                State::Done(Verdict::Failed) => &mut c.failed,
                State::Done(Verdict::Skipped) => &mut c.skipped,
            } += 1;
        }
        c
    }

    /// Written to a new file first, so a crash cannot leave half of one.
    fn save(&self) -> Result<(), String> {
        let Some(file) = &self.file else { return Ok(()) };
        let text = serde_json::to_string_pretty(&self.saved).map_err(|e| e.to_string())?;
        let temp = file.with_extension(format!("tmp{}", std::process::id()));
        file.parent()
            .map_or(Ok(()), std::fs::create_dir_all)
            .and_then(|()| std::fs::write(&temp, text))
            .and_then(|()| std::fs::rename(&temp, file))
            .map_err(|e| format!("could not save the test results: {e}"))
    }

    /// The results as Markdown, ready to paste into the pull request.
    pub fn markdown(&self, title: &str, items: &[Item], files: &[FileDiff]) -> String {
        let c = self.counts(items);
        let revision = self.revision.get(..10).unwrap_or(&self.revision);
        let mut out = format!("## Manual testing: {title}\n\nVersion `{revision}`: {} passed, {} failed, {} skipped", c.passed, c.failed, c.skipped);
        out += &format!(", {} not tested\n", c.left + c.stale);
        if !files.is_empty() {
            out += &format!("Files read: {} of {}\n", self.seen_count(files), files.len());
        }
        let groups: [(&str, Belongs); 3] = [
            ("From the description", |i| i.described),
            ("From the review", |i| !i.described && !i.check),
            ("Looked at in the code", |i| i.check),
        ];
        for (heading, belongs) in groups {
            let group: Vec<&Item> = items.iter().filter(|i| belongs(i)).collect();
            if group.is_empty() {
                continue;
            }
            out += &format!("\n### {heading}\n\n");
            for i in group {
                let (mark, tag) = match self.state(&i.id) {
                    State::Done(Verdict::Passed) => ("x", ""),
                    State::Done(Verdict::Failed) => (" ", "**FAILED** "),
                    State::Done(Verdict::Skipped) => (" ", "_skipped_ "),
                    State::Stale(_) => (" ", "_tested on an older version_ "),
                    State::Untested => (" ", ""),
                };
                out += &format!("- [{mark}] {tag}{}\n", i.text);
                if let Some(r) = self.record(&i.id).filter(|r| !r.note.is_empty() && r.revision == self.revision) {
                    out += &format!("  > {}\n", r.note.replace('\n', " "));
                }
            }
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::review::testutil::Scratch;

    fn item(text: &str) -> Item {
        Item { id: fingerprint(&[text]), text: text.into(), described: false, check: false, level: None, findings: Vec::new() }
    }

    #[test]
    fn results_come_back_and_go_stale_with_a_new_version() {
        let s = Scratch::new("session");
        let items = [item("one"), item("two"), item("three")];
        let open = |rev| Session::open(Some(&s.0), Path::new("C:\\App"), "pr 1", rev);
        let mut a = open("aaa");
        a.set(&items[0].id, Verdict::Passed).unwrap();
        a.set(&items[1].id, Verdict::Failed).unwrap();
        a.set_note(&items[1].id, " it crashed ").unwrap();

        let b = open("aaa");
        assert_eq!(b.state(&items[0].id), State::Done(Verdict::Passed));
        assert_eq!(b.record(&items[1].id).unwrap().note, "it crashed");
        assert_eq!(b.counts(&items), Counts { passed: 1, failed: 1, skipped: 0, stale: 0, left: 1 });
        let md = b.markdown("T", &items, &[]);
        assert!(md.contains("- [x] one") && md.contains("- [ ] **FAILED** two\n  > it crashed") && md.contains("- [ ] three"), "{md}");

        let mut c = open("bbb");
        assert_eq!(c.state(&items[0].id), State::Stale(Verdict::Passed));
        assert_eq!(c.counts(&items).stale, 2);
        c.set(&items[1].id, Verdict::Passed).unwrap();
        assert_eq!(c.record(&items[1].id).unwrap().note, "", "an old note does not carry over");

        c.reset(&items).unwrap();
        assert_eq!(open("bbb").counts(&items).left, 3);
        // Another repository or change has its own results.
        assert_eq!(Session::open(Some(&s.0), Path::new("C:\\Other"), "pr 1", "aaa").counts(&items).left, 3);
    }

    fn file(path: &str, added: &str) -> FileDiff {
        let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -1 +1,2 @@\n x\n+{added}\n");
        crate::review::diff::parse(&diff).files.remove(0)
    }

    #[test]
    fn ticked_files_stay_ticked_until_they_change() {
        let s = Scratch::new("seen");
        let open = |rev| Session::open(Some(&s.0), Path::new("C:\\App"), "pr 2", rev);
        let files = [file("a.rs", "one"), file("b.rs", "two")];
        let mut a = open("aaa");
        assert!(a.toggle_seen(&files[0]).unwrap());
        assert!(!a.approved());
        a.set_approved().unwrap();

        // Another version where only b.rs moved on: a.rs is still read.
        let mut b = open("bbb");
        let moved = [file("a.rs", "one"), file("b.rs", "three")];
        assert_eq!(b.seen(&moved[0]), Seen::Yes);
        assert!(!b.approved(), "an approval is for the version it was given to");
        assert!(open("aaa").approved());
        b.toggle_seen(&moved[1]).unwrap();
        assert_eq!(open("ccc").seen(&files[1]), Seen::Changed);
        assert_eq!(b.seen_count(&moved), 2);
        assert!(b.markdown("T", &[], &moved).contains("Files read: 2 of 2"));
        assert!(!b.toggle_seen(&moved[0]).unwrap(), "a second tick takes it off");
        b.reset(&[]).unwrap();
        assert_eq!(open("bbb").seen_count(&moved), 0);
    }

    #[test]
    fn quoted_commands_are_found_and_made_safe_to_type() {
        let q = quoted("run `php artisan migrate` and `legacy_total`, then `php artisan migrate`; a lone ` tick");
        assert_eq!(q, ["php artisan migrate", "legacy_total"]);
        assert!(is_command("php artisan migrate") && is_command("./vendor/bin/sail artisan test"));
        assert!(!is_command("legacy_total") && !is_command("await invoke('x')") && !is_command("git"));
        assert_eq!(typeable("php artisan test a\r\nrm -rf /\x1b[A\x03"), "php artisan test arm -rf /[A");
    }
}