rustik-diff 0.2.0

Pure diff viewer and Git diff pager for Rustik.
Documentation
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
//! File-tree model, rendering, and navigation for the diff viewer.

use std::collections::BTreeSet;
use std::path::PathBuf;

use rustik_tui as tui;
use tui::{
    Buffer, Color, Label, Line, Placement, Point, Rect, Style, Table, TableOptions, Tree,
    TreeModel, TreeNodeKind, TreeRow, TreeState, TreeStyle, View, Widget, colors,
};

use super::{DiffPalette, FILE_KIND_BADGE_FG, MIN_RENDER_COLS};
use crate::{DiffDocument, FileId, FileKind, Stats};

/// Minimum columns reserved for the file tree when it is visible.
const DEFAULT_COLS: usize = 28;
/// Blank rows above the file tree list.
const TOP_PADDING_ROWS: usize = 1;
/// Rows reserved for the summary box below the file tree.
const INFO_BOX_ROWS: usize = 4;
/// Blank rows between the file tree and the summary box.
const INFO_BOX_GAP_ROWS: usize = 1;
/// Minimum tree rows kept visible when the summary box is shown.
const MIN_TREE_ROWS_WITH_INFO: usize = 3;
/// Columns added by the tree widget for each nesting level.
const TREE_INDENT_COLS: usize = 2;
/// Background color for the selected or active file row.
const SELECTED_FILE_BG: Color = Color::Fixed(235);
/// Background color for the selected or active folder row.
const SELECTED_FOLDER_BG: Color = Color::Fixed(234);
/// Foreground color for active file-tree row labels.
const SELECTED_FG: Color = Color::Fixed(252);
/// Foreground color for folder labels in the file tree.
const FOLDER_FG: Color = Color::Fixed(245);
/// Foreground color for collapsed folders containing the active file.
const SELECTED_FOLDER_FG: Color = Color::Fixed(246);
/// Selected-row styling for the file tree.
const FILE_TREE_STYLE: TreeStyle =
    TreeStyle::new(Style::new(Color::Unset), Style::new(Color::Unset));
/// Style for the active file row.
const SELECTED_FILE_STYLE: Style = Style::new(SELECTED_FG).bg(SELECTED_FILE_BG);
/// Style for a collapsed folder containing the active file.
const SELECTED_FOLDER_STYLE: Style = Style::new(SELECTED_FOLDER_FG).bg(SELECTED_FOLDER_BG);

/// Blank columns between the file tree and the diff body.
pub(super) const GAP_COLS: usize = 1;
/// Minimum viewport width that can show the file tree beside the diff.
pub(super) const MIN_VIEW_COLS: usize = 80;

/// Selectable target in the file tree.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum FileTreeTarget {
    /// Root row for the current working directory.
    Root,
    /// Directory row containing changed files.
    Directory(PathBuf),
    /// File row from the diff document.
    File(FileId),
}

/// Mouse target selected inside the file tree.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum FileTreeClick {
    /// The disclosure marker for a folder row was clicked.
    Disclosure,
    /// The row body was clicked.
    Row,
}

/// File-tree rendering policy.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum FileTreeMode {
    /// Never render the file tree.
    #[default]
    Hidden,
    /// Render the file tree when the viewport is wide enough.
    Auto,
}

/// One node in the rendered file tree.
#[derive(Clone, Debug, Eq, PartialEq)]
struct FileTreeNode {
    /// Display name for this path segment.
    name: String,
    /// Child node ids.
    children: Vec<usize>,
    /// Diff file data when this node is a file leaf.
    file: Option<FileTreeFile>,
    /// Stable tree target represented by this node.
    target: FileTreeTarget,
}

/// Diff file metadata stored in a file-tree leaf node.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct FileTreeFile {
    /// Stable file identifier.
    id: FileId,
    /// Kind of file-level change.
    kind: FileKind,
}

/// Stateful file tree owned by the diff viewer.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct FileTreeViewer {
    /// Path tree rendered in the file tree.
    model: FileTreeModel,
    /// Expansion and cursor state for the file tree.
    state: TreeState<usize>,
}

impl FileTreeViewer {
    /// Creates a file-tree viewer from `document`.
    pub(super) fn new(document: &DiffDocument, root: String) -> Self {
        let model = FileTreeModel::new(document, root);
        let state = model.initial_state();

        Self { model, state }
    }

    /// Returns the file tree's expansion and cursor state.
    ///
    /// The `model` is immutable after construction, so this is the only part
    /// that changes between actions.
    pub(super) fn state(&self) -> &TreeState<usize> {
        &self.state
    }

    /// Returns the file-tree target under the cursor.
    #[cfg(test)]
    pub(super) fn target(&self) -> Option<FileTreeTarget> {
        self.state
            .selected()
            .and_then(|id| self.model.target_for(id))
    }

    /// Returns the file tree width for a viewport.
    pub(super) fn cols(&self, view_cols: usize) -> usize {
        let available = view_cols.saturating_sub(GAP_COLS + MIN_RENDER_COLS);

        Tree::new(&self.model, &self.state)
            .content_cols(DEFAULT_COLS)
            .min(available)
    }

    /// Renders the file tree.
    pub(super) fn render(
        &mut self,
        active_file: Option<FileId>,
        palette: DiffPalette,
        area: Rect,
        buf: &mut Buffer,
    ) {
        let Some((tree_area, info_area)) = Self::areas(area) else {
            return;
        };
        let collapsed = self
            .model
            .branch_ids()
            .filter(|id| !self.state.is_expanded(*id))
            .collect();
        let styled = StyledFileTree {
            model: &self.model,
            selected: self.state.selected(),
            active_file,
            collapsed,
            palette,
        };
        let tree = Tree::new(&styled, &self.state).style(FILE_TREE_STYLE);
        let rows = tree.visible_rows();
        let row = tree.selected_row(&rows).unwrap_or_default();
        let view =
            View::new(0, rows.len(), tree_area.rows).with_row_visible(row, Placement::Minimal);

        view.render_rows(tree_area, buf, |row, cols| tree.render_row(rows[row], cols));
        if let Some(area) = info_area {
            let mut table = Table::new(TableOptions {
                border: Some(tui::Border::new(colors::FAINT)),
                spacing: 2,
                ..TableOptions::default()
            });
            let stats = self.model.stats;

            table.push([
                Line::new(Label::new("lines changed").fg(FOLDER_FG)),
                Line::spaced([
                    Label::from(format!("+{}", stats.insertions)).fg(palette.positive_fg),
                    Label::from(format!("-{}", stats.deletions)).fg(palette.negative_fg),
                ]),
            ]);
            table.push([
                Line::new(Label::new("files changed").fg(FOLDER_FG)),
                Line::new(Label::from(format!(" {}", stats.files_changed)).fg(Color::White)),
            ]);
            table.render(area, buf);
        }
    }

    /// Enters the file tree when it is visible.
    pub(super) fn enter(&mut self, active_file: Option<FileId>) {
        let chosen = active_file
            .and_then(|file| self.visible_node_for_file(file))
            .or_else(|| self.first_visible_node());
        if let Some(id) = chosen {
            self.state.select(id);
        }
    }

    /// Moves the file-tree cursor by `delta` visible rows.
    pub(super) fn select(&mut self, delta: isize) -> Option<FileId> {
        self.state.select_next(&self.model, delta);
        self.selected_file()
    }

    /// Selects the visible file-tree row for `file`.
    pub(super) fn select_file(&mut self, file: FileId) -> bool {
        let Some(id) = self.visible_node_for_file(file) else {
            return false;
        };
        self.state.select(id)
    }

    /// Selects the file-tree row at `point` inside `area`.
    pub(super) fn select_at(&mut self, area: Rect, point: Point) -> Option<FileTreeClick> {
        let (tree_area, _) = Self::areas(area)?;
        let tree = Tree::new(&self.model, &self.state);
        let rows = tree.visible_rows();
        let row = tree.selected_row(&rows).unwrap_or_default();
        let view =
            View::new(0, rows.len(), tree_area.rows).with_row_visible(row, Placement::Minimal);
        let row = view.row_at(tree_area, point)?;
        let row = rows.get(row)?;
        if self.model.kind(row.id) == TreeNodeKind::Branch
            && point.x.saturating_sub(tree_area.x) == row.depth.saturating_mul(TREE_INDENT_COLS)
        {
            self.state.toggle(&self.model, row.id);
            Some(FileTreeClick::Disclosure)
        } else {
            self.state.select(row.id);
            Some(FileTreeClick::Row)
        }
    }

    /// Activates the current file-tree cursor.
    pub(super) fn activate_target(&mut self) -> Option<FileId> {
        let id = self.state.selected()?;
        if self.model.kind(id) == TreeNodeKind::Branch {
            self.state.toggle(&self.model, id);
        }
        self.selected_file()
    }

    /// Returns the file represented by the selected file-tree row.
    pub(super) fn selected_file(&self) -> Option<FileId> {
        self.state
            .selected()
            .and_then(|id| self.model.first_file_for(id))
    }

    /// Collapses the focused file-tree folder.
    pub(super) fn collapse_folder(&mut self) {
        let Some(id) = self.state.selected() else {
            return;
        };
        if self.model.kind(id) == TreeNodeKind::Branch {
            self.state.collapse(id);
        }
    }

    /// Expands the focused file-tree folder.
    pub(super) fn expand_folder(&mut self) {
        let Some(id) = self.state.selected() else {
            return;
        };
        if self.model.kind(id) == TreeNodeKind::Branch {
            self.state.expand(id);
        }
    }

    /// Returns the visible tree row that best represents `file`.
    fn visible_node_for_file(&self, file: FileId) -> Option<usize> {
        let mut collapsed_branch = None;

        for row in Tree::new(&self.model, &self.state).visible_rows() {
            match self.model.target_for(row.id) {
                Some(FileTreeTarget::File(candidate)) if candidate == file => {
                    return Some(row.id);
                }
                Some(FileTreeTarget::Root | FileTreeTarget::Directory(_))
                    if !self.state.is_expanded(row.id)
                        && self.model.files_for(row.id).contains(&file) =>
                {
                    collapsed_branch = Some(row.id);
                }
                _ => {}
            }
        }
        collapsed_branch
    }

    /// Returns the first visible tree row.
    fn first_visible_node(&self) -> Option<usize> {
        Tree::new(&self.model, &self.state)
            .visible_rows()
            .into_iter()
            .next()
            .map(|row| row.id)
    }

    /// Returns the drawable row area for file-tree contents.
    fn areas(area: Rect) -> Option<(Rect, Option<Rect>)> {
        let body: Rect = Rect::new(
            area.x,
            area.y.saturating_add(TOP_PADDING_ROWS),
            area.cols,
            area.rows.saturating_sub(TOP_PADDING_ROWS),
        );
        if body.is_empty() {
            return None;
        }
        let info_rows = INFO_BOX_ROWS + INFO_BOX_GAP_ROWS + MIN_TREE_ROWS_WITH_INFO;
        let info = (body.rows >= info_rows).then(|| {
            Rect::new(
                body.x,
                body.bottom().saturating_sub(INFO_BOX_ROWS),
                body.cols,
                INFO_BOX_ROWS,
            )
        });
        let tree_rows = if info.is_some() {
            body.rows.saturating_sub(INFO_BOX_ROWS + INFO_BOX_GAP_ROWS)
        } else {
            body.rows
        };

        Some((Rect::new(body.x, body.y, body.cols, tree_rows), info))
    }
}

/// Path tree built once from a diff document. Immutable after construction.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct FileTreeModel {
    /// Root node ids.
    roots: Vec<usize>,
    /// Tree nodes indexed by id.
    nodes: Vec<FileTreeNode>,
    /// Aggregate diff statistics for the summary box.
    stats: Stats,
}

impl FileTreeModel {
    /// Creates a path tree from the files in `document`.
    pub(super) fn new(document: &DiffDocument, root: String) -> Self {
        let mut model = Self {
            roots: Vec::new(),
            nodes: Vec::new(),
            stats: document.stats(),
        };
        let root = model.push_node(None, root, None, FileTreeTarget::Root);

        for file in &document.files {
            model.insert_file(
                root,
                Self::path_parts(file.header.display_path()),
                file.id,
                file.header.kind,
            );
        }
        model
    }

    /// Returns a tree state with every branch expanded.
    pub(super) fn initial_state(&self) -> TreeState<usize> {
        let mut state = TreeState::new();

        for id in self.branch_ids() {
            state.expand(id);
        }
        state
    }

    /// Returns the tree target represented by `id`.
    fn target_for(&self, id: usize) -> Option<FileTreeTarget> {
        self.nodes.get(id).map(|node| node.target.clone())
    }

    /// Returns the ids of every branch (non-leaf) node.
    fn branch_ids(&self) -> impl Iterator<Item = usize> + '_ {
        self.nodes
            .iter()
            .enumerate()
            .filter_map(|(id, node)| (!node.children.is_empty()).then_some(id))
    }

    /// Returns the files included below `id`.
    fn files_for(&self, id: usize) -> BTreeSet<FileId> {
        let mut files = BTreeSet::new();

        if let Some(file) = self.nodes[id].file {
            files.insert(file.id);
        }
        for child in &self.nodes[id].children {
            files.extend(self.files_for(*child));
        }
        files
    }

    /// Returns the first file contained by `id` in tree order.
    fn first_file_for(&self, id: usize) -> Option<FileId> {
        if let Some(file) = self.nodes[id].file {
            return Some(file.id);
        }
        self.nodes[id]
            .children
            .iter()
            .find_map(|child| self.first_file_for(*child))
    }

    /// Returns display path components for a file header path.
    fn path_parts(path: Option<&PathBuf>) -> Vec<String> {
        let Some(path) = path else {
            return vec!["<unknown>".to_owned()];
        };
        let parts: Vec<String> = path
            .iter()
            .map(|part| part.to_string_lossy().into_owned())
            .filter(|part| !part.is_empty())
            .collect();

        if parts.is_empty() {
            vec!["<unknown>".to_owned()]
        } else {
            parts
        }
    }

    /// Inserts one file path into the model.
    fn insert_file(&mut self, root: usize, parts: Vec<String>, file: FileId, kind: FileKind) {
        let mut parent = Some(root);
        let mut path = PathBuf::new();
        let end = parts.len().saturating_sub(1);

        for (index, name) in parts.into_iter().enumerate() {
            path.push(&name);
            let is_file = index == end;
            let target = if is_file {
                FileTreeTarget::File(file)
            } else {
                FileTreeTarget::Directory(path.clone())
            };
            let existing = self.child(parent, &target);
            let node = existing.unwrap_or_else(|| {
                let file = is_file.then_some(FileTreeFile { id: file, kind });
                self.push_node(parent, name, file, target)
            });
            parent = Some(node);
        }
    }

    /// Returns a matching child node below `parent`.
    fn child(&self, parent: Option<usize>, target: &FileTreeTarget) -> Option<usize> {
        let children = parent.map_or(self.roots.as_slice(), |id| {
            self.nodes[id].children.as_slice()
        });

        children
            .iter()
            .copied()
            .find(|&child| self.nodes[child].target == *target)
    }

    /// Appends a node below `parent`.
    fn push_node(
        &mut self,
        parent: Option<usize>,
        name: String,
        file: Option<FileTreeFile>,
        target: FileTreeTarget,
    ) -> usize {
        let id = self.nodes.len();

        self.nodes.push(FileTreeNode {
            name,
            children: Vec::new(),
            file,
            target,
        });
        if let Some(parent) = parent {
            self.nodes[parent].children.push(id);
        } else {
            self.roots.push(id);
        }
        id
    }

    /// Returns a folder row (used by both structural and styled tree views).
    fn folder_row(&self, id: usize, fg: Color, style: Style) -> TreeRow {
        let node = &self.nodes[id];
        let label = if node.name == "/" {
            node.name.to_owned()
        } else {
            format!("{}/", node.name)
        };
        TreeRow::new(Label::from(label).fg(fg))
            .marker_style(Style::new(fg))
            .style(style)
    }
}

impl TreeModel for FileTreeModel {
    type Id = usize;

    fn roots(&self) -> &[Self::Id] {
        &self.roots
    }

    fn children(&self, id: Self::Id) -> &[Self::Id] {
        &self.nodes[id].children
    }

    fn kind(&self, id: Self::Id) -> TreeNodeKind {
        if self.nodes[id].file.is_some() {
            TreeNodeKind::Leaf
        } else {
            TreeNodeKind::Branch
        }
    }

    fn row(&self, id: Self::Id) -> TreeRow {
        let node = &self.nodes[id];
        let Some(file) = node.file else {
            return self.folder_row(id, FOLDER_FG, Style::default());
        };
        TreeRow::new(Label::new(&node.name).fg(Color::White))
            .marker(file.kind.marker())
            .marker_style(Style::new(Color::Unset))
    }
}

/// Render-time view over a [`FileTreeModel`] that applies active-file styling.
///
/// Built each frame; implements [`TreeModel`] so the tree widget renders styled rows
/// without forcing render-time state into the structural model.
struct StyledFileTree<'a> {
    /// Underlying structural tree.
    model: &'a FileTreeModel,
    /// File-tree cursor row.
    selected: Option<usize>,
    /// File currently active in the diff view.
    active_file: Option<FileId>,
    /// Branch ids that are currently collapsed.
    collapsed: BTreeSet<usize>,
    /// Positive and negative colors used for file details.
    palette: DiffPalette,
}

impl StyledFileTree<'_> {
    /// Returns whether `id` should render with active styling.
    ///
    /// True when the file-tree cursor is on `id` or when `id` represents the
    /// active diff file directly (a file row) or indirectly (a collapsed folder
    /// containing it).
    fn is_active(&self, id: usize) -> bool {
        if self.selected == Some(id) {
            return true;
        }
        let Some(node) = self.model.nodes.get(id) else {
            return false;
        };
        let Some(active_file) = self.active_file else {
            return false;
        };
        match &node.target {
            FileTreeTarget::File(file) => *file == active_file,
            FileTreeTarget::Root | FileTreeTarget::Directory(_) => {
                self.collapsed.contains(&id) && self.model.files_for(id).contains(&active_file)
            }
        }
    }

    /// Returns the full-row style for an active tree target.
    fn row_style(&self, id: usize) -> Style {
        if !self.is_active(id) {
            return Style::default();
        }
        match self.model.nodes[id].target {
            FileTreeTarget::Root | FileTreeTarget::Directory(_) => SELECTED_FOLDER_STYLE,
            FileTreeTarget::File(_) => SELECTED_FILE_STYLE,
        }
    }
}

impl TreeModel for StyledFileTree<'_> {
    type Id = usize;

    fn roots(&self) -> &[Self::Id] {
        self.model.roots()
    }

    fn children(&self, id: Self::Id) -> &[Self::Id] {
        self.model.children(id)
    }

    fn kind(&self, id: Self::Id) -> TreeNodeKind {
        self.model.kind(id)
    }

    fn row(&self, id: Self::Id) -> TreeRow {
        let node = &self.model.nodes[id];
        let active = self.is_active(id);
        let Some(file) = node.file else {
            let fg = if active {
                SELECTED_FOLDER_FG
            } else {
                FOLDER_FG
            };
            return self.model.folder_row(id, fg, self.row_style(id));
        };
        let fg = if active { SELECTED_FG } else { Color::White };
        let kind_fg = match file.kind {
            FileKind::Added => self.palette.positive_fg,
            FileKind::Deleted => self.palette.negative_fg,
            FileKind::Renamed => FILE_KIND_BADGE_FG,
            FileKind::Modified | FileKind::Copied | FileKind::ModeChanged | FileKind::Binary => {
                Color::Yellow
            }
        };

        TreeRow::new(Label::new(&node.name).fg(fg))
            .marker(file.kind.marker())
            .marker_style(Style::new(kind_fg))
            .style(self.row_style(id))
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use crate::{Decode, DiffDocument, DiffOptions, DiffViewer};

    fn two_file_viewer() -> DiffViewer {
        let document = DiffDocument::decode_str(
            "\
diff --git a/a.rs b/a.rs
index 1111111..2222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,3 +1,4 @@ fn a
 context
-old
+new
+extra
 tail
diff --git a/b.rs b/b.rs
index 3333333..4444444 100644
--- a/b.rs
+++ b/b.rs
@@ -1,2 +1,2 @@ fn b
 keep
-before
+after
",
        )
        .unwrap();

        DiffViewer::new(document, DiffOptions::default())
    }

    #[test]
    fn file_tree_keeps_all_files_in_main_diff_rows() {
        let viewer = two_file_viewer();

        assert_eq!(viewer.index.files.len(), 2);
        assert_eq!(viewer.index.rows, 16);
    }
}