repotoire 0.8.2

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Parse git diff -U0 output to extract changed line ranges per file.
//!
//! Used by the diff command to attribute findings to changed hunks.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// How a finding relates to the code changes in a diff.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Attribution {
    /// Finding's line falls within a changed hunk (±3 lines margin).
    /// This is the PR author's responsibility.
    InChangedHunk,
    /// Finding is in a changed file but NOT in a changed hunk.
    /// Pre-existing issue.
    InChangedFile,
    /// Finding is in a file not touched by the diff.
    InUnchangedFile,
}

/// Changed line ranges extracted from a git diff.
pub struct DiffHunks {
    /// file_path → Vec of (start_line, end_line) ranges (1-based, inclusive).
    hunks: HashMap<PathBuf, Vec<(u32, u32)>>,
    /// All files that appear in the diff.
    changed_files: HashSet<PathBuf>,
    /// Renamed files: old_path → new_path.
    renames: HashMap<PathBuf, PathBuf>,
}

/// Line tolerance for hunk attribution (matches fuzzy matching in findings_match).
const HUNK_MARGIN: u32 = 3;

impl DiffHunks {
    /// An empty diff (nothing changed): every finding attributes as `InUnchangedFile`.
    fn empty() -> Self {
        Self {
            hunks: HashMap::new(),
            changed_files: HashSet::new(),
            renames: HashMap::new(),
        }
    }

    /// Run `git <args>` in `repo_path`; on failure (e.g. invalid ref) return an empty
    /// `DiffHunks`, otherwise parse the `-U0` diff on stdout.
    fn from_git_args(repo_path: &Path, args: &[&str]) -> anyhow::Result<Self> {
        let output = std::process::Command::new("git")
            .args(args)
            .current_dir(repo_path)
            .output()
            .map_err(|e| anyhow::anyhow!("Failed to run git {}: {e}", args.join(" ")))?;

        if !output.status.success() {
            return Ok(Self::empty());
        }

        Ok(Self::parse_diff(&String::from_utf8_lossy(&output.stdout)))
    }

    /// Parse `git diff -U0 <base_ref>..HEAD` output (committed changes only).
    pub fn from_git_diff(repo_path: &Path, base_ref: &str) -> anyhow::Result<Self> {
        Self::from_git_args(repo_path, &["diff", "-U0", &format!("{base_ref}..HEAD")])
    }

    /// Like [`from_git_diff`] but against the *working tree*: `git diff -U0 <base_ref>` (ref →
    /// on-disk files, including staged + unstaged tracked edits) plus untracked files (each marked
    /// entirely changed). Lets `repotoire diff --working-tree` attribute findings in uncommitted code.
    pub fn from_git_diff_worktree(repo_path: &Path, base_ref: &str) -> anyhow::Result<Self> {
        let mut hunks = Self::from_git_args(repo_path, &["diff", "-U0", base_ref])?;

        // Untracked, non-ignored files don't appear in `git diff <ref>` — pull them in directly.
        if let Ok(out) = std::process::Command::new("git")
            .args(["ls-files", "--others", "--exclude-standard", "-z"])
            .current_dir(repo_path)
            .output()
        {
            if out.status.success() {
                for rel in String::from_utf8_lossy(&out.stdout)
                    .split('\0')
                    .filter(|s| !s.is_empty())
                {
                    let line_count = std::fs::read_to_string(repo_path.join(rel))
                        .map(|c| c.lines().count() as u32)
                        .unwrap_or(1);
                    hunks.merge_untracked(PathBuf::from(rel), line_count);
                }
            }
        }

        Ok(hunks)
    }

    /// Parse raw git diff -U0 text into DiffHunks.
    pub fn parse_diff(diff_text: &str) -> Self {
        let mut hunks: HashMap<PathBuf, Vec<(u32, u32)>> = HashMap::new();
        let mut changed_files: HashSet<PathBuf> = HashSet::new();
        let mut renames: HashMap<PathBuf, PathBuf> = HashMap::new();
        let mut current_file: Option<PathBuf> = None;
        let mut pending_rename_from: Option<PathBuf> = None;

        for line in diff_text.lines() {
            // Reset pending rename on new diff block
            if line.starts_with("diff --git ") {
                pending_rename_from = None;
            }

            // Track renames and copies (git diff -M / -C)
            if let Some(old) = line
                .strip_prefix("rename from ")
                .or_else(|| line.strip_prefix("copy from "))
            {
                pending_rename_from = Some(PathBuf::from(old));
            } else if let Some(new) = line
                .strip_prefix("rename to ")
                .or_else(|| line.strip_prefix("copy to "))
            {
                if let Some(old) = pending_rename_from.take() {
                    let new_path = PathBuf::from(new);
                    changed_files.insert(new_path.clone());
                    renames.insert(old, new_path);
                }
            } else if let Some(path) = line.strip_prefix("+++ b/") {
                let p = PathBuf::from(path);
                changed_files.insert(p.clone());
                current_file = Some(p);
            } else if line.starts_with("--- ") {
                // Also track files from --- header (for deleted files)
                if let Some(path) = line.strip_prefix("--- a/") {
                    changed_files.insert(PathBuf::from(path));
                }
            } else if line.starts_with("@@ ") {
                // Parse hunk header: @@ -old_start,old_count +new_start,new_count @@
                if let Some(ref file) = current_file {
                    if let Some((start, count)) = parse_hunk_header(line) {
                        let end = if count == 0 {
                            start // deletion at this line, no new lines
                        } else {
                            start + count - 1
                        };
                        if count > 0 {
                            hunks.entry(file.clone()).or_default().push((start, end));
                        }
                    }
                }
            }
        }

        Self {
            hunks,
            changed_files,
            renames,
        }
    }

    /// Attribute a finding based on its file and line.
    pub fn attribute(&self, file: &Path, line: Option<u32>) -> Attribution {
        // Resolve old->new rename if this finding uses the pre-rename path
        let effective = self.renames.get(file).map(|p| p.as_path()).unwrap_or(file);

        if !self.changed_files.contains(effective) {
            return Attribution::InUnchangedFile;
        }

        // File-level findings (no line number) → InChangedFile
        let line = match line {
            Some(l) => l,
            None => return Attribution::InChangedFile,
        };

        // Check if line falls within any hunk (±HUNK_MARGIN)
        if let Some(file_hunks) = self.hunks.get(effective) {
            for &(start, end) in file_hunks {
                let expanded_start = start.saturating_sub(HUNK_MARGIN);
                let expanded_end = end.saturating_add(HUNK_MARGIN);
                if line >= expanded_start && line <= expanded_end {
                    return Attribution::InChangedHunk;
                }
            }
        }

        Attribution::InChangedFile
    }

    /// Number of changed files.
    pub fn changed_file_count(&self) -> usize {
        self.changed_files.len()
    }

    /// Mark an untracked file as entirely changed: every line attributes as `InChangedHunk`.
    /// `line_count` is the file's line count; 0 (empty file) is treated as 1.
    pub(crate) fn merge_untracked(&mut self, path: PathBuf, line_count: u32) {
        let end = line_count.max(1);
        self.hunks.entry(path.clone()).or_default().push((1, end));
        self.changed_files.insert(path);
    }
}

/// Parse a hunk header line and extract (new_start, new_count).
/// Format: @@ -old_start,old_count +new_start,new_count @@
/// Count defaults to 1 if omitted (e.g., @@ -1 +1 @@).
fn parse_hunk_header(line: &str) -> Option<(u32, u32)> {
    // Find the + section
    let plus_idx = line.find('+')?;
    let after_plus = &line[plus_idx + 1..];

    // Find the end (space before @@)
    let end_idx = after_plus.find(" @@").unwrap_or(after_plus.len());
    let range_str = &after_plus[..end_idx];

    if let Some((start_str, count_str)) = range_str.split_once(',') {
        let start = start_str.parse::<u32>().ok()?;
        let count = count_str.parse::<u32>().ok()?;
        Some((start, count))
    } else {
        let start = range_str.parse::<u32>().ok()?;
        Some((start, 1)) // count defaults to 1
    }
}

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

    #[test]
    fn test_parse_hunk_header_with_count() {
        assert_eq!(
            parse_hunk_header("@@ -10,5 +20,3 @@ fn foo()"),
            Some((20, 3))
        );
    }

    #[test]
    fn test_parse_hunk_header_without_count() {
        assert_eq!(parse_hunk_header("@@ -10 +20 @@"), Some((20, 1)));
    }

    #[test]
    fn test_parse_hunk_header_zero_count() {
        // Deletion: no new lines added
        assert_eq!(parse_hunk_header("@@ -10,3 +20,0 @@"), Some((20, 0)));
    }

    #[test]
    fn test_parse_diff_single_file() {
        let diff = "\
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -10,3 +10,5 @@ fn main() {
+    let x = 1;
+    let y = 2;
";
        let hunks = DiffHunks::parse_diff(diff);
        assert!(hunks.changed_files.contains(&PathBuf::from("src/main.rs")));
        let file_hunks = hunks.hunks.get(&PathBuf::from("src/main.rs")).unwrap();
        assert_eq!(file_hunks, &[(10, 14)]); // start=10, count=5, end=14
    }

    #[test]
    fn test_parse_diff_multiple_hunks() {
        let diff = "\
diff --git a/src/api.rs b/src/api.rs
--- a/src/api.rs
+++ b/src/api.rs
@@ -5,2 +5,3 @@ fn handler() {
+    new_line();
@@ -50,1 +51,4 @@ fn query() {
+    more();
+    code();
+    here();
";
        let hunks = DiffHunks::parse_diff(diff);
        let file_hunks = hunks.hunks.get(&PathBuf::from("src/api.rs")).unwrap();
        assert_eq!(file_hunks.len(), 2);
        assert_eq!(file_hunks[0], (5, 7)); // start=5, count=3
        assert_eq!(file_hunks[1], (51, 54)); // start=51, count=4
    }

    #[test]
    fn test_attribute_in_changed_hunk() {
        let diff = "\
diff --git a/src/api.rs b/src/api.rs
--- a/src/api.rs
+++ b/src/api.rs
@@ -10,2 +10,5 @@ fn handler() {
";
        let hunks = DiffHunks::parse_diff(diff);
        // Line 12 is within hunk (10-14)
        assert_eq!(
            hunks.attribute(Path::new("src/api.rs"), Some(12)),
            Attribution::InChangedHunk
        );
    }

    #[test]
    fn test_attribute_in_changed_hunk_with_margin() {
        let diff = "\
diff --git a/src/api.rs b/src/api.rs
--- a/src/api.rs
+++ b/src/api.rs
@@ -10,2 +10,5 @@ fn handler() {
";
        let hunks = DiffHunks::parse_diff(diff);
        // Line 17 is hunk_end(14) + 3 margin = within margin
        assert_eq!(
            hunks.attribute(Path::new("src/api.rs"), Some(17)),
            Attribution::InChangedHunk
        );
        // Line 18 is hunk_end(14) + 4 = outside margin
        assert_eq!(
            hunks.attribute(Path::new("src/api.rs"), Some(18)),
            Attribution::InChangedFile
        );
    }

    #[test]
    fn test_attribute_in_changed_file() {
        let diff = "\
diff --git a/src/api.rs b/src/api.rs
--- a/src/api.rs
+++ b/src/api.rs
@@ -10,2 +10,5 @@ fn handler() {
";
        let hunks = DiffHunks::parse_diff(diff);
        // Line 100 is in the file but far from the hunk
        assert_eq!(
            hunks.attribute(Path::new("src/api.rs"), Some(100)),
            Attribution::InChangedFile
        );
    }

    #[test]
    fn test_attribute_in_unchanged_file() {
        let diff = "\
diff --git a/src/api.rs b/src/api.rs
--- a/src/api.rs
+++ b/src/api.rs
@@ -10,2 +10,5 @@ fn handler() {
";
        let hunks = DiffHunks::parse_diff(diff);
        assert_eq!(
            hunks.attribute(Path::new("src/other.rs"), Some(10)),
            Attribution::InUnchangedFile
        );
    }

    #[test]
    fn test_attribute_no_line_number() {
        let diff = "\
diff --git a/src/api.rs b/src/api.rs
--- a/src/api.rs
+++ b/src/api.rs
@@ -10,2 +10,5 @@ fn handler() {
";
        let hunks = DiffHunks::parse_diff(diff);
        // File-level finding (no line) → InChangedFile
        assert_eq!(
            hunks.attribute(Path::new("src/api.rs"), None),
            Attribution::InChangedFile
        );
    }

    #[test]
    fn test_empty_diff() {
        let hunks = DiffHunks::parse_diff("");
        assert_eq!(hunks.changed_file_count(), 0);
        assert_eq!(
            hunks.attribute(Path::new("any.rs"), Some(1)),
            Attribution::InUnchangedFile
        );
    }

    #[test]
    fn test_parse_diff_rename_without_content_change() {
        let diff = "\
diff --git a/src/old.rs b/src/new.rs
similarity index 100%
rename from src/old.rs
rename to src/new.rs
";
        let hunks = DiffHunks::parse_diff(diff);
        // Old path resolves to new path via rename
        assert_eq!(
            hunks.attribute(Path::new("src/old.rs"), Some(10)),
            Attribution::InChangedFile
        );
    }

    #[test]
    fn test_parse_diff_rename_with_content_change() {
        let diff = "\
diff --git a/src/old.rs b/src/new.rs
similarity index 80%
rename from src/old.rs
rename to src/new.rs
--- a/src/old.rs
+++ b/src/new.rs
@@ -5,0 +5,3 @@ fn foo() {
+    added();
+    lines();
+    here();
";
        let hunks = DiffHunks::parse_diff(diff);
        // Finding at line 6 in old path -> resolves via rename -> in hunk
        assert_eq!(
            hunks.attribute(Path::new("src/old.rs"), Some(6)),
            Attribution::InChangedHunk
        );
        // Finding at line 100 in old path -> resolves via rename -> in file but not hunk
        assert_eq!(
            hunks.attribute(Path::new("src/old.rs"), Some(100)),
            Attribution::InChangedFile
        );
    }

    #[test]
    fn merge_untracked_marks_whole_file_as_changed_hunk() {
        let mut hunks = DiffHunks::parse_diff(""); // empty
        assert_eq!(hunks.changed_file_count(), 0);
        hunks.merge_untracked(PathBuf::from("src/new.js"), 5);
        assert_eq!(hunks.changed_file_count(), 1);
        for line in 1..=5u32 {
            assert_eq!(
                hunks.attribute(Path::new("src/new.js"), Some(line)),
                Attribution::InChangedHunk,
                "line {line} of an untracked file should be InChangedHunk"
            );
        }
        // a file-level finding (no line) in an untracked file → at least InChangedFile
        assert_ne!(
            hunks.attribute(Path::new("src/new.js"), None),
            Attribution::InUnchangedFile
        );
        // zero-line file still counts as changed
        hunks.merge_untracked(PathBuf::from("src/empty.js"), 0);
        assert_eq!(hunks.changed_file_count(), 2);
        assert_ne!(
            hunks.attribute(Path::new("src/empty.js"), Some(1)),
            Attribution::InUnchangedFile
        );
    }

    #[test]
    fn parse_diff_is_indifferent_to_ref_form() {
        // `git diff -U0` emits the same text whether the second side is a commit or the
        // working tree, so the worktree variant reuses parse_diff unchanged. Regression guard.
        let payload = "\
diff --git a/src/api.rs b/src/api.rs
--- a/src/api.rs
+++ b/src/api.rs
@@ -10,0 +11,2 @@
+let x = 1;
+let y = 2;
";
        let h = DiffHunks::parse_diff(payload);
        assert_eq!(
            h.attribute(Path::new("src/api.rs"), Some(11)),
            Attribution::InChangedHunk
        );
        assert_eq!(
            h.attribute(Path::new("src/api.rs"), Some(12)),
            Attribution::InChangedHunk
        );
        assert_eq!(
            h.attribute(Path::new("src/other.rs"), Some(1)),
            Attribution::InUnchangedFile
        );
    }
}