gitpoulpi-git2-backend 1.3.0

GitBackend implementation over libgit2 (git2 crate), decorating gitpoulpi-cli-backend for operations git2 doesn't support natively.
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use gitpoulpi_core::domain::{
    finish_hits, grep_bytes, usable_terms, Blame, BlameContent, BlameLine, Blob, BlobBody,
    BlobBytes, BlobContent, BlobSource, ConflictEntry, GrepHit, ImageInfo, MergeDocument, Oid,
    RawStage, RepoRef, StageEntry, Worktree, MAX_GREP_FILE_BYTES, MAX_TEXT_BLOB_BYTES,
    MODE_GITLINK,
};
#[cfg(feature = "submodule")]
use gitpoulpi_core::domain::{Submodule, SubmoduleState};
use gitpoulpi_core::{Error, Result};

use crate::repo::{map_err, open, to_domain_oid, to_git2_oid};

/// `git2::Repository::worktrees()` lists only *linked* worktrees, so the
/// main one is synthesized here from the common dir - see [`Worktree`]
/// for why the contract requires it to be present and first.
pub fn worktrees(repo: &RepoRef) -> Result<Vec<Worktree>> {
    let git_repo = open(repo)?;

    // The shared `.git` directory's parent is the main worktree, even
    // when `repo` points at a linked one.
    let common = common_git_dir(&git_repo);
    let main_path = common
        .parent()
        .map(PathBuf::from)
        .unwrap_or_else(|| common.clone());

    // Linked worktrees first (cheap admin-dir reads), then every branch
    // lookup (one `Repository::open` per worktree, the dominant cost) on
    // scoped threads, so N worktrees cost about one open.
    let mut linked: Vec<(PathBuf, bool)> = Vec::new();
    for name in git_repo
        .worktrees()
        .map_err(map_err)?
        .iter()
        .flatten()
        .flatten()
    {
        let wt = match git_repo.find_worktree(name) {
            Ok(wt) => wt,
            // A worktree whose directory was deleted without
            // `git worktree prune` still has an admin entry; skip it
            // rather than failing the whole listing.
            Err(_) => continue,
        };
        let locked = matches!(wt.is_locked(), Ok(git2::WorktreeLockStatus::Locked(_)));
        linked.push((wt.path().to_path_buf(), locked));
    }

    let mut paths: Vec<&Path> = vec![main_path.as_path()];
    paths.extend(linked.iter().map(|(p, _)| p.as_path()));
    let branches: Vec<Option<String>> = std::thread::scope(|scope| {
        let handles: Vec<_> = paths
            .iter()
            .map(|p| scope.spawn(move || branch_at(p)))
            .collect();
        handles
            .into_iter()
            .map(|h| h.join().unwrap_or(None))
            .collect()
    });
    let mut branches = branches.into_iter();

    let mut out = vec![Worktree {
        branch: branches.next().flatten(),
        path: main_path.clone(),
        is_main: true,
        is_locked: false,
    }];
    for ((path, is_locked), branch) in linked.into_iter().zip(branches) {
        out.push(Worktree {
            branch,
            path,
            is_main: false,
            is_locked,
        });
    }

    Ok(out)
}

/// `true` when the repository provably has no unmerged paths, so the
/// caller can skip the `git diff --diff-filter=U` process (100-300 ms on
/// Windows, paid by every refresh). `false` means "possibly": ask git.
pub fn provably_no_conflicts(repo: &RepoRef) -> bool {
    open(repo)
        .and_then(|r| r.index().map_err(map_err))
        .map(|index| !index.has_conflicts())
        .unwrap_or(false)
}

/// `true` when no rebase is in progress: neither `rebase-merge` nor
/// `rebase-apply` exists in the git directory (the first test
/// `SystemGitBackend::rebase_state` makes). Saves a `git rev-parse
/// --absolute-git-dir` spawn on every refresh.
pub fn provably_no_rebase(repo: &RepoRef) -> bool {
    open(repo)
        .map(|r| {
            let dir = r.path();
            !dir.join("rebase-merge").exists() && !dir.join("rebase-apply").exists()
        })
        .unwrap_or(false)
}

/// The shared `.git` directory. git2 0.19 exposes no `commondir()`, but
/// a linked worktree's own git dir (`<main>/.git/worktrees/<name>`)
/// contains a `commondir` file pointing back at the shared one; without
/// that file we already are the main repo.
fn common_git_dir(repo: &git2::Repository) -> PathBuf {
    let git_dir = repo.path();
    let common = gitpoulpi_core::paths::common_dir(git_dir);
    if common == git_dir {
        return common;
    }
    std::fs::canonicalize(&common).unwrap_or(common)
}

/// Short branch name checked out at `path`, or `None` when HEAD is
/// detached, unborn, or the path isn't readable as a repo.
fn branch_at(path: &std::path::Path) -> Option<String> {
    let repo = git2::Repository::open(path).ok()?;
    let head = repo.head().ok()?;
    if !head.is_branch() {
        return None;
    }
    head.shorthand().ok().map(str::to_string)
}

/// See `GitBackend::read_blob`.
///
/// The size is learned from the object database's *header*
/// (`odb.read_header`), so a 400 MiB file is rejected without being
/// loaded; the working-tree case does the same with `fs::metadata`.
///
/// The working tree is read straight off disk, never through `git show
/// :path` or a checkout, which apply smudge filters and would return a
/// *filtered* rendering instead of the bytes an editor would open.
pub fn read_blob(repo: &RepoRef, path: &Path, source: &BlobSource) -> Result<Blob> {
    let rel = repo_relative(path)?;
    let (size, content, image) = match source {
        BlobSource::WorkingTree => {
            let full = repo.root.join(&rel);
            let size = std::fs::metadata(&full)
                .map_err(|e| Error::Backend(format!("{rel}: {e}")))?
                .len();
            if size > MAX_TEXT_BLOB_BYTES {
                (size, BlobContent::TooLarge, None)
            } else {
                let raw =
                    std::fs::read(&full).map_err(|e| Error::Backend(format!("{rel}: {e}")))?;
                let content = BlobContent::from_bytes(&raw);
                let image = Blob::image_of(&content, &raw);
                (size, content, image)
            }
        }
        _ => {
            let git_repo = open(repo)?;
            read_odb_blob(&git_repo, object_id(&git_repo, &rel, source)?)?
        }
    };

    Ok(Blob {
        path: PathBuf::from(rel),
        source: source.clone(),
        size,
        content,
        image,
    })
}

/// The object id of `rel` at an index or commit `source`.
fn object_id(git_repo: &git2::Repository, rel: &str, source: &BlobSource) -> Result<git2::Oid> {
    match source {
        BlobSource::WorkingTree => Err(Error::Backend("the working tree has no object".into())),
        BlobSource::Index => {
            let index = git_repo.index().map_err(map_err)?;
            // Stage 0 only: an unmerged path has stages 1/2/3 and no
            // single "the staged content", so it is an error here rather
            // than an arbitrary side silently winning.
            let entry = index
                .get_path(Path::new(rel), 0)
                .ok_or_else(|| Error::Backend(format!("{rel} is not in the index")))?;
            Ok(entry.id)
        }
        BlobSource::Stage(stage) => {
            let index = git_repo.index().map_err(map_err)?;
            let entry = (1..=3)
                .contains(stage)
                .then(|| index.get_path(Path::new(rel), i32::from(*stage)));
            entry
                .flatten()
                .map(|e| e.id)
                .ok_or_else(|| Error::Backend(format!("{rel} has no stage {stage}")))
        }
        BlobSource::Commit(oid) => {
            let commit = git_repo.find_commit(to_git2_oid(*oid)?).map_err(map_err)?;
            let tree = commit.tree().map_err(map_err)?;
            let entry = tree
                .get_path(Path::new(rel))
                .map_err(|_| Error::Backend(format!("{rel} is not in commit {oid}")))?;
            if entry.kind() != Some(git2::ObjectType::Blob) {
                return Err(Error::Backend(format!("{rel} is not a file at {oid}")));
            }
            Ok(entry.id())
        }
    }
}

/// See `GitBackend::read_blob_bytes`. Same size-before-content rule as
/// [`read_blob`]; an LFS pointer is resolved by the system-git backend's
/// shared helper so both backends answer alike.
pub fn read_blob_bytes(
    repo: &RepoRef,
    path: &Path,
    source: &BlobSource,
    max: u64,
) -> Result<BlobBytes> {
    let rel = repo_relative(path)?;
    let (size, raw) = match source {
        BlobSource::WorkingTree => {
            let full = repo.root.join(&rel);
            let size = std::fs::metadata(&full)
                .map_err(|e| Error::Backend(format!("{rel}: {e}")))?
                .len();
            let raw = if size > max {
                None
            } else {
                Some(std::fs::read(&full).map_err(|e| Error::Backend(format!("{rel}: {e}")))?)
            };
            (size, raw)
        }
        _ => {
            let git_repo = open(repo)?;
            let id = object_id(&git_repo, &rel, source)?;
            let (len, _kind) = git_repo
                .odb()
                .map_err(map_err)?
                .read_header(id)
                .map_err(map_err)?;
            let raw = if len as u64 > max {
                None
            } else {
                Some(git_repo.find_blob(id).map_err(map_err)?.content().to_vec())
            };
            (len as u64, raw)
        }
    };
    let body = match raw {
        None => BlobBody::TooLarge,
        Some(raw) => gitpoulpi_cli_backend::body_of(repo, raw, max),
    };
    Ok(BlobBytes {
        path: PathBuf::from(rel),
        source: source.clone(),
        size,
        body,
    })
}

/// Size-then-content for one object-database blob, so the size cap is
/// honoured without the content ever being read.
fn read_odb_blob(
    git_repo: &git2::Repository,
    id: git2::Oid,
) -> Result<(u64, BlobContent, Option<ImageInfo>)> {
    let odb = git_repo.odb().map_err(map_err)?;
    let (len, _kind) = odb.read_header(id).map_err(map_err)?;
    let size = len as u64;
    if size > MAX_TEXT_BLOB_BYTES {
        return Ok((size, BlobContent::TooLarge, None));
    }
    let blob = git_repo.find_blob(id).map_err(map_err)?;
    let content = BlobContent::from_bytes(blob.content());
    let image = Blob::image_of(&content, blob.content());
    Ok((size, content, image))
}

/// See `GitBackend::blame`.
///
/// The blob at `at` is read first and the result is built from *its*
/// lines, not libgit2's idea of the line count: blame is rendered beside
/// file content, so both must be split by the same code
/// (`BlobContent::from_bytes`), and a binary or oversized file must be
/// reported the same way by both backends.
pub fn blame(repo: &RepoRef, path: &Path, at: Oid) -> Result<Blame> {
    let rel = repo_relative(path)?;
    let blob = read_blob(repo, path, &BlobSource::Commit(at))?;
    let lines = match &blob.content {
        BlobContent::Text { lines, .. } => lines.clone(),
        BlobContent::Binary => {
            return Ok(Blame {
                path: blob.path,
                at,
                size: blob.size,
                content: BlameContent::Binary,
            })
        }
        BlobContent::TooLarge => {
            return Ok(Blame {
                path: blob.path,
                at,
                size: blob.size,
                content: BlameContent::TooLarge,
            })
        }
        BlobContent::LfsPointer(pointer) => {
            return Ok(Blame {
                path: blob.path,
                at,
                size: blob.size,
                content: BlameContent::LfsPointer(pointer.clone()),
            })
        }
    };

    let git_repo = open(repo)?;
    let mut opts = git2::BlameOptions::new();
    // Without `newest_commit` libgit2 blames HEAD's version of the file,
    // which would silently ignore `at` entirely and hand a File History
    // view the wrong lines for every commit but the tip.
    opts.newest_commit(to_git2_oid(at)?);
    let blame = git_repo
        .blame_file(Path::new(&rel), Some(&mut opts))
        .map_err(map_err)?;

    // One metadata lookup (and one `previous` computation) per *commit and
    // path*, not per line: a 5000-line file typically has a few dozen
    // distinct blamed commits.
    let mut metas: HashMap<(git2::Oid, String), CommitMeta> = HashMap::new();
    let mut out = Vec::with_capacity(lines.len());
    for (idx, content) in lines.into_iter().enumerate() {
        let final_line = idx as u32 + 1;
        let hunk = blame.get_line(final_line as usize).ok_or_else(|| {
            Error::Backend(format!("blame has no entry for {rel} line {final_line}"))
        })?;
        let commit_id = hunk.final_commit_id();
        let orig_path = hunk
            .path()
            .map(|p| p.to_string_lossy().replace('\\', "/"))
            .unwrap_or_else(|| rel.clone());
        let key = (commit_id, orig_path.clone());
        if !metas.contains_key(&key) {
            let meta = commit_meta(&git_repo, commit_id, &orig_path)?;
            metas.insert(key.clone(), meta);
        }
        let meta = &metas[&key];
        let signature = hunk
            .final_signature()
            .ok_or_else(|| Error::Backend("a blame hunk without a signature".into()))?;
        // A hunk covers a run of consecutive lines; this line's position
        // inside that run is the same in the original file.
        let offset = final_line.saturating_sub(hunk.final_start_line() as u32);
        out.push(BlameLine {
            commit: to_domain_oid(commit_id)?,
            author_name: signature.name().unwrap_or_default().to_string(),
            author_email: signature.email().unwrap_or_default().to_string(),
            timestamp: signature.when().seconds(),
            committer_time: meta.committer_time,
            summary: meta.summary.clone(),
            final_line,
            orig_line: hunk.orig_start_line() as u32 + offset,
            orig_path: PathBuf::from(orig_path),
            previous: meta.previous.clone(),
            content,
        });
    }

    Ok(Blame {
        path: blob.path,
        at,
        size: blob.size,
        content: BlameContent::Lines(out),
    })
}

/// What blame needs about one `(commit, path)`, computed once.
struct CommitMeta {
    summary: String,
    committer_time: i64,
    previous: Option<(Oid, PathBuf)>,
}

/// `previous` is the commit's **first parent** and the file's path there,
/// the same pair `git blame --porcelain` prints: the path itself when the
/// parent has it, else the old name when rename detection (50%) pairs the
/// two across the commit, else `None` (root commit, or the file is born
/// here).
fn commit_meta(repo: &git2::Repository, id: git2::Oid, path: &str) -> Result<CommitMeta> {
    let commit = repo.find_commit(id).map_err(map_err)?;
    let summary = commit
        .summary()
        .ok()
        .flatten()
        .unwrap_or_default()
        .to_string();
    let committer_time = commit.committer().when().seconds();
    let Ok(parent) = commit.parent(0) else {
        return Ok(CommitMeta {
            summary,
            committer_time,
            previous: None,
        });
    };
    let parent_tree = parent.tree().map_err(map_err)?;
    let previous_path = if parent_tree.get_path(Path::new(path)).is_ok() {
        Some(path.to_string())
    } else {
        let tree = commit.tree().map_err(map_err)?;
        let mut diff = repo
            .diff_tree_to_tree(Some(&parent_tree), Some(&tree), None)
            .map_err(map_err)?;
        let mut find = git2::DiffFindOptions::new();
        find.renames(true);
        diff.find_similar(Some(&mut find)).map_err(map_err)?;
        diff.deltas()
            .find(|d| {
                d.status() == git2::Delta::Renamed
                    && d.new_file()
                        .path()
                        .is_some_and(|p| p.to_string_lossy().replace('\\', "/") == path)
            })
            .and_then(|d| d.old_file().path())
            .map(|p| p.to_string_lossy().replace('\\', "/"))
    };
    Ok(CommitMeta {
        summary,
        committer_time,
        previous: match previous_path {
            Some(p) => Some((to_domain_oid(parent.id())?, PathBuf::from(p))),
            None => None,
        },
    })
}

/// Domain paths are repo-relative and git spells them with `/` on every
/// platform; a `PathBuf` join on Windows yields backslashes no tree lookup
/// matches. Normalizing here, not at each call site, is why there is no
/// `cfg(windows)` in this crate.
fn repo_relative(path: &Path) -> Result<String> {
    let text = path
        .to_str()
        .ok_or_else(|| Error::Backend(format!("path {} is not valid utf-8", path.display())))?;
    Ok(text.replace('\\', "/").trim_start_matches("./").to_string())
}

/// Every path at `at`, sorted, with `/` separators. Mirrors
/// `gitpoulpi_cli_backend::content::list_tree`; the contract suite holds
/// the two to the same answer.
pub fn list_tree(repo: &RepoRef, at: Oid) -> Result<Vec<PathBuf>> {
    let git = open(repo)?;
    let oid = to_git2_oid(at)?;
    // `find_commit` rather than `find_object` + peel: an oid that is not
    // a commit must be an error, not an empty listing, and the contract
    // suite pins that. The system-git twin gets it from `^{tree}`.
    let commit = git
        .find_commit(oid)
        .map_err(|e| Error::Backend(format!("no commit {}: {e}", at.to_hex())))?;
    let tree = commit
        .tree()
        .map_err(|e| Error::Backend(format!("commit {} has no tree: {e}", at.to_hex())))?;

    let mut paths: Vec<PathBuf> = Vec::new();
    // `walk` yields a directory entry *and* then its contents, so the
    // filter is what keeps directories out -- see the trait doc for why
    // they are not entries.
    tree.walk(git2::TreeWalkMode::PreOrder, |dir, entry| {
        if entry.kind() == Some(git2::ObjectType::Tree) {
            return git2::TreeWalkResult::Ok;
        }
        if let Ok(name) = entry.name() {
            // `dir` is already `/`-separated and either empty or
            // `/`-terminated, so this concatenation is the whole conversion.
            paths.push(PathBuf::from(format!("{dir}{name}")));
        }
        git2::TreeWalkResult::Ok
    })
    .map_err(|e| Error::Backend(format!("walking the tree of {}: {e}", at.to_hex())))?;

    // Defensive, not load-bearing: git sorts tree entries comparing a
    // directory as if it ended in `/`, so a recursive walk already comes
    // out ordered by full path and removing this breaks no test. It stays
    // because the contract promises sorted output and should be enforced,
    // not coincidental.
    paths.sort();
    Ok(paths)
}

/// The lines of the files at `at` that contain `terms`, by walking the
/// tree's blobs. The rules (binary, pointer, size, cut, order, per-term
/// cap) are `gitpoulpi_core::domain::grep_bytes` / `finish_hits`, shared
/// with the system-git twin.
pub fn grep_tree(
    repo: &RepoRef,
    at: Oid,
    terms: &[String],
    max_hits: usize,
) -> Result<Vec<GrepHit>> {
    let git = open(repo)?;
    let oid = to_git2_oid(at)?;
    let commit = git
        .find_commit(oid)
        .map_err(|e| Error::Backend(format!("no commit {}: {e}", at.to_hex())))?;
    let tree = commit
        .tree()
        .map_err(|e| Error::Backend(format!("commit {} has no tree: {e}", at.to_hex())))?;
    let terms = usable_terms(terms);
    if terms.is_empty() || max_hits == 0 {
        return Ok(Vec::new());
    }
    let mut hits: Vec<GrepHit> = Vec::new();
    tree.walk(git2::TreeWalkMode::PreOrder, |dir, entry| {
        if entry.kind() != Some(git2::ObjectType::Blob) {
            return git2::TreeWalkResult::Ok;
        }
        // Submodule links are commits, symlinks are blobs of a path: both
        // are skipped by the same rules as the system twin (`git grep`
        // follows neither).
        if entry.filemode() == 0o120000 {
            return git2::TreeWalkResult::Ok;
        }
        let Ok(name) = entry.name() else {
            return git2::TreeWalkResult::Ok;
        };
        let Ok(odb) = git.odb() else {
            return git2::TreeWalkResult::Ok;
        };
        // The size first: an oversized file is never read.
        match odb.read_header(entry.id()) {
            Ok((size, _)) if (size as u64) <= MAX_GREP_FILE_BYTES => {}
            _ => return git2::TreeWalkResult::Ok,
        }
        if let Ok(blob) = git.find_blob(entry.id()) {
            hits.extend(grep_bytes(&format!("{dir}{name}"), blob.content(), &terms));
        }
        git2::TreeWalkResult::Ok
    })
    .map_err(|e| Error::Backend(format!("walking the tree of {}: {e}", at.to_hex())))?;
    Ok(finish_hits(hits, &terms, max_hits))
}

/// Every submodule `.gitmodules` declares, natively (no process): what is
/// declared, what the index records, and what is checked out. Agrees with
/// the system backend's `git submodule status` reading (the contract suite
/// holds them to it): not populated is `Uninitialized`, a checked-out
/// commit other than the recorded one is `Modified`.
#[cfg(feature = "submodule")]
pub fn submodules(repo: &RepoRef) -> Result<Vec<Submodule>> {
    if !repo.root.join(".gitmodules").is_file() {
        return Ok(Vec::new());
    }
    let git_repo = open(repo)?;
    let conflicted: std::collections::HashSet<String> = git_repo
        .index()
        .ok()
        .filter(|index| index.has_conflicts())
        .map(|index| {
            index
                .conflicts()
                .into_iter()
                .flatten()
                .flatten()
                .filter_map(|c| c.our.or(c.their).or(c.ancestor))
                .map(|e| String::from_utf8_lossy(&e.path).into_owned())
                .collect()
        })
        .unwrap_or_default();
    let mut out = Vec::new();
    for sm in git_repo.submodules().map_err(map_err)? {
        let path = sm.path().to_string_lossy().replace('\\', "/");
        let expected = sm.index_id().and_then(|id| to_domain_oid(id).ok());
        let head = sm.workdir_id().and_then(|id| to_domain_oid(id).ok());
        let state = if conflicted.contains(&path) {
            SubmoduleState::Conflicted
        } else if head.is_none() {
            SubmoduleState::Uninitialized
        } else if head != expected {
            SubmoduleState::Modified
        } else {
            SubmoduleState::UpToDate
        };
        out.push(Submodule {
            name: sm.name().ok().unwrap_or(&path).to_string(),
            url: sm.url().ok().flatten().unwrap_or_default().to_string(),
            branch: sm.branch().ok().flatten().map(str::to_string),
            state,
            expected,
            head,
            path,
        });
    }
    out.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(out)
}

fn stage_entry(entry: &Option<git2::IndexEntry>) -> Result<Option<StageEntry>> {
    entry
        .as_ref()
        .map(|e| {
            Ok(StageEntry {
                mode: e.mode,
                oid: to_domain_oid(e.id)?,
            })
        })
        .transpose()
}

fn conflict_entry(c: &git2::IndexConflict) -> Result<Option<ConflictEntry>> {
    let Some(path) = c
        .our
        .as_ref()
        .or(c.their.as_ref())
        .or(c.ancestor.as_ref())
        .map(|e| String::from_utf8_lossy(&e.path).into_owned())
    else {
        return Ok(None);
    };
    Ok(ConflictEntry::from_stages(
        PathBuf::from(path),
        stage_entry(&c.ancestor)?,
        stage_entry(&c.our)?,
        stage_entry(&c.their)?,
    ))
}

/// See `GitBackend::conflict_entries`: libgit2 reads the index's unmerged
/// entries, no process and no blob. Sorted by path, as `git ls-files -u`
/// lists them.
pub fn conflict_entries(repo: &RepoRef) -> Result<Vec<ConflictEntry>> {
    let git_repo = open(repo)?;
    let index = git_repo.index().map_err(map_err)?;
    if !index.has_conflicts() {
        return Ok(Vec::new());
    }
    let mut out = Vec::new();
    for conflict in index.conflicts().map_err(map_err)? {
        let conflict = conflict.map_err(map_err)?;
        out.extend(conflict_entry(&conflict)?);
    }
    out.sort_by(|a, b| a.path.as_os_str().cmp(b.path.as_os_str()));
    Ok(out)
}

/// See `GitBackend::merge_document`: the stages are read natively (header
/// first, so an oversized blob is never loaded); the merge itself is
/// `CliFallback` (libgit2 0.19's binding has no `git_merge_file`, and its
/// xdiff could place regions differently than git's), through the same
/// code `SystemGitBackend` runs.
pub fn merge_document(repo: &RepoRef, path: &Path) -> Result<MergeDocument> {
    let rel = repo_relative(path)?;
    let git_repo = open(repo)?;
    let index = git_repo.index().map_err(map_err)?;
    let conflict = git2::IndexConflict {
        ancestor: index.get_path(Path::new(&rel), 1),
        our: index.get_path(Path::new(&rel), 2),
        their: index.get_path(Path::new(&rel), 3),
    };
    let entry = conflict_entry(&conflict)?
        .ok_or_else(|| Error::Backend(format!("{rel} is not conflicted")))?;
    let odb = git_repo.odb().map_err(map_err)?;
    let read = |stage: Option<StageEntry>| -> Result<Option<RawStage>> {
        let Some(stage) = stage else { return Ok(None) };
        if stage.mode == MODE_GITLINK {
            return Ok(Some(RawStage {
                entry: stage,
                size: 0,
                bytes: None,
            }));
        }
        let id = to_git2_oid(stage.oid)?;
        let (len, _kind) = odb.read_header(id).map_err(map_err)?;
        let size = len as u64;
        let bytes = if size > MAX_TEXT_BLOB_BYTES {
            None
        } else {
            Some(git_repo.find_blob(id).map_err(map_err)?.content().to_vec())
        };
        Ok(Some(RawStage {
            entry: stage,
            size,
            bytes,
        }))
    };
    let raws = [read(entry.base)?, read(entry.ours)?, read(entry.theirs)?];
    gitpoulpi_cli_backend::document_from_stages(repo, entry, raws)
}