//! Diff context expansion bookkeeping. //! //! This module owns the pure logic for expanding and contracting the unchanged //! context around hunks: the requested context width, the set of fully //! expanded files, and stable id remapping for refetched diffs. The `git diff` //! invocation itself is supplied by the caller as a closure, so the library //! stays I/O-free. use std::collections::{BTreeSet, HashMap}; use std::path::{Path, PathBuf}; use crate::{DiffDocument, FileDiff, FileId, HunkId, RowId}; /// Context line count Git uses when no explicit `-U` option is passed. const DEFAULT_CONTEXT_LINES: usize = 3; /// Unified diff context used for fully expanded files. pub(crate) const FULL_CONTEXT_LINES: usize = 999_999; /// Tracks the requested diff context width and the set of expanded files. #[derive(Clone, Debug)] pub(crate) struct ContextState { /// Requested context line count. context_lines: usize, /// Files currently expanded to their full source. expanded_files: BTreeSet, } /// Planned context refetch for a set of files. #[derive(Clone, Debug)] pub(crate) struct ContextPlan { /// Context state to install after a successful refetch. pub(crate) state: ContextState, /// Git context width to request. pub(crate) context_lines: usize, /// Paths and file ids to refetch. pub(crate) files: Vec<(PathBuf, FileId)>, } /// Change to the requested hunk context. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ContextChange { /// Show one more unchanged line around each changed group. Increase, /// Show one fewer unchanged line around each changed group. Decrease, /// Toggle the active file between bounded hunks and full source. ToggleFile, } impl ContextState { /// Creates a fresh tracker at Git's default context width. pub(crate) fn new() -> Self { Self { context_lines: DEFAULT_CONTEXT_LINES, expanded_files: BTreeSet::new(), } } /// Returns whether a file is expanded to its full source. pub(crate) fn is_expanded(&self, file: FileId) -> bool { self.expanded_files.contains(&file) } /// Returns the refetch needed for a context change without mutating state. pub(crate) fn plan( &self, change: ContextChange, file_ids: &[FileId], document: &DiffDocument, ) -> Option { let mut next = self.clone(); match change { ContextChange::Increase => next.context_lines = next.context_lines.saturating_add(1), ContextChange::Decrease => { next.context_lines = next.context_lines.checked_sub(1)?; } ContextChange::ToggleFile => { let all_expanded = file_ids .iter() .all(|file_id| next.expanded_files.contains(file_id)); for file_id in file_ids.iter().copied() { if all_expanded { next.expanded_files.remove(&file_id); } else { next.expanded_files.insert(file_id); } } } } let mut target_context = None; let mut files = Vec::with_capacity(file_ids.len()); for file_id in file_ids.iter().copied() { let Some(file) = document .files .iter() .find(|candidate| candidate.id == file_id) else { continue; }; let Some(path) = file.path() else { continue; }; let previous = Self::context_size(&self.expanded_files, file_id, self.context_lines); let target = Self::context_size(&next.expanded_files, file_id, next.context_lines); if previous == target { continue; } debug_assert!(target_context.is_none_or(|shared| shared == target)); target_context = Some(target); files.push((path.to_path_buf(), file_id)); } Some(ContextPlan { state: next, context_lines: target_context?, files, }) } /// Returns the Git context size for a file given the active expansion set. fn context_size(expanded: &BTreeSet, file: FileId, default: usize) -> usize { if expanded.contains(&file) { FULL_CONTEXT_LINES } else { default } } } impl Default for ContextState { fn default() -> Self { Self::new() } } impl FileDiff { /// Returns the diff path recorded for this file, preferring the new path. pub(crate) fn path(&self) -> Option<&Path> { self.header .new_path .as_deref() .or(self.header.old_path.as_deref()) } /// Replaces local hunk and row ids after per-file document replacement. pub(crate) fn remap_ids(&mut self, next_hunk_id: &mut usize, next_row_id: &mut usize) { for hunk in &mut self.hunks { hunk.id = HunkId::new(*next_hunk_id); *next_hunk_id += 1; for line in &mut hunk.lines { line.id = RowId::new(*next_row_id); *next_row_id += 1; } } } } /// Refetches `files` at `target_context_lines` and remaps their ids. /// /// Returns `None` when Git's output does not cover every requested file. pub(crate) fn rebuild( next_ids: (usize, usize), files: &[(PathBuf, FileId)], target_context_lines: usize, fetch: F, ) -> Result>, E> where F: FnOnce(usize, &[&Path]) -> Result, E>, { let paths = files .iter() .map(|(path, _)| path.as_path()) .collect::>(); let mut replacements = HashMap::new(); for file in fetch(target_context_lines, &paths)? { let Some(path) = file.path() else { return Ok(None); }; replacements.insert(path.to_path_buf(), file); } let (mut next_hunk_id, mut next_row_id) = next_ids; let mut rebuilt = Vec::with_capacity(files.len()); for (path, file_id) in files { let Some(mut replacement) = replacements.remove(path) else { return Ok(None); }; replacement.id = *file_id; replacement.remap_ids(&mut next_hunk_id, &mut next_row_id); rebuilt.push(replacement); } Ok(Some(rebuilt)) } /// Returns the next hunk and row ids after existing content. pub(crate) fn next_ids(files: &[FileDiff]) -> (usize, usize) { let mut next_hunk_id = 0; let mut next_row_id = 0; for file in files { for hunk in &file.hunks { next_hunk_id = next_hunk_id.max(*hunk.id + 1); for line in &hunk.lines { next_row_id = next_row_id.max(*line.id + 1); } } } (next_hunk_id, next_row_id) } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use crate::Decode; use super::*; /// A one-file diff with default (`-U3`) context. fn base_document() -> DiffDocument { DiffDocument::decode_str( "\ diff --git a/a.txt b/a.txt index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644 --- a/a.txt +++ b/a.txt @@ -3 +3 @@ -one +ONE ", ) .unwrap() } /// The same file refetched with wider context, as `fetch` would return it. fn expanded_files() -> Vec { DiffDocument::decode_str( "\ diff --git a/a.txt b/a.txt index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644 --- a/a.txt +++ b/a.txt @@ -1,5 +1,5 @@ ctx1 ctx2 -one +ONE ctx4 ctx5 ", ) .unwrap() .files } #[test] fn increase_plans_one_line_wider() { let document = base_document(); let plan = ContextState::new() .plan(ContextChange::Increase, &[FileId::new(0)], &document) .unwrap(); assert_eq!(plan.context_lines, DEFAULT_CONTEXT_LINES + 1); assert_eq!(plan.files, vec![(PathBuf::from("a.txt"), FileId::new(0))]); } #[test] fn toggle_file_expands_then_collapses() { let document = base_document(); let expand = ContextState::new() .plan(ContextChange::ToggleFile, &[FileId::new(0)], &document) .unwrap(); assert_eq!(expand.context_lines, FULL_CONTEXT_LINES); let collapse = expand .state .plan(ContextChange::ToggleFile, &[FileId::new(0)], &document) .unwrap(); assert_eq!(collapse.context_lines, DEFAULT_CONTEXT_LINES); } #[test] fn rebuild_remaps_ids_above_existing_document() { let document = base_document(); let (next_hunk, next_row) = next_ids(&document.files); let files = vec![(PathBuf::from("a.txt"), FileId::new(0))]; let rebuilt = rebuild((next_hunk, next_row), &files, 5, |_, _| { Ok::<_, ()>(expanded_files()) }) .unwrap() .unwrap(); let hunk = &rebuilt[0].hunks[0]; assert_eq!(hunk.id, HunkId::new(next_hunk)); // Row ids stay contiguous and never collide with the base document. for (offset, line) in hunk.lines.iter().enumerate() { assert_eq!(line.id, RowId::new(next_row + offset)); } } #[test] fn decrease_below_zero_has_no_plan() { let document = base_document(); let mut state = ContextState::new(); // Walk the context width down to zero. for _ in 0..DEFAULT_CONTEXT_LINES { state = state .plan(ContextChange::Decrease, &[FileId::new(0)], &document) .unwrap() .state; } // A further decrease cannot widen below zero. assert!( state .plan(ContextChange::Decrease, &[FileId::new(0)], &document) .is_none() ); } #[test] fn no_target_files_has_no_plan() { let document = base_document(); assert!( ContextState::new() .plan(ContextChange::Increase, &[], &document) .is_none() ); } }