jj-compose 0.2.2

Easily split big jujutsu working copy changes into atomic commits
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! The diff pane: loading `jj diff` output and scrolling through it.

use std::{iter, ops::Range};

use ansi_to_tui::IntoText;
use anyhow::{Context, Result, anyhow};
use ratatui::{
    Frame,
    layout::{Constraint, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Paragraph},
};

use jj_compose_core::{FileDiff, HunkId, Jj, Patch, Target, patch};

/// Columns a tab advances to. Terminal tab stops are every 8 columns, but
/// diffs are already indented by line numbers, so a narrower stop keeps
/// tab-indented code readable in a half-width pane.
const TAB_WIDTH: usize = 4;

/// Load and parse the diff of `target`.
///
/// # Errors
///
/// Returns an error if:
/// * Executing the underlying `jj diff` command fails or returns a non-zero exit status.
/// * Parsing the generated git diff output and its ANSI escape sequences into a `DiffView` fails.
pub fn load(jj: &Jj, target: &Target) -> Result<DiffView> {
    let stdout = jj.git_diff(target).map_err(|e| anyhow!("{e}"))?;
    let empty = format!("(no changes in {})", target.change_id);
    DiffView::from_output(&stdout, &empty)
}

/// A file's position in the rendered diff.
pub struct FileEntry {
    pub path: String,
    pub added: usize,
    pub removed: usize,
    /// Row of the file's title line.
    pub row: usize,
}

/// Replace tabs with spaces up to the next tab stop. Terminals would do
/// this, but ratatui gives a tab zero width, so tab-indented code would
/// otherwise lose its indentation. Escape sequences take no columns.
fn expand_tabs(bytes: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(bytes.len());
    let mut column = 0;
    let mut in_escape = false;
    for &b in bytes {
        match b {
            b'\t' => {
                let spaces = TAB_WIDTH - column % TAB_WIDTH;
                out.extend(iter::repeat_n(b' ', spaces));
                column += spaces;
                continue;
            }
            b'\n' => column = 0,
            0x1b => in_escape = true,
            // An SGR sequence (the only kind jj emits) ends with `m`.
            b'm' if in_escape => in_escape = false,
            // Count characters, not UTF-8 continuation bytes.
            _ if !in_escape && b & 0xC0 != 0x80 => column += 1,
            _ => {}
        }
        out.push(b);
    }
    out
}

/// One hunk's place on screen and in the patch.
#[derive(Debug, Clone)]
pub struct HunkEntry {
    pub id: HunkId,
    /// Path of the file it belongs to.
    pub path: String,
    /// Rows it occupies, header line first.
    pub rows: Range<usize>,
}

/// What to say about one line of a hunk being divided.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mark {
    /// A context line: not a choice, so it is dimmed out of the way.
    Context,
    /// A `+`/`-` line: the commit it is going to, whether the cursor is on
    /// it, and whether a visual selection covers it.
    Line {
        commit: Option<u8>,
        cursor: bool,
        selected: bool,
    },
}

impl Mark {
    const fn is_cursor(self) -> bool {
        matches!(self, Self::Line { cursor: true, .. })
    }

    /// Style `line` to say where it is going. jj's own colors reset at each
    /// span, so the style is patched onto every span rather than set on the
    /// line, exactly as a search match is.
    fn apply(self, mut line: Line<'static>) -> Line<'static> {
        let Self::Line {
            commit,
            cursor,
            selected,
        } = self
        else {
            for span in &mut line.spans {
                span.style = span.style.patch(Style::new().add_modifier(Modifier::DIM));
            }
            return line;
        };
        let mut style = commit.map_or_else(
            || {
                Style::new()
                    .add_modifier(Modifier::DIM)
                    .add_modifier(Modifier::CROSSED_OUT)
            },
            |n| Style::new().fg(crate::app::ui::box_color(n)),
        );
        // A selection is a background, so the cursor's reverse still reads
        // against it. Unlike the hunk list, the range is shown rather than
        // only announced in the status bar.
        if selected {
            style = style.bg(Color::Indexed(238));
        }
        if cursor {
            style = style.add_modifier(Modifier::REVERSED);
        }
        for span in &mut line.spans {
            span.style = span.style.patch(style);
        }
        line
    }
}

/// The diff text plus its scroll position.
pub struct DiffView {
    rows: Vec<Line<'static>>,
    files: Vec<FileEntry>,
    /// Every hunk, in order.
    hunks: Vec<HunkEntry>,
    /// The diff as text, for building a patch of chosen hunks.
    patch: Patch,
    scroll: usize,
    /// Columns scrolled to the right, for long lines.
    pan: u16,
    /// Rows visible inside the pane, updated on every draw.
    height: usize,
    /// Show the list of files down the left side.
    show_files: bool,
    search: Option<Search>,
}

/// The last search and where its matches are.
struct Search {
    query: String,
    /// Rows containing the query, in order.
    rows: Vec<usize>,
    /// Index into `rows` of the match last jumped to.
    current: usize,
}

impl DiffView {
    /// Build the view from `jj diff --git --color=always` output. `empty` is
    /// shown when there are no changes.
    ///
    /// # Errors
    ///
    /// If the colors in `output` can't be parsed.
    pub fn from_output(output: &[u8], empty: &str) -> Result<Self> {
        let expanded = expand_tabs(output);
        let styled = expanded
            .into_text()
            .context("Failed to parse ANSI colors in diff output")?
            .lines;

        let plain: Vec<String> = patch::strip_ansi(&String::from_utf8_lossy(&expanded))
            .lines()
            .map(str::to_owned)
            .collect();

        let patch = Patch::new(plain);

        let mut view = Self {
            rows: Vec::new(),
            files: Vec::new(),
            hunks: Vec::new(),
            patch: patch.clone(),
            scroll: 0,
            pan: 0,
            height: 0,
            show_files: false,
            search: None,
        };
        if patch.files().is_empty() {
            view.rows
                .push(Line::raw(empty.to_owned()).style(Color::DarkGray));
        }
        for (i, file) in patch.files().iter().enumerate() {
            view.push_file(i, file, &styled, &patch);
        }
        Ok(view)
    }

    /// The parsed diff, for building a patch of chosen hunks.
    #[must_use]
    pub const fn patch(&self) -> &Patch {
        &self.patch
    }

    /// Every hunk, in the order they appear.
    #[must_use]
    pub fn hunks(&self) -> &[HunkEntry] {
        &self.hunks
    }

    /// A title row with the path and counts, any header lines that say
    /// something (new, deleted, renamed, binary), then the hunks.
    fn push_file(
        &mut self,
        index: usize,
        file: &FileDiff,
        styled: &[Line<'static>],
        patch: &Patch,
    ) {
        if !self.rows.is_empty() {
            self.rows.push(Line::default()); // blank line between files
        }
        self.files.push(FileEntry {
            path: file.path.clone(),
            added: file.added,
            removed: file.removed,
            row: self.rows.len(),
        });
        self.rows.push(file_title(file));

        let line = |i: usize| styled.get(i).cloned().unwrap_or_default();
        for i in file.header.clone() {
            // The path and counts are already in the title.
            let noise = ["diff --git ", "index ", "--- ", "+++ "];
            if !noise.iter().any(|p| patch.line(i).starts_with(p)) {
                self.rows.push(line(i).style(Color::DarkGray));
            }
        }
        for (h, hunk) in file.hunks.iter().enumerate() {
            let start = self.rows.len();
            self.rows.push(line(hunk.header));
            self.rows.extend(hunk.lines.clone().map(line));
            self.hunks.push(HunkEntry {
                id: HunkId {
                    file: index,
                    hunk: h,
                },
                path: file.path.clone(),
                rows: start..self.rows.len(),
            });
        }
    }

    /// The file at the top of the pane, numbered from 1.
    #[must_use]
    pub fn current_file(&self) -> Option<(usize, &FileEntry)> {
        // The last file whose title is at or above the first visible row.
        let i = self.files.partition_point(|f| f.row <= self.scroll);
        let i = i.checked_sub(1)?;
        Some((i + 1, &self.files[i]))
    }

    #[must_use]
    pub const fn file_count(&self) -> usize {
        self.files.len()
    }

    /// Half the visible height (at least one line).
    #[must_use]
    pub const fn half_page(&self) -> usize {
        if self.height > 2 { self.height / 2 } else { 1 }
    }

    pub fn scroll_down(&mut self, n: usize) {
        // Past a jumps position near the end, don't snap back up.
        let limit = self.max_scroll().max(self.scroll);
        self.scroll = self.scroll.saturating_add(n).min(limit);
    }

    pub const fn scroll_up(&mut self, n: usize) {
        self.scroll = self.scroll.saturating_sub(n);
    }

    pub const fn scroll_to_top(&mut self) {
        self.scroll = 0;
    }

    pub const fn scroll_to_bottom(&mut self) {
        self.scroll = self.max_scroll();
    }

    pub const fn pan_right(&mut self, n: u16) {
        self.pan = self.pan.saturating_add(n);
    }

    pub const fn pan_left(&mut self, n: u16) {
        self.pan = self.pan.saturating_sub(n);
    }

    /// The last scroll offset that still fills the pane.
    const fn max_scroll(&self) -> usize {
        self.rows.len().saturating_sub(self.height)
    }

    /// Draw only the visible lines, so a large diff costs the same per
    /// frame as a small one.
    pub fn render(&mut self, frame: &mut Frame<'_>, area: Rect, block: Block<'static>) {
        let mut inner = block.inner(area);
        frame.render_widget(block, area);
        if self.show_files && !self.files.is_empty() {
            let [list, rest] = Layout::horizontal([
                Constraint::Length(self.file_list_width(inner)),
                Constraint::Fill(1),
            ])
            .areas(inner);
            self.render_file_list(frame, list);
            inner = rest;
        }
        self.height = usize::from(inner.height);
        // Clamp to the last row, not the last full page (see `jump`).
        self.scroll = self.scroll.min(self.rows.len().saturating_sub(1));

        let end = (self.scroll + self.height).min(self.rows.len());
        let visible = (self.scroll..end)
            .map(|i| self.highlighted(i))
            .collect::<Vec<_>>();
        frame.render_widget(Paragraph::new(visible).scroll((0, self.pan)), inner);
    }

    /// Wide enough for the longest entry, up to a third of the pane.
    fn file_list_width(&self, area: Rect) -> u16 {
        let longest = self.files.iter().map(|f| list_entry(f).width()).max();
        let wanted = u16::try_from(longest.unwrap_or(0) + 2).unwrap_or(u16::MAX);
        wanted.min(area.width / 3)
    }

    /// One row per file with its counts; the file at the top of the diff is
    /// highlighted and kept in view.
    fn render_file_list(&self, frame: &mut Frame<'_>, area: Rect) {
        let current = self.current_file().map_or(0, |(n, _)| n - 1);
        let height = usize::from(area.height);
        let first = current.saturating_sub(height.saturating_sub(1));
        let rows: Vec<Line<'_>> = self.files[first..]
            .iter()
            .take(height)
            .enumerate()
            .map(|(i, file)| {
                let line = list_entry(file);
                if first + i == current {
                    line.patch_style(Modifier::REVERSED)
                } else {
                    line
                }
            })
            .collect();
        let block = Block::new()
            .borders(ratatui::widgets::Borders::RIGHT)
            .border_style(Color::DarkGray);
        frame.render_widget(Paragraph::new(rows).block(block), area);
    }

    pub const fn toggle_file_list(&mut self) {
        self.show_files = !self.show_files;
    }

    pub fn next_file(&mut self) {
        self.jump(first_after(self.files.iter().map(|f| f.row), self.scroll));
    }

    pub fn prev_file(&mut self) {
        self.jump(last_before(self.files.iter().map(|f| f.row), self.scroll));
    }

    pub fn next_hunk(&mut self) {
        self.jump(first_after(
            self.hunks.iter().map(|h| h.rows.start),
            self.scroll,
        ));
    }

    pub fn prev_hunk(&mut self) {
        self.jump(last_before(
            self.hunks.iter().map(|h| h.rows.start),
            self.scroll,
        ));
    }

    /// Draw one hunk on its own, filling the pane: the whole of the view
    /// while a split is being chosen.
    pub fn render_hunk(
        &mut self,
        frame: &mut Frame<'_>,
        area: Rect,
        block: Block<'static>,
        at: usize,
    ) {
        let inner = block.inner(area);
        frame.render_widget(block, area);
        self.height = usize::from(inner.height);
        let Some(hunk) = self.hunks.get(at) else {
            return;
        };
        // Scrolling applies within the hunk, so a long one is still readable.
        self.scroll = self.scroll.clamp(hunk.rows.start, hunk.rows.end);
        let end = (self.scroll + self.height).min(hunk.rows.end);
        let visible = (self.scroll..end)
            .map(|i| self.highlighted(i))
            .collect::<Vec<_>>();
        frame.render_widget(Paragraph::new(visible).scroll((0, self.pan)), inner);
    }

    /// Draw a hunk opened up for line-level assignment: its lines in the
    /// order they will be committed in, each showing where it is going.
    ///
    /// `rows` names the patch lines to draw, in order, with what to say
    /// about each; the caller works that out, because it is the one holding
    /// the plan. The window follows the cursor rather than the pane's own
    /// scroll, since the cursor is what is being moved.
    pub fn render_divided(
        &mut self,
        frame: &mut Frame<'_>,
        area: Rect,
        block: Block<'static>,
        at: usize,
        rows: &[(usize, Mark)],
    ) {
        let inner = block.inner(area);
        frame.render_widget(block, area);
        self.height = usize::from(inner.height);
        let Some(hunk) = self.hunks.get(at) else {
            return;
        };
        let Some(parsed) = self
            .patch
            .files()
            .get(hunk.id.file)
            .and_then(|f| f.hunks.get(hunk.id.hunk))
        else {
            return;
        };
        // A hunk's rows are its header then its lines, one for one and in
        // order, so a patch line's row follows from where the hunk starts.
        let row_of = |l: usize| hunk.rows.start + 1 + l.saturating_sub(parsed.lines.start);

        let height = self.height.max(1);
        let cursor = rows.iter().position(|(_, m)| m.is_cursor()).unwrap_or(0);
        let top = cursor
            .saturating_sub(height / 2)
            .min(rows.len().saturating_sub(height));
        let lines: Vec<Line<'static>> = rows
            .iter()
            .skip(top)
            .take(height)
            .map(|&(l, mark)| mark.apply(self.rows.get(row_of(l)).cloned().unwrap_or_default()))
            .collect();
        frame.render_widget(Paragraph::new(lines).scroll((0, self.pan)), inner);
    }

    /// Put the hunk at `at` at the top of the pane.
    pub fn show_hunk(&mut self, at: usize) {
        if let Some(hunk) = self.hunks.get(at) {
            self.scroll = hunk.rows.start;
        }
    }

    /// Put `row` at the top of the pane, if there is one, even near the end
    /// of the diff (like Vim's `zt`), so the file or hunk is what's on top.
    const fn jump(&mut self, row: Option<usize>) {
        if let Some(row) = row {
            self.scroll = row;
        }
    }
    /// Find the rows containing `query`, ignoring case unless it has a
    /// capital letter, and jump to the first at or below the top of the pane.
    /// Returns the number of matches.
    pub fn search(&mut self, query: &str) -> usize {
        if query.is_empty() {
            self.search = None;
            return 0;
        }
        let ignore_case = !query.chars().any(char::is_uppercase);
        let needle = if ignore_case {
            query.to_lowercase()
        } else {
            query.to_owned()
        };
        let rows: Vec<usize> = (0..self.rows.len())
            .filter(|&i| {
                let text = line_text(&self.rows[i]);
                if ignore_case {
                    text.to_lowercase()
                } else {
                    text
                }
                .contains(&needle)
            })
            .collect();
        let count = rows.len();
        let current = rows.iter().position(|&row| row >= self.scroll).unwrap_or(0);
        self.search = Some(Search {
            query: query.to_owned(),
            rows,
            current,
        });
        self.show_match();
        count
    }

    /// Go to the next match, wrapping around at the end.
    pub fn next_match(&mut self) {
        if let Some(search) = &mut self.search
            && !search.rows.is_empty()
        {
            search.current = (search.current + 1) % search.rows.len();
        }
        self.show_match();
    }

    /// Go to the previous match, wrapping around at the start.
    pub fn prev_match(&mut self) {
        if let Some(search) = &mut self.search
            && !search.rows.is_empty()
        {
            search.current = search
                .current
                .checked_sub(1)
                .unwrap_or(search.rows.len() - 1);
        }
        self.show_match();
    }

    /// The query, the current match (from 1) and the number of matches.
    #[must_use]
    pub fn search_status(&self) -> Option<(&str, usize, usize)> {
        let search = self.search.as_ref()?;
        let current = if search.rows.is_empty() {
            0
        } else {
            search.current + 1
        };
        Some((&search.query, current, search.rows.len()))
    }

    /// Scroll the current match into view, a third of the way down so the
    /// lines before it are visible too.
    fn show_match(&mut self) {
        if let Some(&row) = self.search.as_ref().and_then(|s| s.rows.get(s.current)) {
            self.scroll = row.saturating_sub(self.height / 3);
        }
    }

    /// Row `i`, with a background if it matches the search; the current
    /// match is shown reversed.
    fn highlighted(&self, i: usize) -> Line<'static> {
        let mut line = self.rows[i].clone();
        let Some(search) = &self.search else {
            return line;
        };
        let style = match search.rows.binary_search(&i) {
            Ok(n) if n == search.current => Style::new().add_modifier(Modifier::REVERSED),
            Ok(_) => Style::new().bg(Color::DarkGray),
            Err(_) => return line,
        };
        // Per span: jj's colors reset at each span, which would undo a
        // style set on the line as a whole.
        for span in &mut line.spans {
            span.style = span.style.patch(style);
        }
        line
    }
}

/// `path  +12 -3` in bold, with the counts in green and red.
fn file_title(file: &FileDiff) -> Line<'static> {
    let bold = Style::new().add_modifier(Modifier::BOLD);
    let mut spans = vec![Span::styled(file.path.clone(), bold.fg(Color::Yellow))];
    if file.binary {
        spans.push(Span::styled("  binary", Style::new().fg(Color::DarkGray)));
    } else {
        spans.push(Span::styled(
            format!("  +{}", file.added),
            bold.fg(Color::Green),
        ));
        spans.push(Span::styled(
            format!(" -{}", file.removed),
            bold.fg(Color::Red),
        ));
    }
    Line::from(spans)
}

/// The first of `rows` below `top`.
fn first_after(mut rows: impl Iterator<Item = usize>, top: usize) -> Option<usize> {
    rows.find(|&row| row > top)
}

/// The last of `rows` above `top`.
fn last_before(rows: impl Iterator<Item = usize>, top: usize) -> Option<usize> {
    rows.take_while(|&row| row < top).last()
}

/// `path +12 -3` for the file list.
fn list_entry(file: &FileEntry) -> Line<'static> {
    Line::from(vec![
        Span::raw(file.path.clone()),
        Span::styled(format!(" +{}", file.added), Color::Green),
        Span::styled(format!(" -{}", file.removed), Color::Red),
    ])
}
/// A row's text without its styling.
fn line_text(line: &Line<'_>) -> String {
    line.spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect()
}

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

    /// What `jj diff --git --color=always` prints for a two-file change.
    const OUTPUT: &[u8] = b"\
\x1b[1mdiff --git a/a.rs b/a.rs\x1b[0m
\x1b[1mindex 1111..2222 100644\x1b[0m
\x1b[1m--- a/a.rs\x1b[0m
\x1b[1m+++ b/a.rs\x1b[0m
\x1b[38;5;6m@@ -1,2 +1,2 @@\x1b[39m
 keep
\x1b[38;5;1m-\told\x1b[39m
\x1b[38;5;2m+\tnew\x1b[39m
\x1b[1mdiff --git a/b.txt b/b.txt\x1b[0m
\x1b[1mnew file mode 100644\x1b[0m
\x1b[38;5;6m@@ -0,0 +1,1 @@\x1b[39m
\x1b[38;5;2m+hi\x1b[39m
";

    fn text(line: &Line<'_>) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn expands_tabs_to_tab_stops() {
        assert_eq!(expand_tabs(b"\tx"), b"    x");
        assert_eq!(expand_tabs(b"ab\tx\n\ty"), b"ab  x\n    y");
    }

    #[test]
    fn escapes_and_multibyte_chars_take_no_extra_columns() {
        assert_eq!(expand_tabs(b"\x1b[32m+\x1b[0m\tx"), b"\x1b[32m+\x1b[0m   x");
        assert_eq!(expand_tabs("é\tx".as_bytes()), "é   x".as_bytes());
    }

    #[test]
    fn rows_have_titles_hunks_and_no_header_noise() {
        let view = DiffView::from_output(OUTPUT, "").unwrap();
        let rows: Vec<String> = view.rows.iter().map(text).collect();
        assert_eq!(
            rows,
            [
                "a.rs  +1 -1",
                "@@ -1,2 +1,2 @@",
                " keep",
                "-   old",
                "+   new",
                "",
                "b.txt  +1 -0",
                "new file mode 100644",
                "@@ -0,0 +1,1 @@",
                "+hi",
            ]
        );
        assert_eq!(view.files.iter().map(|f| f.row).collect::<Vec<_>>(), [0, 6]);
        let starts: Vec<usize> = view.hunks.iter().map(|h| h.rows.start).collect();
        assert_eq!(starts, [1, 8]);
    }

    #[test]
    fn current_file_follows_the_scroll() {
        let mut view = DiffView::from_output(OUTPUT, "").unwrap();
        view.height = 2;
        assert_eq!(view.current_file().unwrap().0, 1);
        view.scroll_down(5);
        assert_eq!(view.current_file().unwrap().0, 1);
        view.scroll_down(1);
        let (n, file) = view.current_file().unwrap();
        assert_eq!((n, file.path.as_str(), file.added), (2, "b.txt", 1));
    }

    #[test]
    fn empty_diff_says_so() {
        let view = DiffView::from_output(b"", "(no changes)").unwrap();
        assert_eq!(text(&view.rows[0]), "(no changes)");
        assert!(view.files.is_empty());
    }

    #[test]
    fn scrolling_is_clamped() {
        let mut view = DiffView::from_output(OUTPUT, "").unwrap();
        view.height = 4;
        view.scroll_down(100);
        assert_eq!(view.scroll, 6);
        view.scroll_up(100);
        assert_eq!(view.scroll, 0);
    }

    #[test]
    fn jumps_between_files_and_hunks() {
        let mut view = DiffView::from_output(OUTPUT, "").unwrap();
        view.height = 2;
        view.next_hunk();
        assert_eq!(view.scroll, 1);
        view.next_file();
        assert_eq!(view.scroll, 6);
        view.next_hunk();
        assert_eq!(view.scroll, 8);
        view.next_hunk(); // no more hunks: stay put
        assert_eq!(view.scroll, 8);
        view.prev_file();
        assert_eq!(view.scroll, 6);
        view.prev_hunk();
        assert_eq!(view.scroll, 1);
        view.prev_file();
        assert_eq!(view.scroll, 0);
    }

    #[test]
    fn jumping_to_the_last_file_puts_it_on_top() {
        let mut view = DiffView::from_output(OUTPUT, "").unwrap();
        view.height = 8; // the second file's title would fit on screen
        view.next_file();
        assert_eq!(view.current_file().unwrap().0, 2);
        view.scroll_down(1); // stays put rather than snapping back up
        assert_eq!(view.scroll, 6);
    }

    #[test]
    fn search_finds_rows_and_wraps() {
        let mut view = DiffView::from_output(OUTPUT, "").unwrap();
        view.height = 3;
        assert_eq!(view.search("B.txt"), 0); // has a capital: exact case
        assert_eq!(view.search("b.txt"), 1); // no capitals: any case
        view.scroll_to_top();
        assert_eq!(view.search("new"), 2); // `+   new`, `new file mode`
        assert_eq!(view.search_status(), Some(("new", 1, 2)));
        assert_eq!(view.scroll, 4 - 1);
        view.next_match();
        assert_eq!(view.search_status(), Some(("new", 2, 2)));
        view.next_match();
        assert_eq!(view.search_status(), Some(("new", 1, 2)));
        view.prev_match();
        assert_eq!(view.search_status(), Some(("new", 2, 2)));
        assert_eq!(view.search(""), 0);
        assert_eq!(view.search_status(), None);
    }
}