ghtui 0.2.0

A keyboard-driven terminal client for GitHub, with a pull request diff viewer that goes further than GitHub's
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
//! Line diffs with context, as hunks.

pub use imara_diff::Algorithm;
use imara_diff::{Diff, InternedInput};

use crate::diff::anchor::{LinePos, Side};
use crate::diff::sat_u32;
use crate::diff::text::Text;

/// One entry of an alignment: a line on both sides, or on one. Line
/// numbers are 1-based, as in files and in GitHub's comment API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DiffLine {
    Context { old: u32, new: u32 },
    Removed(u32),
    Added(u32),
}

impl DiffLine {
    /// The old-side line, unless added.
    pub fn left(self) -> Option<LinePos> {
        self.on(Side::Left)
    }

    /// The new-side line, unless removed.
    pub fn right(self) -> Option<LinePos> {
        self.on(Side::Right)
    }

    pub fn on(self, side: Side) -> Option<LinePos> {
        let line = match (self, side) {
            (Self::Context { old, .. } | Self::Removed(old), Side::Left) => old,
            (Self::Context { new, .. } | Self::Added(new), Side::Right) => new,
            _ => return None,
        };
        Some(LinePos { side, line })
    }

    /// Its lines, left then right.
    pub fn lines(self) -> impl Iterator<Item = LinePos> {
        self.left().into_iter().chain(self.right())
    }

    /// The line a unified view shows: the old one when removed, else the new.
    pub fn shown(self) -> LinePos {
        let (side, line) = match self {
            Self::Removed(line) => (Side::Left, line),
            Self::Context { new: line, .. } | Self::Added(line) => (Side::Right, line),
        };
        LinePos { side, line }
    }

    pub fn is_change(self) -> bool {
        !matches!(self, Self::Context { .. })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hunk {
    /// 1-based start and length, as in `@@ -a,b +c,d @@`.
    pub old_start: u32,
    pub old_len: u32,
    pub new_start: u32,
    pub new_len: u32,
    pub lines: Vec<DiffLine>,
}

impl Hunk {
    pub fn header(&self) -> String {
        format!(
            "@@ -{},{} +{},{} @@",
            self.old_start, self.old_len, self.new_start, self.new_len
        )
    }
}

/// How lines are compared.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Whitespace {
    /// Byte-exact, including line endings (like `git diff`).
    #[default]
    Exact,
    /// All whitespace ignored, including CR (like `git diff -w`).
    Ignore,
}

/// The full alignment of `old` and `new`: every line of both files, in
/// order, as context (present in both), removed or added. Within a change,
/// removed lines come before added ones.
pub fn align(
    old: &Text,
    new: &Text,
    algorithm: Algorithm,
    whitespace: Whitespace,
) -> Vec<DiffLine> {
    let key = |text: &Text, i: usize| -> String {
        match whitespace {
            Whitespace::Exact => text.token(i),
            Whitespace::Ignore => text
                .line(i)
                .chars()
                .filter(|c| !c.is_whitespace())
                .collect(),
        }
    };
    let before: Vec<String> = (0..old.len()).map(|i| key(old, i)).collect();
    let after: Vec<String> = (0..new.len()).map(|i| key(new, i)).collect();
    let mut input = InternedInput::default();
    input.update_before(before.iter().map(String::as_str));
    input.update_after(after.iter().map(String::as_str));
    let mut diff = Diff::compute(algorithm, &input);
    diff.postprocess_lines(&input);

    // Indices are 0-based, line numbers 1-based.
    let mut lines = Vec::with_capacity(old.len().max(new.len()));
    let (mut o, mut n) = (0, 0);
    // The context after the last change comes before an empty one at the end.
    let (old_end, new_end) = (sat_u32(old.len()), sat_u32(new.len()));
    let end = (old_end..old_end, new_end..new_end);
    for (before, after) in diff.hunks().map(|h| (h.before, h.after)).chain([end]) {
        let context = (o..before.start).zip(n..);
        lines.extend(context.map(|(o, n)| DiffLine::Context {
            old: o + 1,
            new: n + 1,
        }));
        lines.extend(before.clone().map(|o| DiffLine::Removed(o + 1)));
        lines.extend(after.clone().map(|n| DiffLine::Added(n + 1)));
        (o, n) = (before.end, after.end);
    }
    lines
}

/// Ranges of `lines` to show: everything within `context` lines of a
/// change, plus any `windows`, or everything when `full`. Adjacent visible
/// lines form one range, so changes closer than `2 * context` share a hunk.
pub fn segments(
    lines: &[DiffLine],
    context: u32,
    windows: &[std::ops::Range<u32>],
    full: bool,
) -> Vec<std::ops::Range<usize>> {
    segments_by(
        lines.len(),
        |i| lines.get(i).is_some_and(|l| l.is_change()),
        context,
        windows,
        full,
    )
}

/// [`segments`] with the caller deciding which lines count as changes
/// (e.g. only changes made since a previous review).
#[expect(clippy::single_range_in_vec_init, reason = "a list of one range")]
pub fn segments_by(
    len: usize,
    is_change: impl Fn(usize) -> bool,
    context: u32,
    windows: &[std::ops::Range<u32>],
    full: bool,
) -> Vec<std::ops::Range<usize>> {
    if len == 0 {
        return Vec::new();
    }
    if full {
        return vec![0..len];
    }
    let context = context as usize;
    let mut visible = vec![false; len];
    let mut show = |range: std::ops::Range<usize>| {
        if let Some(lines) = visible.get_mut(range.start..range.end.min(len)) {
            lines.fill(true);
        }
    };
    // Each change shows from where the previous one's context ended.
    let mut shown = 0;
    for i in (0..len).filter(|&i| is_change(i)) {
        let end = i.saturating_add(context).saturating_add(1);
        show(i.saturating_sub(context).max(shown)..end);
        shown = end;
    }
    for window in windows {
        show(window.start as usize..window.end as usize);
    }
    let mut end = 0;
    visible
        .chunk_by(|a, b| a == b)
        .filter_map(|run| {
            let start = end;
            end += run.len();
            (run.first() == Some(&true)).then_some(start..end)
        })
        .collect()
}

/// How many old and new lines `lines` show.
pub fn side_counts(lines: &[DiffLine]) -> (u32, u32) {
    lines.iter().fold((0, 0), |(o, n), l| {
        (
            o + u32::from(l.left().is_some()),
            n + u32::from(l.right().is_some()),
        )
    })
}

/// The hunk for `range`, given how many old/new lines precede it.
fn hunk(lines: &[DiffLine], range: std::ops::Range<usize>, before: (u32, u32)) -> Hunk {
    let lines = lines.get(range).unwrap_or_default().to_vec();
    let (old_len, new_len) = side_counts(&lines);
    let start = |seen: u32, len: u32| if len > 0 { seen + 1 } else { seen };
    Hunk {
        old_start: start(before.0, old_len),
        old_len,
        new_start: start(before.1, new_len),
        new_len,
        lines,
    }
}

/// The hunks of `lines` for ranges `segs`, in order.
pub fn hunks(lines: &[DiffLine], segs: &[std::ops::Range<usize>]) -> Vec<Hunk> {
    let (mut seen, mut before) = (0, (0, 0));
    let hunk_at = |seg: &std::ops::Range<usize>| {
        let (o, n) = side_counts(lines.get(seen..seg.start).unwrap_or_default());
        (seen, before) = (seg.start, (before.0 + o, before.1 + n));
        hunk(lines, seg.clone(), before)
    };
    segs.iter().map(hunk_at).collect()
}

/// Diffs `old` against `new` and groups changes into hunks with `context`
/// lines around them, as `git diff -U<context>` does.
pub fn diff_lines(old: &Text, new: &Text, algorithm: Algorithm, context: u32) -> Vec<Hunk> {
    let lines = align(old, new, algorithm, Whitespace::Exact);
    hunks(&lines, &segments(&lines, context, &[], false))
}

#[cfg(test)]
#[expect(clippy::single_range_in_vec_init, reason = "lists of ranges")]
mod tests {
    use super::*;

    fn hunks(old: &str, new: &str, algorithm: Algorithm) -> Vec<Hunk> {
        diff_lines(
            &Text::new(old.as_bytes()),
            &Text::new(new.as_bytes()),
            algorithm,
            3,
        )
    }

    fn render(old: &str, new: &str) -> String {
        let (old, new) = (Text::new(old.as_bytes()), Text::new(new.as_bytes()));
        let mut out = String::new();
        for hunk in diff_lines(&old, &new, Algorithm::Histogram, 3) {
            out.push_str(&hunk.header());
            out.push('\n');
            for line in &hunk.lines {
                let (sign, text) = match *line {
                    DiffLine::Context { new: n, .. } => (' ', new.line_no(n)),
                    DiffLine::Added(n) => ('+', new.line_no(n)),
                    DiffLine::Removed(o) => ('-', old.line_no(o)),
                };
                out.push(sign);
                out.push_str(text);
                out.push('\n');
            }
        }
        out
    }

    fn numbered(n: u32) -> String {
        (1..=n).map(|i| format!("line {i}\n")).collect()
    }

    #[test]
    fn single_change_with_context() {
        let old = numbered(10);
        let new = old.replace("line 5\n", "line five\n");
        assert_eq!(
            render(&old, &new),
            "@@ -2,7 +2,7 @@\n line 2\n line 3\n line 4\n-line 5\n+line five\n line 6\n line 7\n line 8\n"
        );
    }

    #[test]
    fn close_changes_merge_far_ones_split() {
        let old = numbered(30);
        let near = old.replace("line 5\n", "x\n").replace("line 9\n", "y\n");
        assert_eq!(hunks(&old, &near, Algorithm::Histogram).len(), 1);
        let far = old.replace("line 5\n", "x\n").replace("line 25\n", "y\n");
        assert_eq!(hunks(&old, &far, Algorithm::Histogram).len(), 2);
    }

    #[test]
    fn added_and_deleted_files() {
        assert_eq!(render("", "a\nb\n"), "@@ -0,0 +1,2 @@\n+a\n+b\n");
        assert_eq!(render("a\nb\n", ""), "@@ -1,2 +0,0 @@\n-a\n-b\n");
        assert_eq!(render("same\n", "same\n"), "");
    }

    #[test]
    fn insertion_at_start_and_end() {
        assert_eq!(
            render("a\nb\n", "z\na\nb\n"),
            "@@ -1,2 +1,3 @@\n+z\n a\n b\n"
        );
        assert_eq!(
            render("a\nb\n", "a\nb\nc\n"),
            "@@ -1,2 +1,3 @@\n a\n b\n+c\n"
        );
    }

    #[test]
    fn missing_final_newline_is_a_change() {
        assert_eq!(render("a\nb\n", "a\nb"), "@@ -1,2 +1,2 @@\n a\n-b\n+b\n");
    }

    #[test]
    fn crlf_change_is_a_change() {
        assert_eq!(
            render("a\nb\n", "a\r\nb\n"),
            "@@ -1,2 +1,2 @@\n-a\n+a\n b\n"
        );
    }

    /// Hunk headers must match `git diff` exactly: GitHub's commentable
    /// ranges and our rendering are compared by line numbers.
    #[test]
    fn hunk_headers_match_git() {
        let base = numbered(40);
        let cases = [
            (base.clone(), base.replace("line 2\n", "")),
            (
                base.clone(),
                base.replace("line 10\n", "line 10\nnew a\nnew b\n"),
            ),
            (
                base.clone(),
                base.replace("line 1\n", "first\n")
                    .replace("line 40\n", "last\n"),
            ),
            (
                base.clone(),
                base.replace("line 5\n", "x\n")
                    .replace("line 12\n", "y\n")
                    .replace("line 30\n", ""),
            ),
            (base.clone(), format!("{base}tail\n")),
            (format!("head\n{base}"), base.clone()),
        ];
        let dir = std::env::temp_dir().join(format!("ghtui-hunks-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        for (i, (old, new)) in cases.iter().enumerate() {
            let (a, b) = (dir.join(format!("{i}.old")), dir.join(format!("{i}.new")));
            std::fs::write(&a, old).unwrap();
            std::fs::write(&b, new).unwrap();
            let out = std::process::Command::new("git")
                .args(["diff", "--no-index", "-U3", "--diff-algorithm=myers"])
                .arg(&a)
                .arg(&b)
                .output()
                .unwrap();
            let expected: Vec<String> = String::from_utf8_lossy(&out.stdout)
                .lines()
                .filter(|l| l.starts_with("@@"))
                .map(|l| {
                    // Normalize git's `-a` (len 1 omitted) to `-a,1`.
                    let inner = l.trim_start_matches("@@ ").split(" @@").next().unwrap();
                    let parts: Vec<String> = inner
                        .split(' ')
                        .map(|p| {
                            if p.contains(',') {
                                p.to_owned()
                            } else {
                                format!("{p},1")
                            }
                        })
                        .collect();
                    format!("@@ {} @@", parts.join(" "))
                })
                .collect();
            let actual: Vec<String> = hunks(old, new, Algorithm::Myers)
                .iter()
                .map(Hunk::header)
                .collect();
            assert_eq!(actual, expected, "case {i}");
        }
        std::fs::remove_dir_all(&dir).unwrap();
    }

    fn kinds(lines: &[DiffLine]) -> String {
        lines
            .iter()
            .map(|l| match l {
                DiffLine::Context { .. } => ' ',
                DiffLine::Removed(_) => '-',
                DiffLine::Added(_) => '+',
            })
            .collect()
    }

    #[test]
    fn alignment_covers_every_line() {
        let old = Text::new(b"a\nb\nc\n");
        let new = Text::new(b"a\nB\nc\nd\n");
        let lines = align(&old, &new, Algorithm::Histogram, Whitespace::Exact);
        assert_eq!(kinds(&lines), " -+ +");
        assert_eq!(side_counts(&lines), (3, 4));
    }

    #[test]
    fn ignoring_whitespace() {
        let old = Text::new(b"fn f() {\n  x();\n}\nend\n");
        let new = Text::new(b"fn f() {\n\tx( );\r\n}\nEND\n");
        assert_eq!(
            kinds(&align(&old, &new, Algorithm::Histogram, Whitespace::Exact)),
            " -+ -+"
        );
        assert_eq!(
            kinds(&align(&old, &new, Algorithm::Histogram, Whitespace::Ignore)),
            "   -+"
        );
    }

    #[test]
    fn segments_with_windows_and_full() {
        let old = numbered(40);
        let new = old.replace("line 20\n", "x\n");
        let lines = align(
            &Text::new(old.as_bytes()),
            &Text::new(new.as_bytes()),
            Algorithm::Histogram,
            Whitespace::Exact,
        );
        assert_eq!(segments(&lines, 3, &[], false), [16..24]);
        assert_eq!(segments(&lines, 3, &[0..2], false), [0..2, 16..24]);
        assert_eq!(segments(&lines, 3, &[10..16], false), [10..24]);
        assert_eq!(segments(&lines, 3, &[], true), [0..41]);
        assert!(segments(&[], 3, &[], false).is_empty());
    }
}