crates/brain/src/session/commit.rs 9.3 KiB raw
1
//! Per-commit review state for the session.
2
3
use std::collections::BTreeMap;
4
5
use rustik_diff::{
6
    ContextUpdate, DiffDocument, DiffOptions, DiffViewer, FileId, FileStats, HunkId, ReviewProgress,
7
};
8
use rustik_repo::DiffStat;
9
use rustik_tui::Rect;
10
11
use crate::backend::{AcceptedHunk, Brain, Commit, CommitReviewState, commit_remaining_stats};
12
use crate::comments::{CommentTarget, Comments, ReviewComments};
13
use crate::decorate::Decorations;
14
use crate::error::Error;
15
use crate::review::Review;
16
17
/// One commit in the reviewed range: header data plus lazily decoded state.
18
pub(super) struct CommitSlot {
19
    /// Commit under review.
20
    pub(super) commit: Commit,
21
    /// Accepted-line progress for this commit.
22
    ///
23
    /// Persisted line totals provide progress before the diff is decoded.
24
    pub(super) progress: ReviewProgress,
25
    /// Number of accepted hunks in this commit.
26
    pub(super) accepted_hunks: usize,
27
    /// Total number of hunks in this commit.
28
    pub(super) total_hunks: usize,
29
    /// Number of comments attached to hunks in this commit.
30
    pub(super) comment_count: usize,
31
    /// Final review state of this commit.
32
    pub(super) state: CommitReviewState,
33
    /// Remaining diff statistics for this commit.
34
    pub(super) remaining_stats: DiffStat,
35
    /// Split diff document retained from history progress calculation.
36
    pub(super) document: Option<DiffDocument>,
37
    /// Exact hunk identities retained from history progress calculation.
38
    pub(super) identities: Option<BTreeMap<HunkId, AcceptedHunk>>,
39
    /// Decoded diff state, populated when the commit is first displayed.
40
    pub(super) loaded: Option<CommitReview>,
41
}
42
43
impl CommitSlot {
44
    /// Returns the original, unfiltered diff document in either slot state.
45
    pub(super) fn document(&self) -> Result<&DiffDocument, Error> {
46
        self.document
47
            .as_ref()
48
            .or_else(|| self.loaded.as_ref().map(|loaded| &loaded.document))
49
            .ok_or_else(|| Error::Git("commit slot has no diff document".to_owned()))
50
    }
51
52
    /// Returns exact hunk identities in either slot state.
53
    pub(super) fn identities(&self) -> Result<&BTreeMap<HunkId, AcceptedHunk>, Error> {
54
        self.identities
55
            .as_ref()
56
            .or_else(|| self.loaded.as_ref().map(|loaded| &loaded.identities))
57
            .ok_or_else(|| Error::Git("commit slot has no cached identities".to_owned()))
58
    }
59
60
    /// Returns the number of canonical hunks cached for this commit.
61
    pub(super) fn hunk_count(&self) -> usize {
62
        self.identities.as_ref().map_or_else(
63
            || {
64
                self.loaded
65
                    .as_ref()
66
                    .map_or(0, |loaded| loaded.identities.len())
67
            },
68
            BTreeMap::len,
69
        )
70
    }
71
72
    /// Returns the remaining diff statistics in either slot state.
73
    pub(super) fn remaining_stats(&self) -> DiffStat {
74
        self.loaded
75
            .as_ref()
76
            .map_or(self.remaining_stats, CommitReview::remaining_stats)
77
    }
78
}
79
80
/// Decoded review state for one commit: its viewer, accepted hunks, and the
81
/// full document used to restore hidden hunks.
82
///
83
/// Each commit keeps its own viewer so its highlight and word-diff caches
84
/// persist across commit switches, and its own [`Review`] because decoded hunk
85
/// ids restart per commit.
86
pub(super) struct CommitReview {
87
    /// Viewer rendering this commit's diff, owning its caches.
88
    pub(super) viewer: DiffViewer,
89
    /// Accepted-hunk state projected from exact persisted identities.
90
    pub(super) review: Review,
91
    /// Per-hunk comment view for this commit.
92
    pub(super) comments: Comments,
93
    /// Exact accepted-state identity, including patch id, of each original hunk.
94
    pub(super) identities: BTreeMap<HunkId, AcceptedHunk>,
95
    /// Full, unfiltered diff document used to restore hidden hunks.
96
    pub(super) document: DiffDocument,
97
    /// Original hunk ids per file, used for decoration snapshots.
98
    pub(super) file_hunks: BTreeMap<FileId, Vec<HunkId>>,
99
    /// Original diff stats per hunk, used for file-level remaining diffstats.
100
    pub(super) hunk_stats: BTreeMap<HunkId, FileStats>,
101
}
102
103
impl CommitReview {
104
    /// Returns the combined diffstat of files that still need review.
105
    pub(super) fn remaining_stats(&self) -> DiffStat {
106
        commit_remaining_stats(&self.document, self.review.accepted())
107
    }
108
109
    /// Returns whether this commit's active file is expanded to its full source.
110
    pub(super) fn is_full_file(&self) -> bool {
111
        self.viewer.is_full_file()
112
    }
113
114
    /// Builds one commit's review state from its split diff document.
115
    ///
116
    /// Hunk identities are computed here once, so later reconciliations only
117
    /// hash residual hunks and comment lookups can match on stable patch ids.
118
    pub(super) fn load(
119
        commit: &Commit,
120
        document: DiffDocument,
121
        identities: Option<BTreeMap<HunkId, AcceptedHunk>>,
122
        options: DiffOptions,
123
        brain: &Brain,
124
        store: &ReviewComments,
125
    ) -> Result<Self, Error> {
126
        let mut viewer = DiffViewer::new(document.clone(), options);
127
        viewer.load_file_sources(|oid| brain.read_blob(oid))?;
128
        let identities = match identities {
129
            Some(identities) => identities,
130
            None => brain.hunk_identities(&document, commit.id)?,
131
        };
132
        let heading = format!("{} {}", commit.id.short(), commit.summary);
133
        let review = Review::new();
134
        let mut targets = BTreeMap::new();
135
        let mut file_hunks = BTreeMap::new();
136
        let mut hunk_stats = BTreeMap::new();
137
138
        for file in &document.files {
139
            let path = file.header.display_path().map(|path| path.to_path_buf());
140
            file_hunks.insert(
141
                file.id,
142
                file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>(),
143
            );
144
            for hunk in &file.hunks {
145
                hunk_stats.insert(hunk.id, hunk.stats());
146
                // `hunk_identities` covers every hunk of the same document, so
147
                // a miss is a bug: the hunk could never be accepted or
148
                // commented on, which is worse left silent.
149
                let identity = identities
150
                    .get(&hunk.id)
151
                    .ok_or_else(|| Error::Git(format!("hunk {:?} has no identity", hunk.id)))?;
152
                targets.insert(
153
                    hunk.id,
154
                    CommentTarget {
155
                        commit: commit.id,
156
                        heading: heading.clone(),
157
                        path: path.clone(),
158
                        patch_id: identity.patch_id.clone(),
159
                        ordinal: identity.ordinal,
160
                    },
161
                );
162
            }
163
        }
164
        let comments = Comments::new(store, targets);
165
        let mut loaded = Self {
166
            viewer,
167
            review,
168
            comments,
169
            identities,
170
            document,
171
            file_hunks,
172
            hunk_stats,
173
        };
174
        loaded.refresh_decorations();
175
176
        Ok(loaded)
177
    }
178
179
    /// Reinstalls a fresh decoration snapshot on the viewer.
180
    ///
181
    /// Decorations are immutable snapshots, so this must run after every
182
    /// change to acceptance or comment state for the viewer to observe it.
183
    pub(super) fn refresh_decorations(&mut self) {
184
        self.viewer.set_decorator(Decorations::snapshot(
185
            &self.review,
186
            &self.comments,
187
            &self.file_hunks,
188
            &self.hunk_stats,
189
            self.viewer.options().diff_palette,
190
        ));
191
    }
192
193
    /// Applies a context refetch while preserving review hunk identities.
194
    pub(super) fn apply_context_update(
195
        &mut self,
196
        mut update: ContextUpdate,
197
        brain: &Brain,
198
        area: Rect,
199
    ) -> Result<(), Error> {
200
        let mut hunk_ids = BTreeMap::<_, Vec<_>>::new();
201
        for file in &self.document.files {
202
            for hunk in &file.hunks {
203
                if let Some(identity) = self.identities.get(&hunk.id) {
204
                    hunk_ids
205
                        .entry((file.id, identity.patch_id.clone()))
206
                        .or_default()
207
                        .push(hunk.id);
208
                }
209
            }
210
        }
211
        for ids in hunk_ids.values_mut() {
212
            ids.reverse();
213
        }
214
        for file in update.files_mut() {
215
            for index in 0..file.hunks.len() {
216
                let patch_id = brain.hunk_patch_id(file, &file.hunks[index])?;
217
                if let Some(id) = hunk_ids.get_mut(&(file.id, patch_id)).and_then(Vec::pop) {
218
                    file.hunks[index].id = id;
219
                }
220
            }
221
        }
222
        self.viewer.apply_context_update(update, area);
223
        Ok(())
224
    }
225
}
226
227
#[cfg(test)]
228
mod tests {
229
    use super::*;
230
    use rustik_diff::Decode as _;
231
232
    #[test]
233
    fn review_hunks_split_by_change_group() {
234
        let document = DiffDocument::decode_str(
235
            "\
236
diff --git a/a.rs b/a.rs
237
--- a/a.rs
238
+++ b/a.rs
239
@@ -1,4 +1,5 @@
240
-old
241
+new
242
+extra
243
 context
244
-before
245
+after
246
 tail
247
",
248
        )
249
        .unwrap();
250
251
        let document = document.split_hunks();
252
253
        assert_eq!(document.files[0].hunks.len(), 2);
254
        assert_eq!(document.files[0].hunks[0].id, HunkId::new(0));
255
        assert_eq!(document.files[0].hunks[1].id, HunkId::new(1));
256
        assert_eq!(document.files[0].hunks[0].header.old_line_no, 1);
257
        assert_eq!(document.files[0].hunks[1].header.old_line_no, 2);
258
    }
259
}