hewdiff 0.2.0

High-performance review-first terminal diff viewer with PR-style comments
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Flatten a [`Changeset`] into lightweight rows for rendering + anchoring.

use crate::comments::model::{CommentStore, Thread};
use crate::diff::model::{Changeset, LineKind, Side};
use std::collections::HashSet;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

/// Format a `SystemTime` as a UTC `YYYY-MM-DD HH:MM` timestamp (no external
/// date crate).
fn fmt_date(t: SystemTime) -> String {
    let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() as i64;
    let days = secs.div_euclid(86_400);
    let tod = secs.rem_euclid(86_400);
    let (hh, mm) = (tod / 3600, (tod % 3600) / 60);
    // Howard Hinnant's civil-from-days algorithm.
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = y + if m <= 2 { 1 } else { 0 };
    format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}")
}

/// One visual line of an inline-expanded comment thread.
#[derive(Debug, Clone)]
pub enum CommentLine {
    /// Top rounded border of the thread box.
    Top,
    /// Thread header: resolved state + message count.
    Head { resolved: bool, replies: usize },
    /// A message author line (`@name`) with its formatted date.
    Author { name: String, date: String },
    /// A (pre-wrapped) body line.
    Body(String),
    /// Blank spacer between messages.
    Gap,
    /// Bottom rounded border of the thread box.
    Bottom,
}

/// Greedy word-wrap to `width` columns, hard-splitting over-long words.
fn wrap_text(s: &str, width: usize) -> Vec<String> {
    let width = width.max(1);
    let mut out = Vec::new();
    let mut line = String::new();
    let mut w = 0usize;
    let push_word = |word: &str, out: &mut Vec<String>, line: &mut String, w: &mut usize| {
        let ww = word.chars().count();
        if *w == 0 {
            if ww <= width {
                line.push_str(word);
                *w = ww;
            } else {
                let mut cw = 0;
                for ch in word.chars() {
                    if cw == width {
                        out.push(std::mem::take(line));
                        cw = 0;
                    }
                    line.push(ch);
                    cw += 1;
                }
                *w = cw;
            }
        } else if *w + 1 + ww <= width {
            line.push(' ');
            line.push_str(word);
            *w += 1 + ww;
        } else {
            out.push(std::mem::take(line));
            *w = 0;
            // re-handle this word at the start of a fresh line
            if ww <= width {
                line.push_str(word);
                *w = ww;
            } else {
                let mut cw = 0;
                for ch in word.chars() {
                    if cw == width {
                        out.push(std::mem::take(line));
                        cw = 0;
                    }
                    line.push(ch);
                    cw += 1;
                }
                *w = cw;
            }
        }
    };
    for word in s.split_whitespace() {
        push_word(word, &mut out, &mut line, &mut w);
    }
    out.push(line);
    out
}

/// Expand a thread into wrapped visual lines.
pub fn thread_lines(t: &Thread, width: usize) -> Vec<CommentLine> {
    let mut out = vec![
        CommentLine::Top,
        CommentLine::Head {
            resolved: t.resolved,
            replies: t.comments.len(),
        },
    ];
    for (i, c) in t.comments.iter().enumerate() {
        out.push(CommentLine::Author {
            name: c.author.clone().unwrap_or_else(|| "?".into()),
            date: fmt_date(c.created_at),
        });
        for raw in c.body.split('\n') {
            let s = sanitize_line(raw);
            if s.is_empty() {
                out.push(CommentLine::Body(String::new()));
            } else {
                for wl in wrap_text(&s, width) {
                    out.push(CommentLine::Body(wl));
                }
            }
        }
        if i + 1 < t.comments.len() {
            out.push(CommentLine::Gap);
        }
    }
    out.push(CommentLine::Bottom);
    out
}

/// Inline-comment lines to inject after a code row, for every expanded thread
/// whose anchor matches one of the row's `(side, line)` anchors.
fn comment_rows_for(
    comments: &CommentStore,
    expanded: &HashSet<usize>,
    emitted: &mut HashSet<usize>,
    path: &str,
    anchors: &[(Side, u32)],
    width: usize,
) -> Vec<CommentLine> {
    let mut out = Vec::new();
    for (i, t) in comments.threads.iter().enumerate() {
        if !expanded.contains(&i) || emitted.contains(&i) || t.file.as_path() != Path::new(path) {
            continue;
        }
        // Emit once per thread, at the first line of its range present in the
        // diff (anchor ranges can span several lines).
        if anchors
            .iter()
            .any(|(s, l)| *s == t.side && t.range.contains(*l))
        {
            emitted.insert(i);
            out.extend(thread_lines(t, width));
        }
    }
    out
}

/// Make a line safe for a TUI cell grid. ratatui diffs cells between frames, so
/// a stray `\r`, tab, or ANSI escape corrupts the terminal and never self-heals.
/// We expand tabs (4-col stops), drop CR/LF, strip ANSI CSI/OSC sequences, and
/// drop any remaining control characters.
pub fn sanitize_line(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut col = 0usize;
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\t' => {
                let n = 4 - (col % 4);
                out.extend(std::iter::repeat_n(' ', n));
                col += n;
            }
            '\r' | '\n' => {}
            '\u{1b}' => match chars.peek() {
                // CSI: ESC [ ... <final 0x40..=0x7e>
                Some('[') => {
                    chars.next();
                    while let Some(&p) = chars.peek() {
                        chars.next();
                        if ('@'..='~').contains(&p) {
                            break;
                        }
                    }
                }
                // OSC: ESC ] ... (BEL | ESC \)
                Some(']') => {
                    chars.next();
                    while let Some(&p) = chars.peek() {
                        chars.next();
                        if p == '\u{7}' {
                            break;
                        }
                        if p == '\u{1b}' {
                            if chars.peek() == Some(&'\\') {
                                chars.next();
                            }
                            break;
                        }
                    }
                }
                _ => {}
            },
            c if c.is_control() => {}
            c => {
                out.push(c);
                col += 1;
            }
        }
    }
    out
}

#[derive(Debug, Clone)]
pub enum RowKind {
    FileHeader,
    HunkHeader,
    Line {
        kind: LineKind,
        old_line: Option<u32>,
        new_line: Option<u32>,
    },
    /// An inline-expanded comment-thread line (non-selectable).
    Comment(CommentLine),
}

#[derive(Debug, Clone)]
pub struct Row {
    pub file_idx: usize,
    pub kind: RowKind,
    pub text: String,
}

impl Row {
    /// The comment anchor (side, line) for a code line, if any.
    pub fn anchor(&self) -> Option<(Side, u32)> {
        match &self.kind {
            RowKind::Line {
                kind,
                old_line,
                new_line,
            } => match kind {
                LineKind::Deletion => old_line.map(|l| (Side::Old, l)),
                _ => new_line.map(|l| (Side::New, l)),
            },
            _ => None,
        }
    }
    pub fn is_selectable(&self) -> bool {
        matches!(self.kind, RowKind::Line { .. })
    }
}

/// One side (left=old / right=new) of a split row.
#[derive(Debug, Clone)]
pub struct SideCell {
    pub kind: LineKind,
    pub line: Option<u32>,
    pub text: String,
}

#[derive(Debug, Clone)]
pub enum SplitRowKind {
    FileHeader,
    HunkHeader,
    /// A side-by-side pair. Either side may be empty (padding).
    Pair {
        left: Option<SideCell>,
        right: Option<SideCell>,
    },
    /// An inline-expanded comment-thread line (non-selectable).
    Comment(CommentLine),
}

#[derive(Debug, Clone)]
pub struct SplitRow {
    pub file_idx: usize,
    pub kind: SplitRowKind,
    pub text: String, // header text
}

impl SplitRow {
    pub fn is_selectable(&self) -> bool {
        matches!(self.kind, SplitRowKind::Pair { .. })
    }

    /// Comment anchor: prefer the new (right) side, fall back to old (left).
    pub fn anchor(&self) -> Option<(Side, u32)> {
        match &self.kind {
            SplitRowKind::Pair { left, right } => right
                .as_ref()
                .and_then(|c| c.line.map(|l| (Side::New, l)))
                .or_else(|| left.as_ref().and_then(|c| c.line.map(|l| (Side::Old, l)))),
            _ => None,
        }
    }
}

fn hunk_header(hunk: &crate::diff::model::Hunk) -> String {
    format!(
        "@@ -{},{} +{},{} @@{}",
        hunk.old_start,
        hunk.old_count,
        hunk.new_start,
        hunk.new_count,
        hunk.section
            .as_ref()
            .map(|s| format!(" {s}"))
            .unwrap_or_default()
    )
}

/// Build the side-by-side (split) row list. Within a change block, consecutive
/// deletions (left) are zipped with consecutive additions (right); context
/// lines appear on both sides.
pub fn build_split_rows(
    changeset: &Changeset,
    comments: &CommentStore,
    expanded: &HashSet<usize>,
    width: usize,
) -> Vec<SplitRow> {
    let mut rows = Vec::new();
    let mut emitted = HashSet::new();
    for (fi, file) in changeset.files.iter().enumerate() {
        let path = file.display_path();
        rows.push(SplitRow {
            file_idx: fi,
            kind: SplitRowKind::FileHeader,
            text: file.display_path().to_string(),
        });
        if file.is_binary {
            rows.push(SplitRow {
                file_idx: fi,
                kind: SplitRowKind::HunkHeader,
                text: "Binary file".into(),
            });
            continue;
        }
        for hunk in &file.hunks {
            rows.push(SplitRow {
                file_idx: fi,
                kind: SplitRowKind::HunkHeader,
                text: hunk_header(hunk),
            });
            let mut dels: Vec<SideCell> = Vec::new();
            let mut adds: Vec<SideCell> = Vec::new();
            for line in &hunk.lines {
                let cell = SideCell {
                    kind: line.kind,
                    line: match line.kind {
                        LineKind::Deletion => line.old_line,
                        _ => line.new_line,
                    },
                    text: sanitize_line(&line.text),
                };
                match line.kind {
                    LineKind::Deletion => dels.push(cell),
                    LineKind::Addition => adds.push(cell),
                    LineKind::Context => {
                        flush_pairs(
                            fi,
                            &mut dels,
                            &mut adds,
                            &mut rows,
                            comments,
                            expanded,
                            &mut emitted,
                            path,
                            width,
                        );
                        rows.push(SplitRow {
                            file_idx: fi,
                            kind: SplitRowKind::Pair {
                                left: Some(SideCell {
                                    kind: LineKind::Context,
                                    line: line.old_line,
                                    text: sanitize_line(&line.text),
                                }),
                                right: Some(cell),
                            },
                            text: String::new(),
                        });
                        let mut anchors = Vec::new();
                        if let Some(l) = line.old_line {
                            anchors.push((Side::Old, l));
                        }
                        if let Some(l) = line.new_line {
                            anchors.push((Side::New, l));
                        }
                        for cl in comment_rows_for(
                            comments,
                            expanded,
                            &mut emitted,
                            path,
                            &anchors,
                            width,
                        ) {
                            rows.push(SplitRow {
                                file_idx: fi,
                                kind: SplitRowKind::Comment(cl),
                                text: String::new(),
                            });
                        }
                    }
                }
            }
            flush_pairs(
                fi,
                &mut dels,
                &mut adds,
                &mut rows,
                comments,
                expanded,
                &mut emitted,
                path,
                width,
            );
        }
    }
    rows
}

/// Emit the accumulated deletion/addition runs as zipped pairs.
#[allow(clippy::too_many_arguments)]
fn flush_pairs(
    file_idx: usize,
    dels: &mut Vec<SideCell>,
    adds: &mut Vec<SideCell>,
    rows: &mut Vec<SplitRow>,
    comments: &CommentStore,
    expanded: &HashSet<usize>,
    emitted: &mut HashSet<usize>,
    path: &str,
    width: usize,
) {
    let n = dels.len().max(adds.len());
    let mut di = dels.drain(..);
    let mut ai = adds.drain(..);
    for _ in 0..n {
        let left = di.next();
        let right = ai.next();
        let mut anchors = Vec::new();
        if let Some(l) = left.as_ref().and_then(|c| c.line) {
            anchors.push((Side::Old, l));
        }
        if let Some(l) = right.as_ref().and_then(|c| c.line) {
            anchors.push((Side::New, l));
        }
        rows.push(SplitRow {
            file_idx,
            kind: SplitRowKind::Pair { left, right },
            text: String::new(),
        });
        for cl in comment_rows_for(comments, expanded, emitted, path, &anchors, width) {
            rows.push(SplitRow {
                file_idx,
                kind: SplitRowKind::Comment(cl),
                text: String::new(),
            });
        }
    }
}

/// Build the unified (stack) row list.
pub fn build_rows(
    changeset: &Changeset,
    comments: &CommentStore,
    expanded: &HashSet<usize>,
    width: usize,
) -> Vec<Row> {
    let mut rows = Vec::new();
    let mut emitted = HashSet::new();
    for (fi, file) in changeset.files.iter().enumerate() {
        let path = file.display_path();
        rows.push(Row {
            file_idx: fi,
            kind: RowKind::FileHeader,
            text: file.display_path().to_string(),
        });
        if file.is_binary {
            rows.push(Row {
                file_idx: fi,
                kind: RowKind::HunkHeader,
                text: "Binary file".into(),
            });
            continue;
        }
        for hunk in &file.hunks {
            rows.push(Row {
                file_idx: fi,
                kind: RowKind::HunkHeader,
                text: hunk_header(hunk),
            });
            for line in &hunk.lines {
                let prefix = match line.kind {
                    LineKind::Addition => '+',
                    LineKind::Deletion => '-',
                    LineKind::Context => ' ',
                };
                rows.push(Row {
                    file_idx: fi,
                    kind: RowKind::Line {
                        kind: line.kind,
                        old_line: line.old_line,
                        new_line: line.new_line,
                    },
                    text: format!("{prefix}{}", sanitize_line(&line.text)),
                });
                let (side, ln) = match line.kind {
                    LineKind::Deletion => (Side::Old, line.old_line),
                    _ => (Side::New, line.new_line),
                };
                if let Some(ln) = ln {
                    for cl in comment_rows_for(
                        comments,
                        expanded,
                        &mut emitted,
                        path,
                        &[(side, ln)],
                        width,
                    ) {
                        rows.push(Row {
                            file_idx: fi,
                            kind: RowKind::Comment(cl),
                            text: String::new(),
                        });
                    }
                }
            }
        }
    }
    rows
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::loader::{load_comments, load_patch};
    use std::collections::HashSet;
    use std::path::Path;

    #[test]
    fn expands_tabs_and_strips_controls() {
        assert_eq!(sanitize_line("\tx"), "    x");
        assert_eq!(sanitize_line("a\tb"), "a   b"); // tab to next 4-col stop
        assert_eq!(sanitize_line("end\r"), "end");
        assert_eq!(sanitize_line("a\u{0}b"), "ab");
        // ANSI CSI color sequence is removed, payload kept.
        assert_eq!(sanitize_line("\u{1b}[31mred\u{1b}[0m"), "red");
    }

    #[test]
    fn injects_expanded_thread_rows() {
        let cs = load_patch(Some(Path::new("examples/rust-long-en.patch"))).unwrap();
        let comments = load_comments(Path::new("examples/rust-long-en.comments.json")).unwrap();
        let none = HashSet::new();
        let all: HashSet<usize> = (0..comments.threads.len()).collect();
        let base = build_rows(&cs, &comments, &none, 80);
        let rows = build_rows(&cs, &comments, &all, 80);
        // Expanding threads injects extra rows.
        assert!(rows.len() > base.len());
        // Those rows are comment rows: non-selectable and anchorless.
        let comment_rows = rows
            .iter()
            .filter(|r| matches!(r.kind, RowKind::Comment(_)))
            .count();
        assert!(comment_rows > 0);
        // Each thread renders exactly one header, regardless of multi-line
        // anchor ranges (no per-line duplication).
        let heads = rows
            .iter()
            .filter(|r| matches!(r.kind, RowKind::Comment(CommentLine::Head { .. })))
            .count();
        assert_eq!(heads, comments.threads.len());
        assert!(rows.iter().all(|r| !matches!(r.kind, RowKind::Comment(_))
            || (!r.is_selectable() && r.anchor().is_none())));
    }
}