1use std::borrow::Cow;
2use std::path::{Path, PathBuf};
3
4use rustc_hash::{FxHashMap, FxHashSet};
5
6use crate::unified_diff::{DiffEvent, DiffFileHeader, unified_diff_events};
7
8pub const MAX_DIFF_BYTES: u64 = 10 * 1024 * 1024;
10
11pub const MAX_ADDED_LINES: usize = 1_000_000;
13
14#[derive(Debug, Default, Clone)]
24pub struct DiffIndex {
25 added_lines: FxHashMap<String, FxHashSet<u64>>,
26 changed_paths: FxHashSet<String>,
27 touched_files: FxHashSet<String>,
28 added_line_count: usize,
29 total_added_lines: usize,
30 total_removed_lines: usize,
31 hunk_count: usize,
32 rename_pairs: FxHashMap<String, String>,
33 base: Option<PathBuf>,
34 root_offset: String,
35 base_lines: Box<BaseLineMap>,
36}
37
38#[derive(Debug, Default, Clone)]
41struct BaseLineMap {
42 change_blocks: FxHashMap<String, Vec<ChangeBlock>>,
43 new_files: FxHashSet<String>,
44 lines_capped: bool,
45}
46
47#[derive(Debug, Clone, Copy)]
49struct ChangeBlock {
50 new_start: u64,
53 new_len: u64,
55 old_start: u64,
58 old_len: u64,
60}
61
62impl ChangeBlock {
63 fn last_removed_line(self) -> Option<u64> {
65 (self.old_start + self.old_len)
66 .checked_sub(1)
67 .filter(|_| self.old_len > 0)
68 }
69}
70
71enum HeadLinePlace {
73 Unchanged(u64),
75 Added(ChangeBlock),
77}
78
79#[derive(Default)]
81struct DiffParseState {
82 current_file: Option<String>,
83 new_line: u64,
84 old_line: u64,
85}
86
87impl DiffIndex {
88 #[must_use]
93 pub fn from_unified_diff(diff: &str) -> Self {
94 let mut index = Self::default();
95 let mut state = DiffParseState::default();
96
97 for event in unified_diff_events(diff) {
98 match event {
99 DiffEvent::File(header) => state.current_file = index.record_file(header),
100 DiffEvent::Hunk {
101 old_start,
102 old_len,
103 new_start,
104 new_len,
105 } => {
106 state.old_line = if old_len == 0 {
108 old_start + 1
109 } else {
110 old_start
111 };
112 state.new_line = if new_len == 0 {
113 new_start + 1
114 } else {
115 new_start
116 };
117 index.hunk_count += 1;
118 }
119 DiffEvent::Added(_) => index.record_added_line(&mut state),
120 DiffEvent::Removed(_) => index.record_removed_line(&mut state),
121 DiffEvent::Context(_) => {
122 state.new_line += 1;
123 state.old_line += 1;
124 }
125 DiffEvent::NoNewline => {}
126 }
127 }
128
129 index
130 }
131
132 fn record_file(&mut self, header: DiffFileHeader<'_>) -> Option<String> {
136 if let Some(path) = header.new_path {
137 let path = path.into_owned();
138 self.changed_paths.insert(path.clone());
139 self.touched_files.insert(path.clone());
140 if let Some(from) = header.renamed_from {
141 self.rename_pairs.insert(path.clone(), from.into_owned());
142 }
143 if header.is_new {
144 self.base_lines.new_files.insert(path.clone());
145 }
146 return Some(path);
147 }
148 let old = header.old_path.filter(|_| header.is_deleted)?.into_owned();
149 self.changed_paths.insert(old.clone());
150 Some(old)
151 }
152
153 fn record_added_line(&mut self, state: &mut DiffParseState) {
154 let Some(path) = state.current_file.as_ref() else {
155 return;
156 };
157 self.total_added_lines += 1;
158 if self.added_line_count < MAX_ADDED_LINES {
159 self.added_lines
160 .entry(path.clone())
161 .or_default()
162 .insert(state.new_line);
163 self.added_line_count += 1;
164 self.record_change_line(state, true);
165 } else {
166 self.base_lines.lines_capped = true;
167 }
168 state.new_line += 1;
169 }
170
171 fn record_removed_line(&mut self, state: &mut DiffParseState) {
172 if state.current_file.is_none() {
173 return;
174 }
175 self.total_removed_lines += 1;
176 self.record_change_line(state, false);
177 state.old_line += 1;
178 }
179
180 fn record_change_line(&mut self, state: &DiffParseState, added: bool) {
183 let Some(path) = state.current_file.as_ref() else {
184 return;
185 };
186 let blocks = self
187 .base_lines
188 .change_blocks
189 .entry(path.clone())
190 .or_default();
191 let continues = blocks.last().is_some_and(|block| {
192 block.new_start + block.new_len == state.new_line
193 && block.old_start + block.old_len == state.old_line
194 });
195 if !continues {
196 blocks.push(ChangeBlock {
197 new_start: state.new_line,
198 new_len: 0,
199 old_start: state.old_line,
200 old_len: 0,
201 });
202 }
203 if let Some(block) = blocks.last_mut() {
204 if added {
205 block.new_len += 1;
206 } else {
207 block.old_len += 1;
208 }
209 }
210 }
211
212 #[must_use]
226 pub fn base_line_range(&self, path: &str, start: u64, end: u64) -> Option<(u64, u64)> {
227 let map = &self.base_lines;
228 if map.lines_capped || start > end || map.new_files.contains(path) {
229 return None;
230 }
231 let blocks = map.change_blocks.get(path).map_or(&[][..], Vec::as_slice);
232 let (base_start, base_end) =
233 match (head_line_place(blocks, start), head_line_place(blocks, end)) {
234 (HeadLinePlace::Added(first), HeadLinePlace::Added(last))
235 if first.new_start == last.new_start =>
236 {
237 (first.old_start, first.last_removed_line()?)
238 }
239 (start_place, end_place) => {
240 let base_start = match start_place {
241 HeadLinePlace::Unchanged(line) => line,
242 HeadLinePlace::Added(block) => {
243 block.last_removed_line().unwrap_or(block.old_start)
244 }
245 };
246 let base_end = match end_place {
247 HeadLinePlace::Unchanged(line) => line,
248 HeadLinePlace::Added(block) if block.old_len > 0 => block.old_start,
249 HeadLinePlace::Added(block) => block.old_start.checked_sub(1)?,
250 };
251 (base_start, base_end)
252 }
253 };
254 (base_start <= base_end).then_some((base_start, base_end))
255 }
256
257 #[must_use]
260 pub fn old_path_for(&self, head_path: &str) -> Option<&str> {
261 self.rename_pairs.get(head_path).map(String::as_str)
262 }
263
264 #[must_use]
266 pub fn added_line_count(&self) -> usize {
267 self.added_line_count
268 }
269
270 #[must_use]
277 pub fn filter_scope_size(&self) -> usize {
278 if self.added_line_count >= MAX_ADDED_LINES {
279 return self.added_line_count;
280 }
281 let files_without_lines = self
282 .touched_files
283 .iter()
284 .filter(|path| !self.added_lines.contains_key(*path))
285 .count();
286 self.added_line_count.saturating_add(files_without_lines)
287 }
288
289 #[must_use]
291 pub fn hunk_count(&self) -> usize {
292 self.hunk_count
293 }
294
295 #[must_use]
298 pub fn net_lines(&self) -> i64 {
299 let added = i64::try_from(self.total_added_lines).unwrap_or(i64::MAX);
300 let removed = i64::try_from(self.total_removed_lines).unwrap_or(i64::MAX);
301 added.saturating_sub(removed)
302 }
303
304 #[must_use]
306 pub fn changes_path(&self, path: &str) -> bool {
307 self.changed_paths.contains(path)
308 }
309
310 pub fn changed_paths(&self) -> impl Iterator<Item = &str> {
312 self.changed_paths.iter().map(String::as_str)
313 }
314
315 #[must_use]
317 pub fn touches_file(&self, path: &str) -> bool {
318 self.touched_files.contains(path)
319 }
320
321 #[must_use]
324 pub fn range_overlaps_added(&self, path: &str, start: u64, end: u64) -> bool {
325 self.first_added_line_in_range(path, start, end).is_some()
326 }
327
328 #[must_use]
331 pub fn first_added_line_in_range(&self, path: &str, start: u64, end: u64) -> Option<u64> {
332 if end < start {
333 return None;
334 }
335 let added = self.added_lines.get(path)?;
336 let lo = start.max(1);
337 added
338 .iter()
339 .copied()
340 .filter(|line| *line >= lo && *line <= end)
341 .min()
342 }
343
344 #[must_use]
346 pub fn line_is_added(&self, path: &str, line: u64) -> bool {
347 self.added_lines
348 .get(path)
349 .is_some_and(|lines| lines.contains(&line))
350 }
351
352 #[must_use]
354 pub fn line_within_added_context(&self, path: &str, line: u64, radius: u64) -> bool {
355 self.added_lines
356 .get(path)
357 .is_some_and(|lines| lines.iter().any(|added| line.abs_diff(*added) <= radius))
358 }
359
360 #[must_use]
362 pub fn added_lines_in(&self, path: &str) -> Option<&FxHashSet<u64>> {
363 self.added_lines.get(path)
364 }
365
366 #[must_use]
369 pub fn with_base(mut self, base: impl Into<PathBuf>) -> Self {
370 self.base = Some(base.into());
371 self
372 }
373
374 #[must_use]
382 pub fn with_root_offset(mut self, offset: impl Into<String>) -> Self {
383 let mut offset = offset.into();
384 offset.truncate(offset.trim_end_matches('/').len());
387 self.root_offset = offset;
388 self
389 }
390
391 #[must_use]
394 pub fn root_offset(&self) -> &str {
395 &self.root_offset
396 }
397
398 #[must_use]
400 pub fn key_for_root_relative<'a>(&self, rel: &'a str) -> Cow<'a, str> {
401 if self.root_offset.is_empty() {
402 return Cow::Borrowed(rel);
403 }
404 Cow::Owned(format!("{}/{rel}", self.root_offset))
405 }
406
407 #[must_use]
410 pub fn root_relative_from_key<'a>(&self, key: &'a str) -> Option<Cow<'a, str>> {
411 if self.root_offset.is_empty() {
412 return Some(Cow::Borrowed(key));
413 }
414 strip_path_component_prefix(key, &self.root_offset).map(Cow::Borrowed)
415 }
416
417 #[must_use]
421 pub fn old_path_for_root_relative<'a>(&'a self, rel: &str) -> Option<Cow<'a, str>> {
422 let old = self.old_path_for(&self.key_for_root_relative(rel))?;
423 self.root_relative_from_key(old)
424 }
425
426 #[must_use]
429 pub fn base(&self) -> Option<&Path> {
430 self.base.as_deref()
431 }
432
433 pub fn touched_files(&self) -> impl Iterator<Item = &str> {
436 self.touched_files.iter().map(String::as_str)
437 }
438
439 #[must_use]
445 pub fn key_for(&self, path: &Path, fallback_root: &Path) -> Option<String> {
446 relative_to_diff_path(path, self.base.as_deref().unwrap_or(fallback_root))
447 }
448}
449
450#[must_use]
453pub fn relative_to_diff_path(path: &Path, root: &Path) -> Option<String> {
454 if let Ok(stripped) = path.strip_prefix(root) {
455 return Some(stripped.to_string_lossy().replace('\\', "/"));
456 }
457 if fallow_types::path_util::is_absolute_path_any_platform(path) {
458 return None;
459 }
460 Some(path.to_string_lossy().replace('\\', "/"))
461}
462
463#[must_use]
467pub fn strip_path_component_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
468 path.strip_prefix(prefix)?.strip_prefix('/')
469}
470
471fn head_line_place(blocks: &[ChangeBlock], line: u64) -> HeadLinePlace {
473 let mut shift: i128 = 0;
474 for block in blocks {
475 if line < block.new_start {
476 break;
477 }
478 if line < block.new_start + block.new_len {
479 return HeadLinePlace::Added(*block);
480 }
481 shift += i128::from(block.old_len) - i128::from(block.new_len);
482 }
483 HeadLinePlace::Unchanged(u64::try_from(i128::from(line) + shift).unwrap_or(0))
484}
485
486#[cfg(test)]
487mod tests {
488 use super::*;
489
490 const EDIT_DIFF: &str = "diff --git a/a.js b/a.js\n--- a/a.js\n+++ b/a.js\n@@ -7 +7 @@\n-old seven\n+new seven\n@@ -10,0 +11,2 @@\n+added eleven\n+added twelve\n@@ -20,2 +21,0 @@\n-gone twenty\n-gone twenty-one\n";
491
492 #[test]
493 fn base_line_range_maps_unchanged_lines_across_blocks() {
494 let index = DiffIndex::from_unified_diff(EDIT_DIFF);
495 assert_eq!(index.base_line_range("a.js", 1, 6), Some((1, 6)));
496 assert_eq!(index.base_line_range("a.js", 13, 21), Some((11, 19)));
498 assert_eq!(index.base_line_range("a.js", 22, 25), Some((22, 25)));
500 }
501
502 #[test]
503 fn base_line_range_maps_a_replaced_line_to_its_removed_line() {
504 let index = DiffIndex::from_unified_diff(EDIT_DIFF);
505 assert_eq!(index.base_line_range("a.js", 7, 7), Some((7, 7)));
506 assert_eq!(index.base_line_range("a.js", 1, 12), Some((1, 10)));
507 }
508
509 #[test]
513 fn base_line_range_maps_a_start_in_a_multi_line_replacement_to_its_last_removed_line() {
514 let index = DiffIndex::from_unified_diff(
515 "diff --git a/b.ts b/b.ts\n--- a/b.ts\n+++ b/b.ts\n@@ -1,3 +1,2 @@\n-one\n-two\n-three\n+ONE\n+TWO\n",
516 );
517 assert_eq!(index.base_line_range("b.ts", 2, 15), Some((3, 16)));
518 assert_eq!(index.base_line_range("b.ts", 1, 2), Some((1, 3)));
519 }
520
521 #[test]
522 fn base_line_range_maps_an_end_in_a_multi_line_replacement_to_its_first_removed_line() {
523 let index = DiffIndex::from_unified_diff(
524 "diff --git a/b.ts b/b.ts\n--- a/b.ts\n+++ b/b.ts\n@@ -10,3 +10,2 @@\n-ten\n-eleven\n-twelve\n+TEN\n+ELEVEN\n",
525 );
526 assert_eq!(index.base_line_range("b.ts", 1, 10), Some((1, 10)));
527 assert_eq!(index.base_line_range("b.ts", 1, 11), Some((1, 10)));
528 assert_eq!(index.base_line_range("b.ts", 12, 20), Some((13, 21)));
529 }
530
531 #[test]
532 fn base_line_range_has_no_base_line_for_pure_additions() {
533 let index = DiffIndex::from_unified_diff(EDIT_DIFF);
534 assert_eq!(index.base_line_range("a.js", 11, 12), None);
535 let new_file = DiffIndex::from_unified_diff(
536 "diff --git a/n.js b/n.js\n--- /dev/null\n+++ b/n.js\n@@ -0,0 +1,2 @@\n+one\n+two\n",
537 );
538 assert_eq!(new_file.base_line_range("n.js", 1, 2), None);
539 assert_eq!(new_file.base_line_range("n.js", 3, 4), None);
541 }
542
543 #[test]
544 fn base_line_range_keeps_files_outside_the_diff() {
545 let index = DiffIndex::from_unified_diff(EDIT_DIFF);
546 assert_eq!(index.base_line_range("other.js", 3, 9), Some((3, 9)));
547 }
548
549 #[test]
550 fn no_newline_marker_does_not_move_the_line_cursor() {
551 let index = DiffIndex::from_unified_diff(
552 "diff --git a/a.js b/a.js\n--- a/a.js\n+++ b/a.js\n@@ -3 +3,2 @@\n-last\n\\ No newline at end of file\n+last\n+more\n",
553 );
554 assert!(index.line_is_added("a.js", 3));
555 assert!(index.line_is_added("a.js", 4));
556 assert!(!index.line_is_added("a.js", 5));
557 }
558
559 #[test]
560 fn from_unified_diff_caps_added_lines_at_threshold() {
561 let header =
562 "diff --git a/big.txt b/big.txt\n--- a/big.txt\n+++ b/big.txt\n@@ -0,0 +1,100 @@\n";
563 let mut body = String::with_capacity(MAX_ADDED_LINES * 16);
564 for _ in 0..(MAX_ADDED_LINES + 100) {
565 body.push_str("+x\n");
566 }
567 let mut diff = String::with_capacity(header.len() + body.len());
568 diff.push_str(header);
569 diff.push_str(&body);
570
571 let index = DiffIndex::from_unified_diff(&diff);
572 assert!(
573 index.added_line_count() <= MAX_ADDED_LINES,
574 "indexed {} lines, cap is {MAX_ADDED_LINES}",
575 index.added_line_count()
576 );
577 assert_eq!(
578 Some(index.net_lines()),
579 i64::try_from(MAX_ADDED_LINES + 100).ok()
580 );
581 assert_eq!(index.filter_scope_size(), index.added_line_count());
582 assert_eq!(index.hunk_count(), 1);
583 assert_eq!(
584 index.base_line_range("other.txt", 1, 1),
585 None,
586 "a real cap still stops the base-line map"
587 );
588 }
589
590 #[test]
591 fn added_plus_plus_line_is_indexed_and_keeps_base_line_ranges() {
592 let diff = "diff --git a/src/a.js b/src/a.js\n--- a/src/a.js\n+++ b/src/a.js\n@@ -1,0 +2,2 @@ let count = 0;\n+++count;\n+--count;\n";
593 let index = DiffIndex::from_unified_diff(diff);
594 assert!(index.line_is_added("src/a.js", 2));
595 assert!(index.line_is_added("src/a.js", 3));
596 assert_eq!(index.base_line_range("src/a.js", 1, 1), Some((1, 1)));
597 assert_eq!(index.base_line_range("src/other.js", 4, 9), Some((4, 9)));
598 }
599
600 #[test]
601 fn header_shaped_added_line_keeps_the_current_file() {
602 let diff = "diff --git a/a.js b/a.js\n--- a/a.js\n+++ b/a.js\n@@ -0,0 +1,2 @@\n+++ b/other.js\n+x\n";
603 let index = DiffIndex::from_unified_diff(diff);
604 assert!(!index.changes_path("other.js"));
605 assert!(index.line_is_added("a.js", 1));
606 assert!(index.line_is_added("a.js", 2));
607 }
608
609 #[test]
610 fn quoted_and_tab_suffixed_paths_are_index_keys() {
611 let diff = "\
612diff --git \"a/src/caf\\303\\251.ts\" \"b/src/caf\\303\\251.ts\"
613--- \"a/src/caf\\303\\251.ts\"
614+++ \"b/src/caf\\303\\251.ts\"
615@@ -1,0 +2 @@ x
616+x2
617diff --git \"a/src/del \\303\\251.ts\" \"b/src/del \\303\\251.ts\"
618deleted file mode 100644
619--- \"a/src/del \\303\\251.ts\"\t
620+++ /dev/null
621@@ -1 +0,0 @@
622-gone
623diff --git a/src/my file.ts b/src/my file.ts
624--- a/src/my file.ts\t
625+++ b/src/my file.ts\t
626@@ -1,0 +2 @@ y
627+y2
628\\ No newline at end of file
629diff --git a/src/old name.ts b/src/new name.ts
630similarity index 82%
631rename from src/old name.ts
632rename to src/new name.ts
633--- a/src/old name.ts\t
634+++ b/src/new name.ts\t
635@@ -6,0 +7 @@ six
636+seven
637";
638 let index = DiffIndex::from_unified_diff(diff);
639 assert!(index.line_is_added("src/café.ts", 2));
640 assert!(index.changes_path("src/del é.ts"));
641 assert!(!index.touches_file("src/del é.ts"));
642 assert!(index.line_is_added("src/my file.ts", 2));
643 assert!(index.line_is_added("src/new name.ts", 7));
644 assert_eq!(
645 index.old_path_for("src/new name.ts"),
646 Some("src/old name.ts")
647 );
648 }
649
650 #[test]
651 fn from_unified_diff_counts_additions_removals_and_hunks() {
652 let diff = "\
653diff --git a/src/a.ts b/src/a.ts
654--- a/src/a.ts
655+++ b/src/a.ts
656@@ -1,3 +1,4 @@
657-old
658+new
659+extra
660+++flag
661 context
662@@ -10,2 +11,1 @@
663-removed
664---flag
665 kept
666";
667 let index = DiffIndex::from_unified_diff(diff);
668
669 assert_eq!(index.hunk_count(), 2);
670 assert_eq!(index.net_lines(), 0);
671 assert!(index.changes_path("src/a.ts"));
672 assert!(index.touches_file("src/a.ts"));
673 }
674
675 #[test]
676 fn rename_only_diff_has_no_line_or_hunk_changes() {
677 let diff = "\
678diff --git a/src/old.ts b/src/new.ts
679similarity index 100%
680rename from src/old.ts
681rename to src/new.ts
682";
683 let index = DiffIndex::from_unified_diff(diff);
684
685 assert_eq!(index.hunk_count(), 0);
686 assert_eq!(index.net_lines(), 0);
687 assert!(index.changes_path("src/new.ts"));
688 assert!(index.touches_file("src/new.ts"));
689 }
690
691 #[test]
692 fn range_overlaps_added_hotspot_starting_before_diff_touches_inside() {
693 let diff = "\
694diff --git a/src/big.ts b/src/big.ts
695--- a/src/big.ts
696+++ b/src/big.ts
697@@ -114,1 +114,2 @@
698 ctx
699+touched
700";
701 let index = DiffIndex::from_unified_diff(diff);
702 assert!(index.range_overlaps_added("src/big.ts", 10, 120));
703 assert!(!index.range_overlaps_added("src/other.ts", 10, 120));
704 assert!(!index.range_overlaps_added("src/big.ts", 10, 100));
705 assert!(!index.range_overlaps_added("src/big.ts", 200, 100));
706 }
707
708 #[test]
709 fn rename_header_records_old_path() {
710 let diff = "\
711diff --git a/src/old.ts b/src/new.ts
712similarity index 90%
713rename from src/old.ts
714rename to src/new.ts
715--- a/src/old.ts
716+++ b/src/new.ts
717@@ -1,1 +1,1 @@
718-old
719+new
720";
721 let index = DiffIndex::from_unified_diff(diff);
722 assert_eq!(index.old_path_for("src/new.ts"), Some("src/old.ts"));
723 assert!(index.touches_file("src/new.ts"));
724 }
725
726 #[test]
727 fn empty_diff_has_zero_added_lines_and_no_touched_files() {
728 let index = DiffIndex::from_unified_diff("");
729 assert_eq!(index.added_line_count(), 0);
730 assert!(!index.touches_file("src/a.ts"));
731 assert_eq!(index.filter_scope_size(), 0);
732 }
733
734 #[test]
735 fn filter_scope_size_counts_added_lines_and_files_without_lines() {
736 let diff = "\
737diff --git a/src/old.ts b/src/renamed.ts
738similarity index 100%
739rename from src/old.ts
740rename to src/renamed.ts
741diff --git a/src/a.ts b/src/a.ts
742--- a/src/a.ts
743+++ b/src/a.ts
744@@ -1,1 +1,2 @@
745 keep
746+added
747diff --git a/bin/run.ts b/bin/run.ts
748old mode 100644
749new mode 100755
750diff --git a/src/gone.ts b/src/gone.ts
751deleted file mode 100644
752--- a/src/gone.ts
753+++ /dev/null
754@@ -1,1 +0,0 @@
755-old
756";
757 let index = DiffIndex::from_unified_diff(diff);
758 assert_eq!(index.added_line_count(), 1);
759 assert!(
760 !index.touches_file("bin/run.ts"),
761 "a mode-only section names no head path, so the filter keeps nothing on it"
762 );
763 assert_eq!(
764 index.filter_scope_size(),
765 2,
766 "one added line plus the renamed file; the mode-only and deleted files \
767 are not touched in the head tree"
768 );
769 }
770
771 #[test]
772 fn delete_only_diff_records_removal_without_touching_head_file() {
773 let diff = "\
774diff --git a/src/a.ts b/src/a.ts
775--- a/src/a.ts
776+++ /dev/null
777@@ -1,1 +0,0 @@
778-old
779";
780 let index = DiffIndex::from_unified_diff(diff);
781 assert_eq!(index.added_line_count(), 0);
782 assert_eq!(index.hunk_count(), 1);
783 assert_eq!(index.net_lines(), -1);
784 assert!(index.changes_path("src/a.ts"));
785 assert!(!index.touches_file("src/a.ts"));
786 }
787
788 #[test]
789 fn relative_to_diff_path_strips_absolute_root() {
790 let root = Path::new("/project");
791 let path = Path::new("/project/src/a.ts");
792 assert_eq!(
793 relative_to_diff_path(path, root).as_deref(),
794 Some("src/a.ts")
795 );
796 }
797
798 #[test]
799 fn relative_to_diff_path_passes_through_relative() {
800 let root = Path::new("/project");
801 let path = Path::new("src/a.ts");
802 assert_eq!(
803 relative_to_diff_path(path, root).as_deref(),
804 Some("src/a.ts")
805 );
806 }
807
808 #[test]
809 fn relative_to_diff_path_returns_none_for_path_outside_root() {
810 let root = Path::new("/project");
811 let path = Path::new("/elsewhere/src/a.ts");
812 assert!(relative_to_diff_path(path, root).is_none());
813 }
814
815 #[test]
816 fn key_for_without_base_relativizes_against_the_fallback_root() {
817 let index = DiffIndex::default();
818 assert_eq!(
819 index
820 .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
821 .as_deref(),
822 Some("src/a.ts")
823 );
824 }
825
826 #[test]
827 fn key_for_with_base_equal_to_root_is_unchanged() {
828 let index = DiffIndex::default().with_base("/repo");
829 assert_eq!(
830 index
831 .key_for(Path::new("/repo/src/a.ts"), Path::new("/repo"))
832 .as_deref(),
833 Some("src/a.ts")
834 );
835 }
836
837 #[test]
840 fn key_for_with_base_above_root_yields_repo_root_relative_key() {
841 let index = DiffIndex::default().with_base("/repo");
842 assert_eq!(
843 index
844 .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
845 .as_deref(),
846 Some("pkg/src/a.ts")
847 );
848 }
849
850 #[test]
851 fn key_for_with_base_above_root_matches_a_repo_root_relative_diff() {
852 let diff = "\
853diff --git a/pkg/src/a.ts b/pkg/src/a.ts
854--- a/pkg/src/a.ts
855+++ b/pkg/src/a.ts
856@@ -1,0 +2,1 @@
857+added
858";
859 let index = DiffIndex::from_unified_diff(diff).with_base("/repo");
860 let key = index
861 .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
862 .expect("finding path is under the base");
863
864 assert!(index.touches_file(&key));
865 assert!(index.line_is_added(&key, 2));
866
867 let unbased = DiffIndex::from_unified_diff(diff);
869 let missed = unbased
870 .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
871 .expect("still relativizable");
872 assert_eq!(missed, "src/a.ts");
873 assert!(!unbased.touches_file(&missed));
874 }
875
876 #[test]
877 fn key_for_returns_none_for_path_outside_the_base() {
878 let index = DiffIndex::default().with_base("/repo");
879 assert!(
880 index
881 .key_for(Path::new("/elsewhere/a.ts"), Path::new("/repo/pkg"))
882 .is_none()
883 );
884 }
885
886 #[test]
887 fn old_path_for_root_relative_crosses_the_namespace_and_back() {
888 let diff = "\
889diff --git a/pkg/src/old.ts b/pkg/src/new.ts
890similarity index 90%
891rename from pkg/src/old.ts
892rename to pkg/src/new.ts
893--- a/pkg/src/old.ts
894+++ b/pkg/src/new.ts
895@@ -1,1 +1,1 @@
896-old
897+new
898";
899 let index = DiffIndex::from_unified_diff(diff)
900 .with_base("/repo")
901 .with_root_offset("pkg");
902
903 assert_eq!(
905 index.old_path_for_root_relative("src/new.ts").as_deref(),
906 Some("src/old.ts")
907 );
908 assert_eq!(index.old_path_for("pkg/src/new.ts"), Some("pkg/src/old.ts"));
910 assert_eq!(index.old_path_for_root_relative("src/absent.ts"), None);
911 }
912
913 #[test]
914 fn root_relative_key_round_trips() {
915 let index = DiffIndex::default().with_root_offset("packages/pkg");
916 assert_eq!(
917 index.key_for_root_relative("src/a.ts"),
918 "packages/pkg/src/a.ts"
919 );
920 assert_eq!(
921 index
922 .root_relative_from_key("packages/pkg/src/a.ts")
923 .as_deref(),
924 Some("src/a.ts")
925 );
926 assert_eq!(index.root_relative_from_key("other/src/a.ts"), None);
928 assert_eq!(
930 index.root_relative_from_key("packages/pkg-extra/a.ts"),
931 None
932 );
933 }
934
935 #[test]
936 fn empty_root_offset_is_identity() {
937 let index = DiffIndex::default();
938 assert_eq!(index.key_for_root_relative("src/a.ts"), "src/a.ts");
939 assert_eq!(
940 index.root_relative_from_key("src/a.ts").as_deref(),
941 Some("src/a.ts")
942 );
943 }
944
945 #[test]
946 fn touched_files_enumerates_diff_header_paths() {
947 let diff = "\
948diff --git a/pkg/a.ts b/pkg/a.ts
949--- a/pkg/a.ts
950+++ b/pkg/a.ts
951@@ -0,0 +1,1 @@
952+x
953";
954 let index = DiffIndex::from_unified_diff(diff);
955 assert_eq!(index.touched_files().collect::<Vec<_>>(), vec!["pkg/a.ts"]);
956 }
957}