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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! A forgiving parser for unified diffs, as `git diff` (and the hosts' `.diff` URLs) write them.
//!
//! It never fails: whatever it cannot understand is skipped, so a odd diff gives a partial
//! review rather than none. Hunks are read by their line counts, so a removed line that
//! happens to start with `-- ` or a context line starting with `diff` is not mistaken for
//! a header.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    Context,
    Added,
    Removed,
}

#[derive(Clone, Debug)]
pub struct Line {
    pub kind: Kind,
    pub text: String,
    pub old_no: Option<u32>,
    pub new_no: Option<u32>,
}

#[derive(Clone, Debug, Default)]
pub struct Hunk {
    pub lines: Vec<Line>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
    Added,
    Deleted,
    Modified,
    Renamed,
    Copied,
}

#[derive(Clone, Debug)]
pub struct FileDiff {
    /// The path after the change (before it, for a deleted file), with `/` separators.
    pub path: String,
    /// The path before a rename or copy.
    pub old_path: Option<String>,
    pub status: Status,
    pub binary: bool,
    pub old_mode: Option<String>,
    pub new_mode: Option<String>,
    pub hunks: Vec<Hunk>,
}

#[derive(Clone, Debug, Default)]
pub struct Diff {
    pub files: Vec<FileDiff>,
}

impl FileDiff {
    pub fn lines(&self) -> impl Iterator<Item = &Line> {
        self.hunks.iter().flat_map(|h| h.lines.iter())
    }
    pub fn added(&self) -> impl Iterator<Item = &Line> {
        self.lines().filter(|l| l.kind == Kind::Added)
    }
    pub fn removed(&self) -> impl Iterator<Item = &Line> {
        self.lines().filter(|l| l.kind == Kind::Removed)
    }
    pub fn added_count(&self) -> usize {
        self.added().count()
    }
    pub fn removed_count(&self) -> usize {
        self.removed().count()
    }
}

impl Diff {
    pub fn added_count(&self) -> usize {
        self.files.iter().map(FileDiff::added_count).sum()
    }
    pub fn removed_count(&self) -> usize {
        self.files.iter().map(FileDiff::removed_count).sum()
    }
}

/// The file being read, with what the header lines said about it so far.
struct Builder {
    file: FileDiff,
    git: bool,
    old_null: bool,
    new_null: bool,
    new_file: bool,
    deleted_file: bool,
    renamed: bool,
    copied: bool,
}

impl Builder {
    fn new(path: String, old: Option<String>, git: bool) -> Self {
        let old_path = old.filter(|o| *o != path);
        Builder {
            file: FileDiff {
                path,
                old_path,
                status: Status::Modified,
                binary: false,
                old_mode: None,
                new_mode: None,
                hunks: Vec::new(),
            },
            git,
            old_null: false,
            new_null: false,
            new_file: false,
            deleted_file: false,
            renamed: false,
            copied: false,
        }
    }

    fn finish(mut self) -> FileDiff {
        self.file.status = if self.renamed {
            Status::Renamed
        } else if self.copied {
            Status::Copied
        } else if self.new_file || self.old_null {
            Status::Added
        } else if self.deleted_file || self.new_null {
            Status::Deleted
        } else {
            Status::Modified
        };
        self.file
    }
}

struct HunkState {
    hunk: Hunk,
    old_left: u32,
    new_left: u32,
    old_no: u32,
    new_no: u32,
}

#[derive(Default)]
struct Parser {
    files: Vec<FileDiff>,
    cur: Option<Builder>,
    hunk: Option<HunkState>,
    /// Inside a combined (`diff --cc`) diff, which is not supported: skip to the next file.
    skipping: bool,
}

pub fn parse(text: &str) -> Diff {
    let mut p = Parser::default();
    for raw in text.lines() {
        p.line(raw);
    }
    p.finish_file();
    Diff { files: p.files }
}

impl Parser {
    fn finish_hunk(&mut self) {
        if let (Some(h), Some(cur)) = (self.hunk.take(), self.cur.as_mut()) {
            cur.file.hunks.push(h.hunk);
        }
    }

    fn finish_file(&mut self) {
        self.finish_hunk();
        if let Some(cur) = self.cur.take() {
            self.files.push(cur.finish());
        }
    }

    /// A line inside a hunk. Returns whether it was one.
    fn hunk_line(&mut self, raw: &str) -> bool {
        let Some(h) = self.hunk.as_mut() else { return false };
        if h.old_left == 0 && h.new_left == 0 {
            return false;
        }
        let (kind, text) = match raw.as_bytes().first() {
            Some(b'\\') => return true, // "\ No newline at end of file"
            Some(b'+') if h.new_left > 0 => (Kind::Added, &raw[1..]),
            Some(b'-') if h.old_left > 0 => (Kind::Removed, &raw[1..]),
            Some(b' ') => (Kind::Context, &raw[1..]),
            // Some tools strip the trailing space of an empty context line.
            None => (Kind::Context, ""),
            _ => {
                self.finish_hunk();
                return false;
            }
        };
        let (old_no, new_no) = match kind {
            Kind::Added => (None, Some(h.new_no)),
            Kind::Removed => (Some(h.old_no), None),
            Kind::Context => (Some(h.old_no), Some(h.new_no)),
        };
        if kind != Kind::Added {
            h.old_left = h.old_left.saturating_sub(1);
            h.old_no += 1;
        }
        if kind != Kind::Removed {
            h.new_left = h.new_left.saturating_sub(1);
            h.new_no += 1;
        }
        h.hunk.lines.push(Line { kind, text: text.to_string(), old_no, new_no });
        true
    }

    fn line(&mut self, raw: &str) {
        if self.hunk_line(raw) {
            return;
        }
        if let Some(rest) = raw.strip_prefix("diff --git ") {
            self.finish_file();
            self.skipping = false;
            let (old, new) = split_git_header(rest).unzip();
            let path = new.or_else(|| old.clone()).unwrap_or_default();
            self.cur = Some(Builder::new(path, old, true));
            return;
        }
        if raw.starts_with("diff --cc ") || raw.starts_with("diff --combined ") {
            self.finish_file();
            self.skipping = true;
            return;
        }
        if self.skipping {
            return;
        }
        if let Some(rest) = raw.strip_prefix("@@ ") {
            self.finish_hunk();
            if self.cur.is_none() {
                return;
            }
            if let Some((old_start, old_len, new_start, new_len)) = parse_hunk_header(rest) {
                self.hunk = Some(HunkState {
                    hunk: Hunk::default(),
                    old_left: old_len,
                    new_left: new_len,
                    old_no: old_start,
                    new_no: new_start,
                });
            }
            return;
        }
        if let Some(rest) = raw.strip_prefix("--- ") {
            // Plain `diff -u` has no `diff --git` line: a `---` after hunks starts a new file.
            if self.cur.as_ref().is_none_or(|c| !c.git || !c.file.hunks.is_empty()) {
                self.finish_file();
                self.cur = Some(Builder::new(String::new(), None, false));
            }
            let cur = self.cur.as_mut().unwrap();
            let (path, null) = header_path(rest, cur.git, "a/");
            if null {
                cur.old_null = true;
            } else {
                if cur.file.old_path.is_none() && !cur.git {
                    cur.file.old_path = Some(path.clone());
                }
                if cur.file.path.is_empty() {
                    cur.file.path = path;
                }
            }
            return;
        }
        if let Some(rest) = raw.strip_prefix("+++ ") {
            let Some(cur) = self.cur.as_mut() else { return };
            let (path, null) = header_path(rest, cur.git, "b/");
            if null {
                cur.new_null = true;
            } else if !path.is_empty() {
                cur.file.path = path;
                if cur.file.old_path.as_deref() == Some(cur.file.path.as_str()) {
                    cur.file.old_path = None;
                }
            }
            return;
        }
        let Some(cur) = self.cur.as_mut() else { return };
        if let Some(mode) = raw.strip_prefix("new file mode ") {
            cur.new_file = true;
            cur.file.new_mode = Some(mode.trim().to_string());
        } else if let Some(mode) = raw.strip_prefix("deleted file mode ") {
            cur.deleted_file = true;
            cur.file.old_mode = Some(mode.trim().to_string());
        } else if let Some(mode) = raw.strip_prefix("old mode ") {
            cur.file.old_mode = Some(mode.trim().to_string());
        } else if let Some(mode) = raw.strip_prefix("new mode ") {
            cur.file.new_mode = Some(mode.trim().to_string());
        } else if let Some(p) = raw.strip_prefix("rename from ") {
            cur.renamed = true;
            cur.file.old_path = Some(unquote(p));
        } else if let Some(p) = raw.strip_prefix("rename to ") {
            cur.renamed = true;
            cur.file.path = unquote(p);
        } else if let Some(p) = raw.strip_prefix("copy from ") {
            cur.copied = true;
            cur.file.old_path = Some(unquote(p));
        } else if let Some(p) = raw.strip_prefix("copy to ") {
            cur.copied = true;
            cur.file.path = unquote(p);
        } else if raw.starts_with("Binary files ") || raw.starts_with("GIT binary patch") {
            cur.file.binary = true;
        }
    }
}

/// `-12,3 +14,4 @@ section` (after the leading `@@ `) as (old start, old len, new start, new len).
fn parse_hunk_header(rest: &str) -> Option<(u32, u32, u32, u32)> {
    let rest = rest.strip_prefix('-')?;
    let (old, rest) = rest.split_once(" +")?;
    let new = rest.split(" @@").next()?;
    let range = |r: &str| -> Option<(u32, u32)> {
        match r.split_once(',') {
            Some((a, b)) => Some((a.parse().ok()?, b.parse().ok()?)),
            None => Some((r.parse().ok()?, 1)),
        }
    };
    let (os, ol) = range(old)?;
    let (ns, nl) = range(new)?;
    Some((os, ol, ns, nl))
}

/// The path from a `---` or `+++` line, and whether it is `/dev/null`.
fn header_path(rest: &str, git: bool, prefix: &str) -> (String, bool) {
    let rest = rest.trim_end_matches(['\r', '\n']);
    // Paths with spaces are followed by a tab (and, from `diff -u`, a timestamp).
    let rest = if rest.starts_with('"') { rest } else { rest.split('\t').next().unwrap_or(rest) };
    let path = unquote(rest.trim_end());
    if path == "/dev/null" {
        return (String::new(), true);
    }
    let path = if git { path.strip_prefix(prefix).unwrap_or(&path).to_string() } else { path };
    (path, false)
}

/// The two paths of `a/x b/x` (after `diff --git `), without their `a/` and `b/`.
fn split_git_header(rest: &str) -> Option<(String, String)> {
    let strip = |s: String| s.strip_prefix("a/").or_else(|| s.strip_prefix("b/")).map(str::to_string).unwrap_or(s);
    if rest.starts_with('"') {
        let end = quoted_end(rest)?;
        let first = unquote(&rest[..=end]);
        let second = unquote(rest[end + 1..].trim_start());
        return Some((strip(first), strip(second)));
    }
    // Unquoted paths may contain spaces: prefer the split where both halves are the same
    // path, which is every case except renames (those are corrected by `rename from/to`).
    let mut fallback = None;
    for (i, _) in rest.match_indices(" b/") {
        let (a, b) = (&rest[..i], &rest[i + 1..]);
        if let (Some(a2), Some(b2)) = (a.strip_prefix("a/"), b.strip_prefix("b/")) {
            if a2 == b2 {
                return Some((a2.to_string(), b2.to_string()));
            }
            fallback = Some((a2.to_string(), b2.to_string()));
        }
    }
    if fallback.is_some() {
        return fallback;
    }
    let (a, b) = rest.split_once(' ')?;
    Some((strip(a.to_string()), strip(b.to_string())))
}

/// Index of the closing quote of the string starting at `s[0]`.
fn quoted_end(s: &str) -> Option<usize> {
    let mut escaped = false;
    for (i, c) in s.char_indices().skip(1) {
        match c {
            _ if escaped => escaped = false,
            '\\' => escaped = true,
            '"' => return Some(i),
            _ => {}
        }
    }
    None
}

/// Undo git's C-style quoting (`"caf\303\251\t.txt"`), if `s` is quoted.
pub fn unquote(s: &str) -> String {
    let Some(inner) = s.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else {
        return s.to_string();
    };
    let bytes = inner.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'\\' || i + 1 >= bytes.len() {
            out.push(bytes[i]);
            i += 1;
            continue;
        }
        i += 1;
        match bytes[i] {
            b'n' => out.push(b'\n'),
            b't' => out.push(b'\t'),
            b'r' => out.push(b'\r'),
            b'a' => out.push(7),
            b'b' => out.push(8),
            b'f' => out.push(12),
            b'v' => out.push(11),
            b'0'..=b'7' => {
                let mut v = 0u32;
                let mut n = 0;
                while n < 3 && i < bytes.len() && (b'0'..=b'7').contains(&bytes[i]) {
                    v = v * 8 + u32::from(bytes[i] - b'0');
                    i += 1;
                    n += 1;
                }
                out.push(v as u8);
                continue;
            }
            other => out.push(other),
        }
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;

    const BASIC: &str = "\
diff --git a/src/a.rs b/src/a.rs
index 1111111..2222222 100644
--- a/src/a.rs
+++ b/src/a.rs
@@ -1,4 +1,5 @@ fn main
 one
-two
+TWO
+two and a half
 three
 four
diff --git a/new.txt b/new.txt
new file mode 100644
index 0000000..3333333
--- /dev/null
+++ b/new.txt
@@ -0,0 +1,2 @@
+hello
+world
\\ No newline at end of file
diff --git a/gone.txt b/gone.txt
deleted file mode 100644
index 4444444..0000000
--- a/gone.txt
+++ /dev/null
@@ -1 +0,0 @@
-bye
";

    #[test]
    fn reads_files_statuses_and_line_numbers() {
        let d = parse(BASIC);
        assert_eq!(d.files.len(), 3);
        let a = &d.files[0];
        assert_eq!((a.path.as_str(), a.status), ("src/a.rs", Status::Modified));
        assert_eq!((a.added_count(), a.removed_count()), (2, 1));
        let lines = &a.hunks[0].lines;
        assert_eq!(lines[0].old_no, Some(1));
        assert_eq!(lines[1].kind, Kind::Removed);
        assert_eq!((lines[1].old_no, lines[1].new_no), (Some(2), None));
        assert_eq!((lines[2].old_no, lines[2].new_no), (None, Some(2)));
        assert_eq!(lines[4].new_no, Some(4));
        assert_eq!(d.files[1].status, Status::Added);
        assert_eq!(d.files[1].added_count(), 2);
        assert_eq!((d.files[2].status, d.files[2].path.as_str()), (Status::Deleted, "gone.txt"));
        assert_eq!((d.added_count(), d.removed_count()), (4, 2));
    }

    #[test]
    fn content_that_looks_like_headers_is_content() {
        let d = parse(
            "diff --git a/x.sql b/x.sql\n--- a/x.sql\n+++ b/x.sql\n@@ -1,3 +1,3 @@\n -- a comment\n--- removed dashes\n+++ added pluses\n+diff --git a/fake b/fake\n ok\n",
        );
        assert_eq!(d.files.len(), 1);
        let l = &d.files[0].hunks[0].lines;
        assert_eq!(l.len(), 5);
        assert_eq!(l[1].text, "-- removed dashes");
        assert_eq!(l[2].text, "++ added pluses");
        assert_eq!(l[3].text, "diff --git a/fake b/fake");
    }

    #[test]
    fn renames_copies_modes_and_binaries() {
        let d = parse(
            "diff --git a/old name.txt b/new name.txt\nsimilarity index 90%\nrename from old name.txt\nrename to new name.txt\n\
diff --git a/run.sh b/run.sh\nold mode 100644\nnew mode 100755\n\
diff --git a/logo.png b/logo.png\nBinary files a/logo.png and b/logo.png differ\n",
        );
        assert_eq!(d.files.len(), 3);
        assert_eq!(d.files[0].status, Status::Renamed);
        assert_eq!(d.files[0].path, "new name.txt");
        assert_eq!(d.files[0].old_path.as_deref(), Some("old name.txt"));
        assert_eq!((d.files[1].old_mode.as_deref(), d.files[1].new_mode.as_deref()), (Some("100644"), Some("100755")));
        assert!(d.files[2].binary);
    }

    #[test]
    fn quoted_and_spaced_paths() {
        let d = parse(
            "diff --git \"a/caf\\303\\251 \\\"x\\\".txt\" \"b/caf\\303\\251 \\\"x\\\".txt\"\n--- \"a/caf\\303\\251 \\\"x\\\".txt\"\n+++ \"b/caf\\303\\251 \\\"x\\\".txt\"\n@@ -1 +1 @@\n-a\n+b\n\
diff --git a/my file.txt b/my file.txt\n--- a/my file.txt\t\n+++ b/my file.txt\t\n@@ -1 +1 @@\n-a\n+b\n",
        );
        assert_eq!(d.files[0].path, "café \"x\".txt");
        assert_eq!(d.files[1].path, "my file.txt");
        assert_eq!(d.files[1].added_count(), 1);
    }

    #[test]
    fn plain_unified_diffs_and_stripped_context_lines() {
        let d = parse(
            "--- a.txt\t2024-01-01\n+++ a.txt\t2024-01-02\n@@ -1,3 +1,3 @@\n x\n\n-y\n+z\n--- b.txt\n+++ b.txt\n@@ -1 +1 @@\n-1\n+2\n",
        );
        assert_eq!(d.files.len(), 2);
        assert_eq!(d.files[0].path, "a.txt");
        assert_eq!(d.files[0].hunks[0].lines.len(), 4);
        assert_eq!(d.files[1].path, "b.txt");
    }

    #[test]
    fn garbage_and_empty_input_do_not_panic() {
        assert!(parse("").files.is_empty());
        assert!(parse("hello\nworld\n@@ nonsense\n+x\n").files.is_empty());
        let d = parse("diff --git a/x b/x\n@@ -1,2 +1,2 @@\n a\n?what\n+b\n");
        assert_eq!(d.files.len(), 1);
        let d = parse("diff --cc x\n@@@ -1,1 -1,1 +1,1 @@@\n+++ b/x\n");
        assert!(d.files.is_empty());
    }

    #[test]
    fn multiple_hunks_keep_their_own_numbers() {
        let d = parse(
            "diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1,2 +1,2 @@\n a\n-b\n+B\n@@ -10,2 +10,3 @@\n j\n+new\n k\n",
        );
        let h = &d.files[0].hunks;
        assert_eq!(h.len(), 2);
        assert_eq!(h[1].lines[1].new_no, Some(11));
    }
}