covguard-adapters-diff 0.1.0

Unified diff parsing and git-diff loading adapter for covguard
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
//! Diff parsing adapters for covguard.
//!
//! This crate provides a unified diff parser that extracts changed line ranges
//! from patch files or git diff output.

use std::collections::{BTreeMap, BTreeSet};
use std::ops::RangeInclusive;
use std::path::Path;

use covguard_paths::normalize_diff_path;
use covguard_ports::{DiffParseResult as PortDiffParseResult, DiffProvider};
use thiserror::Error;

// ============================================================================
// Types
// ============================================================================

/// Map of file paths to their changed line ranges.
///
/// Keys are normalized repo-relative paths with forward slashes.
/// Values are sorted, non-overlapping, inclusive line ranges (1-indexed).
pub type ChangedRanges = BTreeMap<String, Vec<RangeInclusive<u32>>>;

/// Result of parsing a diff with metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffParseResult {
    /// Parsed changed line ranges.
    pub changed_ranges: ChangedRanges,
    /// Detected binary files (normalized paths).
    pub binary_files: Vec<String>,
}

/// Errors that can occur during diff parsing.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum DiffError {
    /// The diff format is invalid or malformed.
    #[error("invalid diff format: {0}")]
    InvalidFormat(String),

    /// An I/O error occurred while reading the diff.
    #[error("I/O error: {0}")]
    IoError(String),
}

/// Default diff provider backed by git subprocess calls and unified diff parsing.
pub struct GitDiffProvider;

impl DiffProvider for GitDiffProvider {
    fn parse_patch(&self, text: &str) -> Result<PortDiffParseResult, String> {
        parse_patch_with_meta(text)
            .map(|parsed| PortDiffParseResult {
                changed_ranges: parsed.changed_ranges,
                binary_files: parsed.binary_files,
            })
            .map_err(|e| e.to_string())
    }

    fn load_diff_from_git(
        &self,
        base: &str,
        head: &str,
        repo_root: &Path,
    ) -> Result<String, String> {
        load_diff_from_git(base, head, repo_root).map_err(|e| e.to_string())
    }
}

/// Load unified diff text from git for a `base..head` range.
///
/// This is an adapter boundary for subprocess interaction.
pub fn load_diff_from_git(base: &str, head: &str, repo_root: &Path) -> Result<String, DiffError> {
    let output = std::process::Command::new("git")
        .current_dir(repo_root)
        .args(["diff", base, head])
        .output()
        .map_err(|e| DiffError::IoError(e.to_string()))?;
    // Preserve prior CLI behavior: if git exits non-zero, still return stdout.
    // The caller can then treat empty output as "no changed lines".
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

// ============================================================================
// Path Normalization
// ============================================================================

/// Normalize a path from a diff header to repo-relative format.
///
/// - Strips `b/` prefix (git diff convention)
/// - Strips `a/` prefix
/// - Converts backslashes to forward slashes
/// - Removes leading `./`
///
/// # Examples
///
/// ```
/// use covguard_adapters_diff::normalize_path;
///
/// assert_eq!(normalize_path("b/src/lib.rs"), "src/lib.rs");
/// assert_eq!(normalize_path("a/src/lib.rs"), "src/lib.rs");
/// assert_eq!(normalize_path("./src/lib.rs"), "src/lib.rs");
/// assert_eq!(normalize_path("src\\lib.rs"), "src/lib.rs");
/// ```
pub fn normalize_path(path: &str) -> String {
    normalize_diff_path(path)
}

// ============================================================================
// Range Merging
// ============================================================================
/// Re-exported range-merging utility for backward compatibility.
pub use covguard_ranges::merge_ranges;

// ============================================================================
// Diff Parsing
// ============================================================================

/// Parse a unified diff/patch and extract changed (added) line ranges.
///
/// This function parses the standard unified diff format as produced by
/// `git diff` or patch files. It extracts only added lines (lines starting
/// with `+` that aren't header lines).
///
/// # Arguments
///
/// * `text` - The unified diff text to parse
///
/// # Returns
///
/// A `ChangedRanges` map where keys are normalized file paths and values
/// are sorted, non-overlapping line ranges of added lines.
///
/// # Errors
///
/// Returns `DiffError::InvalidFormat` if the diff is malformed.
///
/// # Examples
///
/// ```
/// use covguard_adapters_diff::parse_patch;
///
/// let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
/// new file mode 100644
/// index 0000000..1111111
/// --- /dev/null
/// +++ b/src/lib.rs
/// @@ -0,0 +1,3 @@
/// +pub fn add(a: i32, b: i32) -> i32 {
/// +    a + b
/// +}
/// "#;
///
/// let ranges = parse_patch(diff).unwrap();
/// assert_eq!(ranges.get("src/lib.rs"), Some(&vec![1..=3]));
/// ```
pub fn parse_patch(text: &str) -> Result<ChangedRanges, DiffError> {
    Ok(parse_patch_with_meta(text)?.changed_ranges)
}

/// Parse a unified diff/patch and extract changed (added) line ranges with metadata.
///
/// In addition to changed ranges, this records binary files detected via:
/// - "Binary files ... and ... differ" lines
/// - "GIT binary patch" markers
pub fn parse_patch_with_meta(text: &str) -> Result<DiffParseResult, DiffError> {
    // Normalize line endings (handle CRLF)
    let text = text.replace("\r\n", "\n");
    let lines: Vec<&str> = text.lines().collect();

    let mut result: BTreeMap<String, Vec<u32>> = BTreeMap::new();
    let mut current_file: Option<String> = None;
    let mut current_diff_file: Option<String> = None;
    let mut current_new_line: u32 = 0;
    let mut in_hunk = false;

    // Track rename information
    let mut rename_to: Option<String> = None;
    // Track binary files
    let mut binary_files: BTreeSet<String> = BTreeSet::new();

    for line in lines {
        // Track diff header for fallback file identity
        if let Some(rest) = line.strip_prefix("diff --git ") {
            let mut parts = rest.split_whitespace();
            let _a = parts.next();
            let b = parts.next();
            current_diff_file = b.map(normalize_path);
            continue;
        }

        // Check for rename to header
        if line.starts_with("rename to ") {
            rename_to = Some(normalize_path(line.strip_prefix("rename to ").unwrap()));
            continue;
        }

        // Detect binary file marker line
        if let Some(rest) = line.strip_prefix("Binary files ") {
            if let Some(and_pos) = rest.find(" and ") {
                let after_and = &rest[and_pos + 5..];
                let path_part = after_and.strip_suffix(" differ").unwrap_or(after_and);
                let path = path_part.trim();
                if path != "/dev/null" {
                    binary_files.insert(normalize_path(path));
                }
            }
            continue;
        }

        // Detect git binary patch marker
        if line.starts_with("GIT binary patch") {
            if let Some(path) = current_file.clone().or_else(|| current_diff_file.clone()) {
                binary_files.insert(path);
            }
            continue;
        }

        // Check for new file header (+++ line)
        if let Some(path) = line.strip_prefix("+++ ") {
            let path = path.trim();

            // Handle /dev/null (deleted files)
            if path == "/dev/null" {
                current_file = None;
                continue;
            }

            // Use rename target if available, otherwise normalize the path
            let normalized = if let Some(ref rename) = rename_to {
                rename.clone()
            } else {
                normalize_path(path)
            };

            current_file = Some(normalized);
            rename_to = None;
            in_hunk = false;
            continue;
        }

        // Check for hunk header
        if line.starts_with("@@ ") {
            if let Some(ref _file) = current_file {
                // Parse @@ -old_start,old_count +new_start,new_count @@
                if let Some(new_start) = parse_hunk_header(line) {
                    current_new_line = new_start;
                    in_hunk = true;
                } else {
                    return Err(DiffError::InvalidFormat(format!(
                        "malformed hunk header: '{}'",
                        line
                    )));
                }
            }
            continue;
        }

        // Process lines within a hunk
        if in_hunk && let Some(ref file) = current_file {
            if let Some(first_char) = line.chars().next() {
                match first_char {
                    '+' => {
                        // Added line (but not +++ header)
                        result
                            .entry(file.clone())
                            .or_default()
                            .push(current_new_line);
                        current_new_line += 1;
                    }
                    '-' => {
                        // Deleted line - doesn't affect new-side line numbers
                    }
                    ' ' => {
                        // Context line
                        current_new_line += 1;
                    }
                    '\\' => {
                        // "\ No newline at end of file" - ignore
                    }
                    _ => {
                        // Some diffs may have other content, treat as context
                        current_new_line += 1;
                    }
                }
            } else {
                // Empty line in the hunk, could be context
                current_new_line += 1;
            }
        }
    }

    // Convert line lists to merged ranges
    let mut ranges: ChangedRanges = BTreeMap::new();
    for (file, lines) in result {
        let line_ranges: Vec<RangeInclusive<u32>> = lines.into_iter().map(|l| l..=l).collect();
        ranges.insert(file, merge_ranges(line_ranges));
    }
    // Remove any binary files from the ranges
    for binary in &binary_files {
        ranges.remove(binary);
    }

    Ok(DiffParseResult {
        changed_ranges: ranges,
        binary_files: binary_files.into_iter().collect(),
    })
}

/// Parse a hunk header and return the new-side starting line number.
///
/// Hunk headers have the format: `@@ -old_start,old_count +new_start,new_count @@ optional context`
/// or: `@@ -old_start +new_start @@ optional context` (count defaults to 1)
fn parse_hunk_header(line: &str) -> Option<u32> {
    // Find the +new_start part
    let parts: Vec<&str> = line.split_whitespace().collect();

    for part in parts {
        if let Some(new_part) = part.strip_prefix('+') {
            // new_part is either "start,count" or just "start"
            let start_str = new_part.split(',').next()?;
            return start_str.parse().ok();
        }
    }

    None
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use covguard_ports::DiffProvider;
    use std::fs;

    #[test]
    fn test_normalize_path_b_prefix() {
        assert_eq!(normalize_path("b/src/lib.rs"), "src/lib.rs");
    }

    #[test]
    fn test_normalize_path_a_prefix() {
        assert_eq!(normalize_path("a/src/lib.rs"), "src/lib.rs");
    }

    #[test]
    fn test_normalize_path_dot_slash() {
        assert_eq!(normalize_path("./src/lib.rs"), "src/lib.rs");
    }

    #[test]
    fn test_normalize_path_backslash() {
        assert_eq!(normalize_path("src\\lib.rs"), "src/lib.rs");
        // After converting backslashes to forward slashes, b/ prefix is stripped
        assert_eq!(normalize_path("b\\src\\lib.rs"), "src/lib.rs");
    }

    #[test]
    fn test_normalize_path_combined() {
        // b/ is stripped first, then ./ is stripped
        assert_eq!(normalize_path("b/./src/lib.rs"), "src/lib.rs");
        // ./ is stripped, leaving b/src/lib.rs, then b/ is not at start so stays
        assert_eq!(normalize_path("./b/src/lib.rs"), "b/src/lib.rs");
    }

    #[test]
    fn test_normalize_path_no_change() {
        assert_eq!(normalize_path("src/lib.rs"), "src/lib.rs");
    }

    #[test]
    fn test_parse_patch_simple_added() {
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..1111111
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,3 @@
+pub fn add(a: i32, b: i32) -> i32 {
+    a + b
+}
"#;

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges.get("src/lib.rs"), Some(&vec![1..=3]));
    }

    #[test]
    fn test_parse_patch_modified_file_multiple_hunks() {
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
index 1111111..2222222 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,3 +1,5 @@
 pub fn add(a: i32, b: i32) -> i32 {
+    // Adding numbers
     a + b
 }
+
@@ -10,2 +12,4 @@
 fn other() {
+    // New comment
+    println!("hello");
 }
"#;

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.len(), 1);
        let file_ranges = ranges.get("src/lib.rs").unwrap();
        // Line 2 from first hunk, line 5 (empty line), lines 13-14 from second hunk
        assert_eq!(file_ranges, &vec![2..=2, 5..=5, 13..=14]);
    }

    #[test]
    fn test_parse_patch_deletion_only_hunk() {
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
index 1111111..2222222 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,5 +1,3 @@
 pub fn add(a: i32, b: i32) -> i32 {
-    // Old comment
-    // Another old comment
     a + b
 }
"#;

        let ranges = parse_patch(diff).unwrap();
        // No added lines, so file should not be in the map (or have empty ranges)
        assert!(!ranges.contains_key("src/lib.rs"));
    }

    #[test]
    fn test_parse_patch_rename() {
        let diff = r#"diff --git a/old_name.rs b/new_name.rs
similarity index 95%
rename from old_name.rs
rename to new_name.rs
index 1111111..2222222 100644
--- a/old_name.rs
+++ b/new_name.rs
@@ -1,3 +1,4 @@
 fn main() {
+    println!("added line");
     println!("Hello");
 }
"#;

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.len(), 1);
        // Should use the new name
        assert!(ranges.contains_key("new_name.rs"));
        assert_eq!(ranges.get("new_name.rs"), Some(&vec![2..=2]));
    }

    #[test]
    fn test_parse_patch_deleted_file() {
        let diff = r#"diff --git a/deleted.rs b/deleted.rs
deleted file mode 100644
index 1111111..0000000
--- a/deleted.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-fn main() {
-    println!("goodbye");
-}
"#;

        let ranges = parse_patch(diff).unwrap();
        // Deleted file should not contribute any ranges
        assert!(ranges.is_empty());
    }

    #[test]
    fn test_parse_patch_crlf() {
        let diff = "diff --git a/src/lib.rs b/src/lib.rs\r\n\
            new file mode 100644\r\n\
            index 0000000..1111111\r\n\
            --- /dev/null\r\n\
            +++ b/src/lib.rs\r\n\
            @@ -0,0 +1,2 @@\r\n\
            +line one\r\n\
            +line two\r\n";

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges.get("src/lib.rs"), Some(&vec![1..=2]));
    }

    #[test]
    fn test_parse_patch_multiple_files() {
        let diff = r#"diff --git a/src/a.rs b/src/a.rs
new file mode 100644
index 0000000..1111111
--- /dev/null
+++ b/src/a.rs
@@ -0,0 +1,2 @@
+fn a() {}
+fn b() {}
diff --git a/src/c.rs b/src/c.rs
new file mode 100644
index 0000000..2222222
--- /dev/null
+++ b/src/c.rs
@@ -0,0 +1,1 @@
+fn c() {}
"#;

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.len(), 2);
        assert_eq!(ranges.get("src/a.rs"), Some(&vec![1..=2]));
        assert_eq!(ranges.get("src/c.rs"), Some(&vec![1..=1]));
    }

    #[test]
    fn test_parse_patch_no_newline_marker() {
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..1111111
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,2 @@
+fn main() {}
+fn other() {}
\ No newline at end of file
"#;

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges.get("src/lib.rs"), Some(&vec![1..=2]));
    }

    #[test]
    fn test_parse_patch_empty() {
        let ranges = parse_patch("").unwrap();
        assert!(ranges.is_empty());
    }

    #[test]
    fn test_parse_patch_binary_files_marker() {
        let diff = r#"diff --git a/assets/logo.png b/assets/logo.png
index 1111111..2222222
Binary files a/assets/logo.png and b/assets/logo.png differ
"#;

        let result = parse_patch_with_meta(diff).unwrap();
        assert!(result.changed_ranges.is_empty());
        assert_eq!(result.binary_files, vec!["assets/logo.png".to_string()]);
    }

    #[test]
    fn test_parse_patch_binary_files_marker_dev_null() {
        let diff = r#"diff --git a/assets/logo.png b/assets/logo.png
index 1111111..2222222
Binary files a/assets/logo.png and /dev/null differ
"#;

        let result = parse_patch_with_meta(diff).unwrap();
        assert!(result.changed_ranges.is_empty());
        assert!(result.binary_files.is_empty());
    }

    #[test]
    fn test_parse_patch_binary_files_marker_without_and() {
        let diff = r#"diff --git a/assets/logo.png b/assets/logo.png
index 1111111..2222222
Binary files a/assets/logo.png differ
"#;

        let result = parse_patch_with_meta(diff).unwrap();
        assert!(result.changed_ranges.is_empty());
        assert!(result.binary_files.is_empty());
    }

    #[test]
    fn test_parse_patch_git_binary_patch_marker() {
        let diff = r#"diff --git a/assets/data.bin b/assets/data.bin
index 1111111..2222222
GIT binary patch
literal 0
HcmV?d00001
"#;

        let result = parse_patch_with_meta(diff).unwrap();
        assert!(result.changed_ranges.is_empty());
        assert_eq!(result.binary_files, vec!["assets/data.bin".to_string()]);
    }

    #[test]
    fn test_parse_patch_malformed_hunk_header_returns_error() {
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
index 1111111..2222222 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,1 @@
+line
"#;

        let result = parse_patch(diff);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_patch_empty_line_in_hunk() {
        let diff = "diff --git a/src/lib.rs b/src/lib.rs\n\
index 1111111..2222222 100644\n\
--- a/src/lib.rs\n\
+++ b/src/lib.rs\n\
@@ -1,1 +1,3 @@\n\
+line1\n\
\n\
+line2\n";

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.get("src/lib.rs"), Some(&vec![1..=1, 3..=3]));
    }

    #[test]
    fn test_parse_hunk_header_with_counts() {
        let line = "@@ -10,5 +20,8 @@ fn context()";
        assert_eq!(parse_hunk_header(line), Some(20));
    }

    #[test]
    fn test_parse_hunk_header_without_counts() {
        let line = "@@ -1 +1 @@";
        assert_eq!(parse_hunk_header(line), Some(1));
    }

    #[test]
    fn test_parse_hunk_header_missing_plus_returns_none() {
        let line = "@@ -10,5 @@ fn context()";
        assert_eq!(parse_hunk_header(line), None);
    }

    #[test]
    fn test_parse_hunk_header_new_file() {
        let line = "@@ -0,0 +1,3 @@";
        assert_eq!(parse_hunk_header(line), Some(1));
    }

    #[test]
    fn test_parse_patch_mixed_additions_deletions() {
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
index 1111111..2222222 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,5 +1,6 @@
 fn main() {
-    old_code();
+    new_code();
+    extra_code();
     common();
 }
"#;

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.len(), 1);
        // Lines 2 and 3 are the added lines (new_code and extra_code)
        assert_eq!(ranges.get("src/lib.rs"), Some(&vec![2..=3]));
    }

    #[test]
    fn test_parse_fixture_simple_added_patch() {
        // This matches the content of fixtures/diff/simple_added.patch
        let fixture_content = r#"diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..1111111
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,3 @@
+pub fn add(a: i32, b: i32) -> i32 {
+    a + b
+}
"#;

        let ranges = parse_patch(fixture_content).unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges.get("src/lib.rs"), Some(&vec![1..=3]));
    }

    #[test]
    fn test_parse_patch_context_without_leading_space() {
        // Some tools may generate diffs where context lines don't have a leading space
        // This tests that we handle that gracefully
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
index 1111111..2222222 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,3 +1,4 @@
fn main() {
+    println!("added");
}
"#;

        let ranges = parse_patch(diff).unwrap();
        assert_eq!(ranges.len(), 1);
        // Line 2 is the added line
        assert_eq!(ranges.get("src/lib.rs"), Some(&vec![2..=2]));
    }

    #[test]
    fn test_load_diff_from_git_bad_repo_path_returns_io_error() {
        let temp = std::env::temp_dir().join(format!(
            "covguard-diff-adapter-missing-{}",
            std::process::id()
        ));
        let err = load_diff_from_git("HEAD~1", "HEAD", &temp).expect_err("expected error");
        assert!(matches!(err, DiffError::IoError(_)));
    }

    #[test]
    fn test_load_diff_from_git_success_in_temp_repo() {
        let unique = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("time")
            .as_nanos();
        let root = std::env::temp_dir().join(format!("covguard-diff-adapter-{unique}"));
        fs::create_dir_all(&root).expect("create temp dir");

        let init = std::process::Command::new("git")
            .current_dir(&root)
            .args(["init"])
            .output()
            .expect("git init");
        assert!(init.status.success());

        let user_name = std::process::Command::new("git")
            .current_dir(&root)
            .args(["config", "user.name", "covguard-test"])
            .output()
            .expect("git config user.name");
        assert!(user_name.status.success());

        let user_email = std::process::Command::new("git")
            .current_dir(&root)
            .args(["config", "user.email", "covguard-test@example.com"])
            .output()
            .expect("git config user.email");
        assert!(user_email.status.success());

        fs::write(root.join("a.txt"), "line1\n").expect("write initial file");
        let add_first = std::process::Command::new("git")
            .current_dir(&root)
            .args(["add", "a.txt"])
            .output()
            .expect("git add first");
        assert!(add_first.status.success());

        let commit_first = std::process::Command::new("git")
            .current_dir(&root)
            .args(["commit", "-m", "first"])
            .output()
            .expect("git commit first");
        assert!(commit_first.status.success());

        fs::write(root.join("a.txt"), "line1\nline2\n").expect("write changed file");
        let add_second = std::process::Command::new("git")
            .current_dir(&root)
            .args(["add", "a.txt"])
            .output()
            .expect("git add second");
        assert!(add_second.status.success());

        let commit_second = std::process::Command::new("git")
            .current_dir(&root)
            .args(["commit", "-m", "second"])
            .output()
            .expect("git commit second");
        assert!(commit_second.status.success());

        let diff = load_diff_from_git("HEAD~1", "HEAD", &root).expect("load diff");
        assert!(diff.contains("diff --git"));
        assert!(diff.contains("+++ b/a.txt"));

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn test_git_diff_provider_parse_patch() {
        let provider = GitDiffProvider;
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,1 @@
+fn main() {}
"#;

        let parsed = provider.parse_patch(diff).expect("parse via provider");
        assert_eq!(parsed.changed_ranges.get("src/lib.rs"), Some(&vec![1..=1]));
        assert!(parsed.binary_files.is_empty());
    }
}

// ============================================================================
// Property Tests
// ============================================================================

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn normalize_path_never_panics(path in ".*") {
            let _ = normalize_path(&path);
        }

        #[test]
        fn normalize_path_removes_leading_b_prefix(suffix in "[a-z]+") {
            // Only test with suffixes that don't start with b/ to avoid "b/b/..." edge case
            prop_assume!(!suffix.starts_with("b"));
            let path = format!("b/{}", suffix);
            let normalized = normalize_path(&path);
            prop_assert!(!normalized.starts_with("b/"), "Should remove b/ prefix from {}", path);
        }
    }
}