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