1use std::collections::{BTreeSet, HashMap};
10use std::path::{Path, PathBuf};
11
12use crate::{DiffDocument, FileDiff, FileId, HunkId, RowId};
13
14const DEFAULT_CONTEXT_LINES: usize = 3;
16pub(crate) const FULL_CONTEXT_LINES: usize = 999_999;
18
19#[derive(Clone, Debug)]
21pub(crate) struct ContextState {
22 context_lines: usize,
24 expanded_files: BTreeSet<FileId>,
26}
27
28#[derive(Clone, Debug)]
30pub(crate) struct ContextPlan {
31 pub(crate) state: ContextState,
33 pub(crate) context_lines: usize,
35 pub(crate) files: Vec<(PathBuf, FileId)>,
37}
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41pub enum ContextChange {
42 Increase,
44 Decrease,
46 ToggleFile,
48}
49
50impl ContextState {
51 pub(crate) fn new() -> Self {
53 Self {
54 context_lines: DEFAULT_CONTEXT_LINES,
55 expanded_files: BTreeSet::new(),
56 }
57 }
58
59 pub(crate) fn is_expanded(&self, file: FileId) -> bool {
61 self.expanded_files.contains(&file)
62 }
63
64 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 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
135impl Default for ContextState {
136 fn default() -> Self {
137 Self::new()
138 }
139}
140
141impl FileDiff {
142 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 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
164pub(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>
173where
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
202pub(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)]
220mod tests {
221 use crate::Decode;
222
223 use super::*;
224
225 fn base_document() -> DiffDocument {
227 DiffDocument::decode_str(
228 "\
229diff --git a/a.txt b/a.txt
230index 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 fn expanded_files() -> Vec<FileDiff> {
243 DiffDocument::decode_str(
244 "\
245diff --git a/a.txt b/a.txt
246index 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 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 for _ in 0..DEFAULT_CONTEXT_LINES {
316 state = state
317 .plan(ContextChange::Decrease, &[FileId::new(0)], &document)
318 .unwrap()
319 .state;
320 }
321
322 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}