//! Per-commit review state for the session. use std::collections::BTreeMap; use rustik_diff::{ ContextUpdate, DiffDocument, DiffOptions, DiffViewer, FileId, FileStats, HunkId, ReviewProgress, }; use rustik_repo::DiffStat; use rustik_tui::Rect; use crate::backend::{AcceptedHunk, Brain, Commit, CommitReviewState, commit_remaining_stats}; use crate::comments::{CommentTarget, Comments, ReviewComments}; use crate::decorate::Decorations; use crate::error::Error; use crate::review::Review; /// One commit in the reviewed range: header data plus lazily decoded state. pub(super) struct CommitSlot { /// Commit under review. pub(super) commit: Commit, /// Accepted-line progress for this commit. /// /// Persisted line totals provide progress before the diff is decoded. pub(super) progress: ReviewProgress, /// Total number of hunks in this commit. pub(super) total_hunks: usize, /// Number of comments attached to hunks in this commit. pub(super) comment_count: usize, /// Final review state of this commit. pub(super) state: CommitReviewState, /// Remaining diff statistics for this commit. pub(super) remaining_stats: DiffStat, /// Split diff document retained from history progress calculation. pub(super) document: Option, /// Exact hunk identities retained from history progress calculation. pub(super) identities: Option>, /// Decoded diff state, populated when the commit is first displayed. pub(super) loaded: Option, } impl CommitSlot { /// Returns the original, unfiltered diff document in either slot state. pub(super) fn document(&self) -> Result<&DiffDocument, Error> { self.document .as_ref() .or_else(|| self.loaded.as_ref().map(|loaded| &loaded.document)) .ok_or_else(|| Error::Git("commit slot has no diff document".to_owned())) } /// Returns exact hunk identities in either slot state. pub(super) fn identities(&self) -> Result<&BTreeMap, Error> { self.identities .as_ref() .or_else(|| self.loaded.as_ref().map(|loaded| &loaded.identities)) .ok_or_else(|| Error::Git("commit slot has no cached identities".to_owned())) } /// Returns the number of canonical hunks cached for this commit. pub(super) fn hunk_count(&self) -> usize { self.identities.as_ref().map_or_else( || { self.loaded .as_ref() .map_or(0, |loaded| loaded.identities.len()) }, BTreeMap::len, ) } /// Returns the remaining diff statistics in either slot state. pub(super) fn remaining_stats(&self) -> DiffStat { self.loaded .as_ref() .map_or(self.remaining_stats, CommitReview::remaining_stats) } } /// Decoded review state for one commit: its viewer, accepted hunks, and the /// full document used to restore hidden hunks. /// /// Each commit keeps its own viewer so its highlight and word-diff caches /// persist across commit switches, and its own [`Review`] because decoded hunk /// ids restart per commit. pub(super) struct CommitReview { /// Viewer rendering this commit's diff, owning its caches. pub(super) viewer: DiffViewer, /// Accepted-hunk state projected from exact persisted identities. pub(super) review: Review, /// Per-hunk comment view for this commit. pub(super) comments: Comments, /// Exact accepted-state identity, including patch id, of each original hunk. pub(super) identities: BTreeMap, /// Full, unfiltered diff document used to restore hidden hunks. pub(super) document: DiffDocument, /// Original hunk ids per file, used for decoration snapshots. pub(super) file_hunks: BTreeMap>, /// Original diff stats per hunk, used for file-level remaining diffstats. pub(super) hunk_stats: BTreeMap, } impl CommitReview { /// Returns the combined diffstat of files that still need review. pub(super) fn remaining_stats(&self) -> DiffStat { commit_remaining_stats(&self.document, self.review.accepted()) } /// Returns whether this commit's active file is expanded to its full source. pub(super) fn is_full_file(&self) -> bool { self.viewer.is_full_file() } /// Builds one commit's review state from its split diff document. /// /// Hunk identities are computed here once, so later reconciliations only /// hash residual hunks and comment lookups can match on stable patch ids. pub(super) fn load( commit: &Commit, document: DiffDocument, identities: Option>, options: DiffOptions, brain: &Brain, store: &ReviewComments, ) -> Result { let mut viewer = DiffViewer::new(document.clone(), options); viewer.load_file_sources(|oid| brain.read_blob(oid))?; let identities = match identities { Some(identities) => identities, None => brain.hunk_identities(&document, commit.id)?, }; let heading = format!("{} {}", commit.id.short(), commit.summary); let review = Review::new(); let mut targets = BTreeMap::new(); let mut file_hunks = BTreeMap::new(); let mut hunk_stats = BTreeMap::new(); for file in &document.files { let path = file.header.display_path().map(|path| path.to_path_buf()); file_hunks.insert( file.id, file.hunks.iter().map(|hunk| hunk.id).collect::>(), ); for hunk in &file.hunks { hunk_stats.insert(hunk.id, hunk.stats()); // `hunk_identities` covers every hunk of the same document, so // a miss is a bug: the hunk could never be accepted or // commented on, which is worse left silent. let identity = identities .get(&hunk.id) .ok_or_else(|| Error::Git(format!("hunk {:?} has no identity", hunk.id)))?; targets.insert( hunk.id, CommentTarget { commit: commit.id, heading: heading.clone(), path: path.clone(), patch_id: identity.patch_id.clone(), ordinal: identity.ordinal, }, ); } } let comments = Comments::new(store, targets); let mut loaded = Self { viewer, review, comments, identities, document, file_hunks, hunk_stats, }; loaded.refresh_decorations(); Ok(loaded) } /// Reinstalls a fresh decoration snapshot on the viewer. /// /// Decorations are immutable snapshots, so this must run after every /// change to acceptance or comment state for the viewer to observe it. pub(super) fn refresh_decorations(&mut self) { self.viewer.set_decorator(Decorations::snapshot( &self.review, &self.comments, &self.file_hunks, &self.hunk_stats, self.viewer.options().diff_palette, )); } /// Applies a context refetch while preserving review hunk identities. pub(super) fn apply_context_update( &mut self, mut update: ContextUpdate, brain: &Brain, area: Rect, ) -> Result<(), Error> { let mut hunk_ids = BTreeMap::<_, Vec<_>>::new(); for file in &self.document.files { for hunk in &file.hunks { if let Some(identity) = self.identities.get(&hunk.id) { hunk_ids .entry((file.id, identity.patch_id.clone())) .or_default() .push(hunk.id); } } } for ids in hunk_ids.values_mut() { ids.reverse(); } for file in update.files_mut() { for index in 0..file.hunks.len() { let patch_id = brain.hunk_patch_id(file, &file.hunks[index])?; if let Some(id) = hunk_ids.get_mut(&(file.id, patch_id)).and_then(Vec::pop) { file.hunks[index].id = id; } } } self.viewer.apply_context_update(update, area); Ok(()) } } #[cfg(test)] mod tests { use super::*; use rustik_diff::Decode as _; #[test] fn review_hunks_split_by_change_group() { let document = DiffDocument::decode_str( "\ diff --git a/a.rs b/a.rs --- a/a.rs +++ b/a.rs @@ -1,4 +1,5 @@ -old +new +extra context -before +after tail ", ) .unwrap(); let document = document.split_hunks(); assert_eq!(document.files[0].hunks.len(), 2); assert_eq!(document.files[0].hunks[0].id, HunkId::new(0)); assert_eq!(document.files[0].hunks[1].id, HunkId::new(1)); assert_eq!(document.files[0].hunks[0].header.old_line_no, 1); assert_eq!(document.files[0].hunks[1].header.old_line_no, 2); } }