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