Skip to main content

fallow_output/
diff.rs

1use std::borrow::Cow;
2use std::path::{Path, PathBuf};
3
4use rustc_hash::{FxHashMap, FxHashSet};
5
6/// Refuse to parse a unified diff larger than this.
7pub const MAX_DIFF_BYTES: u64 = 10 * 1024 * 1024;
8
9/// Stop indexing added lines past this count.
10pub const MAX_ADDED_LINES: usize = 1_000_000;
11
12/// Parsed, command-neutral index of files and added lines in a unified diff.
13///
14/// Keys are exactly the paths the diff names in its `+++ b/<path>` headers,
15/// so they live in whatever namespace produced the diff — for `git diff`,
16/// relative to the repository toplevel. [`DiffIndex::base`] records the
17/// directory those keys are relative to, so a finding's absolute path can be
18/// mapped into the same namespace before lookup. Without it, an analysis root
19/// below the toplevel silently misses every key.
20#[derive(Debug, Default, Clone)]
21pub struct DiffIndex {
22    added_lines: FxHashMap<String, FxHashSet<u64>>,
23    changed_paths: FxHashSet<String>,
24    touched_files: FxHashSet<String>,
25    added_line_count: usize,
26    total_added_lines: usize,
27    total_removed_lines: usize,
28    hunk_count: usize,
29    rename_pairs: FxHashMap<String, String>,
30    base: Option<PathBuf>,
31    root_offset: String,
32    base_lines: Box<BaseLineMap>,
33}
34
35/// The data that maps head lines back to base lines. It is boxed, so the
36/// index stays small in the enums that hold it.
37#[derive(Debug, Default, Clone)]
38struct BaseLineMap {
39    change_blocks: FxHashMap<String, Vec<ChangeBlock>>,
40    new_files: FxHashSet<String>,
41    lines_capped: bool,
42}
43
44/// One run of removed and added lines with no unchanged line in it.
45#[derive(Debug, Clone, Copy)]
46struct ChangeBlock {
47    /// First head line of the run. When the run adds no line, the head line
48    /// after it.
49    new_start: u64,
50    /// Number of added lines.
51    new_len: u64,
52    /// First base line of the run. When the run removes no line, the base
53    /// line after it.
54    old_start: u64,
55    /// Number of removed lines.
56    old_len: u64,
57}
58
59/// Where one head line sits relative to the change blocks of its file.
60enum HeadLinePlace {
61    /// An unchanged line, at this base line.
62    Unchanged(u64),
63    /// An added line of this block.
64    Added(ChangeBlock),
65}
66
67/// Mutable cursor state threaded through unified-diff parsing.
68#[derive(Default)]
69struct DiffParseState {
70    current_file: Option<String>,
71    new_line: u64,
72    old_line: u64,
73    pending_old_path: Option<String>,
74    pending_rename_from: Option<String>,
75    pending_new_file: bool,
76}
77
78impl DiffIndex {
79    /// Parse a unified diff into an index of changed files and added lines.
80    ///
81    /// Indexes at most [`MAX_ADDED_LINES`] added lines; totals used by
82    /// [`DiffIndex::net_lines`] keep counting past the cap.
83    #[must_use]
84    pub fn from_unified_diff(diff: &str) -> Self {
85        let mut index = Self::default();
86        let mut state = DiffParseState::default();
87
88        for line in diff.lines() {
89            if index.handle_diff_header_line(line, &mut state) {
90                continue;
91            }
92            index.handle_diff_content_line(line, &mut state);
93        }
94
95        index
96    }
97
98    fn handle_diff_header_line(&mut self, line: &str, state: &mut DiffParseState) -> bool {
99        if line.starts_with("diff --git ") {
100            state.current_file = None;
101            state.pending_new_file = false;
102            state.pending_old_path = None;
103            state.pending_rename_from = None;
104            return true;
105        }
106        if let Some(rest) = line.strip_prefix("rename from ") {
107            state.pending_rename_from = Some(rest.to_owned());
108            return true;
109        }
110        if let Some(rest) = line.strip_prefix("rename to ") {
111            if let Some(from) = state.pending_rename_from.take() {
112                self.rename_pairs.insert(rest.to_owned(), from);
113                self.changed_paths.insert(rest.to_owned());
114                self.touched_files.insert(rest.to_owned());
115            }
116            return true;
117        }
118        if let Some(path) = line.strip_prefix("--- a/") {
119            state.pending_old_path = Some(path.to_string());
120            return true;
121        }
122        if line.starts_with("--- /dev/null") {
123            state.pending_old_path = None;
124            state.pending_new_file = true;
125            return true;
126        }
127        if let Some(path) = line.strip_prefix("+++ b/") {
128            state.pending_old_path = None;
129            if std::mem::take(&mut state.pending_new_file) {
130                self.base_lines.new_files.insert(path.to_string());
131            }
132            state.current_file = Some(path.to_string());
133            self.changed_paths.insert(path.to_string());
134            self.touched_files.insert(path.to_string());
135            return true;
136        }
137        if line.starts_with("+++ /dev/null") {
138            state.current_file = state.pending_old_path.take();
139            if let Some(path) = state.current_file.as_ref() {
140                self.changed_paths.insert(path.clone());
141            }
142            return true;
143        }
144        if let Some(header) = line.strip_prefix("@@ ") {
145            if let Some(start) = parse_new_hunk_start(header) {
146                state.old_line = hunk_next_line(header, '-').unwrap_or(start);
147                state.new_line = hunk_next_line(header, '+').unwrap_or(start);
148                self.hunk_count += 1;
149            }
150            return true;
151        }
152        false
153    }
154
155    fn handle_diff_content_line(&mut self, line: &str, state: &mut DiffParseState) {
156        let Some(path) = state.current_file.as_ref() else {
157            return;
158        };
159        if line.starts_with('+') {
160            self.total_added_lines += 1;
161            if !line.starts_with("+++") && self.added_line_count < MAX_ADDED_LINES {
162                self.added_lines
163                    .entry(path.clone())
164                    .or_default()
165                    .insert(state.new_line);
166                self.added_line_count += 1;
167                self.record_change_line(state, true);
168            } else {
169                self.base_lines.lines_capped = true;
170            }
171            state.new_line += 1;
172        } else if line.starts_with('-') {
173            self.total_removed_lines += 1;
174            self.record_change_line(state, false);
175            state.old_line += 1;
176        } else if !line.starts_with('\\') {
177            // A `\ No newline at end of file` marker is not a file line.
178            state.new_line += 1;
179            state.old_line += 1;
180        }
181    }
182
183    /// Add one removed or added line to the change block that ends at the
184    /// cursor, or open a new block there.
185    fn record_change_line(&mut self, state: &DiffParseState, added: bool) {
186        let Some(path) = state.current_file.as_ref() else {
187            return;
188        };
189        let blocks = self
190            .base_lines
191            .change_blocks
192            .entry(path.clone())
193            .or_default();
194        let continues = blocks.last().is_some_and(|block| {
195            block.new_start + block.new_len == state.new_line
196                && block.old_start + block.old_len == state.old_line
197        });
198        if !continues {
199            blocks.push(ChangeBlock {
200                new_start: state.new_line,
201                new_len: 0,
202                old_start: state.old_line,
203                old_len: 0,
204            });
205        }
206        if let Some(block) = blocks.last_mut() {
207            if added {
208                block.new_len += 1;
209            } else {
210                block.old_len += 1;
211            }
212        }
213    }
214
215    /// Map an inclusive head line range of `path` to the base tree. `path`
216    /// is a key of this diff.
217    ///
218    /// Unchanged lines map exactly. An added line at the start of the range
219    /// maps to the first base line that its block removed. An added line at
220    /// the end maps to the last one. A file that the diff does not name maps
221    /// unchanged. `None` when the range holds no base line, when the diff
222    /// adds `path` as a new file, or when the index stopped at
223    /// [`MAX_ADDED_LINES`].
224    #[must_use]
225    pub fn base_line_range(&self, path: &str, start: u64, end: u64) -> Option<(u64, u64)> {
226        let map = &self.base_lines;
227        if map.lines_capped || start > end || map.new_files.contains(path) {
228            return None;
229        }
230        let blocks = map.change_blocks.get(path).map_or(&[][..], Vec::as_slice);
231        let base_start = match head_line_place(blocks, start) {
232            HeadLinePlace::Unchanged(line) => line,
233            HeadLinePlace::Added(block) => block.old_start,
234        };
235        let base_end = match head_line_place(blocks, end) {
236            HeadLinePlace::Unchanged(line) => line,
237            HeadLinePlace::Added(block) => (block.old_start + block.old_len).checked_sub(1)?,
238        };
239        (base_start <= base_end).then_some((base_start, base_end))
240    }
241
242    /// Pre-rename path for `head_path`, in the diff's key namespace, when the
243    /// diff renamed it.
244    #[must_use]
245    pub fn old_path_for(&self, head_path: &str) -> Option<&str> {
246        self.rename_pairs.get(head_path).map(String::as_str)
247    }
248
249    /// Number of indexed added lines, capped at [`MAX_ADDED_LINES`].
250    #[must_use]
251    pub fn added_line_count(&self) -> usize {
252        self.added_line_count
253    }
254
255    /// Number of parsed unified-diff hunk headers.
256    #[must_use]
257    pub fn hunk_count(&self) -> usize {
258        self.hunk_count
259    }
260
261    /// Total added lines minus total removed lines, independent of the added
262    /// line indexing cap.
263    #[must_use]
264    pub fn net_lines(&self) -> i64 {
265        let added = i64::try_from(self.total_added_lines).unwrap_or(i64::MAX);
266        let removed = i64::try_from(self.total_removed_lines).unwrap_or(i64::MAX);
267        added.saturating_sub(removed)
268    }
269
270    /// Whether this diff changes the path, including when the path is deleted.
271    #[must_use]
272    pub fn changes_path(&self, path: &str) -> bool {
273        self.changed_paths.contains(path)
274    }
275
276    /// Paths changed by the diff, using the old path for deleted files.
277    pub fn changed_paths(&self) -> impl Iterator<Item = &str> {
278        self.changed_paths.iter().map(String::as_str)
279    }
280
281    /// Whether this diff touches an analyzable path in the head tree.
282    #[must_use]
283    pub fn touches_file(&self, path: &str) -> bool {
284        self.touched_files.contains(path)
285    }
286
287    /// Whether any added line in `path` falls inside the inclusive 1-based
288    /// `start..=end` range.
289    #[must_use]
290    pub fn range_overlaps_added(&self, path: &str, start: u64, end: u64) -> bool {
291        self.first_added_line_in_range(path, start, end).is_some()
292    }
293
294    /// Lowest 1-based added line inside the inclusive `start..=end` range.
295    /// Returns `None` for an invalid range or when the diff adds no line in it.
296    #[must_use]
297    pub fn first_added_line_in_range(&self, path: &str, start: u64, end: u64) -> Option<u64> {
298        if end < start {
299            return None;
300        }
301        let added = self.added_lines.get(path)?;
302        let lo = start.max(1);
303        added
304            .iter()
305            .copied()
306            .filter(|line| *line >= lo && *line <= end)
307            .min()
308    }
309
310    /// Whether the 1-based `line` in `path` was added by this diff.
311    #[must_use]
312    pub fn line_is_added(&self, path: &str, line: u64) -> bool {
313        self.added_lines
314            .get(path)
315            .is_some_and(|lines| lines.contains(&line))
316    }
317
318    /// Whether `line` sits within `radius` lines of any added line in `path`.
319    #[must_use]
320    pub fn line_within_added_context(&self, path: &str, line: u64, radius: u64) -> bool {
321        self.added_lines
322            .get(path)
323            .is_some_and(|lines| lines.iter().any(|added| line.abs_diff(*added) <= radius))
324    }
325
326    /// Set of 1-based added line numbers for `path`, when the diff added any.
327    #[must_use]
328    pub fn added_lines_in(&self, path: &str) -> Option<&FxHashSet<u64>> {
329        self.added_lines.get(path)
330    }
331
332    /// Declare the directory this diff's paths are relative to (the git
333    /// toplevel for `git diff` output).
334    #[must_use]
335    pub fn with_base(mut self, base: impl Into<PathBuf>) -> Self {
336        self.base = Some(base.into());
337        self
338    }
339
340    /// Declare where the analysis root sits below [`DiffIndex::base`], as a
341    /// forward-slashed relative path (empty when they are the same directory).
342    ///
343    /// Findings are addressed relative to the analysis root; this diff's keys
344    /// are relative to its base. Everything that looks a finding up in this
345    /// index has to cross that gap, so the index carries the offset rather than
346    /// making each caller rediscover it.
347    #[must_use]
348    pub fn with_root_offset(mut self, offset: impl Into<String>) -> Self {
349        let mut offset = offset.into();
350        // A trailing separator would make `strip_path_component_prefix` demand a
351        // second one and never match. Normalize rather than trust the caller.
352        offset.truncate(offset.trim_end_matches('/').len());
353        self.root_offset = offset;
354        self
355    }
356
357    /// Relative path of the analysis root below [`DiffIndex::base`]; empty
358    /// when they coincide.
359    #[must_use]
360    pub fn root_offset(&self) -> &str {
361        &self.root_offset
362    }
363
364    /// Lift an analysis-root-relative path into this diff's key namespace.
365    #[must_use]
366    pub fn key_for_root_relative<'a>(&self, rel: &'a str) -> Cow<'a, str> {
367        if self.root_offset.is_empty() {
368            return Cow::Borrowed(rel);
369        }
370        Cow::Owned(format!("{}/{rel}", self.root_offset))
371    }
372
373    /// Lower one of this diff's keys back to an analysis-root-relative path.
374    /// `None` when the key names a file outside the analysis root.
375    #[must_use]
376    pub fn root_relative_from_key<'a>(&self, key: &'a str) -> Option<Cow<'a, str>> {
377        if self.root_offset.is_empty() {
378            return Some(Cow::Borrowed(key));
379        }
380        strip_path_component_prefix(key, &self.root_offset).map(Cow::Borrowed)
381    }
382
383    /// The pre-rename path of an analysis-root-relative path, itself
384    /// analysis-root-relative. Crosses into the diff's key namespace and back,
385    /// so a monorepo package below the diff's base resolves its renames.
386    #[must_use]
387    pub fn old_path_for_root_relative<'a>(&'a self, rel: &str) -> Option<Cow<'a, str>> {
388        let old = self.old_path_for(&self.key_for_root_relative(rel))?;
389        self.root_relative_from_key(old)
390    }
391
392    /// Directory this diff's keys are relative to, when declared via
393    /// [`DiffIndex::with_base`].
394    #[must_use]
395    pub fn base(&self) -> Option<&Path> {
396        self.base.as_deref()
397    }
398
399    /// Analyzable head-tree paths this diff touches, in the diff's key
400    /// namespace.
401    pub fn touched_files(&self) -> impl Iterator<Item = &str> {
402        self.touched_files.iter().map(String::as_str)
403    }
404
405    /// Map a finding's path into this diff's key namespace.
406    ///
407    /// Relativizes against [`DiffIndex::base`] when one was declared, else
408    /// against `fallback_root`. When base == `fallback_root` (the analysis
409    /// root is the repository toplevel) both agree, so behavior is unchanged.
410    #[must_use]
411    pub fn key_for(&self, path: &Path, fallback_root: &Path) -> Option<String> {
412        relative_to_diff_path(path, self.base.as_deref().unwrap_or(fallback_root))
413    }
414}
415
416/// Relativize `path` against `root` with forward slashes, passing an already
417/// relative path through unchanged. `None` for absolute paths outside `root`.
418#[must_use]
419pub fn relative_to_diff_path(path: &Path, root: &Path) -> Option<String> {
420    if let Ok(stripped) = path.strip_prefix(root) {
421        return Some(stripped.to_string_lossy().replace('\\', "/"));
422    }
423    if fallow_types::path_util::is_absolute_path_any_platform(path) {
424        return None;
425    }
426    Some(path.to_string_lossy().replace('\\', "/"))
427}
428
429/// Strip `prefix` and its trailing separator, only on a path-component
430/// boundary, so `packages/pkg-extra/a.ts` is never read as `packages/pkg`
431/// plus `-extra/a.ts`.
432#[must_use]
433pub fn strip_path_component_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
434    path.strip_prefix(prefix)?.strip_prefix('/')
435}
436
437/// Place one head line among the change blocks of its file, in head order.
438fn head_line_place(blocks: &[ChangeBlock], line: u64) -> HeadLinePlace {
439    let mut shift: i128 = 0;
440    for block in blocks {
441        if line < block.new_start {
442            break;
443        }
444        if line < block.new_start + block.new_len {
445            return HeadLinePlace::Added(*block);
446        }
447        shift += i128::from(block.old_len) - i128::from(block.new_len);
448    }
449    HeadLinePlace::Unchanged(u64::try_from(i128::from(line) + shift).unwrap_or(0))
450}
451
452/// The first line of one side of a `@@ -a,b +c,d @@` hunk. `side` is `-` for
453/// the base and `+` for the head. A side with no line (`b` or `d` is 0) names
454/// the line before the hunk, so its first line is the next one.
455fn hunk_next_line(header: &str, side: char) -> Option<u64> {
456    let range = header
457        .split_whitespace()
458        .find_map(|part| part.strip_prefix(side))?;
459    let (start, len) = match range.split_once(',') {
460        Some((start, len)) => (start.parse::<u64>().ok()?, len.parse::<u64>().ok()?),
461        None => (range.parse::<u64>().ok()?, 1),
462    };
463    Some(if len == 0 { start + 1 } else { start })
464}
465
466/// Parse the new-file start line out of a `@@ -a,b +c,d @@` hunk header.
467pub fn parse_new_hunk_start(header: &str) -> Option<u64> {
468    let plus = header.find('+')?;
469    let rest = &header[plus + 1..];
470    let end = rest
471        .find(|c: char| c == ',' || c.is_ascii_whitespace())
472        .unwrap_or(rest.len());
473    rest[..end].parse().ok()
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479
480    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";
481
482    #[test]
483    fn base_line_range_maps_unchanged_lines_across_blocks() {
484        let index = DiffIndex::from_unified_diff(EDIT_DIFF);
485        assert_eq!(index.base_line_range("a.js", 1, 6), Some((1, 6)));
486        // Lines after the two-line insertion move up by two.
487        assert_eq!(index.base_line_range("a.js", 13, 21), Some((11, 19)));
488        // Lines after the two-line removal move back down by two.
489        assert_eq!(index.base_line_range("a.js", 22, 25), Some((22, 25)));
490    }
491
492    #[test]
493    fn base_line_range_maps_a_replaced_line_to_its_removed_line() {
494        let index = DiffIndex::from_unified_diff(EDIT_DIFF);
495        assert_eq!(index.base_line_range("a.js", 7, 7), Some((7, 7)));
496        assert_eq!(index.base_line_range("a.js", 1, 12), Some((1, 10)));
497    }
498
499    #[test]
500    fn base_line_range_has_no_base_line_for_pure_additions() {
501        let index = DiffIndex::from_unified_diff(EDIT_DIFF);
502        assert_eq!(index.base_line_range("a.js", 11, 12), None);
503        let new_file = DiffIndex::from_unified_diff(
504            "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",
505        );
506        assert_eq!(new_file.base_line_range("n.js", 1, 2), None);
507        // A new file has no base line, also outside its added lines.
508        assert_eq!(new_file.base_line_range("n.js", 3, 4), None);
509    }
510
511    #[test]
512    fn base_line_range_keeps_files_outside_the_diff() {
513        let index = DiffIndex::from_unified_diff(EDIT_DIFF);
514        assert_eq!(index.base_line_range("other.js", 3, 9), Some((3, 9)));
515    }
516
517    #[test]
518    fn no_newline_marker_does_not_move_the_line_cursor() {
519        let index = DiffIndex::from_unified_diff(
520            "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",
521        );
522        assert!(index.line_is_added("a.js", 3));
523        assert!(index.line_is_added("a.js", 4));
524        assert!(!index.line_is_added("a.js", 5));
525    }
526
527    #[test]
528    fn from_unified_diff_caps_added_lines_at_threshold() {
529        let header =
530            "diff --git a/big.txt b/big.txt\n--- a/big.txt\n+++ b/big.txt\n@@ -0,0 +1,100 @@\n";
531        let mut body = String::with_capacity(MAX_ADDED_LINES * 16);
532        for _ in 0..(MAX_ADDED_LINES + 100) {
533            body.push_str("+x\n");
534        }
535        let mut diff = String::with_capacity(header.len() + body.len());
536        diff.push_str(header);
537        diff.push_str(&body);
538
539        let index = DiffIndex::from_unified_diff(&diff);
540        assert!(
541            index.added_line_count() <= MAX_ADDED_LINES,
542            "indexed {} lines, cap is {MAX_ADDED_LINES}",
543            index.added_line_count()
544        );
545        assert_eq!(
546            Some(index.net_lines()),
547            i64::try_from(MAX_ADDED_LINES + 100).ok()
548        );
549        assert_eq!(index.hunk_count(), 1);
550    }
551
552    #[test]
553    fn from_unified_diff_counts_additions_removals_and_hunks() {
554        let diff = "\
555diff --git a/src/a.ts b/src/a.ts
556--- a/src/a.ts
557+++ b/src/a.ts
558@@ -1,3 +1,4 @@
559-old
560+new
561+extra
562+++flag
563 context
564@@ -10,2 +11,1 @@
565-removed
566---flag
567 kept
568";
569        let index = DiffIndex::from_unified_diff(diff);
570
571        assert_eq!(index.hunk_count(), 2);
572        assert_eq!(index.net_lines(), 0);
573        assert!(index.changes_path("src/a.ts"));
574        assert!(index.touches_file("src/a.ts"));
575    }
576
577    #[test]
578    fn rename_only_diff_has_no_line_or_hunk_changes() {
579        let diff = "\
580diff --git a/src/old.ts b/src/new.ts
581similarity index 100%
582rename from src/old.ts
583rename to src/new.ts
584";
585        let index = DiffIndex::from_unified_diff(diff);
586
587        assert_eq!(index.hunk_count(), 0);
588        assert_eq!(index.net_lines(), 0);
589        assert!(index.changes_path("src/new.ts"));
590        assert!(index.touches_file("src/new.ts"));
591    }
592
593    #[test]
594    fn range_overlaps_added_hotspot_starting_before_diff_touches_inside() {
595        let diff = "\
596diff --git a/src/big.ts b/src/big.ts
597--- a/src/big.ts
598+++ b/src/big.ts
599@@ -114,1 +114,2 @@
600 ctx
601+touched
602";
603        let index = DiffIndex::from_unified_diff(diff);
604        assert!(index.range_overlaps_added("src/big.ts", 10, 120));
605        assert!(!index.range_overlaps_added("src/other.ts", 10, 120));
606        assert!(!index.range_overlaps_added("src/big.ts", 10, 100));
607        assert!(!index.range_overlaps_added("src/big.ts", 200, 100));
608    }
609
610    #[test]
611    fn rename_header_records_old_path() {
612        let diff = "\
613diff --git a/src/old.ts b/src/new.ts
614similarity index 90%
615rename from src/old.ts
616rename to src/new.ts
617--- a/src/old.ts
618+++ b/src/new.ts
619@@ -1,1 +1,1 @@
620-old
621+new
622";
623        let index = DiffIndex::from_unified_diff(diff);
624        assert_eq!(index.old_path_for("src/new.ts"), Some("src/old.ts"));
625        assert!(index.touches_file("src/new.ts"));
626    }
627
628    #[test]
629    fn empty_diff_has_zero_added_lines_and_no_touched_files() {
630        let index = DiffIndex::from_unified_diff("");
631        assert_eq!(index.added_line_count(), 0);
632        assert!(!index.touches_file("src/a.ts"));
633    }
634
635    #[test]
636    fn delete_only_diff_records_removal_without_touching_head_file() {
637        let diff = "\
638diff --git a/src/a.ts b/src/a.ts
639--- a/src/a.ts
640+++ /dev/null
641@@ -1,1 +0,0 @@
642-old
643";
644        let index = DiffIndex::from_unified_diff(diff);
645        assert_eq!(index.added_line_count(), 0);
646        assert_eq!(index.hunk_count(), 1);
647        assert_eq!(index.net_lines(), -1);
648        assert!(index.changes_path("src/a.ts"));
649        assert!(!index.touches_file("src/a.ts"));
650    }
651
652    #[test]
653    fn relative_to_diff_path_strips_absolute_root() {
654        let root = Path::new("/project");
655        let path = Path::new("/project/src/a.ts");
656        assert_eq!(
657            relative_to_diff_path(path, root).as_deref(),
658            Some("src/a.ts")
659        );
660    }
661
662    #[test]
663    fn relative_to_diff_path_passes_through_relative() {
664        let root = Path::new("/project");
665        let path = Path::new("src/a.ts");
666        assert_eq!(
667            relative_to_diff_path(path, root).as_deref(),
668            Some("src/a.ts")
669        );
670    }
671
672    #[test]
673    fn relative_to_diff_path_returns_none_for_path_outside_root() {
674        let root = Path::new("/project");
675        let path = Path::new("/elsewhere/src/a.ts");
676        assert!(relative_to_diff_path(path, root).is_none());
677    }
678
679    #[test]
680    fn key_for_without_base_relativizes_against_the_fallback_root() {
681        let index = DiffIndex::default();
682        assert_eq!(
683            index
684                .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
685                .as_deref(),
686            Some("src/a.ts")
687        );
688    }
689
690    #[test]
691    fn key_for_with_base_equal_to_root_is_unchanged() {
692        let index = DiffIndex::default().with_base("/repo");
693        assert_eq!(
694            index
695                .key_for(Path::new("/repo/src/a.ts"), Path::new("/repo"))
696                .as_deref(),
697            Some("src/a.ts")
698        );
699    }
700
701    /// The regression: an analysis root below the repo toplevel must still
702    /// produce the toplevel-relative key `git diff` writes.
703    #[test]
704    fn key_for_with_base_above_root_yields_repo_root_relative_key() {
705        let index = DiffIndex::default().with_base("/repo");
706        assert_eq!(
707            index
708                .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
709                .as_deref(),
710            Some("pkg/src/a.ts")
711        );
712    }
713
714    #[test]
715    fn key_for_with_base_above_root_matches_a_repo_root_relative_diff() {
716        let diff = "\
717diff --git a/pkg/src/a.ts b/pkg/src/a.ts
718--- a/pkg/src/a.ts
719+++ b/pkg/src/a.ts
720@@ -1,0 +2,1 @@
721+added
722";
723        let index = DiffIndex::from_unified_diff(diff).with_base("/repo");
724        let key = index
725            .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
726            .expect("finding path is under the base");
727
728        assert!(index.touches_file(&key));
729        assert!(index.line_is_added(&key, 2));
730
731        // Without the base, the same finding keys as `src/a.ts` and misses.
732        let unbased = DiffIndex::from_unified_diff(diff);
733        let missed = unbased
734            .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
735            .expect("still relativizable");
736        assert_eq!(missed, "src/a.ts");
737        assert!(!unbased.touches_file(&missed));
738    }
739
740    #[test]
741    fn key_for_returns_none_for_path_outside_the_base() {
742        let index = DiffIndex::default().with_base("/repo");
743        assert!(
744            index
745                .key_for(Path::new("/elsewhere/a.ts"), Path::new("/repo/pkg"))
746                .is_none()
747        );
748    }
749
750    #[test]
751    fn old_path_for_root_relative_crosses_the_namespace_and_back() {
752        let diff = "\
753diff --git a/pkg/src/old.ts b/pkg/src/new.ts
754similarity index 90%
755rename from pkg/src/old.ts
756rename to pkg/src/new.ts
757--- a/pkg/src/old.ts
758+++ b/pkg/src/new.ts
759@@ -1,1 +1,1 @@
760-old
761+new
762";
763        let index = DiffIndex::from_unified_diff(diff)
764            .with_base("/repo")
765            .with_root_offset("pkg");
766
767        // The finding is addressed `src/new.ts`; the diff says `pkg/src/new.ts`.
768        assert_eq!(
769            index.old_path_for_root_relative("src/new.ts").as_deref(),
770            Some("src/old.ts")
771        );
772        // The raw lookup, in the diff's own namespace, still works.
773        assert_eq!(index.old_path_for("pkg/src/new.ts"), Some("pkg/src/old.ts"));
774        assert_eq!(index.old_path_for_root_relative("src/absent.ts"), None);
775    }
776
777    #[test]
778    fn root_relative_key_round_trips() {
779        let index = DiffIndex::default().with_root_offset("packages/pkg");
780        assert_eq!(
781            index.key_for_root_relative("src/a.ts"),
782            "packages/pkg/src/a.ts"
783        );
784        assert_eq!(
785            index
786                .root_relative_from_key("packages/pkg/src/a.ts")
787                .as_deref(),
788            Some("src/a.ts")
789        );
790        // A key outside the analysis root has no root-relative form.
791        assert_eq!(index.root_relative_from_key("other/src/a.ts"), None);
792        // Sibling directory sharing a name prefix is not a match.
793        assert_eq!(
794            index.root_relative_from_key("packages/pkg-extra/a.ts"),
795            None
796        );
797    }
798
799    #[test]
800    fn empty_root_offset_is_identity() {
801        let index = DiffIndex::default();
802        assert_eq!(index.key_for_root_relative("src/a.ts"), "src/a.ts");
803        assert_eq!(
804            index.root_relative_from_key("src/a.ts").as_deref(),
805            Some("src/a.ts")
806        );
807    }
808
809    #[test]
810    fn touched_files_enumerates_diff_header_paths() {
811        let diff = "\
812diff --git a/pkg/a.ts b/pkg/a.ts
813--- a/pkg/a.ts
814+++ b/pkg/a.ts
815@@ -0,0 +1,1 @@
816+x
817";
818        let index = DiffIndex::from_unified_diff(diff);
819        assert_eq!(index.touched_files().collect::<Vec<_>>(), vec!["pkg/a.ts"]);
820    }
821}