diffctx 1.12.0

Selects the minimum code an LLM needs to review a git diff: walks the dependency graph outward from changed lines and stops when extra context stops paying for itself
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
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdout, Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use once_cell::sync::Lazy;
use regex::Regex;
use rustc_hash::FxHashSet;
use wait_timeout::ChildExt;

use crate::config::git::{self, GIT};
use crate::types::DiffHunk;

static GIT_TIMEOUT_SECS: AtomicU64 = AtomicU64::new(git::DEFAULT_TIMEOUT_SECONDS);

pub fn set_git_timeout(secs: u64) {
    GIT_TIMEOUT_SECS.store(secs, Ordering::Relaxed);
}

fn git_timeout() -> u64 {
    GIT_TIMEOUT_SECS.load(Ordering::Relaxed)
}
const SAFE_DIFF_FLAGS: &[&str] = &["--no-textconv", "--no-ext-diff"];

static HUNK_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@").unwrap());

static RANGE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^\s*(\S+?)(\.\.\.?)(\S*?)\s*$").unwrap());

static SAFE_RANGE_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"^[a-zA-Z0-9_.^~/@{}\-]+(\.\.\.?[a-zA-Z0-9_.^~/@{}\-]*)?$").unwrap());

#[derive(Debug, thiserror::Error)]
pub enum GitError {
    #[error("{0}")]
    CommandFailed(String),
    #[error("not a git repository: {0}")]
    NotARepo(PathBuf),
    #[error("invalid diff range: {0}")]
    InvalidRange(String),
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("timeout after {0}s")]
    Timeout(u64),
}

pub type Result<T> = std::result::Result<T, GitError>;

fn validate_diff_range(diff_range: &str) -> Result<()> {
    let trimmed = diff_range.trim();
    // Reject leading-dot ranges like `..origin/main` (audit X16): the regex
    // character class allows `.`, so a string of only dots/identifier-chars
    // passes as a "ref" before being rejected by git itself with a less
    // informative `fatal: ambiguous argument`. Surface the dedicated error.
    if trimmed.starts_with('.') || trimmed.starts_with('/') {
        return Err(GitError::InvalidRange(diff_range.to_string()));
    }
    if !SAFE_RANGE_RE.is_match(trimmed) {
        return Err(GitError::InvalidRange(diff_range.to_string()));
    }
    Ok(())
}

/// Always targets the repo via `-C`.
///
/// Repo-locating variables inherited from a parent process (e.g. a git
/// hook exporting `GIT_DIR` / `GIT_INDEX_FILE`) must be scrubbed or they
/// silently redirect every command to the wrong repository.
pub fn git_command(repo_root: &Path) -> Command {
    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(repo_root)
        .env_remove("GIT_DIR")
        .env_remove("GIT_WORK_TREE")
        .env_remove("GIT_INDEX_FILE");
    cmd
}

pub fn run_git(repo_root: &Path, args: &[&str]) -> Result<String> {
    let mut cmd = git_command(repo_root);
    cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());

    let child = cmd.spawn().map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            GitError::CommandFailed("git is not installed or not in PATH".into())
        } else {
            GitError::Io(e)
        }
    })?;

    let output = wait_with_timeout(child, Duration::from_secs(git_timeout()), args)?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let subcommand = args
            .iter()
            .find(|a| !a.starts_with('-'))
            .copied()
            .unwrap_or("command");
        let reason = stderr
            .lines()
            .map(str::trim)
            .find(|l| l.starts_with("fatal:") || l.starts_with("error:"))
            .or_else(|| stderr.lines().map(str::trim).find(|l| !l.is_empty()))
            .unwrap_or("unknown error");
        return Err(GitError::CommandFailed(format!(
            "git {subcommand} failed: {reason}"
        )));
    }

    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

fn wait_with_timeout(
    child: Child,
    timeout: Duration,
    _args: &[&str],
) -> Result<std::process::Output> {
    let mut child = child;
    let stdout_handle = child.stdout.take().map(|mut s| {
        std::thread::spawn(move || -> std::io::Result<Vec<u8>> {
            let mut buf = Vec::new();
            s.read_to_end(&mut buf)?;
            Ok(buf)
        })
    });
    let stderr_handle = child.stderr.take().map(|mut s| {
        std::thread::spawn(move || -> std::io::Result<Vec<u8>> {
            let mut buf = Vec::new();
            s.read_to_end(&mut buf)?;
            Ok(buf)
        })
    });

    let status = match child.wait_timeout(timeout)? {
        Some(status) => status,
        None => {
            let _ = child.kill();
            let _ = child.wait();
            return Err(GitError::Timeout(timeout.as_secs()));
        }
    };

    let stdout = stdout_handle
        .and_then(|h| h.join().ok())
        .and_then(|r| r.ok())
        .unwrap_or_default();
    let stderr = stderr_handle
        .and_then(|h| h.join().ok())
        .and_then(|r| r.ok())
        .unwrap_or_default();

    Ok(std::process::Output {
        status,
        stdout,
        stderr,
    })
}

pub fn is_git_repo(path: &Path) -> bool {
    run_git(path, &["rev-parse", "--git-dir"]).is_ok()
}

/// Resolves the actual working-tree root for `path`, which may be a
/// subdirectory of the repository. `git diff`/`git cat-file` paths are
/// always reported relative to this root, not to an arbitrary `-C` cwd -
/// running the pipeline with `path` still set to a subdirectory silently
/// produces zero fragments because file lookups get double-prefixed
/// (e.g. `src/src/app.py`).
pub fn find_toplevel(path: &Path) -> Option<PathBuf> {
    let out = run_git(path, &["rev-parse", "--show-toplevel"]).ok()?;
    let trimmed = out.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(PathBuf::from(trimmed))
}

pub fn get_diff_text(repo_root: &Path, diff_range: Option<&str>) -> Result<String> {
    let mut args: Vec<&str> = vec!["diff"];
    args.extend_from_slice(SAFE_DIFF_FLAGS);
    if let Some(range) = diff_range {
        validate_diff_range(range)?;
        args.push(range);
    }
    run_git(repo_root, &args)
}

fn unquote_c_style(quoted: &str) -> String {
    if !(quoted.starts_with('"') && quoted.ends_with('"')) {
        return quoted.to_string();
    }

    let raw = &quoted[1..quoted.len() - 1];
    let bytes = raw.as_bytes();
    let mut result: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'\\' && i + 1 < bytes.len() {
            let nxt = bytes[i + 1];
            match nxt {
                b't' => {
                    result.push(b'\t');
                    i += 2;
                }
                b'n' => {
                    result.push(b'\n');
                    i += 2;
                }
                b'r' => {
                    result.push(b'\r');
                    i += 2;
                }
                b'b' => {
                    result.push(0x08);
                    i += 2;
                }
                b'f' => {
                    result.push(0x0C);
                    i += 2;
                }
                b'v' => {
                    result.push(0x0B);
                    i += 2;
                }
                b'a' => {
                    result.push(0x07);
                    i += 2;
                }
                b'\\' => {
                    result.push(b'\\');
                    i += 2;
                }
                b'"' => {
                    result.push(b'"');
                    i += 2;
                }
                b'0'..=b'7'
                    if i + 3 < bytes.len()
                        && bytes[i + 2].is_ascii_digit()
                        && bytes[i + 2] <= b'7'
                        && bytes[i + 3].is_ascii_digit()
                        && bytes[i + 3] <= b'7' =>
                {
                    let val = (nxt - b'0') * 64 + (bytes[i + 2] - b'0') * 8 + (bytes[i + 3] - b'0');
                    result.push(val);
                    i += 4;
                }
                _ => {
                    result.push(b'\\');
                    i += 1;
                }
            }
        } else {
            result.push(bytes[i]);
            i += 1;
        }
    }

    String::from_utf8(result).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
}

fn parse_path_line(line: &str, repo_root: &Path) -> (&'static str, Option<PathBuf>) {
    let resolved_root = repo_root
        .canonicalize()
        .unwrap_or_else(|_| repo_root.to_path_buf());

    if line.starts_with("--- /dev/null") {
        return ("old", None);
    }
    if line.starts_with("+++ /dev/null") {
        return ("new", None);
    }

    if let Some(rest) = line.strip_prefix("--- a/") {
        let rel_path = rest.trim();
        let resolved = (repo_root.join(rel_path))
            .canonicalize()
            .unwrap_or_else(|_| repo_root.join(rel_path));
        if !resolved.starts_with(&resolved_root) {
            return ("", None);
        }
        return ("old", Some(repo_root.join(rel_path)));
    }

    if let Some(rest) = line.strip_prefix("+++ b/") {
        let rel_path = rest.trim();
        let resolved = (repo_root.join(rel_path))
            .canonicalize()
            .unwrap_or_else(|_| repo_root.join(rel_path));
        if !resolved.starts_with(&resolved_root) {
            return ("", None);
        }
        return ("new", Some(repo_root.join(rel_path)));
    }

    if let Some(rest) = line.strip_prefix("--- ").filter(|r| r.starts_with("\"a/")) {
        let quoted = rest.trim();
        let unquoted = unquote_c_style(quoted);
        let rel_path = unquoted.strip_prefix("a/").unwrap_or(&unquoted);
        let resolved = (repo_root.join(rel_path))
            .canonicalize()
            .unwrap_or_else(|_| repo_root.join(rel_path));
        if !resolved.starts_with(&resolved_root) {
            return ("", None);
        }
        return ("old", Some(repo_root.join(rel_path)));
    }

    if let Some(rest) = line.strip_prefix("+++ ").filter(|r| r.starts_with("\"b/")) {
        let quoted = rest.trim();
        let unquoted = unquote_c_style(quoted);
        let rel_path = unquoted.strip_prefix("b/").unwrap_or(&unquoted);
        let resolved = (repo_root.join(rel_path))
            .canonicalize()
            .unwrap_or_else(|_| repo_root.join(rel_path));
        if !resolved.starts_with(&resolved_root) {
            return ("", None);
        }
        return ("new", Some(repo_root.join(rel_path)));
    }

    ("", None)
}

fn parse_hunk_header(caps: &regex::Captures, path: &Path) -> Option<DiffHunk> {
    // Adversarial-diff hardening: integers parsed from the hunk regex are
    // small ASCII digits matched by `\d+`, so `parse::<u32>` can only fail
    // on overflow (e.g. lines > 2^32). Skip such hunks instead of crashing
    // the host process — they are degenerate and have no useful semantics.
    let old_start: u32 = caps[1].parse().ok()?;
    let old_len: u32 = match caps.get(2) {
        Some(m) => m.as_str().parse().ok()?,
        None => 1,
    };
    let new_start: u32 = caps[3].parse().ok()?;
    let new_len: u32 = match caps.get(4) {
        Some(m) => m.as_str().parse().ok()?,
        None => 1,
    };

    Some(DiffHunk {
        path: Arc::from(path.to_string_lossy().as_ref()),
        new_start,
        new_len,
        old_start,
        old_len,
    })
}

pub fn parse_diff(repo_root: &Path, diff_range: Option<&str>) -> Result<Vec<DiffHunk>> {
    let mut args: Vec<&str> = vec!["diff"];
    args.extend_from_slice(SAFE_DIFF_FLAGS);
    args.push("--unified=0");
    args.push("-M");
    if let Some(range) = diff_range {
        validate_diff_range(range)?;
        args.push(range);
    }

    let output = run_git(repo_root, &args)?;
    let mut hunks = Vec::new();
    let mut old_path: Option<PathBuf> = None;
    let mut new_path: Option<PathBuf> = None;

    for line in output.lines() {
        let (path_type, path) = parse_path_line(line, repo_root);
        match path_type {
            "old" => {
                old_path = path;
                continue;
            }
            "new" => {
                new_path = path;
                continue;
            }
            _ => {}
        }

        if let Some(caps) = HUNK_RE.captures(line) {
            let current_path = new_path.as_deref().or(old_path.as_deref());
            if let Some(p) = current_path {
                if let Some(hunk) = parse_hunk_header(&caps, p) {
                    hunks.push(hunk);
                }
            }
        }
    }

    Ok(hunks)
}

pub fn run_git_z(repo_root: &Path, args: &[&str]) -> Result<Vec<String>> {
    let output = run_git(repo_root, args)?;
    Ok(output
        .split('\0')
        .filter(|s| !s.is_empty())
        .map(String::from)
        .collect())
}

pub fn get_changed_files(repo_root: &Path, diff_range: Option<&str>) -> Result<Vec<PathBuf>> {
    let mut args: Vec<&str> = vec!["diff"];
    args.extend_from_slice(SAFE_DIFF_FLAGS);
    args.extend_from_slice(&["--name-only", "-M", "-z"]);
    if let Some(range) = diff_range {
        validate_diff_range(range)?;
        args.push(range);
    }
    let parts = run_git_z(repo_root, &args)?;
    Ok(parts
        .iter()
        .map(|p| {
            repo_root
                .join(p)
                .canonicalize()
                .unwrap_or_else(|_| repo_root.join(p))
        })
        .collect())
}

pub fn get_deleted_files(repo_root: &Path, diff_range: Option<&str>) -> Result<FxHashSet<PathBuf>> {
    let mut args: Vec<&str> = vec!["diff"];
    args.extend_from_slice(SAFE_DIFF_FLAGS);
    args.extend_from_slice(&["--diff-filter=D", "--name-only", "-M", "-z"]);
    if let Some(range) = diff_range {
        validate_diff_range(range)?;
        args.push(range);
    }
    let parts = run_git_z(repo_root, &args)?;
    Ok(parts
        .iter()
        .map(|p| {
            repo_root
                .join(p)
                .canonicalize()
                .unwrap_or_else(|_| repo_root.join(p))
        })
        .collect())
}

pub fn get_renamed_paths(
    repo_root: &Path,
    diff_range: Option<&str>,
    min_similarity: u32,
) -> Result<(FxHashSet<PathBuf>, FxHashSet<PathBuf>)> {
    let mut args: Vec<&str> = vec!["diff"];
    args.extend_from_slice(SAFE_DIFF_FLAGS);
    args.extend_from_slice(&["--diff-filter=R", "--name-status", "-M", "-z"]);
    if let Some(range) = diff_range {
        validate_diff_range(range)?;
        args.push(range);
    }
    let output = run_git(repo_root, &args)?;
    let parts: Vec<&str> = output.split('\0').collect();

    let mut old_paths = FxHashSet::default();
    let mut pure_new_paths = FxHashSet::default();
    let mut i = 0;

    while i < parts.len() {
        if parts[i].starts_with('R') {
            let sim: u32 = parts[i][1..].parse().unwrap_or(0);

            if i + 1 < parts.len() && !parts[i + 1].is_empty() {
                let resolved = repo_root
                    .join(parts[i + 1])
                    .canonicalize()
                    .unwrap_or_else(|_| repo_root.join(parts[i + 1]));
                old_paths.insert(resolved);
            }

            if sim >= min_similarity && i + 2 < parts.len() && !parts[i + 2].is_empty() {
                let resolved = repo_root
                    .join(parts[i + 2])
                    .canonicalize()
                    .unwrap_or_else(|_| repo_root.join(parts[i + 2]));
                pure_new_paths.insert(resolved);
            }

            i += 3;
        } else {
            i += 1;
        }
    }

    Ok((old_paths, pure_new_paths))
}

/// Rename pairs as repo-relative display paths (`old -> new`), for the output
/// header. Unlike `get_renamed_paths` this preserves the pairing and does not
/// canonicalize (the old path no longer exists on disk).
pub fn get_rename_pairs(
    repo_root: &Path,
    diff_range: Option<&str>,
) -> Result<Vec<(String, String)>> {
    let mut args: Vec<&str> = vec!["diff"];
    args.extend_from_slice(SAFE_DIFF_FLAGS);
    args.extend_from_slice(&["--diff-filter=R", "--name-status", "-M", "-z"]);
    if let Some(range) = diff_range {
        validate_diff_range(range)?;
        args.push(range);
    }
    let output = run_git(repo_root, &args)?;
    let parts: Vec<&str> = output.split('\0').collect();

    let mut pairs = Vec::new();
    let mut i = 0;
    while i < parts.len() {
        if parts[i].starts_with('R') {
            if i + 2 < parts.len() && !parts[i + 1].is_empty() && !parts[i + 2].is_empty() {
                pairs.push((
                    parts[i + 1].replace('\\', "/"),
                    parts[i + 2].replace('\\', "/"),
                ));
            }
            i += 3;
        } else {
            i += 1;
        }
    }
    Ok(pairs)
}

pub fn split_diff_range(range: &str) -> (Option<String>, Option<String>) {
    match RANGE_RE.captures(range) {
        None => (None, None),
        Some(caps) => {
            let base = caps
                .get(1)
                .map(|m| m.as_str().trim().to_string())
                .filter(|s| !s.is_empty());
            let head = caps
                .get(3)
                .map(|m| m.as_str().trim().to_string())
                .filter(|s| !s.is_empty());
            (base, head)
        }
    }
}

pub fn show_file_at_revision(repo_root: &Path, rev: &str, rel_path: &Path) -> Result<String> {
    let spec = format!("{}:{}", rev, rel_path.to_string_lossy().replace('\\', "/"));
    run_git(repo_root, &["show", &spec])
}

pub fn get_commit_message(repo_root: &Path, rev: &str) -> Result<String> {
    match run_git(repo_root, &["log", "-1", "--format=%s%n%b", rev]) {
        Ok(s) => Ok(s.trim().to_string()),
        Err(_) => Ok(String::new()),
    }
}

pub fn get_untracked_files(repo_root: &Path) -> Result<Vec<PathBuf>> {
    let parts = run_git_z(
        repo_root,
        &["ls-files", "--others", "--exclude-standard", "-z"],
    )?;
    Ok(parts
        .iter()
        .map(|p| {
            repo_root
                .join(p)
                .canonicalize()
                .unwrap_or_else(|_| repo_root.join(p))
        })
        .collect())
}

/// Rewrites one `.diffctx/ignore` pattern line to be anchored to the
/// directory that contains the `.diffctx/` folder (`rel`, repo-root-relative,
/// "" for the repo root itself). Mirrors `_process_ignore_line` in the
/// Python tree-mode ignore resolver (`src/diffctx/ignore.py`) so a pattern
/// declared in `sub/.diffctx/ignore` only ever matches within `sub/`.
fn anchor_diffctx_ignore_line(line: &str, rel: &str) -> String {
    let (neg, pat) = match line.strip_prefix('!') {
        Some(rest) => (true, rest),
        None => (false, line),
    };
    let pat_no_trailing_slash = pat.trim_end_matches('/');
    let full = if pat_no_trailing_slash.starts_with('/') || pat_no_trailing_slash.contains('/') {
        let anchored = pat.trim_start_matches('/');
        if rel.is_empty() {
            format!("/{anchored}")
        } else {
            format!("/{rel}/{anchored}")
        }
    } else if rel.is_empty() {
        pat.to_string()
    } else {
        format!("{rel}/**/{pat}")
    };
    if neg { format!("!{full}") } else { full }
}

/// Finds every `.diffctx/ignore` file tracked or present in `repo_root`
/// (any depth) and returns its patterns rewritten to be repo-root-relative,
/// ready to feed into a combined gitignore-syntax exclude file.
fn collect_diffctx_ignore_patterns(repo_root: &Path) -> Vec<String> {
    let Ok(files) = run_git_z(
        repo_root,
        &[
            "ls-files",
            "-z",
            "--cached",
            "--others",
            "--exclude-standard",
            "--",
            ":(glob)**/.diffctx/ignore",
        ],
    ) else {
        return Vec::new();
    };

    let mut patterns = Vec::new();
    for raw in &files {
        let rel_path = unquote_c_style(raw);
        if !rel_path.ends_with(".diffctx/ignore") {
            continue;
        }
        let rel_dir = rel_path
            .strip_suffix(".diffctx/ignore")
            .unwrap_or("")
            .trim_end_matches('/');
        let Ok(content) = std::fs::read_to_string(repo_root.join(&rel_path)) else {
            continue;
        };
        for line in content.lines() {
            let line = line.trim_end();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            patterns.push(anchor_diffctx_ignore_line(line, rel_dir));
        }
    }
    patterns
}

/// Returns the subset of `rel_paths` (repo-root-relative) excluded by either
/// `.gitignore` (via git's own engine, so nesting/negation/`**` are handled
/// correctly) or `.diffctx/ignore` (patterns anchored per-directory and fed
/// to git as a temporary `core.excludesFile`, so the same engine evaluates
/// both mechanisms uniformly). Best-effort: any failure returns an empty set
/// rather than blocking the diff pipeline on an ignore-resolution problem.
pub fn find_ignored_paths(repo_root: &Path, rel_paths: &[String]) -> FxHashSet<String> {
    if rel_paths.is_empty() {
        return FxHashSet::default();
    }

    let diffctx_patterns = collect_diffctx_ignore_patterns(repo_root);
    let temp_excludes = if diffctx_patterns.is_empty() {
        None
    } else {
        let path = std::env::temp_dir().join(format!("diffctx-ignore-{}.tmp", std::process::id()));
        match std::fs::write(&path, diffctx_patterns.join("\n")) {
            Ok(()) => Some(path),
            Err(_) => None,
        }
    };

    let mut args: Vec<String> = vec!["check-ignore".into(), "--no-index".into()];
    if let Some(ref path) = temp_excludes {
        args.insert(0, format!("core.excludesFile={}", path.display()));
        args.insert(0, "-c".into());
    }
    args.push("--".into());
    args.extend(rel_paths.iter().cloned());
    let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();

    let result = (|| -> Result<FxHashSet<String>> {
        let mut cmd = git_command(repo_root);
        cmd.args(&arg_refs)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let child = cmd.spawn()?;
        let output = wait_with_timeout(child, Duration::from_secs(git_timeout()), &arg_refs)?;
        // Exit code 1 from `check-ignore` means "none of the given paths are
        // ignored" — not a failure. Any other non-zero code is a real error.
        if !output.status.success() && output.status.code() != Some(1) {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(GitError::CommandFailed(format!(
                "git check-ignore failed: {}",
                stderr.trim()
            )));
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        Ok(stdout.lines().map(unquote_c_style).collect())
    })();

    if let Some(path) = temp_excludes {
        let _ = std::fs::remove_file(path);
    }

    result.unwrap_or_default()
}

pub struct CatFileBatch {
    repo_root: PathBuf,
    child: Option<Child>,
    reader: Option<BufReader<ChildStdout>>,
}

impl CatFileBatch {
    pub fn new(repo_root: &Path) -> Result<Self> {
        let mut batch = Self {
            repo_root: repo_root.to_path_buf(),
            child: None,
            reader: None,
        };
        batch.ensure_started()?;
        Ok(batch)
    }

    fn ensure_started(&mut self) -> Result<()> {
        let needs_restart = match &mut self.child {
            None => true,
            Some(child) => child.try_wait().ok().flatten().is_some(),
        };

        if needs_restart {
            let mut child = git_command(&self.repo_root)
                .args(["cat-file", "--batch"])
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::null())
                .spawn()?;
            let stdout = child.stdout.take().ok_or_else(|| {
                GitError::CommandFailed("cat-file: failed to capture stdout pipe".into())
            })?;
            self.reader = Some(BufReader::new(stdout));
            self.child = Some(child);
        }

        Ok(())
    }

    pub fn get(&mut self, rev: &str, rel_path: &Path) -> Result<String> {
        let spec = format!(
            "{}:{}\n",
            rev,
            rel_path.to_string_lossy().replace('\\', "/")
        );

        self.ensure_started()?;

        let stdin = self
            .child
            .as_mut()
            .and_then(|c| c.stdin.as_mut())
            .ok_or_else(|| GitError::CommandFailed("cat-file stdin unavailable".into()))?;
        stdin.write_all(spec.as_bytes())?;
        stdin.flush()?;

        let reader = self
            .reader
            .as_mut()
            .ok_or_else(|| GitError::CommandFailed("cat-file stdout unavailable".into()))?;

        let mut header_line = String::new();
        reader.read_line(&mut header_line)?;

        if header_line.is_empty() {
            return Err(GitError::CommandFailed(format!(
                "cat-file: unexpected EOF for {}",
                spec.trim()
            )));
        }

        let header_str = header_line.trim();
        if header_str.ends_with("missing") {
            return Err(GitError::CommandFailed(format!(
                "Path not found: {}",
                spec.trim()
            )));
        }

        let parts: Vec<&str> = header_str.split_whitespace().collect();
        if parts.len() < 3 {
            return Err(GitError::CommandFailed(format!(
                "cat-file: malformed header: {}",
                header_str
            )));
        }

        let size: usize = parts[2].parse().map_err(|_| {
            GitError::CommandFailed(format!("cat-file: invalid size in header: {}", header_str))
        })?;

        // Guard against allocating an unbounded blob. Anything larger than the
        // biggest size we will ever parse is drained from the stream in bounded
        // chunks (to keep the cat-file pipe in sync for the next request) and
        // rejected, instead of allocating `size` bytes up front (OOM on a
        // pathological multi-hundred-MB blob).
        if size > crate::config::limits::MAX_BLOB_READ_BYTES {
            let mut remaining = size;
            let mut scratch = [0u8; 65536];
            while remaining > 0 {
                let want = remaining.min(scratch.len());
                reader.read_exact(&mut scratch[..want])?;
                remaining -= want;
            }
            let mut trailing = [0u8; 1];
            let _ = reader.read_exact(&mut trailing);
            return Err(GitError::CommandFailed(format!(
                "cat-file: blob too large ({} bytes): {}",
                size,
                spec.trim()
            )));
        }

        let mut content = vec![0u8; size];
        reader.read_exact(&mut content)?;

        let mut trailing = [0u8; 1];
        let _ = reader.read_exact(&mut trailing);

        Ok(String::from_utf8_lossy(&content).into_owned())
    }

    pub fn close(&mut self) {
        self.reader.take();
        if let Some(mut child) = self.child.take() {
            drop(child.stdin.take());
            match child.wait_timeout(Duration::from_secs(GIT.catfile_termination_timeout_seconds)) {
                Ok(Some(_)) => {}
                _ => {
                    let _ = child.kill();
                    let _ = child.wait();
                }
            }
        }
    }
}

impl Drop for CatFileBatch {
    fn drop(&mut self) {
        self.close();
    }
}