diffler-core 0.16.0

Core review engine for diffler: diffs, sessions, comments, viewed marks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
//! git2 backend for the [`Vcs`] trait: the only module that may touch git2
//! (test fixtures aside).

use std::cell::Cell;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::diffalgo::{DiffAlgorithm, DiffSettings, histogram_hunks};
use crate::model::{
    DiffLine, DiffModel, FileDiff, FileStatus, Hunk, HunkId, LineKind, disambiguated_hunk_id,
};
use crate::vcs::{
    BlameSpan, BranchInfo, HeadInfo, LogEntry, NetworkOp, StatusModel, Vcs, VcsError,
};

/// git's own default amount of context around hunks.
pub const DEFAULT_CONTEXT_LINES: u32 = 3;

/// git's own default: on, matching modern git's behaviour.
pub const DEFAULT_INDENT_HEURISTIC: bool = true;

pub struct GitVcs {
    repo: git2::Repository,
    context_lines: u32,
    /// The session's current line-diff algorithm. A `Cell` so a live palette
    /// switch (`Vcs::set_diff_algorithm`) reaches every diff this instance
    /// computes afterward without needing `&mut self`.
    algorithm: Cell<DiffAlgorithm>,
    indent_heuristic: Cell<bool>,
}

impl GitVcs {
    /// Open at [`DiffSettings::default`].
    pub fn open(root: &Path) -> Result<Self, VcsError> {
        Self::open_with_settings(root, &DiffSettings::default())
    }

    /// Open with a custom context, line-diff algorithm and indent heuristic
    /// (config keys `ui.context_lines`, `diff.algorithm`, `diff.indent_heuristic`).
    pub fn open_with_settings(root: &Path, settings: &DiffSettings) -> Result<Self, VcsError> {
        let repo = git2::Repository::open(root)?;
        if repo.workdir().is_none() {
            return Err(VcsError::NoWorkdir);
        }
        Ok(Self {
            repo,
            context_lines: settings.context_lines,
            algorithm: Cell::new(settings.algorithm),
            indent_heuristic: Cell::new(settings.indent_heuristic),
        })
    }

    /// HEAD tree, or `None` on an unborn branch (fresh repo).
    fn head_tree(&self) -> Result<Option<git2::Tree<'_>>, VcsError> {
        match self.repo.head() {
            Ok(head) => Ok(Some(head.peel_to_tree()?)),
            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => Ok(None),
            Err(err) => Err(err.into()),
        }
    }

    fn workdir_path(&self) -> Result<&Path, VcsError> {
        self.repo.workdir().ok_or(VcsError::NoWorkdir)
    }

    /// `base` tree vs workdir+index including untracked, renames folded in.
    /// `None` is the empty tree (an unborn branch).
    fn workdir_diff(&self, base: Option<&git2::Tree<'_>>) -> Result<DiffModel, VcsError> {
        let mut diff = self
            .repo
            .diff_tree_to_workdir_with_index(base, Some(&mut self.workdir_diff_options()))?;
        let mut find = git2::DiffFindOptions::new();
        find.renames(true);
        diff.find_similar(Some(&mut find))?;
        self.diff_to_model(&mut diff)
    }

    /// `git2::DiffOptions` for a tree-vs-tree or tree-vs-index diff at the
    /// session's current context and algorithm.
    fn plain_diff_options(&self) -> git2::DiffOptions {
        let mut opts = git2::DiffOptions::new();
        opts.context_lines(self.context_lines);
        apply_git_algorithm(&mut opts, self.algorithm.get(), self.indent_heuristic.get());
        opts
    }

    /// Working-tree diff options (untracked files included) at the session's
    /// current context and algorithm.
    fn workdir_diff_options(&self) -> git2::DiffOptions {
        let mut opts = self.plain_diff_options();
        opts.include_untracked(true)
            .recurse_untracked_dirs(true)
            .show_untracked_content(true);
        opts
    }

    /// Intra-line emphasis is a render-time concern: the TUI enriches the
    /// file it is about to draw (see `crate::pairing::enrich_file`), so the
    /// backend leaves `.emphasis` empty.
    fn diff_to_model(&self, diff: &mut git2::Diff<'_>) -> Result<DiffModel, VcsError> {
        let mut files = Vec::new();
        for idx in 0..diff.deltas().len() {
            if let Some(file) = self.build_file(diff, idx)? {
                files.push(file);
            }
        }
        Ok(DiffModel { files })
    }

    /// A modified text file's hunks under histogram/structural, which libgit2
    /// cannot compute; `None` keeps git2's own. Model building and hunk
    /// staging both go through here, so the ids they derive agree.
    fn imara_hunks(
        &self,
        delta: &git2::DiffDelta<'_>,
        old: Option<&str>,
        new: Option<&str>,
        path: &str,
    ) -> Option<Vec<Hunk>> {
        if !self.algorithm.get().is_imara() {
            return None;
        }
        let (old, new) = (old?, new?);
        // we read the worktree side raw, so when a clean filter (autocrlf,
        // ident) makes git compare other bytes we keep git's own hunks
        let hashed = git2::Oid::hash_object(git2::ObjectType::Blob, new.as_bytes()).ok()?;
        if hashed != delta.new_file().id() {
            return None;
        }
        Some(histogram_hunks(
            old,
            new,
            path,
            self.context_lines,
            self.indent_heuristic.get(),
        ))
    }

    fn walk_entries(
        &self,
        walk: git2::Revwalk<'_>,
        limit: usize,
    ) -> Result<Vec<LogEntry>, VcsError> {
        let mut entries = Vec::new();
        for oid in walk.take(limit) {
            let oid = oid?;
            let commit = self.repo.find_commit(oid)?;
            let full = oid.to_string();
            entries.push(LogEntry {
                oid7: short7(&full),
                oid: full,
                refs: Vec::new(),
                subject: commit.summary()?.unwrap_or_default().to_owned(),
                author: commit.author().name().unwrap_or_default().to_owned(),
                time_unix: commit.time().seconds(),
            });
        }
        Ok(entries)
    }

    /// Whether any tracked file differs from HEAD or the index, i.e. there is
    /// something `git stash` would save. Untracked files don't count, matching
    /// stash's default.
    fn has_tracked_changes(&self) -> Result<bool, VcsError> {
        let mut opts = git2::StatusOptions::new();
        opts.include_untracked(false).include_ignored(false);
        let statuses = self.repo.statuses(Some(&mut opts))?;
        Ok(statuses.iter().next().is_some())
    }
}

impl Vcs for GitVcs {
    fn has_index(&self) -> bool {
        true
    }

    fn native_git_checkout(&self) -> bool {
        true
    }

    fn git_dir(&self) -> Result<PathBuf, VcsError> {
        // libgit2 resolves gitlink files, so linked worktrees come back as
        // their external gitdir under the main repo's .git/worktrees/
        Ok(self.repo.path().to_path_buf())
    }

    fn head(&self) -> Result<HeadInfo, VcsError> {
        match self.repo.head() {
            Ok(head) => {
                let branch = if head.is_branch() {
                    Some(head.shorthand()?.to_owned())
                } else {
                    None
                };
                let commit = head.peel_to_commit()?;
                let tracking = branch.as_deref().and_then(|name| {
                    let local = self.repo.find_branch(name, git2::BranchType::Local).ok()?;
                    let upstream = local.upstream().ok()?;
                    let name = upstream.name().ok().flatten()?.to_owned();
                    Some((name, upstream.get().target()))
                });
                let (upstream, ahead, behind) = match tracking {
                    Some((name, Some(target))) => {
                        let (ahead, behind) = self
                            .repo
                            .graph_ahead_behind(commit.id(), target)
                            .unwrap_or((0, 0));
                        (Some(name), ahead, behind)
                    }
                    Some((name, None)) => (Some(name), 0, 0),
                    None => (None, 0, 0),
                };
                Ok(HeadInfo {
                    branch,
                    oid7: short7(&commit.id().to_string()),
                    subject: commit.summary()?.unwrap_or_default().to_owned(),
                    upstream,
                    ahead,
                    behind,
                })
            }
            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
                let branch = self
                    .repo
                    .find_reference("HEAD")
                    .ok()
                    .and_then(|r| r.symbolic_target().ok().flatten().map(str::to_owned))
                    .and_then(|t| t.strip_prefix("refs/heads/").map(str::to_owned));
                Ok(HeadInfo {
                    branch,
                    oid7: String::new(),
                    subject: String::new(),
                    upstream: None,
                    ahead: 0,
                    behind: 0,
                })
            }
            Err(err) => Err(err.into()),
        }
    }

    fn status(&self) -> Result<StatusModel, VcsError> {
        // index vs workdir classifies "untracked" against the index, so a
        // staged new file lands in staged only, not here
        let mut workdir = self
            .repo
            .diff_index_to_workdir(None, Some(&mut self.workdir_diff_options()))?;
        let workdir_model = self.diff_to_model(&mut workdir)?;
        let (untracked, unstaged): (Vec<_>, Vec<_>) = workdir_model
            .files
            .into_iter()
            .partition(|f| f.status == FileStatus::Untracked);

        let head_tree = self.head_tree()?;
        let mut staged = self.repo.diff_tree_to_index(
            head_tree.as_ref(),
            None,
            Some(&mut self.plain_diff_options()),
        )?;
        let staged = self.diff_to_model(&mut staged)?;

        Ok(StatusModel {
            untracked: DiffModel { files: untracked },
            unstaged: DiffModel { files: unstaged },
            staged,
        })
    }

    fn working_tree_diff(&self) -> Result<DiffModel, VcsError> {
        self.workdir_diff(self.head_tree()?.as_ref())
    }

    fn tree_to_workdir_diff(&self, base_oid: &str) -> Result<DiffModel, VcsError> {
        let base = self.repo.find_commit(git2::Oid::from_str(base_oid)?)?;
        self.workdir_diff(Some(&base.tree()?))
    }

    fn commit_diff(&self, oid: &str) -> Result<DiffModel, VcsError> {
        let oid = git2::Oid::from_str(oid)?;
        let commit = self.repo.find_commit(oid)?;
        let tree = commit.tree()?;
        // root commit: first-parent tree is the empty tree
        let parent_tree = commit.parent(0).ok().map(|p| p.tree()).transpose()?;
        let mut diff = self.repo.diff_tree_to_tree(
            parent_tree.as_ref(),
            Some(&tree),
            Some(&mut self.plain_diff_options()),
        )?;
        self.diff_to_model(&mut diff)
    }

    fn tree_diff(&self, base_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError> {
        let base = self.repo.find_commit(git2::Oid::from_str(base_oid)?)?;
        let newest = self.repo.find_commit(git2::Oid::from_str(newest_oid)?)?;
        let mut diff = self.repo.diff_tree_to_tree(
            Some(&base.tree()?),
            Some(&newest.tree()?),
            Some(&mut self.plain_diff_options()),
        )?;
        self.diff_to_model(&mut diff)
    }

    fn merge_base(&self, a: &str, b: &str) -> Result<String, VcsError> {
        let base = self
            .repo
            .merge_base(git2::Oid::from_str(a)?, git2::Oid::from_str(b)?)?;
        Ok(base.to_string())
    }

    fn resolve(&self, revision: &str) -> Result<String, VcsError> {
        let object = self.repo.revparse_single(revision)?;
        let commit = object.peel_to_commit()?;
        Ok(commit.id().to_string())
    }

    fn range_diff(&self, oldest_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError> {
        let oldest = self.repo.find_commit(git2::Oid::from_str(oldest_oid)?)?;
        let newest = self.repo.find_commit(git2::Oid::from_str(newest_oid)?)?;
        let newest_tree = newest.tree()?;
        // the range starts before the oldest commit, so its base is that
        // commit's first parent; a root commit has none and diffs against the
        // empty tree, matching commit_diff
        let base_tree = oldest.parent(0).ok().map(|p| p.tree()).transpose()?;
        let mut diff = self.repo.diff_tree_to_tree(
            base_tree.as_ref(),
            Some(&newest_tree),
            Some(&mut self.plain_diff_options()),
        )?;
        self.diff_to_model(&mut diff)
    }

    fn log(&self, limit: usize) -> Result<Vec<LogEntry>, VcsError> {
        if self.head_tree()?.is_none() {
            return Ok(Vec::new());
        }
        let mut refs_by_oid: HashMap<git2::Oid, Vec<String>> = HashMap::new();
        for reference in self.repo.references()?.flatten() {
            let Ok(name) = reference.shorthand().map(str::to_owned) else {
                continue;
            };
            // peel through symbolic refs and annotated tags to the commit
            let Some(target) = reference.peel_to_commit().ok().map(|c| c.id()) else {
                continue;
            };
            refs_by_oid.entry(target).or_default().push(name);
        }

        let mut walk = self.repo.revwalk()?;
        walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
        walk.push_head()?;
        let mut entries = Vec::new();
        for oid in walk.take(limit) {
            let oid = oid?;
            let commit = self.repo.find_commit(oid)?;
            let full = oid.to_string();
            entries.push(LogEntry {
                oid7: short7(&full),
                oid: full,
                refs: refs_by_oid.get(&oid).cloned().unwrap_or_default(),
                subject: commit.summary()?.unwrap_or_default().to_owned(),
                author: commit.author().name().unwrap_or_default().to_owned(),
                time_unix: commit.time().seconds(),
            });
        }
        Ok(entries)
    }

    fn default_branch(&self, remote: &str) -> Result<Option<String>, VcsError> {
        // the remote's own HEAD is authoritative; it exists once the remote
        // has been cloned or fetched with `--set-head`
        let head_ref = format!("refs/remotes/{remote}/HEAD");
        let prefix = format!("refs/remotes/{remote}/");
        if let Ok(reference) = self.repo.find_reference(&head_ref)
            && let Ok(Some(target)) = reference.symbolic_target()
            // the whole remainder, so a branch named `release/2.x` survives
            && let Some(name) = target.strip_prefix(prefix.as_str())
        {
            return Ok(Some(name.to_owned()));
        }
        for name in ["main", "master"] {
            if self
                .repo
                .find_branch(name, git2::BranchType::Local)
                .or_else(|_| {
                    self.repo
                        .find_branch(&format!("{remote}/{name}"), git2::BranchType::Remote)
                })
                .is_ok()
            {
                return Ok(Some(name.to_owned()));
            }
        }
        Ok(None)
    }

    fn commits_between(&self, base: &str, head: &str) -> Result<Vec<LogEntry>, VcsError> {
        let (base, head) = (
            self.repo.revparse_single(base)?,
            self.repo.revparse_single(head)?,
        );
        let mut walk = self.repo.revwalk()?;
        walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
        walk.push(head.id())?;
        walk.hide(base.id())?;
        self.walk_entries(walk, usize::MAX)
    }

    fn unpushed(&self, limit: usize) -> Result<Option<Vec<LogEntry>>, VcsError> {
        let Ok(head) = self.repo.head() else {
            return Ok(None);
        };
        let mut walk = self.repo.revwalk()?;
        walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
        walk.push(head.peel_to_commit()?.id())?;
        let mut remotes = 0;
        for reference in self.repo.references()? {
            let reference = reference?;
            // a symbolic ref (origin/HEAD) has no target of its own and its
            // destination is hidden anyway
            if let (true, Some(oid)) = (reference.is_remote(), reference.target()) {
                remotes += 1;
                walk.hide(oid)?;
            }
        }
        if remotes == 0 {
            return Ok(None);
        }
        self.walk_entries(walk, limit).map(Some)
    }

    fn blame(&self, rel: &Path) -> Result<Vec<BlameSpan>, VcsError> {
        let mut options = git2::BlameOptions::new();
        options.track_copies_same_file(true);
        let blame = self.repo.blame_file(rel, Some(&mut options))?;
        // blame_file only knows committed content, so an edited worktree would
        // report the wrong line for everything below the edit; blame_buffer
        // re-maps the spans onto what is actually on disk.
        let workdir = self.workdir()?.join(rel);
        let blame = match fs::read(&workdir) {
            Ok(bytes) => blame.blame_buffer(&bytes)?,
            Err(_) => blame,
        };

        let mut out = Vec::new();
        for hunk in blame.iter() {
            let oid = hunk.final_commit_id();
            let commit = self.repo.find_commit(oid).ok();
            let full = oid.to_string();
            out.push(BlameSpan {
                start_line: u32::try_from(hunk.final_start_line()).unwrap_or(u32::MAX),
                line_count: u32::try_from(hunk.lines_in_hunk()).unwrap_or(u32::MAX),
                oid7: short7(&full),
                oid: full,
                author: commit
                    .as_ref()
                    .map(|c| c.author().name().unwrap_or_default().to_owned())
                    .unwrap_or_default(),
                time_unix: commit.as_ref().map_or(0, |c| c.time().seconds()),
                summary: commit
                    .as_ref()
                    .and_then(|c| c.summary().ok().flatten().map(str::to_owned))
                    .unwrap_or_default(),
                committed: !oid.is_zero(),
            });
        }
        out.sort_by_key(|span| span.start_line);
        Ok(out)
    }

    fn read_at(&self, rev: &str, path: &str) -> Result<Option<String>, VcsError> {
        let commit = self.repo.revparse_single(rev)?.peel_to_commit()?;
        match commit.tree()?.get_path(Path::new(path)) {
            Ok(entry) => Ok(blob_text(&self.repo, entry.id())),
            Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
            Err(err) => Err(err.into()),
        }
    }

    fn tracked_files(&self) -> Result<Vec<PathBuf>, VcsError> {
        let index = self.repo.index()?;
        let mut out: Vec<PathBuf> = index
            .iter()
            .filter_map(|entry| {
                std::str::from_utf8(&entry.path)
                    .ok()
                    .map(|path| PathBuf::from(path.to_owned()))
            })
            .collect();
        out.sort_unstable();
        out.dedup();
        Ok(out)
    }

    fn attr(&self, rel: &Path, name: &str) -> bool {
        let Ok(value) = self.repo.get_attr(rel, name, git2::AttrCheckFlags::empty()) else {
            return false;
        };
        // both spellings are in the wild: a bare `linguist-generated` sets
        // git's boolean, while the `=true` GitHub documents is a string value
        matches!(
            git2::AttrValue::from_string(value),
            git2::AttrValue::True | git2::AttrValue::String("true")
        )
    }

    fn branches(&self) -> Result<Vec<BranchInfo>, VcsError> {
        let mut out = Vec::new();
        for entry in self.repo.branches(Some(git2::BranchType::Local))? {
            let (branch, _) = entry?;
            let Some(name) = branch.name()?.map(str::to_owned) else {
                continue;
            };
            let tip_unix = branch
                .get()
                .peel_to_commit()
                .ok()
                .map_or(0, |commit| commit.time().seconds());
            out.push(BranchInfo {
                name,
                is_head: branch.is_head(),
                tip_unix,
                divergence: None,
            });
        }
        Ok(out)
    }

    fn divergence(&self, branch: &str) -> Result<Option<(usize, usize)>, VcsError> {
        let branch = self.repo.find_branch(branch, git2::BranchType::Local)?;
        let Some(tip) = branch.get().peel_to_commit().ok() else {
            return Ok(None);
        };
        let Some(target) = branch.upstream().ok().and_then(|up| up.get().target()) else {
            return Ok(None);
        };
        Ok(Some(self.repo.graph_ahead_behind(tip.id(), target)?))
    }

    fn all_branches(&self) -> Result<Vec<String>, VcsError> {
        let mut out = Vec::new();
        for entry in self.repo.branches(None)? {
            let (branch, _) = entry?;
            let Some(name) = branch.name()?.map(str::to_owned) else {
                continue;
            };
            // refs/remotes/<remote>/HEAD is a symbolic alias, not a branch
            if name.ends_with("/HEAD") {
                continue;
            }
            out.push(name);
        }
        Ok(out)
    }

    fn stage(&self, rel: &Path) -> Result<(), VcsError> {
        let root = self.workdir_path()?;
        let mut index = self.repo.index()?;
        if root.join(rel).exists() {
            index.add_path(rel)?;
        } else {
            index.remove_path(rel)?;
        }
        index.write()?;
        Ok(())
    }

    fn stage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError> {
        let diff = self
            .repo
            .diff_index_to_workdir(None, Some(&mut self.workdir_diff_options()))?;
        let patch = self.synthesize_patch(&diff, rel, hunk, false)?;
        let diff = git2::Diff::from_buffer(&patch)?;
        self.repo.apply(&diff, git2::ApplyLocation::Index, None)?;
        Ok(())
    }

    fn stage_everything(&self) -> Result<(), VcsError> {
        let mut index = self.repo.index()?;
        // update_all catches deletions and edits to files already tracked;
        // add_all then picks up whatever is untracked
        index.update_all(["*"], None)?;
        index.add_all(["*"], git2::IndexAddOption::DEFAULT, None)?;
        index.write()?;
        Ok(())
    }

    fn unstage_everything(&self) -> Result<(), VcsError> {
        match self.repo.head() {
            Ok(head) => {
                let target = head.peel(git2::ObjectType::Commit)?;
                self.repo.reset_default(Some(&target), ["*"])?;
            }
            // unborn branch: nothing in HEAD to restore, so empty the index
            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
                let mut index = self.repo.index()?;
                index.clear()?;
                index.write()?;
            }
            Err(err) => return Err(err.into()),
        }
        Ok(())
    }

    fn unstage(&self, rel: &Path) -> Result<(), VcsError> {
        match self.repo.head() {
            Ok(head) => {
                let target = head.peel(git2::ObjectType::Commit)?;
                self.repo.reset_default(Some(&target), [rel])?;
            }
            // unborn branch: there is no HEAD entry to restore, drop from index
            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => {
                let mut index = self.repo.index()?;
                index.remove_path(rel)?;
                index.write()?;
            }
            Err(err) => return Err(err.into()),
        }
        Ok(())
    }

    fn unstage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError> {
        let head_tree = self.head_tree()?;
        let diff = self.repo.diff_tree_to_index(
            head_tree.as_ref(),
            None,
            Some(&mut self.plain_diff_options()),
        )?;
        let patch = self.synthesize_patch(&diff, rel, hunk, true)?;
        let diff = git2::Diff::from_buffer(&patch)?;
        self.repo.apply(&diff, git2::ApplyLocation::Index, None)?;
        Ok(())
    }

    fn discard(&self, rel: &Path) -> Result<(), VcsError> {
        let head_tree = self.head_tree()?;
        let mut opts = git2::DiffOptions::new();
        opts.pathspec(rel).disable_pathspec_match(true);
        let staged = self
            .repo
            .diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts))?;
        if staged.deltas().len() > 0 {
            return Err(VcsError::Rejected(
                "file has staged changes; unstage first".into(),
            ));
        }
        let status = self.repo.status_file(rel)?;
        if status.contains(git2::Status::WT_NEW) {
            fs::remove_file(self.workdir_path()?.join(rel))?;
            return Ok(());
        }
        // refresh the index stat cache to match the file we just wrote. with
        // autocrlf the checkout smudges LF->CRLF, growing the file; leaving the
        // cached stat stale makes git report a phantom modification (size
        // mismatch defeats the racy-clean check) even though the content is
        // identical to HEAD. the file has no staged changes here, so the index
        // blob already equals HEAD and updating it only corrects the metadata.
        let mut checkout = git2::build::CheckoutBuilder::new();
        checkout.path(rel).force().update_index(true);
        self.repo.checkout_head(Some(&mut checkout))?;
        Ok(())
    }

    fn commit(&self, message: &str) -> Result<String, VcsError> {
        if message.trim().is_empty() {
            return Err(VcsError::Rejected("empty commit message".into()));
        }
        let mut index = self.repo.index()?;
        let tree_id = index.write_tree()?;
        let tree = self.repo.find_tree(tree_id)?;
        let signature = self.repo.signature()?;
        let parent = match self.repo.head() {
            Ok(head) => Some(head.peel_to_commit()?),
            Err(err) if err.code() == git2::ErrorCode::UnbornBranch => None,
            Err(err) => return Err(err.into()),
        };
        let parents: Vec<&git2::Commit<'_>> = parent.iter().collect();
        let oid = self.repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &parents,
        )?;
        Ok(oid.to_string())
    }

    fn head_message(&self) -> Result<String, VcsError> {
        let commit = self.repo.head()?.peel_to_commit()?;
        Ok(commit.message().unwrap_or_default().to_owned())
    }

    fn amend(&self, message: Option<&str>, use_index: bool) -> Result<String, VcsError> {
        if let Some(message) = message
            && message.trim().is_empty()
        {
            return Err(VcsError::Rejected("empty commit message".into()));
        }
        let head = self.repo.head()?.peel_to_commit()?;
        // extend/amend fold the staged index into the new tree; a pure reword
        // keeps HEAD's tree so only the message changes
        let tree = if use_index {
            let mut index = self.repo.index()?;
            let tree_id = index.write_tree()?;
            self.repo.find_tree(tree_id)?
        } else {
            head.tree()?
        };
        let oid = head.amend(Some("HEAD"), None, None, None, message, Some(&tree))?;
        Ok(oid.to_string())
    }

    fn create_branch(&self, name: &str, checkout: bool) -> Result<(), VcsError> {
        let head = self.repo.head()?.peel_to_commit()?;
        self.repo.branch(name, &head, false)?;
        if checkout {
            self.checkout(name)?;
        }
        Ok(())
    }

    fn delete_branch(&self, name: &str) -> Result<(), VcsError> {
        let mut branch = self.repo.find_branch(name, git2::BranchType::Local)?;
        if branch.is_head() {
            return Err(VcsError::Rejected(
                "cannot delete the checked-out branch".into(),
            ));
        }
        branch.delete()?;
        Ok(())
    }

    fn checkout(&self, name: &str) -> Result<(), VcsError> {
        let branch = self.repo.find_branch(name, git2::BranchType::Local)?;
        let target = branch.get().peel(git2::ObjectType::Commit)?;
        // safe (non-force) checkout: refuses to clobber local modifications
        self.repo.checkout_tree(&target, None)?;
        self.repo.set_head(&format!("refs/heads/{name}"))?;
        Ok(())
    }

    fn stash_push(&self, message: Option<&str>) -> Result<(), VcsError> {
        if !self.has_tracked_changes()? {
            return Err(VcsError::Rejected("nothing to stash".into()));
        }
        // git2 stash mutates the repo, but the trait is &self; a fresh handle on
        // the same workdir gives the &mut without threading mutability everywhere
        let mut repo = git2::Repository::open(self.workdir_path()?)?;
        let signature = repo.signature()?;
        repo.stash_save2(&signature, message, None)?;
        Ok(())
    }

    fn stash_pop(&self) -> Result<(), VcsError> {
        let mut repo = git2::Repository::open(self.workdir_path()?)?;
        match repo.stash_pop(0, None) {
            Ok(()) => Ok(()),
            Err(err) if err.code() == git2::ErrorCode::NotFound => {
                Err(VcsError::Rejected("no stash to pop".into()))
            }
            // a conflicting pop leaves the merge in the worktree and keeps the
            // stash entry; say so rather than surfacing a bare libgit2 error
            Err(err) if err.code() == git2::ErrorCode::Conflict => Err(VcsError::Rejected(
                "stash applied with conflicts; resolve them (the stash was kept)".into(),
            )),
            Err(err) => Err(err.into()),
        }
    }

    fn network_argv(&self, op: NetworkOp) -> Result<Vec<String>, VcsError> {
        // shelling to `git` (not git2) so the user's credential helper, SSH
        // agent, and config drive auth
        let args: Vec<String> = match op {
            NetworkOp::Fetch => vec!["fetch".into()],
            NetworkOp::FetchAll => vec!["fetch".into(), "--all".into()],
            NetworkOp::Push => vec!["push".into()],
            NetworkOp::PushSetUpstream { remote } => {
                vec!["push".into(), "-u".into(), remote, "HEAD".into()]
            }
            NetworkOp::Pull => vec!["pull".into()],
            NetworkOp::PullFrom { remote, branch } => vec!["pull".into(), remote, branch],
            NetworkOp::PullRebase => vec!["pull".into(), "--rebase".into()],
            NetworkOp::PullMerge => vec!["pull".into(), "--no-rebase".into()],
        };
        Ok(std::iter::once("git".to_owned()).chain(args).collect())
    }

    fn workdir(&self) -> Result<PathBuf, VcsError> {
        Ok(self.workdir_path()?.to_path_buf())
    }

    fn remote_url(&self, name: &str) -> Result<Option<String>, VcsError> {
        match self.repo.find_remote(name) {
            // url() errs only on a non-UTF-8 remote URL; treat that as no URL
            Ok(remote) => Ok(remote.url().ok().map(str::to_owned)),
            Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
            Err(err) => Err(err.into()),
        }
    }

    fn remotes(&self) -> Result<Vec<String>, VcsError> {
        let array = self.repo.remotes()?;
        let mut names = Vec::new();
        for i in 0..array.len() {
            if let Ok(Some(name)) = array.get(i) {
                names.push(name.to_owned());
            }
        }
        Ok(names)
    }

    fn set_diff_algorithm(&self, algorithm: DiffAlgorithm, indent_heuristic: bool) {
        self.algorithm.set(algorithm);
        self.indent_heuristic.set(indent_heuristic);
    }
}

/// `DiffOptions` flags for the git2-native algorithms (myers is git2's
/// default, so it sets nothing); `Histogram`/`Structural` have no git2 flag
/// and go through [`GitVcs::imara_hunks`] instead.
fn apply_git_algorithm(
    opts: &mut git2::DiffOptions,
    algorithm: DiffAlgorithm,
    indent_heuristic: bool,
) {
    match algorithm {
        DiffAlgorithm::Minimal => {
            opts.minimal(true);
        }
        DiffAlgorithm::Patience => {
            opts.patience(true);
        }
        DiffAlgorithm::Myers | DiffAlgorithm::Histogram | DiffAlgorithm::Structural => {}
    }
    opts.indent_heuristic(indent_heuristic);
}

impl GitVcs {
    /// Render one hunk of `rel` as a unified patch libgit2 can apply to the
    /// index. `reverse` flips the patch so applying it undoes a staged hunk.
    fn synthesize_patch(
        &self,
        diff: &git2::Diff<'_>,
        rel: &Path,
        target: &HunkId,
        reverse: bool,
    ) -> Result<Vec<u8>, VcsError> {
        let rel = rel.to_string_lossy();
        for idx in 0..diff.deltas().len() {
            let Some(patch) = git2::Patch::from_diff(diff, idx)? else {
                continue;
            };
            // we take `delta` from the patch: loading the patch is what
            // fills in the worktree side's id that `imara_hunks` checks
            // against
            let delta = patch.delta();
            if delta.flags().is_binary() || delta_new_path(&delta) != rel {
                continue;
            }
            if self.algorithm.get().is_imara() {
                let old_text = blob_text(&self.repo, delta.old_file().id());
                let new_text = new_side_text(&self.repo, &delta, &rel);
                let (old, new) = (old_text.as_deref(), new_text.as_deref());
                if let Some(hunks) = self.imara_hunks(&delta, old, new, &rel)
                    && let (Some(old), Some(new)) = (old, new)
                {
                    if let Some(hunk) = hunks.iter().find(|h| h.id == *target) {
                        return Ok(render_hunk_patch_from_model(hunk, &rel, reverse, old, new));
                    }
                    continue;
                }
            }
            let mut seen = HashMap::new();
            for h in 0..patch.num_hunks() {
                let lines = hunk_model_lines(&patch, h)?;
                if disambiguated_hunk_id(&rel, &lines, &mut seen) == *target {
                    return render_hunk_patch(&patch, h, &rel, delta.status(), reverse);
                }
            }
        }
        Err(VcsError::Rejected("hunk not found (diff changed?)".into()))
    }

    fn build_file(
        &self,
        diff: &mut git2::Diff<'_>,
        idx: usize,
    ) -> Result<Option<FileDiff>, VcsError> {
        let repo = &self.repo;
        let Some(patch) = git2::Patch::from_diff(diff, idx)? else {
            // binary or unreadable: fall back to delta metadata only
            return Ok(build_binary_file(diff, idx));
        };
        let delta = patch.delta();
        if delta.flags().is_binary() {
            return Ok(build_binary_file(diff, idx));
        }
        let file_path = delta_new_path(&delta);
        let status = map_status(delta.status());
        let old_path = if status == FileStatus::Renamed {
            delta
                .old_file()
                .path()
                .map(|p| p.to_string_lossy().into_owned())
        } else {
            None
        };

        let old_text = blob_text(repo, delta.old_file().id());
        let new_text = new_side_text(repo, &delta, &file_path);

        let imara = self.imara_hunks(&delta, old_text.as_deref(), new_text.as_deref(), &file_path);
        let hunks = match imara {
            Some(hunks) => hunks,
            None => patch_hunks(&patch, &file_path)?,
        };

        Ok(Some(FileDiff {
            path: file_path,
            old_path,
            status,
            binary: false,
            old_text,
            new_text,
            hunks,
            hashes: crate::model::HashCache::default(),
        }))
    }
}

fn render_hunk_patch(
    patch: &git2::Patch<'_>,
    h: usize,
    rel: &str,
    status: git2::Delta,
    reverse: bool,
) -> Result<Vec<u8>, VcsError> {
    let added = matches!(status, git2::Delta::Added | git2::Delta::Untracked);
    let deleted = status == git2::Delta::Deleted;
    let mut out = Vec::new();
    out.extend_from_slice(format!("diff --git a/{rel} b/{rel}\n").as_bytes());
    // whole-file adds and deletes must keep that identity (with the sides
    // swapped under reverse) so applying creates or drops the index entry
    // instead of leaving an empty blob behind
    if (added && !reverse) || (deleted && reverse) {
        out.extend_from_slice(
            format!("new file mode 100644\n--- /dev/null\n+++ b/{rel}\n").as_bytes(),
        );
    } else if (deleted && !reverse) || (added && reverse) {
        out.extend_from_slice(
            format!("deleted file mode 100644\n--- a/{rel}\n+++ /dev/null\n").as_bytes(),
        );
    } else {
        out.extend_from_slice(format!("--- a/{rel}\n+++ b/{rel}\n").as_bytes());
    }
    let (hunk, line_count) = patch.hunk(h)?;
    let mut lines: Vec<(LineKind, Vec<u8>)> = Vec::with_capacity(line_count);
    for l in 0..line_count {
        let line = patch.line_in_hunk(h, l)?;
        let kind = match line.origin() {
            ' ' => LineKind::Context,
            '+' => LineKind::Added,
            '-' => LineKind::Deleted,
            // EOF-newline markers already carry the full "\ No newline at
            // end of file" text, including the newline that terminates the
            // preceding unterminated line, so they ride along with that line
            '=' | '>' | '<' => {
                if let Some((_, text)) = lines.last_mut() {
                    text.extend_from_slice(line.content());
                }
                continue;
            }
            _ => continue,
        };
        lines.push((kind, line.content().to_vec()));
    }
    write_hunk(
        &mut out,
        (hunk.old_start(), hunk.old_lines()),
        (hunk.new_start(), hunk.new_lines()),
        &lines,
        reverse,
    );
    Ok(out)
}

/// One hunk's `@@` header (`old`/`new` are start and count, git's way) and
/// lines, sent to libgit2 alone. Each line's bytes arrive terminated, an
/// EOF-newline marker included.
fn write_hunk(
    out: &mut Vec<u8>,
    old: (u32, u32),
    new: (u32, u32),
    lines: &[(LineKind, Vec<u8>)],
    reverse: bool,
) {
    let ((minus_start, minus_lines), (_, plus_lines)) =
        if reverse { (new, old) } else { (old, new) };
    // libgit2 applies a hunk at its `+` start, and we send this hunk without
    // the ones before it, so we point that start at the minus side's
    // position; git's header gives an empty side the line before the change
    let plus_start = if minus_lines == 0 {
        minus_start + 1
    } else {
        minus_start
    };
    out.extend_from_slice(
        format!("@@ -{minus_start},{minus_lines} +{plus_start},{plus_lines} @@\n").as_bytes(),
    );
    // minus lines go first in a change run even under `reverse`: libgit2
    // rejects a `+` line marked "No newline at end of file" before a `-` one
    let (minus_kind, plus_kind) = if reverse {
        (LineKind::Added, LineKind::Deleted)
    } else {
        (LineKind::Deleted, LineKind::Added)
    };
    let is_context = |kind: LineKind| kind == LineKind::Context;
    for run in lines.chunk_by(|a, b| is_context(a.0) == is_context(b.0)) {
        for (origin, kind) in [
            (b' ', LineKind::Context),
            (b'-', minus_kind),
            (b'+', plus_kind),
        ] {
            for (_, text) in run.iter().filter(|(k, _)| *k == kind) {
                out.push(origin);
                out.extend_from_slice(text);
            }
        }
    }
}

/// [`render_hunk_patch`] for a hunk of a modified file that imara-diff
/// computed. Each line is copied from `old_text`/`new_text` byte for byte,
/// its own terminator included, since the model's text has CR and LF
/// stripped.
fn render_hunk_patch_from_model(
    hunk: &Hunk,
    rel: &str,
    reverse: bool,
    old_text: &str,
    new_text: &str,
) -> Vec<u8> {
    let old_raw: Vec<&str> = old_text.split_inclusive('\n').collect();
    let new_raw: Vec<&str> = new_text.split_inclusive('\n').collect();
    let raw = |line: &DiffLine| -> Vec<u8> {
        let (side, number) = match line.kind {
            LineKind::Added => (&new_raw, line.new_no),
            LineKind::Deleted | LineKind::Context => (&old_raw, line.old_no),
        };
        let text = number
            .and_then(|n| n.checked_sub(1))
            .and_then(|i| side.get(i as usize))
            .copied()
            .unwrap_or_default();
        let mut bytes = text.as_bytes().to_vec();
        if !text.ends_with('\n') {
            bytes.extend_from_slice(b"\n\\ No newline at end of file\n");
        }
        bytes
    };
    let lines: Vec<(LineKind, Vec<u8>)> = hunk.lines.iter().map(|l| (l.kind, raw(l))).collect();

    let mut out = format!("diff --git a/{rel} b/{rel}\n--- a/{rel}\n+++ b/{rel}\n").into_bytes();
    write_hunk(
        &mut out,
        (hunk.old_start, hunk.old_lines),
        (hunk.new_start, hunk.new_lines),
        &lines,
        reverse,
    );
    out
}

fn short7(oid: &str) -> String {
    oid.get(..7).unwrap_or(oid).to_owned()
}

/// Re-diff a file's own old/new text at `context` lines of surrounding
/// context (`u32::MAX` for the whole file) and `algorithm`, yielding the
/// hunks the diff pane would show at that context. `None` for binary files or
/// when a side's text is absent, so the caller keeps its current hunks.
pub fn rehunk_file(
    file: &FileDiff,
    context: u32,
    algorithm: DiffAlgorithm,
    indent_heuristic: bool,
) -> Option<Vec<Hunk>> {
    if file.binary {
        return None;
    }
    let (old, new) = (file.old_text.as_deref()?, file.new_text.as_deref()?);
    if algorithm.is_imara() {
        return Some(histogram_hunks(
            old,
            new,
            &file.path,
            context,
            indent_heuristic,
        ));
    }
    let as_path = Path::new(&file.path);
    // libgit2's context math overflows on a huge value (the whole-file
    // sentinel u32::MAX), yielding zero context on some platforms; the line
    // count is enough to show the whole file and stays in range everywhere
    let cap = u32::try_from(old.lines().count().max(new.lines().count())).unwrap_or(u32::MAX);
    let mut opts = git2::DiffOptions::new();
    opts.context_lines(context.min(cap));
    apply_git_algorithm(&mut opts, algorithm, indent_heuristic);
    let patch = git2::Patch::from_buffers(
        old.as_bytes(),
        Some(as_path),
        new.as_bytes(),
        Some(as_path),
        Some(&mut opts),
    )
    .ok()?;
    patch_hunks(&patch, &file.path).ok()
}

/// Assemble model hunks from a git2 patch. Shared by the initial diff and the
/// context re-diff so line numbers, ids, and section headings can't drift.
fn patch_hunks(patch: &git2::Patch<'_>, file_path: &str) -> Result<Vec<Hunk>, VcsError> {
    let mut hunks = Vec::with_capacity(patch.num_hunks());
    let mut seen = HashMap::new();
    for h in 0..patch.num_hunks() {
        let (hunk, _) = patch.hunk(h)?;
        let lines = hunk_model_lines(patch, h)?;
        let id = disambiguated_hunk_id(file_path, &lines, &mut seen);
        hunks.push(Hunk {
            id,
            old_start: hunk.old_start(),
            old_lines: hunk.old_lines(),
            new_start: hunk.new_start(),
            new_lines: hunk.new_lines(),
            context: hunk_context(&hunk),
            lines,
        });
    }
    Ok(hunks)
}

/// git's section heading for a hunk: the text git appends after the second
/// `@@` of the header (`@@ -a,b +c,d @@ <context>`), typically the enclosing
/// function or section. Empty when git emits none (e.g. a top-of-file hunk).
fn hunk_context(hunk: &git2::DiffHunk<'_>) -> String {
    let header = String::from_utf8_lossy(hunk.header());
    match header.split_once(" @@") {
        Some((_, rest)) => rest.trim_matches(['\n', '\r', ' ']).to_owned(),
        None => String::new(),
    }
}

/// Content lines of one hunk as model lines (headers and EOF-newline markers
/// excluded). Shared by model building and hunk lookup so the hunk ids
/// computed in both places agree.
fn hunk_model_lines(patch: &git2::Patch<'_>, h: usize) -> Result<Vec<DiffLine>, VcsError> {
    let (_, line_count) = patch.hunk(h)?;
    let mut lines = Vec::with_capacity(line_count);
    for l in 0..line_count {
        let line = patch.line_in_hunk(h, l)?;
        let kind = match line.origin() {
            '-' => LineKind::Deleted,
            '+' => LineKind::Added,
            ' ' => LineKind::Context,
            // headers, EOF-newline markers etc. are not content lines
            _ => continue,
        };
        let text = String::from_utf8_lossy(line.content())
            .trim_end_matches(['\n', '\r'])
            .to_owned();
        lines.push(DiffLine::new(
            kind,
            line.old_lineno(),
            line.new_lineno(),
            text,
        ));
    }
    Ok(lines)
}

fn build_binary_file(diff: &git2::Diff<'_>, idx: usize) -> Option<FileDiff> {
    let delta = diff.get_delta(idx)?;
    Some(FileDiff {
        path: delta_new_path(&delta),
        old_path: None,
        status: map_status(delta.status()),
        binary: true,
        old_text: None,
        new_text: None,
        hunks: Vec::new(),
        hashes: crate::model::HashCache::default(),
    })
}

fn delta_new_path(delta: &git2::DiffDelta<'_>) -> String {
    delta
        .new_file()
        .path()
        .or_else(|| delta.old_file().path())
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_default()
}

fn map_status(status: git2::Delta) -> FileStatus {
    match status {
        git2::Delta::Added => FileStatus::Added,
        git2::Delta::Deleted => FileStatus::Deleted,
        git2::Delta::Renamed => FileStatus::Renamed,
        git2::Delta::Untracked => FileStatus::Untracked,
        _ => FileStatus::Modified,
    }
}

fn blob_text(repo: &git2::Repository, oid: git2::Oid) -> Option<String> {
    if oid.is_zero() {
        return None;
    }
    let blob = repo.find_blob(oid).ok()?;
    if blob.is_binary() {
        return None;
    }
    String::from_utf8(blob.content().to_vec()).ok()
}

/// New-side content: the recorded blob when the diff target is a tree or the
/// index (where the workdir may differ), the workdir file otherwise.
fn new_side_text(
    repo: &git2::Repository,
    delta: &git2::DiffDelta<'_>,
    rel: &str,
) -> Option<String> {
    if delta.status() == git2::Delta::Deleted {
        return None;
    }
    if let Some(text) = blob_text(repo, delta.new_file().id()) {
        return Some(text);
    }
    let root = repo.workdir()?;
    fs::read_to_string(root.join(rel)).ok()
}