Skip to main content

rustik_diff/
context.rs

1//! Diff context expansion bookkeeping.
2//!
3//! This module owns the pure logic for expanding and contracting the unchanged
4//! context around hunks: the requested context width, the set of fully
5//! expanded files, and stable id remapping for refetched diffs. The `git diff`
6//! invocation itself is supplied by the caller as a closure, so the library
7//! stays I/O-free.
8
9use std::collections::{BTreeSet, HashMap};
10use std::path::{Path, PathBuf};
11
12use crate::{DiffDocument, FileDiff, FileId, HunkId, RowId};
13
14/// Context line count Git uses when no explicit `-U` option is passed.
15const DEFAULT_CONTEXT_LINES: usize = 3;
16/// Unified diff context used for fully expanded files.
17pub(crate) const FULL_CONTEXT_LINES: usize = 999_999;
18
19/// Tracks the requested diff context width and the set of expanded files.
20#[derive(Clone, Debug)]
21pub(crate) struct ContextState {
22    /// Requested context line count.
23    context_lines: usize,
24    /// Files currently expanded to their full source.
25    expanded_files: BTreeSet<FileId>,
26}
27
28/// Planned context refetch for a set of files.
29#[derive(Clone, Debug)]
30pub(crate) struct ContextPlan {
31    /// Context state to install after a successful refetch.
32    pub(crate) state: ContextState,
33    /// Git context width to request.
34    pub(crate) context_lines: usize,
35    /// Paths and file ids to refetch.
36    pub(crate) files: Vec<(PathBuf, FileId)>,
37}
38
39/// Change to the requested hunk context.
40#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41pub enum ContextChange {
42    /// Show one more unchanged line around each changed group.
43    Increase,
44    /// Show one fewer unchanged line around each changed group.
45    Decrease,
46    /// Toggle the active file between bounded hunks and full source.
47    ToggleFile,
48}
49
50impl ContextState {
51    /// Creates a fresh tracker at Git's default context width.
52    pub(crate) fn new() -> Self {
53        Self {
54            context_lines: DEFAULT_CONTEXT_LINES,
55            expanded_files: BTreeSet::new(),
56        }
57    }
58
59    /// Returns the refetch needed for a context change without mutating state.
60    pub(crate) fn plan(
61        &self,
62        change: ContextChange,
63        file_ids: &[FileId],
64        document: &DiffDocument,
65    ) -> Option<ContextPlan> {
66        let mut next = self.clone();
67
68        match change {
69            ContextChange::Increase => next.context_lines = next.context_lines.saturating_add(1),
70            ContextChange::Decrease => {
71                next.context_lines = next.context_lines.checked_sub(1)?;
72            }
73            ContextChange::ToggleFile => {
74                let all_expanded = file_ids
75                    .iter()
76                    .all(|file_id| next.expanded_files.contains(file_id));
77
78                for file_id in file_ids.iter().copied() {
79                    if all_expanded {
80                        next.expanded_files.remove(&file_id);
81                    } else {
82                        next.expanded_files.insert(file_id);
83                    }
84                }
85            }
86        }
87
88        let mut target_context = None;
89        let mut files = Vec::with_capacity(file_ids.len());
90
91        for file_id in file_ids.iter().copied() {
92            let Some(file) = document
93                .files
94                .iter()
95                .find(|candidate| candidate.id == file_id)
96            else {
97                continue;
98            };
99            let Some(path) = file.path() else {
100                continue;
101            };
102            let previous = Self::context_size(&self.expanded_files, file_id, self.context_lines);
103            let target = Self::context_size(&next.expanded_files, file_id, next.context_lines);
104            if previous == target {
105                continue;
106            }
107            debug_assert!(target_context.is_none_or(|shared| shared == target));
108
109            target_context = Some(target);
110            files.push((path.to_path_buf(), file_id));
111        }
112
113        Some(ContextPlan {
114            state: next,
115            context_lines: target_context?,
116            files,
117        })
118    }
119
120    /// Returns the Git context size for a file given the active expansion set.
121    fn context_size(expanded: &BTreeSet<FileId>, file: FileId, default: usize) -> usize {
122        if expanded.contains(&file) {
123            FULL_CONTEXT_LINES
124        } else {
125            default
126        }
127    }
128}
129
130impl Default for ContextState {
131    fn default() -> Self {
132        Self::new()
133    }
134}
135
136impl FileDiff {
137    /// Returns the diff path recorded for this file, preferring the new path.
138    pub(crate) fn path(&self) -> Option<&Path> {
139        self.header
140            .new_path
141            .as_deref()
142            .or(self.header.old_path.as_deref())
143    }
144
145    /// Replaces local hunk and row ids after per-file document replacement.
146    pub(crate) fn remap_ids(&mut self, next_hunk_id: &mut usize, next_row_id: &mut usize) {
147        for hunk in &mut self.hunks {
148            hunk.id = HunkId::new(*next_hunk_id);
149            *next_hunk_id += 1;
150
151            for line in &mut hunk.lines {
152                line.id = RowId::new(*next_row_id);
153                *next_row_id += 1;
154            }
155        }
156    }
157}
158
159/// Refetches `files` at `target_context_lines` and remaps their ids.
160///
161/// Returns `None` when Git's output does not cover every requested file.
162pub(crate) fn rebuild<F, E>(
163    next_ids: (usize, usize),
164    files: &[(PathBuf, FileId)],
165    target_context_lines: usize,
166    fetch: F,
167) -> Result<Option<Vec<FileDiff>>, E>
168where
169    F: FnOnce(usize, &[&Path]) -> Result<Vec<FileDiff>, E>,
170{
171    let paths = files
172        .iter()
173        .map(|(path, _)| path.as_path())
174        .collect::<Vec<_>>();
175    let mut replacements = HashMap::new();
176
177    for file in fetch(target_context_lines, &paths)? {
178        let Some(path) = file.path() else {
179            return Ok(None);
180        };
181        replacements.insert(path.to_path_buf(), file);
182    }
183    let (mut next_hunk_id, mut next_row_id) = next_ids;
184    let mut rebuilt = Vec::with_capacity(files.len());
185
186    for (path, file_id) in files {
187        let Some(mut replacement) = replacements.remove(path) else {
188            return Ok(None);
189        };
190        replacement.id = *file_id;
191        replacement.remap_ids(&mut next_hunk_id, &mut next_row_id);
192        rebuilt.push(replacement);
193    }
194    Ok(Some(rebuilt))
195}
196
197/// Returns the next hunk and row ids after existing content.
198pub(crate) fn next_ids(files: &[FileDiff]) -> (usize, usize) {
199    let mut next_hunk_id = 0;
200    let mut next_row_id = 0;
201
202    for file in files {
203        for hunk in &file.hunks {
204            next_hunk_id = next_hunk_id.max(*hunk.id + 1);
205            for line in &hunk.lines {
206                next_row_id = next_row_id.max(*line.id + 1);
207            }
208        }
209    }
210    (next_hunk_id, next_row_id)
211}
212
213#[cfg(test)]
214#[allow(clippy::unwrap_used)]
215mod tests {
216    use crate::Decode;
217
218    use super::*;
219
220    /// A one-file diff with default (`-U3`) context.
221    fn base_document() -> DiffDocument {
222        DiffDocument::decode_str(
223            "\
224diff --git a/a.txt b/a.txt
225index 1111111..2222222 100644
226--- a/a.txt
227+++ b/a.txt
228@@ -3 +3 @@
229-one
230+ONE
231",
232        )
233        .unwrap()
234    }
235
236    /// The same file refetched with wider context, as `fetch` would return it.
237    fn expanded_files() -> Vec<FileDiff> {
238        DiffDocument::decode_str(
239            "\
240diff --git a/a.txt b/a.txt
241index 1111111..2222222 100644
242--- a/a.txt
243+++ b/a.txt
244@@ -1,5 +1,5 @@
245 ctx1
246 ctx2
247-one
248+ONE
249 ctx4
250 ctx5
251",
252        )
253        .unwrap()
254        .files
255    }
256
257    #[test]
258    fn increase_plans_one_line_wider() {
259        let document = base_document();
260        let plan = ContextState::new()
261            .plan(ContextChange::Increase, &[FileId::new(0)], &document)
262            .unwrap();
263
264        assert_eq!(plan.context_lines, DEFAULT_CONTEXT_LINES + 1);
265        assert_eq!(plan.files, vec![(PathBuf::from("a.txt"), FileId::new(0))]);
266    }
267
268    #[test]
269    fn toggle_file_expands_then_collapses() {
270        let document = base_document();
271
272        let expand = ContextState::new()
273            .plan(ContextChange::ToggleFile, &[FileId::new(0)], &document)
274            .unwrap();
275        assert_eq!(expand.context_lines, FULL_CONTEXT_LINES);
276
277        let collapse = expand
278            .state
279            .plan(ContextChange::ToggleFile, &[FileId::new(0)], &document)
280            .unwrap();
281        assert_eq!(collapse.context_lines, DEFAULT_CONTEXT_LINES);
282    }
283
284    #[test]
285    fn rebuild_remaps_ids_above_existing_document() {
286        let document = base_document();
287        let (next_hunk, next_row) = next_ids(&document.files);
288
289        let files = vec![(PathBuf::from("a.txt"), FileId::new(0))];
290        let rebuilt = rebuild((next_hunk, next_row), &files, 5, |_, _| {
291            Ok::<_, ()>(expanded_files())
292        })
293        .unwrap()
294        .unwrap();
295
296        let hunk = &rebuilt[0].hunks[0];
297        assert_eq!(hunk.id, HunkId::new(next_hunk));
298        // Row ids stay contiguous and never collide with the base document.
299        for (offset, line) in hunk.lines.iter().enumerate() {
300            assert_eq!(line.id, RowId::new(next_row + offset));
301        }
302    }
303
304    #[test]
305    fn decrease_below_zero_has_no_plan() {
306        let document = base_document();
307        let mut state = ContextState::new();
308
309        // Walk the context width down to zero.
310        for _ in 0..DEFAULT_CONTEXT_LINES {
311            state = state
312                .plan(ContextChange::Decrease, &[FileId::new(0)], &document)
313                .unwrap()
314                .state;
315        }
316
317        // A further decrease cannot widen below zero.
318        assert!(
319            state
320                .plan(ContextChange::Decrease, &[FileId::new(0)], &document)
321                .is_none()
322        );
323    }
324
325    #[test]
326    fn no_target_files_has_no_plan() {
327        let document = base_document();
328        assert!(
329            ContextState::new()
330                .plan(ContextChange::Increase, &[], &document)
331                .is_none()
332        );
333    }
334}