pointbreak 0.5.0

Durable terminal code review for changes humans and coding agents collaborate on together
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
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsString;
use std::path::{Path, PathBuf};

use crate::error::{Result, ShoreError};
use crate::git::command::{git_worktree_root, run_git, run_git_allowing_statuses};
use crate::git::patch::{PatchFile, parse_patch};
use crate::git::raw::{RawFile, parse_raw};
use crate::model::{DiffFile, DiffSnapshot, FileId, FileMetadataKind, FileMetadataRow, ReviewId};
use crate::session::worktree_fingerprint_for_files;

#[derive(Clone, Debug, Default)]
pub struct IngestOptions {
    helper_paths: Vec<PathBuf>,
    pathspecs: Vec<String>,
}

impl IngestOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn exclude_helper_path(mut self, path: impl AsRef<Path>) -> Self {
        self.helper_paths.push(path.as_ref().to_path_buf());
        self
    }

    /// Scope the ingested diff to the given native git pathspecs, executed by
    /// git itself after `--` (tracked diff and untracked discovery alike).
    /// Empty (the default) ingests the whole repository.
    pub fn with_pathspecs(mut self, pathspecs: Vec<String>) -> Self {
        self.pathspecs = pathspecs;
        self
    }
}

pub fn ingest_tracked_diff(repo: impl AsRef<Path>) -> Result<DiffSnapshot> {
    ingest_tracked_diff_with_options(repo, IngestOptions::new())
}

pub fn ingest_tracked_diff_with_options(
    repo: impl AsRef<Path>,
    options: IngestOptions,
) -> Result<DiffSnapshot> {
    let repo = repo.as_ref();
    let files = filter_helper_paths(
        capture_worktree_diff_files_scoped(repo, &options.pathspecs)?,
        repo,
        &options.helper_paths,
    )?;
    let fingerprint = worktree_fingerprint_for_files(repo, &files)?;

    Ok(DiffSnapshot::new(
        ReviewId::new("working-tree"),
        fingerprint.object_id,
        files,
    ))
}

fn filter_helper_paths(
    files: Vec<DiffFile>,
    repo: &Path,
    helper_paths: &[PathBuf],
) -> Result<Vec<DiffFile>> {
    let excluded_paths = excluded_git_paths(repo, helper_paths)?;
    if excluded_paths.is_empty() {
        return Ok(files);
    }

    Ok(files
        .into_iter()
        .filter(|file| {
            !file
                .old_path
                .as_deref()
                .is_some_and(|path| excluded_paths.contains(path))
                && !file
                    .new_path
                    .as_deref()
                    .is_some_and(|path| excluded_paths.contains(path))
        })
        .collect())
}

fn excluded_git_paths(repo: &Path, helper_paths: &[PathBuf]) -> Result<BTreeSet<String>> {
    let worktree_root = git_worktree_root(repo)?;
    let worktree_root = worktree_root.canonicalize().map_err(|error| {
        ShoreError::Message(format!(
            "canonicalize git worktree root {}: {error}",
            worktree_root.display()
        ))
    })?;
    let paths = helper_paths
        .iter()
        .filter_map(|path| {
            let helper_path = path.canonicalize().ok()?;
            let relative = helper_path.strip_prefix(&worktree_root).ok()?;
            Some(
                relative
                    .to_string_lossy()
                    .replace(std::path::MAIN_SEPARATOR, "/"),
            )
        })
        .collect();
    Ok(paths)
}

/// Diff flags shared by every `git diff` pass, single-sourced so the worktree
/// and commit-range paths cannot drift apart. Mode flags (`--raw -z` vs
/// `--patch`) and the endpoint args are layered on per call.
const SHARED_DIFF_FLAGS: &[&str] = &[
    "--no-ext-diff",
    "--no-color",
    "--full-index",
    "-M",
    "-C",
    "--submodule=short",
];

/// Assemble a `git diff` argument list:
/// `diff <mode_flags> <shared> <endpoints> -- <pathspecs>`. An empty pathspec
/// set reproduces today's whole-repo command exactly.
fn diff_args(mode_flags: &[&str], endpoint_args: &[&str], pathspecs: &[String]) -> Vec<OsString> {
    let mut args: Vec<OsString> = Vec::with_capacity(
        2 + mode_flags.len() + SHARED_DIFF_FLAGS.len() + endpoint_args.len() + pathspecs.len(),
    );
    args.push(OsString::from("diff"));
    args.extend(mode_flags.iter().copied().map(OsString::from));
    args.extend(SHARED_DIFF_FLAGS.iter().copied().map(OsString::from));
    args.extend(endpoint_args.iter().copied().map(OsString::from));
    args.push(OsString::from("--"));
    args.extend(pathspecs.iter().map(OsString::from));
    args
}

/// Run the raw + patch passes for `endpoint_args` and merge them into the
/// `DiffFile` row inventory. Diff-source-agnostic: callers supply the endpoints
/// (`["HEAD"]` for the worktree, `[base_oid, target_oid]` for a commit range)
/// and an optional pathspec scope git applies after `--`.
fn diff_files_for_args(
    repo: &Path,
    endpoint_args: &[&str],
    pathspecs: &[String],
) -> Result<Vec<DiffFile>> {
    let raw_output = run_git(repo, diff_args(&["--raw", "-z"], endpoint_args, pathspecs))?;
    let patch_output = run_git(repo, diff_args(&["--patch"], endpoint_args, pathspecs))?;

    let raw_files = parse_raw(&raw_output.stdout)?;
    let patch_files =
        patch_files_by_key(parse_patch(&String::from_utf8_lossy(&patch_output.stdout))?);

    raw_files
        .into_iter()
        .map(|raw_file| {
            let key = raw_file.key();
            let patch_file = patch_files
                .get(&key)
                .ok_or_else(|| ShoreError::Message(format!("missing patch entry for {key}")))?;
            diff_file(raw_file, patch_file, false)
        })
        .collect::<Result<Vec<_>>>()
}

pub(crate) fn capture_worktree_diff_files(repo: &Path) -> Result<Vec<DiffFile>> {
    capture_worktree_diff_files_scoped(repo, &[])
}

pub(crate) fn capture_worktree_diff_files_scoped(
    repo: &Path,
    pathspecs: &[String],
) -> Result<Vec<DiffFile>> {
    let mut files = diff_files_for_args(repo, &["HEAD"], pathspecs)?;
    files.extend(synthesize_untracked_files(repo, pathspecs)?);
    Ok(files)
}

/// Tree diff between two resolved commits. Never reads the working tree or
/// index and never synthesizes untracked rows: the inventory is exactly
/// `git diff <base_oid> <target_oid> -- <pathspecs>`. Callers pass
/// already-resolved OIDs (see `git_rev_parse_commit_oid`), so there is no
/// `--end-of-options` concern. Scope-boundary renames follow git's pairing
/// rules: a rename whose old side falls outside the pathspec scope reports as
/// an add of the new side (and vice versa).
pub(crate) fn capture_commit_range_diff_files(
    repo: &Path,
    base_oid: &str,
    target_oid: &str,
    pathspecs: &[String],
) -> Result<Vec<DiffFile>> {
    diff_files_for_args(repo, &[base_oid, target_oid], pathspecs)
}

fn synthesize_untracked_files(repo: &Path, pathspecs: &[String]) -> Result<Vec<DiffFile>> {
    discover_untracked_files(repo, pathspecs)?
        .into_iter()
        .map(|path| synthesize_untracked_file(repo, &path))
        .collect()
}

/// Discover untracked files, optionally scoped: the pathspecs ride after `--`,
/// so git matches them itself and untracked scoping shares one semantics with
/// the tracked diff. `--exclude-standard` still applies within the scope.
fn discover_untracked_files(repo: &Path, pathspecs: &[String]) -> Result<Vec<String>> {
    let mut args: Vec<OsString> = ["ls-files", "--others", "--exclude-standard", "-z", "--"]
        .into_iter()
        .map(OsString::from)
        .collect();
    args.extend(pathspecs.iter().map(OsString::from));
    let output = run_git(repo, args)?;
    output
        .stdout
        .split(|byte| *byte == 0)
        .filter(|field| !field.is_empty())
        .map(|field| {
            std::str::from_utf8(field)
                .map(str::to_owned)
                .map_err(|error| {
                    ShoreError::Message(format!("untracked path is not utf-8: {error}"))
                })
        })
        .collect()
}

fn synthesize_untracked_file(repo: &Path, path: &str) -> Result<DiffFile> {
    let patch = no_index_patch(repo, path)?;
    let patch_file = parse_patch(&String::from_utf8_lossy(&patch.stdout))?
        .into_iter()
        .next()
        .ok_or_else(|| ShoreError::Message(format!("missing no-index patch for {path}")))?;
    let raw_file = RawFile {
        status: crate::model::FileStatus::Added,
        old_mode: None,
        new_mode: patch_file.new_mode.clone(),
        type_change: false,
        old_oid: None,
        new_oid: None,
        similarity: None,
        old_path: None,
        new_path: Some(path.to_owned()),
    };
    diff_file(raw_file, &patch_file, true)
}

fn no_index_patch(repo: &Path, path: &str) -> Result<crate::git::command::GitOutput> {
    let args = vec![
        OsString::from("diff"),
        OsString::from("--no-index"),
        OsString::from("--no-ext-diff"),
        OsString::from("--no-color"),
        OsString::from("--full-index"),
        OsString::from("--"),
        OsString::from("/dev/null"),
        OsString::from(PathBuf::from(path)),
    ];
    run_git_allowing_statuses(repo, args, &[0, 1])
}

fn diff_file(raw_file: RawFile, patch_file: &PatchFile, synthetic: bool) -> Result<DiffFile> {
    let is_submodule = raw_file.is_submodule();
    let is_binary = patch_file.is_binary;
    let is_mode_only = is_mode_only(&raw_file, patch_file);
    let metadata_rows = metadata_rows(&raw_file, patch_file);
    let omit_hunks = is_binary || is_submodule || is_mode_only;
    let hunks = if omit_hunks {
        Vec::new()
    } else {
        patch_file.hunks.clone()
    };

    Ok(DiffFile {
        id: FileId::new(raw_file.key()),
        status: raw_file.status,
        old_path: raw_file.old_path,
        new_path: raw_file.new_path,
        old_mode: raw_file.old_mode.or_else(|| patch_file.old_mode.clone()),
        new_mode: raw_file.new_mode.or_else(|| patch_file.new_mode.clone()),
        old_oid: raw_file.old_oid,
        new_oid: raw_file.new_oid,
        similarity: raw_file.similarity.or(patch_file.similarity),
        is_binary,
        is_submodule,
        is_mode_only,
        synthetic,
        metadata_rows,
        hunks,
    })
}

fn patch_files_by_key(files: Vec<PatchFile>) -> BTreeMap<String, PatchFile> {
    let mut by_key = BTreeMap::new();
    for file in files {
        match by_key.entry(file.key()) {
            Entry::Vacant(entry) => {
                entry.insert(file);
            }
            Entry::Occupied(mut entry) => {
                merge_patch_file(entry.get_mut(), file);
            }
        }
    }
    by_key
}

fn merge_patch_file(existing: &mut PatchFile, next: PatchFile) {
    fill_missing(&mut existing.old_path, next.old_path);
    fill_missing(&mut existing.new_path, next.new_path);
    fill_missing(&mut existing.old_mode, next.old_mode);
    fill_missing(&mut existing.new_mode, next.new_mode);
    fill_missing(&mut existing.similarity, next.similarity);
    existing.is_binary |= next.is_binary;
    existing.hunks.extend(next.hunks);
}

fn fill_missing<T>(current: &mut Option<T>, next: Option<T>) {
    if current.is_none() {
        *current = next;
    }
}

fn is_mode_only(raw_file: &RawFile, patch_file: &PatchFile) -> bool {
    raw_file.has_mode_change()
        && !raw_file.type_change
        && !patch_file.is_binary
        && patch_file.hunks.is_empty()
}

fn metadata_rows(
    raw_file: &crate::git::raw::RawFile,
    patch_file: &PatchFile,
) -> Vec<FileMetadataRow> {
    let mut rows = Vec::new();
    if matches!(
        raw_file.status,
        crate::model::FileStatus::Renamed | crate::model::FileStatus::Copied
    ) {
        rows.push(FileMetadataRow {
            kind: FileMetadataKind::RenameSummary,
            text: match (&raw_file.old_path, &raw_file.new_path, raw_file.similarity) {
                (Some(old), Some(new), Some(similarity)) => {
                    format!("renamed {old} -> {new} ({similarity}%)")
                }
                (Some(old), Some(new), None) => format!("renamed {old} -> {new}"),
                _ => "renamed file".to_owned(),
            },
        });
    }
    if patch_file.is_binary {
        rows.push(FileMetadataRow {
            kind: FileMetadataKind::BinarySummary,
            text: "binary files differ".to_owned(),
        });
    }
    if raw_file.has_mode_change() {
        rows.push(FileMetadataRow {
            kind: FileMetadataKind::ModeChange,
            text: match (&raw_file.old_mode, &raw_file.new_mode) {
                (Some(old), Some(new)) => format!("mode changed {old} -> {new}"),
                _ => "mode changed".to_owned(),
            },
        });
    }
    if raw_file.is_submodule() {
        rows.push(FileMetadataRow {
            kind: FileMetadataKind::SubmoduleSummary,
            text: match (&raw_file.old_oid, &raw_file.new_oid) {
                (Some(old), Some(new)) => format!("submodule changed {old} -> {new}"),
                _ => "submodule changed".to_owned(),
            },
        });
    }
    rows
}

#[cfg(test)]
mod tests {
    use std::ffi::OsStr;
    use std::fs;
    use std::path::Path;
    use std::process::Command;

    use super::{
        capture_commit_range_diff_files, capture_worktree_diff_files,
        capture_worktree_diff_files_scoped,
    };
    use crate::git::command::run_git;
    use crate::model::{FileMetadataKind, FileStatus};

    #[test]
    fn scoped_worktree_diff_files_include_only_pathspec_matches() {
        let repo = TestRepo::new();
        repo.write("a/one.txt", "one\n");
        repo.write("b/two.txt", "two\n");
        repo.commit_all("base");
        repo.write("a/one.txt", "one changed\n");
        repo.write("b/two.txt", "two changed\n");

        let files = capture_worktree_diff_files_scoped(repo.path(), &["a".to_owned()]).unwrap();

        let paths: Vec<&str> = files.iter().filter_map(|f| f.new_path.as_deref()).collect();
        assert_eq!(paths, vec!["a/one.txt"]);
    }

    #[test]
    fn scoped_worktree_diff_accepts_multiple_pathspecs() {
        let repo = TestRepo::new();
        repo.write("a/one.txt", "one\n");
        repo.write("b/two.txt", "two\n");
        repo.write("c/three.txt", "three\n");
        repo.commit_all("base");
        repo.write("a/one.txt", "changed\n");
        repo.write("b/two.txt", "changed\n");
        repo.write("c/three.txt", "changed\n");

        let files =
            capture_worktree_diff_files_scoped(repo.path(), &["a".to_owned(), "c".to_owned()])
                .unwrap();

        let paths: Vec<&str> = files.iter().filter_map(|f| f.new_path.as_deref()).collect();
        assert_eq!(paths, vec!["a/one.txt", "c/three.txt"]);
    }

    #[test]
    fn unscoped_worktree_diff_files_delegate_with_empty_pathspecs() {
        let repo = TestRepo::new();
        repo.write("a/one.txt", "one\n");
        repo.commit_all("base");
        repo.write("a/one.txt", "changed\n");

        let unscoped = capture_worktree_diff_files(repo.path()).unwrap();
        let empty_scope = capture_worktree_diff_files_scoped(repo.path(), &[]).unwrap();
        assert_eq!(unscoped, empty_scope);
    }

    #[test]
    fn scoped_worktree_diff_synthesizes_only_untracked_files_under_the_pathspec() {
        let repo = TestRepo::new();
        repo.write("a/tracked.txt", "tracked\n");
        repo.commit_all("base");
        repo.write("a/new.txt", "new in scope\n");
        repo.write("b/new.txt", "new out of scope\n");

        let files = capture_worktree_diff_files_scoped(repo.path(), &["a".to_owned()]).unwrap();

        let paths: Vec<&str> = files.iter().filter_map(|f| f.new_path.as_deref()).collect();
        assert_eq!(paths, vec!["a/new.txt"]);
        assert!(files.iter().all(|file| file.synthetic));
    }

    #[test]
    fn unscoped_worktree_diff_still_synthesizes_all_untracked_files() {
        let repo = TestRepo::new();
        repo.write("a/tracked.txt", "tracked\n");
        repo.commit_all("base");
        repo.write("a/new.txt", "new\n");
        repo.write("b/new.txt", "new\n");

        let files = capture_worktree_diff_files_scoped(repo.path(), &[]).unwrap();

        let paths: Vec<&str> = files.iter().filter_map(|f| f.new_path.as_deref()).collect();
        assert_eq!(paths, vec!["a/new.txt", "b/new.txt"]);
    }

    #[test]
    fn scoped_commit_range_diff_includes_only_pathspec_matches() {
        let repo = TestRepo::new();
        repo.write("a/one.txt", "one\n");
        repo.write("b/two.txt", "two\n");
        repo.commit_all("base");
        let base_oid = repo.rev_parse("HEAD");
        repo.write("a/one.txt", "one changed\n");
        repo.write("b/two.txt", "two changed\n");
        repo.commit_all("change");
        let head_oid = repo.rev_parse("HEAD");

        let files =
            capture_commit_range_diff_files(repo.path(), &base_oid, &head_oid, &["a".to_owned()])
                .unwrap();

        let paths: Vec<&str> = files.iter().filter_map(|f| f.new_path.as_deref()).collect();
        assert_eq!(paths, vec!["a/one.txt"]);
    }

    #[test]
    fn rename_witnessed_from_only_its_new_side_degrades_to_an_add() {
        // Native git pathspec semantics: rename pairing needs both sides in
        // scope. Scoped to the new side only, `a/x.txt -> b/y.txt` reports as
        // an Added `b/y.txt`. We lock, not fight, git here — the scoped
        // inventory is exactly `git diff <base> <target> -- <pathspec>`.
        let repo = TestRepo::new();
        repo.write("a/x.txt", "line one\nline two\nline three\n");
        repo.commit_all("base");
        let base_oid = repo.rev_parse("HEAD");
        // `git mv` requires the destination directory to exist.
        fs::create_dir_all(repo.path().join("b")).unwrap();
        repo.git(["mv", "a/x.txt", "b/y.txt"]);
        repo.commit_all("move");
        let head_oid = repo.rev_parse("HEAD");

        let files =
            capture_commit_range_diff_files(repo.path(), &base_oid, &head_oid, &["b".to_owned()])
                .unwrap();

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].status, FileStatus::Added);
        assert_eq!(files[0].new_path.as_deref(), Some("b/y.txt"));
    }

    #[test]
    fn rename_with_both_sides_in_scope_is_preserved() {
        let repo = TestRepo::new();
        repo.write("a/x.txt", "line one\nline two\nline three\n");
        repo.commit_all("base");
        let base_oid = repo.rev_parse("HEAD");
        // `git mv` requires the destination directory to exist.
        fs::create_dir_all(repo.path().join("b")).unwrap();
        repo.git(["mv", "a/x.txt", "b/y.txt"]);
        repo.commit_all("move");
        let head_oid = repo.rev_parse("HEAD");

        let files = capture_commit_range_diff_files(
            repo.path(),
            &base_oid,
            &head_oid,
            &["a".to_owned(), "b".to_owned()],
        )
        .unwrap();

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].status, FileStatus::Renamed);
        assert_eq!(files[0].old_path.as_deref(), Some("a/x.txt"));
        assert_eq!(files[0].new_path.as_deref(), Some("b/y.txt"));
    }

    #[test]
    fn commit_range_diff_files_capture_committed_change_with_clean_worktree() {
        let repo = TestRepo::new();
        repo.write("file.txt", "one\n");
        repo.commit_all("base");
        let base_oid = repo.rev_parse("HEAD");
        repo.write("file.txt", "two\n");
        repo.commit_all("change");
        let head_oid = repo.rev_parse("HEAD");

        let files =
            capture_commit_range_diff_files(repo.path(), &base_oid, &head_oid, &[]).unwrap();

        assert_eq!(files.len(), 1);
        let file = &files[0];
        assert_eq!(file.status, FileStatus::Modified);
        assert_eq!(file.new_path.as_deref(), Some("file.txt"));
        assert!(!file.hunks.is_empty());
        // Both sides of a committed range diff carry real blob oids.
        assert!(file.old_oid.as_deref().is_some_and(|oid| !oid.is_empty()));
        assert!(file.new_oid.as_deref().is_some_and(|oid| !oid.is_empty()));
        assert!(files.iter().all(|file| !file.synthetic));
    }

    #[test]
    fn commit_range_diff_files_ignore_worktree_and_untracked_state() {
        let repo = TestRepo::new();
        repo.write("file.txt", "one\n");
        repo.commit_all("base");
        let base_oid = repo.rev_parse("HEAD");
        repo.write("file.txt", "two\n");
        repo.commit_all("change");
        let head_oid = repo.rev_parse("HEAD");

        let clean =
            capture_commit_range_diff_files(repo.path(), &base_oid, &head_oid, &[]).unwrap();

        // Dirty the tracked file and add an untracked file; the tree diff must not see either.
        repo.write("file.txt", "dirty worktree edit\n");
        repo.write("untracked.txt", "untracked\n");
        let dirty =
            capture_commit_range_diff_files(repo.path(), &base_oid, &head_oid, &[]).unwrap();

        assert_eq!(clean, dirty);
        assert!(
            dirty
                .iter()
                .all(|file| file.new_path.as_deref() != Some("untracked.txt"))
        );
    }

    #[test]
    fn commit_range_diff_files_preserve_rename_detection() {
        let repo = TestRepo::new();
        repo.write("original.txt", "line one\nline two\nline three\n");
        repo.commit_all("base");
        let base_oid = repo.rev_parse("HEAD");
        repo.git(["mv", "original.txt", "renamed.txt"]);
        repo.commit_all("rename");
        let head_oid = repo.rev_parse("HEAD");

        let files =
            capture_commit_range_diff_files(repo.path(), &base_oid, &head_oid, &[]).unwrap();

        assert_eq!(files.len(), 1);
        let file = &files[0];
        assert_eq!(file.status, FileStatus::Renamed);
        assert_eq!(file.old_path.as_deref(), Some("original.txt"));
        assert_eq!(file.new_path.as_deref(), Some("renamed.txt"));
        assert!(
            file.metadata_rows
                .iter()
                .any(|row| matches!(row.kind, FileMetadataKind::RenameSummary))
        );
    }

    #[test]
    fn commit_range_diff_files_for_identical_trees_are_empty() {
        let repo = TestRepo::new();
        repo.write("file.txt", "one\n");
        repo.commit_all("base");
        let head_oid = repo.rev_parse("HEAD");

        let files =
            capture_commit_range_diff_files(repo.path(), &head_oid, &head_oid, &[]).unwrap();

        assert!(files.is_empty());
    }

    struct TestRepo {
        root: tempfile::TempDir,
    }

    impl TestRepo {
        fn new() -> Self {
            let root = tempfile::tempdir().expect("create temp git repository directory");
            let repo = Self { root };

            repo.git(["init"]);
            repo.git(["config", "user.name", "Shore Tests"]);
            repo.git(["config", "user.email", "shore-tests@example.com"]);
            repo.git(["config", "commit.gpgsign", "false"]);

            repo
        }

        fn path(&self) -> &Path {
            self.root.path()
        }

        fn write(&self, path: impl AsRef<Path>, contents: impl AsRef<[u8]>) {
            let path = self.root.path().join(path);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).expect("create parent directories");
            }
            fs::write(path, contents).expect("write test repository file");
        }

        fn commit_all(&self, message: &str) {
            self.git(["add", "--all"]);
            self.git(["commit", "-m", message]);
        }

        fn rev_parse(&self, rev: &str) -> String {
            let output = run_git(self.root.path(), ["rev-parse", rev]).unwrap();
            String::from_utf8(output.stdout).unwrap().trim().to_owned()
        }

        fn git<I, S>(&self, args: I)
        where
            I: IntoIterator<Item = S>,
            S: AsRef<OsStr>,
        {
            let args = args
                .into_iter()
                .map(|arg| arg.as_ref().to_owned())
                .collect::<Vec<_>>();
            let output = Command::new("git")
                .args(&args)
                .current_dir(self.root.path())
                .output()
                .unwrap_or_else(|error| panic!("run git {:?}: {error}", args));

            assert!(
                output.status.success(),
                "git {:?} failed\nstatus: {}\nstdout:\n{}\nstderr:\n{}",
                args,
                output.status,
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }
}