fallow-output 3.48.0

Output contract types for fallow reports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
use std::borrow::Cow;
use std::path::{Path, PathBuf};

use rustc_hash::{FxHashMap, FxHashSet};

use crate::unified_diff::{DiffEvent, DiffFileHeader, unified_diff_events};

/// Refuse to parse a unified diff larger than this.
pub const MAX_DIFF_BYTES: u64 = 10 * 1024 * 1024;

/// Stop indexing added lines past this count.
pub const MAX_ADDED_LINES: usize = 1_000_000;

/// Parsed, command-neutral index of files and added lines in a unified diff.
///
/// Keys are the decoded paths of the `+++ b/<path>` headers of the diff,
/// without the quotes and the trailing tab that git can write. They live in
/// the namespace that produced the diff (for `git diff`, relative to the
/// repository toplevel). [`DiffIndex::base`] records the
/// directory those keys are relative to, so a finding's absolute path can be
/// mapped into the same namespace before lookup. Without it, an analysis root
/// below the toplevel silently misses every key.
#[derive(Debug, Default, Clone)]
pub struct DiffIndex {
    added_lines: FxHashMap<String, FxHashSet<u64>>,
    changed_paths: FxHashSet<String>,
    touched_files: FxHashSet<String>,
    added_line_count: usize,
    total_added_lines: usize,
    total_removed_lines: usize,
    hunk_count: usize,
    rename_pairs: FxHashMap<String, String>,
    base: Option<PathBuf>,
    root_offset: String,
    base_lines: Box<BaseLineMap>,
}

/// The data that maps head lines back to base lines. It is boxed, so the
/// index stays small in the enums that hold it.
#[derive(Debug, Default, Clone)]
struct BaseLineMap {
    change_blocks: FxHashMap<String, Vec<ChangeBlock>>,
    new_files: FxHashSet<String>,
    lines_capped: bool,
}

/// One run of removed and added lines with no unchanged line in it.
#[derive(Debug, Clone, Copy)]
struct ChangeBlock {
    /// First head line of the run. When the run adds no line, the head line
    /// after it.
    new_start: u64,
    /// Number of added lines.
    new_len: u64,
    /// First base line of the run. When the run removes no line, the base
    /// line after it.
    old_start: u64,
    /// Number of removed lines.
    old_len: u64,
}

impl ChangeBlock {
    /// Last base line that the run removed. `None` when it removed no line.
    fn last_removed_line(self) -> Option<u64> {
        (self.old_start + self.old_len)
            .checked_sub(1)
            .filter(|_| self.old_len > 0)
    }
}

/// Where one head line sits relative to the change blocks of its file.
enum HeadLinePlace {
    /// An unchanged line, at this base line.
    Unchanged(u64),
    /// An added line of this block.
    Added(ChangeBlock),
}

/// Mutable cursor state threaded through unified-diff parsing.
#[derive(Default)]
struct DiffParseState {
    current_file: Option<String>,
    new_line: u64,
    old_line: u64,
}

impl DiffIndex {
    /// Parse a unified diff into an index of changed files and added lines.
    ///
    /// Indexes at most [`MAX_ADDED_LINES`] added lines; totals used by
    /// [`DiffIndex::net_lines`] keep counting past the cap.
    #[must_use]
    pub fn from_unified_diff(diff: &str) -> Self {
        let mut index = Self::default();
        let mut state = DiffParseState::default();

        for event in unified_diff_events(diff) {
            match event {
                DiffEvent::File(header) => state.current_file = index.record_file(header),
                DiffEvent::Hunk {
                    old_start,
                    old_len,
                    new_start,
                    new_len,
                } => {
                    // A side with no line names the line before the hunk.
                    state.old_line = if old_len == 0 {
                        old_start + 1
                    } else {
                        old_start
                    };
                    state.new_line = if new_len == 0 {
                        new_start + 1
                    } else {
                        new_start
                    };
                    index.hunk_count += 1;
                }
                DiffEvent::Added(_) => index.record_added_line(&mut state),
                DiffEvent::Removed(_) => index.record_removed_line(&mut state),
                DiffEvent::Context(_) => {
                    state.new_line += 1;
                    state.old_line += 1;
                }
                DiffEvent::NoNewline => {}
            }
        }

        index
    }

    /// Record the paths of one file section. Returns the file that the lines
    /// of the section belong to: the head path, or the base path of a
    /// deleted file.
    fn record_file(&mut self, header: DiffFileHeader<'_>) -> Option<String> {
        if let Some(path) = header.new_path {
            let path = path.into_owned();
            self.changed_paths.insert(path.clone());
            self.touched_files.insert(path.clone());
            if let Some(from) = header.renamed_from {
                self.rename_pairs.insert(path.clone(), from.into_owned());
            }
            if header.is_new {
                self.base_lines.new_files.insert(path.clone());
            }
            return Some(path);
        }
        let old = header.old_path.filter(|_| header.is_deleted)?.into_owned();
        self.changed_paths.insert(old.clone());
        Some(old)
    }

    fn record_added_line(&mut self, state: &mut DiffParseState) {
        let Some(path) = state.current_file.as_ref() else {
            return;
        };
        self.total_added_lines += 1;
        if self.added_line_count < MAX_ADDED_LINES {
            self.added_lines
                .entry(path.clone())
                .or_default()
                .insert(state.new_line);
            self.added_line_count += 1;
            self.record_change_line(state, true);
        } else {
            self.base_lines.lines_capped = true;
        }
        state.new_line += 1;
    }

    fn record_removed_line(&mut self, state: &mut DiffParseState) {
        if state.current_file.is_none() {
            return;
        }
        self.total_removed_lines += 1;
        self.record_change_line(state, false);
        state.old_line += 1;
    }

    /// Add one removed or added line to the change block that ends at the
    /// cursor, or open a new block there.
    fn record_change_line(&mut self, state: &DiffParseState, added: bool) {
        let Some(path) = state.current_file.as_ref() else {
            return;
        };
        let blocks = self
            .base_lines
            .change_blocks
            .entry(path.clone())
            .or_default();
        let continues = blocks.last().is_some_and(|block| {
            block.new_start + block.new_len == state.new_line
                && block.old_start + block.old_len == state.old_line
        });
        if !continues {
            blocks.push(ChangeBlock {
                new_start: state.new_line,
                new_len: 0,
                old_start: state.old_line,
                old_len: 0,
            });
        }
        if let Some(block) = blocks.last_mut() {
            if added {
                block.new_len += 1;
            } else {
                block.old_len += 1;
            }
        }
    }

    /// Map an inclusive head line range of `path` to the base tree. `path`
    /// is a key of this diff.
    ///
    /// Unchanged lines map exactly. An added line at the start of the range
    /// maps to the last base line that its block removed, which is the
    /// removed line next to the unchanged lines inside the range. An added
    /// line at the end maps to the first removed line, for the same reason.
    /// A block that replaces several lines thus does not widen the range to
    /// base lines that the range does not reach. A range that starts and
    /// ends in one block maps to every line that the block removed. A file
    /// that the diff does not name maps unchanged. `None` when the range
    /// holds no base line, when the diff adds `path` as a new file, or when
    /// the index stopped at [`MAX_ADDED_LINES`].
    #[must_use]
    pub fn base_line_range(&self, path: &str, start: u64, end: u64) -> Option<(u64, u64)> {
        let map = &self.base_lines;
        if map.lines_capped || start > end || map.new_files.contains(path) {
            return None;
        }
        let blocks = map.change_blocks.get(path).map_or(&[][..], Vec::as_slice);
        let (base_start, base_end) =
            match (head_line_place(blocks, start), head_line_place(blocks, end)) {
                (HeadLinePlace::Added(first), HeadLinePlace::Added(last))
                    if first.new_start == last.new_start =>
                {
                    (first.old_start, first.last_removed_line()?)
                }
                (start_place, end_place) => {
                    let base_start = match start_place {
                        HeadLinePlace::Unchanged(line) => line,
                        HeadLinePlace::Added(block) => {
                            block.last_removed_line().unwrap_or(block.old_start)
                        }
                    };
                    let base_end = match end_place {
                        HeadLinePlace::Unchanged(line) => line,
                        HeadLinePlace::Added(block) if block.old_len > 0 => block.old_start,
                        HeadLinePlace::Added(block) => block.old_start.checked_sub(1)?,
                    };
                    (base_start, base_end)
                }
            };
        (base_start <= base_end).then_some((base_start, base_end))
    }

    /// Pre-rename path for `head_path`, in the diff's key namespace, when the
    /// diff renamed it.
    #[must_use]
    pub fn old_path_for(&self, head_path: &str) -> Option<&str> {
        self.rename_pairs.get(head_path).map(String::as_str)
    }

    /// Number of indexed added lines, capped at [`MAX_ADDED_LINES`].
    #[must_use]
    pub fn added_line_count(&self) -> usize {
        self.added_line_count
    }

    /// The scope that a diff filter keeps: the indexed added lines, plus one
    /// for each touched head-tree file that adds no line, such as a pure
    /// rename. The filter keeps a finding on a whole touched file, so `0`
    /// means that the diff touches no file and adds no line. At the
    /// [`MAX_ADDED_LINES`] cap it returns the cap, because the files after the
    /// cap have no indexed line and would each count as a file without lines.
    #[must_use]
    pub fn filter_scope_size(&self) -> usize {
        if self.added_line_count >= MAX_ADDED_LINES {
            return self.added_line_count;
        }
        let files_without_lines = self
            .touched_files
            .iter()
            .filter(|path| !self.added_lines.contains_key(*path))
            .count();
        self.added_line_count.saturating_add(files_without_lines)
    }

    /// Number of parsed unified-diff hunk headers.
    #[must_use]
    pub fn hunk_count(&self) -> usize {
        self.hunk_count
    }

    /// Total added lines minus total removed lines, independent of the added
    /// line indexing cap.
    #[must_use]
    pub fn net_lines(&self) -> i64 {
        let added = i64::try_from(self.total_added_lines).unwrap_or(i64::MAX);
        let removed = i64::try_from(self.total_removed_lines).unwrap_or(i64::MAX);
        added.saturating_sub(removed)
    }

    /// Whether this diff changes the path, including when the path is deleted.
    #[must_use]
    pub fn changes_path(&self, path: &str) -> bool {
        self.changed_paths.contains(path)
    }

    /// Paths changed by the diff, using the old path for deleted files.
    pub fn changed_paths(&self) -> impl Iterator<Item = &str> {
        self.changed_paths.iter().map(String::as_str)
    }

    /// Whether this diff touches an analyzable path in the head tree.
    #[must_use]
    pub fn touches_file(&self, path: &str) -> bool {
        self.touched_files.contains(path)
    }

    /// Whether any added line in `path` falls inside the inclusive 1-based
    /// `start..=end` range.
    #[must_use]
    pub fn range_overlaps_added(&self, path: &str, start: u64, end: u64) -> bool {
        self.first_added_line_in_range(path, start, end).is_some()
    }

    /// Lowest 1-based added line inside the inclusive `start..=end` range.
    /// Returns `None` for an invalid range or when the diff adds no line in it.
    #[must_use]
    pub fn first_added_line_in_range(&self, path: &str, start: u64, end: u64) -> Option<u64> {
        if end < start {
            return None;
        }
        let added = self.added_lines.get(path)?;
        let lo = start.max(1);
        added
            .iter()
            .copied()
            .filter(|line| *line >= lo && *line <= end)
            .min()
    }

    /// Whether the 1-based `line` in `path` was added by this diff.
    #[must_use]
    pub fn line_is_added(&self, path: &str, line: u64) -> bool {
        self.added_lines
            .get(path)
            .is_some_and(|lines| lines.contains(&line))
    }

    /// Whether `line` sits within `radius` lines of any added line in `path`.
    #[must_use]
    pub fn line_within_added_context(&self, path: &str, line: u64, radius: u64) -> bool {
        self.added_lines
            .get(path)
            .is_some_and(|lines| lines.iter().any(|added| line.abs_diff(*added) <= radius))
    }

    /// Set of 1-based added line numbers for `path`, when the diff added any.
    #[must_use]
    pub fn added_lines_in(&self, path: &str) -> Option<&FxHashSet<u64>> {
        self.added_lines.get(path)
    }

    /// Declare the directory this diff's paths are relative to (the git
    /// toplevel for `git diff` output).
    #[must_use]
    pub fn with_base(mut self, base: impl Into<PathBuf>) -> Self {
        self.base = Some(base.into());
        self
    }

    /// Declare where the analysis root sits below [`DiffIndex::base`], as a
    /// forward-slashed relative path (empty when they are the same directory).
    ///
    /// Findings are addressed relative to the analysis root; this diff's keys
    /// are relative to its base. Everything that looks a finding up in this
    /// index has to cross that gap, so the index carries the offset rather than
    /// making each caller rediscover it.
    #[must_use]
    pub fn with_root_offset(mut self, offset: impl Into<String>) -> Self {
        let mut offset = offset.into();
        // A trailing separator would make `strip_path_component_prefix` demand a
        // second one and never match. Normalize rather than trust the caller.
        offset.truncate(offset.trim_end_matches('/').len());
        self.root_offset = offset;
        self
    }

    /// Relative path of the analysis root below [`DiffIndex::base`]; empty
    /// when they coincide.
    #[must_use]
    pub fn root_offset(&self) -> &str {
        &self.root_offset
    }

    /// Lift an analysis-root-relative path into this diff's key namespace.
    #[must_use]
    pub fn key_for_root_relative<'a>(&self, rel: &'a str) -> Cow<'a, str> {
        if self.root_offset.is_empty() {
            return Cow::Borrowed(rel);
        }
        Cow::Owned(format!("{}/{rel}", self.root_offset))
    }

    /// Lower one of this diff's keys back to an analysis-root-relative path.
    /// `None` when the key names a file outside the analysis root.
    #[must_use]
    pub fn root_relative_from_key<'a>(&self, key: &'a str) -> Option<Cow<'a, str>> {
        if self.root_offset.is_empty() {
            return Some(Cow::Borrowed(key));
        }
        strip_path_component_prefix(key, &self.root_offset).map(Cow::Borrowed)
    }

    /// The pre-rename path of an analysis-root-relative path, itself
    /// analysis-root-relative. Crosses into the diff's key namespace and back,
    /// so a monorepo package below the diff's base resolves its renames.
    #[must_use]
    pub fn old_path_for_root_relative<'a>(&'a self, rel: &str) -> Option<Cow<'a, str>> {
        let old = self.old_path_for(&self.key_for_root_relative(rel))?;
        self.root_relative_from_key(old)
    }

    /// Directory this diff's keys are relative to, when declared via
    /// [`DiffIndex::with_base`].
    #[must_use]
    pub fn base(&self) -> Option<&Path> {
        self.base.as_deref()
    }

    /// Analyzable head-tree paths this diff touches, in the diff's key
    /// namespace.
    pub fn touched_files(&self) -> impl Iterator<Item = &str> {
        self.touched_files.iter().map(String::as_str)
    }

    /// Map a finding's path into this diff's key namespace.
    ///
    /// Relativizes against [`DiffIndex::base`] when one was declared, else
    /// against `fallback_root`. When base == `fallback_root` (the analysis
    /// root is the repository toplevel) both agree, so behavior is unchanged.
    #[must_use]
    pub fn key_for(&self, path: &Path, fallback_root: &Path) -> Option<String> {
        relative_to_diff_path(path, self.base.as_deref().unwrap_or(fallback_root))
    }
}

/// Relativize `path` against `root` with forward slashes, passing an already
/// relative path through unchanged. `None` for absolute paths outside `root`.
#[must_use]
pub fn relative_to_diff_path(path: &Path, root: &Path) -> Option<String> {
    if let Ok(stripped) = path.strip_prefix(root) {
        return Some(stripped.to_string_lossy().replace('\\', "/"));
    }
    if fallow_types::path_util::is_absolute_path_any_platform(path) {
        return None;
    }
    Some(path.to_string_lossy().replace('\\', "/"))
}

/// Strip `prefix` and its trailing separator, only on a path-component
/// boundary, so `packages/pkg-extra/a.ts` is never read as `packages/pkg`
/// plus `-extra/a.ts`.
#[must_use]
pub fn strip_path_component_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
    path.strip_prefix(prefix)?.strip_prefix('/')
}

/// Place one head line among the change blocks of its file, in head order.
fn head_line_place(blocks: &[ChangeBlock], line: u64) -> HeadLinePlace {
    let mut shift: i128 = 0;
    for block in blocks {
        if line < block.new_start {
            break;
        }
        if line < block.new_start + block.new_len {
            return HeadLinePlace::Added(*block);
        }
        shift += i128::from(block.old_len) - i128::from(block.new_len);
    }
    HeadLinePlace::Unchanged(u64::try_from(i128::from(line) + shift).unwrap_or(0))
}

#[cfg(test)]
mod tests {
    use super::*;

    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";

    #[test]
    fn base_line_range_maps_unchanged_lines_across_blocks() {
        let index = DiffIndex::from_unified_diff(EDIT_DIFF);
        assert_eq!(index.base_line_range("a.js", 1, 6), Some((1, 6)));
        // Lines after the two-line insertion move up by two.
        assert_eq!(index.base_line_range("a.js", 13, 21), Some((11, 19)));
        // Lines after the two-line removal move back down by two.
        assert_eq!(index.base_line_range("a.js", 22, 25), Some((22, 25)));
    }

    #[test]
    fn base_line_range_maps_a_replaced_line_to_its_removed_line() {
        let index = DiffIndex::from_unified_diff(EDIT_DIFF);
        assert_eq!(index.base_line_range("a.js", 7, 7), Some((7, 7)));
        assert_eq!(index.base_line_range("a.js", 1, 12), Some((1, 10)));
    }

    /// Three base lines become two head lines. A range that starts on the
    /// second head line reaches only the last replaced base line, so it maps
    /// to that line and not to the first one (issue #4580).
    #[test]
    fn base_line_range_maps_a_start_in_a_multi_line_replacement_to_its_last_removed_line() {
        let index = DiffIndex::from_unified_diff(
            "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",
        );
        assert_eq!(index.base_line_range("b.ts", 2, 15), Some((3, 16)));
        assert_eq!(index.base_line_range("b.ts", 1, 2), Some((1, 3)));
    }

    #[test]
    fn base_line_range_maps_an_end_in_a_multi_line_replacement_to_its_first_removed_line() {
        let index = DiffIndex::from_unified_diff(
            "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",
        );
        assert_eq!(index.base_line_range("b.ts", 1, 10), Some((1, 10)));
        assert_eq!(index.base_line_range("b.ts", 1, 11), Some((1, 10)));
        assert_eq!(index.base_line_range("b.ts", 12, 20), Some((13, 21)));
    }

    #[test]
    fn base_line_range_has_no_base_line_for_pure_additions() {
        let index = DiffIndex::from_unified_diff(EDIT_DIFF);
        assert_eq!(index.base_line_range("a.js", 11, 12), None);
        let new_file = DiffIndex::from_unified_diff(
            "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",
        );
        assert_eq!(new_file.base_line_range("n.js", 1, 2), None);
        // A new file has no base line, also outside its added lines.
        assert_eq!(new_file.base_line_range("n.js", 3, 4), None);
    }

    #[test]
    fn base_line_range_keeps_files_outside_the_diff() {
        let index = DiffIndex::from_unified_diff(EDIT_DIFF);
        assert_eq!(index.base_line_range("other.js", 3, 9), Some((3, 9)));
    }

    #[test]
    fn no_newline_marker_does_not_move_the_line_cursor() {
        let index = DiffIndex::from_unified_diff(
            "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",
        );
        assert!(index.line_is_added("a.js", 3));
        assert!(index.line_is_added("a.js", 4));
        assert!(!index.line_is_added("a.js", 5));
    }

    #[test]
    fn from_unified_diff_caps_added_lines_at_threshold() {
        let header =
            "diff --git a/big.txt b/big.txt\n--- a/big.txt\n+++ b/big.txt\n@@ -0,0 +1,100 @@\n";
        let mut body = String::with_capacity(MAX_ADDED_LINES * 16);
        for _ in 0..(MAX_ADDED_LINES + 100) {
            body.push_str("+x\n");
        }
        let mut diff = String::with_capacity(header.len() + body.len());
        diff.push_str(header);
        diff.push_str(&body);

        let index = DiffIndex::from_unified_diff(&diff);
        assert!(
            index.added_line_count() <= MAX_ADDED_LINES,
            "indexed {} lines, cap is {MAX_ADDED_LINES}",
            index.added_line_count()
        );
        assert_eq!(
            Some(index.net_lines()),
            i64::try_from(MAX_ADDED_LINES + 100).ok()
        );
        assert_eq!(index.filter_scope_size(), index.added_line_count());
        assert_eq!(index.hunk_count(), 1);
        assert_eq!(
            index.base_line_range("other.txt", 1, 1),
            None,
            "a real cap still stops the base-line map"
        );
    }

    #[test]
    fn added_plus_plus_line_is_indexed_and_keeps_base_line_ranges() {
        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";
        let index = DiffIndex::from_unified_diff(diff);
        assert!(index.line_is_added("src/a.js", 2));
        assert!(index.line_is_added("src/a.js", 3));
        assert_eq!(index.base_line_range("src/a.js", 1, 1), Some((1, 1)));
        assert_eq!(index.base_line_range("src/other.js", 4, 9), Some((4, 9)));
    }

    #[test]
    fn header_shaped_added_line_keeps_the_current_file() {
        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";
        let index = DiffIndex::from_unified_diff(diff);
        assert!(!index.changes_path("other.js"));
        assert!(index.line_is_added("a.js", 1));
        assert!(index.line_is_added("a.js", 2));
    }

    #[test]
    fn quoted_and_tab_suffixed_paths_are_index_keys() {
        let diff = "\
diff --git \"a/src/caf\\303\\251.ts\" \"b/src/caf\\303\\251.ts\"
--- \"a/src/caf\\303\\251.ts\"
+++ \"b/src/caf\\303\\251.ts\"
@@ -1,0 +2 @@ x
+x2
diff --git \"a/src/del \\303\\251.ts\" \"b/src/del \\303\\251.ts\"
deleted file mode 100644
--- \"a/src/del \\303\\251.ts\"\t
+++ /dev/null
@@ -1 +0,0 @@
-gone
diff --git a/src/my file.ts b/src/my file.ts
--- a/src/my file.ts\t
+++ b/src/my file.ts\t
@@ -1,0 +2 @@ y
+y2
\\ No newline at end of file
diff --git a/src/old name.ts b/src/new name.ts
similarity index 82%
rename from src/old name.ts
rename to src/new name.ts
--- a/src/old name.ts\t
+++ b/src/new name.ts\t
@@ -6,0 +7 @@ six
+seven
";
        let index = DiffIndex::from_unified_diff(diff);
        assert!(index.line_is_added("src/café.ts", 2));
        assert!(index.changes_path("src/del é.ts"));
        assert!(!index.touches_file("src/del é.ts"));
        assert!(index.line_is_added("src/my file.ts", 2));
        assert!(index.line_is_added("src/new name.ts", 7));
        assert_eq!(
            index.old_path_for("src/new name.ts"),
            Some("src/old name.ts")
        );
    }

    #[test]
    fn from_unified_diff_counts_additions_removals_and_hunks() {
        let diff = "\
diff --git a/src/a.ts b/src/a.ts
--- a/src/a.ts
+++ b/src/a.ts
@@ -1,3 +1,4 @@
-old
+new
+extra
+++flag
 context
@@ -10,2 +11,1 @@
-removed
---flag
 kept
";
        let index = DiffIndex::from_unified_diff(diff);

        assert_eq!(index.hunk_count(), 2);
        assert_eq!(index.net_lines(), 0);
        assert!(index.changes_path("src/a.ts"));
        assert!(index.touches_file("src/a.ts"));
    }

    #[test]
    fn rename_only_diff_has_no_line_or_hunk_changes() {
        let diff = "\
diff --git a/src/old.ts b/src/new.ts
similarity index 100%
rename from src/old.ts
rename to src/new.ts
";
        let index = DiffIndex::from_unified_diff(diff);

        assert_eq!(index.hunk_count(), 0);
        assert_eq!(index.net_lines(), 0);
        assert!(index.changes_path("src/new.ts"));
        assert!(index.touches_file("src/new.ts"));
    }

    #[test]
    fn range_overlaps_added_hotspot_starting_before_diff_touches_inside() {
        let diff = "\
diff --git a/src/big.ts b/src/big.ts
--- a/src/big.ts
+++ b/src/big.ts
@@ -114,1 +114,2 @@
 ctx
+touched
";
        let index = DiffIndex::from_unified_diff(diff);
        assert!(index.range_overlaps_added("src/big.ts", 10, 120));
        assert!(!index.range_overlaps_added("src/other.ts", 10, 120));
        assert!(!index.range_overlaps_added("src/big.ts", 10, 100));
        assert!(!index.range_overlaps_added("src/big.ts", 200, 100));
    }

    #[test]
    fn rename_header_records_old_path() {
        let diff = "\
diff --git a/src/old.ts b/src/new.ts
similarity index 90%
rename from src/old.ts
rename to src/new.ts
--- a/src/old.ts
+++ b/src/new.ts
@@ -1,1 +1,1 @@
-old
+new
";
        let index = DiffIndex::from_unified_diff(diff);
        assert_eq!(index.old_path_for("src/new.ts"), Some("src/old.ts"));
        assert!(index.touches_file("src/new.ts"));
    }

    #[test]
    fn empty_diff_has_zero_added_lines_and_no_touched_files() {
        let index = DiffIndex::from_unified_diff("");
        assert_eq!(index.added_line_count(), 0);
        assert!(!index.touches_file("src/a.ts"));
        assert_eq!(index.filter_scope_size(), 0);
    }

    #[test]
    fn filter_scope_size_counts_added_lines_and_files_without_lines() {
        let diff = "\
diff --git a/src/old.ts b/src/renamed.ts
similarity index 100%
rename from src/old.ts
rename to src/renamed.ts
diff --git a/src/a.ts b/src/a.ts
--- a/src/a.ts
+++ b/src/a.ts
@@ -1,1 +1,2 @@
 keep
+added
diff --git a/bin/run.ts b/bin/run.ts
old mode 100644
new mode 100755
diff --git a/src/gone.ts b/src/gone.ts
deleted file mode 100644
--- a/src/gone.ts
+++ /dev/null
@@ -1,1 +0,0 @@
-old
";
        let index = DiffIndex::from_unified_diff(diff);
        assert_eq!(index.added_line_count(), 1);
        assert!(
            !index.touches_file("bin/run.ts"),
            "a mode-only section names no head path, so the filter keeps nothing on it"
        );
        assert_eq!(
            index.filter_scope_size(),
            2,
            "one added line plus the renamed file; the mode-only and deleted files \
             are not touched in the head tree"
        );
    }

    #[test]
    fn delete_only_diff_records_removal_without_touching_head_file() {
        let diff = "\
diff --git a/src/a.ts b/src/a.ts
--- a/src/a.ts
+++ /dev/null
@@ -1,1 +0,0 @@
-old
";
        let index = DiffIndex::from_unified_diff(diff);
        assert_eq!(index.added_line_count(), 0);
        assert_eq!(index.hunk_count(), 1);
        assert_eq!(index.net_lines(), -1);
        assert!(index.changes_path("src/a.ts"));
        assert!(!index.touches_file("src/a.ts"));
    }

    #[test]
    fn relative_to_diff_path_strips_absolute_root() {
        let root = Path::new("/project");
        let path = Path::new("/project/src/a.ts");
        assert_eq!(
            relative_to_diff_path(path, root).as_deref(),
            Some("src/a.ts")
        );
    }

    #[test]
    fn relative_to_diff_path_passes_through_relative() {
        let root = Path::new("/project");
        let path = Path::new("src/a.ts");
        assert_eq!(
            relative_to_diff_path(path, root).as_deref(),
            Some("src/a.ts")
        );
    }

    #[test]
    fn relative_to_diff_path_returns_none_for_path_outside_root() {
        let root = Path::new("/project");
        let path = Path::new("/elsewhere/src/a.ts");
        assert!(relative_to_diff_path(path, root).is_none());
    }

    #[test]
    fn key_for_without_base_relativizes_against_the_fallback_root() {
        let index = DiffIndex::default();
        assert_eq!(
            index
                .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
                .as_deref(),
            Some("src/a.ts")
        );
    }

    #[test]
    fn key_for_with_base_equal_to_root_is_unchanged() {
        let index = DiffIndex::default().with_base("/repo");
        assert_eq!(
            index
                .key_for(Path::new("/repo/src/a.ts"), Path::new("/repo"))
                .as_deref(),
            Some("src/a.ts")
        );
    }

    /// The regression: an analysis root below the repo toplevel must still
    /// produce the toplevel-relative key `git diff` writes.
    #[test]
    fn key_for_with_base_above_root_yields_repo_root_relative_key() {
        let index = DiffIndex::default().with_base("/repo");
        assert_eq!(
            index
                .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
                .as_deref(),
            Some("pkg/src/a.ts")
        );
    }

    #[test]
    fn key_for_with_base_above_root_matches_a_repo_root_relative_diff() {
        let diff = "\
diff --git a/pkg/src/a.ts b/pkg/src/a.ts
--- a/pkg/src/a.ts
+++ b/pkg/src/a.ts
@@ -1,0 +2,1 @@
+added
";
        let index = DiffIndex::from_unified_diff(diff).with_base("/repo");
        let key = index
            .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
            .expect("finding path is under the base");

        assert!(index.touches_file(&key));
        assert!(index.line_is_added(&key, 2));

        // Without the base, the same finding keys as `src/a.ts` and misses.
        let unbased = DiffIndex::from_unified_diff(diff);
        let missed = unbased
            .key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
            .expect("still relativizable");
        assert_eq!(missed, "src/a.ts");
        assert!(!unbased.touches_file(&missed));
    }

    #[test]
    fn key_for_returns_none_for_path_outside_the_base() {
        let index = DiffIndex::default().with_base("/repo");
        assert!(
            index
                .key_for(Path::new("/elsewhere/a.ts"), Path::new("/repo/pkg"))
                .is_none()
        );
    }

    #[test]
    fn old_path_for_root_relative_crosses_the_namespace_and_back() {
        let diff = "\
diff --git a/pkg/src/old.ts b/pkg/src/new.ts
similarity index 90%
rename from pkg/src/old.ts
rename to pkg/src/new.ts
--- a/pkg/src/old.ts
+++ b/pkg/src/new.ts
@@ -1,1 +1,1 @@
-old
+new
";
        let index = DiffIndex::from_unified_diff(diff)
            .with_base("/repo")
            .with_root_offset("pkg");

        // The finding is addressed `src/new.ts`; the diff says `pkg/src/new.ts`.
        assert_eq!(
            index.old_path_for_root_relative("src/new.ts").as_deref(),
            Some("src/old.ts")
        );
        // The raw lookup, in the diff's own namespace, still works.
        assert_eq!(index.old_path_for("pkg/src/new.ts"), Some("pkg/src/old.ts"));
        assert_eq!(index.old_path_for_root_relative("src/absent.ts"), None);
    }

    #[test]
    fn root_relative_key_round_trips() {
        let index = DiffIndex::default().with_root_offset("packages/pkg");
        assert_eq!(
            index.key_for_root_relative("src/a.ts"),
            "packages/pkg/src/a.ts"
        );
        assert_eq!(
            index
                .root_relative_from_key("packages/pkg/src/a.ts")
                .as_deref(),
            Some("src/a.ts")
        );
        // A key outside the analysis root has no root-relative form.
        assert_eq!(index.root_relative_from_key("other/src/a.ts"), None);
        // Sibling directory sharing a name prefix is not a match.
        assert_eq!(
            index.root_relative_from_key("packages/pkg-extra/a.ts"),
            None
        );
    }

    #[test]
    fn empty_root_offset_is_identity() {
        let index = DiffIndex::default();
        assert_eq!(index.key_for_root_relative("src/a.ts"), "src/a.ts");
        assert_eq!(
            index.root_relative_from_key("src/a.ts").as_deref(),
            Some("src/a.ts")
        );
    }

    #[test]
    fn touched_files_enumerates_diff_header_paths() {
        let diff = "\
diff --git a/pkg/a.ts b/pkg/a.ts
--- a/pkg/a.ts
+++ b/pkg/a.ts
@@ -0,0 +1,1 @@
+x
";
        let index = DiffIndex::from_unified_diff(diff);
        assert_eq!(index.touched_files().collect::<Vec<_>>(), vec!["pkg/a.ts"]);
    }
}