crates/brain/src/decorate.rs 6.7 KiB raw
1
//! Diff decorations derived from review and comment state.
2
//!
3
//! The diff viewer is review-agnostic; this decorator feeds it per-hunk
4
//! markers. A [`Decorations`] value is an immutable snapshot of the review
5
//! state, rebuilt and reinstalled by the session whenever acceptance or
6
//! comments change, so the viewer never observes state mutating underneath
7
//! it. Accepted hunks are dimmed and marked by a green gutter; commented
8
//! hunks show a comment marker and count; hunks that need review after a
9
//! rebase show a rebase marker.
10
11
use std::collections::{BTreeMap, BTreeSet};
12
13
use rustik_diff::{
14
    DiffDecorator, DiffPalette, FileDecoration, FileId, FileStats, HunkDecoration, HunkId,
15
    ReviewProgress,
16
};
17
use rustik_tui as tui;
18
use tui::{Label, Line, Paint, Style, colors};
19
20
use crate::comments::{COMMENT_MARK, Comments};
21
use crate::review::Review;
22
23
/// Check mark drawn beside accepted hunks and fully accepted files: ✔.
24
const ACCEPTED_MARK: char = '✔';
25
/// Vertical rule drawn in the gutter beside accepted hunks: ▏.
26
const ACCEPTED_GUTTER: char = '▏';
27
28
/// Immutable decoration snapshot of one commit's review state.
29
#[derive(Clone, Debug)]
30
pub struct Decorations {
31
    /// Hunks accepted at snapshot time.
32
    accepted: BTreeSet<HunkId>,
33
    /// Per-hunk comment counts at snapshot time.
34
    comments: BTreeMap<HunkId, usize>,
35
    /// Original hunk ids for each file in the commit.
36
    file_hunks: BTreeMap<FileId, Vec<HunkId>>,
37
    /// Original addition and deletion counts for each hunk.
38
    hunk_stats: BTreeMap<HunkId, FileStats>,
39
    /// Diff palette the markers are drawn with.
40
    palette: DiffPalette,
41
}
42
43
impl Decorations {
44
    /// Captures the current review and comment state for `file_hunks`.
45
    pub fn snapshot(
46
        review: &Review,
47
        comments: &Comments,
48
        file_hunks: &BTreeMap<FileId, Vec<HunkId>>,
49
        hunk_stats: &BTreeMap<HunkId, FileStats>,
50
        palette: DiffPalette,
51
    ) -> Self {
52
        Self {
53
            accepted: review.accepted().clone(),
54
            comments: comments.counts(),
55
            file_hunks: file_hunks.clone(),
56
            hunk_stats: hunk_stats.clone(),
57
            palette,
58
        }
59
    }
60
61
    /// Returns the combined diffstat of hunks that still need review.
62
    fn remaining_stats(&self, hunks: &[HunkId]) -> FileStats {
63
        hunks
64
            .iter()
65
            .filter(|hunk| !self.accepted.contains(hunk))
66
            .filter_map(|hunk| self.hunk_stats.get(hunk))
67
            .fold(FileStats::default(), |mut total, stats| {
68
                total.additions += stats.additions;
69
                total.deletions += stats.deletions;
70
                total
71
            })
72
    }
73
}
74
75
impl DiffDecorator for Decorations {
76
    fn file(&self, file: FileId) -> FileDecoration {
77
        let hunks = self.file_hunks.get(&file).map_or(&[][..], Vec::as_slice);
78
        let progress = (!hunks.is_empty()).then(|| ReviewProgress {
79
            accepted: hunks
80
                .iter()
81
                .filter(|hunk| self.accepted.contains(hunk))
82
                .filter_map(|hunk| self.hunk_stats.get(hunk))
83
                .map(|stats| (stats.additions + stats.deletions).max(1))
84
                .sum(),
85
            total: hunks
86
                .iter()
87
                .filter_map(|hunk| self.hunk_stats.get(hunk))
88
                .map(|stats| (stats.additions + stats.deletions).max(1))
89
                .sum(),
90
        });
91
        let comment_count = hunks
92
            .iter()
93
            .filter_map(|hunk| self.comments.get(hunk))
94
            .sum::<usize>();
95
        let mut decoration = FileDecoration {
96
            progress,
97
            stats: Some(self.remaining_stats(hunks)),
98
            ..FileDecoration::default()
99
        };
100
        if progress.is_some_and(ReviewProgress::is_complete) {
101
            decoration.status = Some(Paint::new(ACCEPTED_MARK).fg(self.palette.positive_fg));
102
        } else if comment_count > 0 {
103
            decoration.annotations = vec![Line::new(
104
                Label::new(&format!("{comment_count} {COMMENT_MARK}")).fg(colors::rgb::DIM),
105
            )];
106
        }
107
        decoration
108
    }
109
110
    fn hunk(&self, _file: FileId, hunk: HunkId) -> HunkDecoration {
111
        let accepted = self.accepted.contains(&hunk);
112
        let comments = self.comments.get(&hunk).copied().unwrap_or_default();
113
        if !accepted && comments == 0 {
114
            return HunkDecoration::default();
115
        }
116
117
        let mut corner = Line::blank();
118
        if comments > 0 {
119
            corner =
120
                corner.item(Label::new(&format!("{comments} {COMMENT_MARK}")).fg(colors::rgb::DIM));
121
        }
122
123
        HunkDecoration {
124
            gutter: accepted.then(|| Paint::new(ACCEPTED_GUTTER).fg(self.palette.positive_fg)),
125
            corner,
126
            style: accepted.then(|| Style::default().dim()),
127
        }
128
    }
129
}
130
131
#[cfg(test)]
132
mod tests {
133
    use super::*;
134
135
    #[test]
136
    fn file_diffstat_excludes_accepted_hunks() {
137
        let first = HunkId::new(0);
138
        let second = HunkId::new(1);
139
        let decorations = Decorations {
140
            accepted: BTreeSet::from([first]),
141
            comments: BTreeMap::new(),
142
            file_hunks: BTreeMap::from([(FileId::new(0), vec![first, second])]),
143
            hunk_stats: BTreeMap::from([
144
                (
145
                    first,
146
                    FileStats {
147
                        additions: 2,
148
                        deletions: 4,
149
                    },
150
                ),
151
                (
152
                    second,
153
                    FileStats {
154
                        additions: 3,
155
                        deletions: 1,
156
                    },
157
                ),
158
            ]),
159
            palette: DiffPalette::default(),
160
        };
161
162
        assert_eq!(
163
            decorations.remaining_stats(&[first, second]),
164
            FileStats {
165
                additions: 3,
166
                deletions: 1,
167
            }
168
        );
169
    }
170
171
    #[test]
172
    fn zero_line_hunk_has_one_review_unit() {
173
        let hunk = HunkId::new(0);
174
        let file = FileId::new(0);
175
        let decorations = Decorations {
176
            accepted: BTreeSet::new(),
177
            comments: BTreeMap::new(),
178
            file_hunks: BTreeMap::from([(file, vec![hunk])]),
179
            hunk_stats: BTreeMap::from([(hunk, FileStats::default())]),
180
            palette: DiffPalette::default(),
181
        };
182
183
        assert_eq!(
184
            decorations.file(file).progress,
185
            Some(ReviewProgress {
186
                accepted: 0,
187
                total: 1,
188
            })
189
        );
190
        let accepted = Decorations {
191
            accepted: BTreeSet::from([hunk]),
192
            ..decorations
193
        };
194
        assert!(
195
            accepted
196
                .file(file)
197
                .progress
198
                .is_some_and(ReviewProgress::is_complete)
199
        );
200
    }
201
}