Skip to main content

gitpoulpi_git2_backend/
lib.rs

1//! GitBackend implementation over libgit2 (via the `git2` crate).
2//!
3//! `Git2Backend` is a decorator: per-operation it either calls into libgit2
4//! directly or dispatches to an inner `gitpoulpi_cli_backend::SystemGitBackend`
5//! for operations git2 doesn't support well (see
6//! `docs/architecture/git-backend-trait.md` for the capability matrix this
7//! dispatch follows and which operations are currently Native vs.
8//! CliFallback in this implementation).
9
10mod journal_ops;
11#[cfg(feature = "lfs")]
12mod lfs;
13#[cfg(not(feature = "lfs"))]
14#[path = "lfs_stub.rs"]
15mod lfs;
16mod mutate;
17mod predict;
18mod reads;
19mod reflog_ops;
20mod repo;
21mod reword;
22mod snapshot_ops;
23mod staging;
24
25use std::path::{Path, PathBuf};
26
27use gitpoulpi_cli_backend::SystemGitBackend;
28
29/// The commit total counted by an in-process libgit2 revwalk, whichever
30/// backend the session runs (`log.commit_count = "libgit2"`). Spawns no
31/// process, except for a path-filtered count (see `reads::count_commits`).
32pub fn count_commits_in_process(repo: &RepoRef, opts: &LogOptions) -> Result<u64> {
33    reads::count_commits(repo, opts)
34}
35use gitpoulpi_core::domain::rewrite::{
36    Recipe, RewriteOutcome, RewritePlan, RewriteProgressSink, RunId,
37};
38use gitpoulpi_core::domain::*;
39use gitpoulpi_core::{GitBackend, Result};
40
41/// The tree of the index on disk, written to the object database, with no
42/// process. The undo journal calls it for every backend: a tree id is the
43/// same whoever computes it, and it keeps system-git staging at one
44/// process. Errors (conflicts, a split or sparse index libgit2 cannot
45/// read) are the caller's cue to ask the backend instead.
46pub fn native_index_tree(repo: &RepoRef) -> Result<Oid> {
47    journal_ops::index_tree(repo)
48}
49
50/// A fingerprint of what the index *holds*: every entry's mode, blob id,
51/// stage (so unmerged entries count) and path, hashed. Unlike the index
52/// file's checksum it does not change when a `git status` merely
53/// refreshes the stat data.
54pub fn native_index_fingerprint(repo: &RepoRef) -> Result<String> {
55    let git = repo::open(repo)?;
56    let mut index = git.index().map_err(repo::map_err)?;
57    // Read from disk: another process may have written it.
58    index.read(true).map_err(repo::map_err)?;
59    let mut text: Vec<u8> = Vec::new();
60    for entry in index.iter() {
61        let stage = (entry.flags >> 12) & 0x3;
62        text.extend_from_slice(format!("{:o} {} {stage}\t", entry.mode, entry.id).as_bytes());
63        text.extend_from_slice(&entry.path);
64        text.push(b'\n');
65    }
66    let id = git2::Oid::hash_object(git2::ObjectType::Blob, &text).map_err(repo::map_err)?;
67    Ok(id.to_string())
68}
69
70/// `GitBackend::snapshot_create` / `path_hashes` over libgit2, for the
71/// undo journal to use whichever backend serves the session (the contract
72/// suite holds the results identical): no process.
73pub fn native_snapshot_create(repo: &RepoRef, paths: &[String]) -> Result<Snapshot> {
74    snapshot_ops::snapshot_create(repo, paths)
75}
76
77/// `GitBackend::ref_snapshot` and `stashes` over libgit2 (the contract
78/// suite holds them identical to the system git's): the journal reads them
79/// around every recorded operation, so serving them in process saves the
80/// system backend a spawn or two per read.
81pub fn native_ref_snapshot(repo: &RepoRef, scope: &RefScope) -> Result<RefSnapshot> {
82    journal_ops::ref_snapshot(repo, scope)
83}
84
85pub fn native_stashes(repo: &RepoRef) -> Result<Vec<Stash>> {
86    reads::stashes(repo)
87}
88
89pub fn native_path_hashes(repo: &RepoRef, paths: &[String]) -> Result<Vec<PathHash>> {
90    snapshot_ops::path_hashes(repo, paths)
91}
92
93pub struct Git2Backend {
94    fallback: SystemGitBackend,
95}
96
97impl Git2Backend {
98    pub fn new() -> Self {
99        Self {
100            fallback: SystemGitBackend::new(),
101        }
102    }
103}
104
105/// Diff targets that involve the working tree or the index, the only ones
106/// LFS filters can change the answer for.
107fn touches_worktree_or_index(target: &DiffTarget) -> bool {
108    matches!(
109        target,
110        DiffTarget::WorkingTreeVsIndex | DiffTarget::IndexVsHead
111    )
112}
113
114impl Git2Backend {
115    /// A backend that behaves as if `git-lfs` is not installed (see
116    /// `SystemGitBackend::without_lfs`).
117    pub fn without_lfs() -> Self {
118        Self {
119            fallback: SystemGitBackend::without_lfs(),
120        }
121    }
122}
123
124impl Default for Git2Backend {
125    fn default() -> Self {
126        Self::new()
127    }
128}
129
130/// Methods answered by the system-git backend: libgit2 either lacks the
131/// operation or cannot match git's result exactly. (Async methods cannot
132/// be generated here: `async_trait` expands before this macro does.)
133macro_rules! forward_to_fallback {
134    ($(
135        $(#[$meta:meta])*
136        fn $name:ident(&self $(, $arg:ident: $ty:ty)* $(,)?) -> $ret:ty;
137    )*) => {
138        $(
139            $(#[$meta])*
140            fn $name(&self $(, $arg: $ty)*) -> $ret {
141                self.fallback.$name($($arg),*)
142            }
143        )*
144    };
145}
146
147#[async_trait::async_trait]
148impl GitBackend for Git2Backend {
149    fn name(&self) -> &'static str {
150        "git2"
151    }
152    fn discover(&self, path: &Path) -> Result<DiscoveredRepo> {
153        repo::discover(path)
154    }
155    fn init(&self, path: &Path, opts: &InitOptions) -> Result<RepoRef> {
156        repo::init(path, opts)
157    }
158    /// Routed to the system git in an LFS repository: libgit2 has no
159    /// clean filter, so it compares a smudged file with the pointer blob
160    /// and reports every stat-dirty LFS file as modified (ADR 0009).
161    fn status(&self, repo: &RepoRef) -> Result<WorkingTree> {
162        if lfs::is_active(repo) {
163            self.fallback.status(repo)
164        } else {
165            reads::status(repo)
166        }
167    }
168    /// Native, *except* when a path filter is asked for.
169    ///
170    /// `git log -- <path>` applies history simplification (a merge whose
171    /// tree equals a parent's along that path is pruned and only that
172    /// parent followed); libgit2's revwalk has no equivalent, so a
173    /// hand-rolled filter would return a different commit list from
174    /// `SystemGitBackend` on merge-heavy history. Dispatched per variant,
175    /// like `checkout(File)` (see `mutate::checkout`).
176    fn log(&self, repo: &RepoRef, opts: &LogOptions) -> Result<CommitGraph> {
177        if opts.paths.is_empty() {
178            reads::log(repo, opts)
179        } else {
180            self.fallback.log(repo, opts)
181        }
182    }
183    fn count_commits(&self, repo: &RepoRef, opts: &LogOptions) -> Result<u64> {
184        // System git by default (`log.commit_count`; the daemon calls
185        // `count_commits_in_process` for "libgit2"): `rev-list --count` over 50,000 commits takes
186        // about 12 ms where a libgit2 revwalk (oids only, no commit object
187        // loaded by us, still parsed by libgit2 to follow parents) takes
188        // about 210 ms, because git reads the commit-graph file when there
189        // is one and libgit2 does not. One spawn, off the request path.
190        // Path filters need history simplification, which git does too.
191        self.fallback.count_commits(repo, opts)
192    }
193    /// Working-tree and index diffs go to the system git in an LFS
194    /// repository (same reason as `status`); commit-to-commit diffs
195    /// compare trees, never the working tree, so libgit2 keeps them.
196    fn diff(&self, repo: &RepoRef, target: DiffTarget) -> Result<Vec<FileDiff>> {
197        if touches_worktree_or_index(&target) && lfs::is_active(repo) {
198            self.fallback.diff(repo, target)
199        } else {
200            reads::diff(repo, target)
201        }
202    }
203    fn diff_files(&self, repo: &RepoRef, target: DiffTarget) -> Result<DiffFileList> {
204        if touches_worktree_or_index(&target) && lfs::is_active(repo) {
205            self.fallback.diff_files(repo, target)
206        } else {
207            reads::diff_files(repo, target)
208        }
209    }
210    fn commit_stats(&self, repo: &RepoRef, ids: &[Oid]) -> Result<Vec<CommitStat>> {
211        reads::commit_stats(repo, ids)
212    }
213    fn commit_messages(
214        &self,
215        repo: &RepoRef,
216        query: &gitpoulpi_core::domain::CommitMessagesQuery,
217    ) -> Result<gitpoulpi_core::domain::CommitMessages> {
218        reads::commit_messages(repo, query)
219    }
220    fn diff_paths(
221        &self,
222        repo: &RepoRef,
223        target: DiffTarget,
224        paths: &[PathBuf],
225    ) -> Result<Vec<FileDiff>> {
226        if touches_worktree_or_index(&target) && lfs::is_active(repo) {
227            self.fallback.diff_paths(repo, target, paths)
228        } else {
229            reads::diff_paths(repo, target, paths)
230        }
231    }
232    fn refs(&self, repo: &RepoRef) -> Result<Vec<Ref>> {
233        reads::refs(repo)
234    }
235    fn ref_snapshot(&self, repo: &RepoRef, scope: &RefScope) -> Result<RefSnapshot> {
236        journal_ops::ref_snapshot(repo, scope)
237    }
238    fn update_refs(
239        &self,
240        repo: &RepoRef,
241        updates: &[RefUpdate],
242        reflog_message: &str,
243    ) -> Result<()> {
244        journal_ops::update_refs(repo, updates, reflog_message)
245    }
246    /// Native: `index_tree` / `index_restore` are what every staging
247    /// operation's undo records, so they must cost no process.
248    fn index_tree(&self, repo: &RepoRef) -> Result<Oid> {
249        journal_ops::index_tree(repo)
250    }
251    fn index_restore(&self, repo: &RepoRef, tree: Oid) -> Result<()> {
252        journal_ops::index_restore(repo, tree)
253    }
254    /// Native: the snapshot builder and restorer (raw bytes, no filters,
255    /// symlinks, the executable bit) cost no process.
256    fn snapshot_create(&self, repo: &RepoRef, paths: &[String]) -> Result<Snapshot> {
257        snapshot_ops::snapshot_create(repo, paths)
258    }
259    fn snapshot_restore(&self, repo: &RepoRef, snapshot: Oid, paths: &[String]) -> Result<()> {
260        snapshot_ops::snapshot_restore(repo, snapshot, paths)
261    }
262    fn path_hashes(&self, repo: &RepoRef, paths: &[String]) -> Result<Vec<PathHash>> {
263        snapshot_ops::path_hashes(repo, paths)
264    }
265    fn blob_bytes(&self, repo: &RepoRef, oid: Oid) -> Result<Vec<u8>> {
266        reflog_ops::blob_bytes(repo, oid)
267    }
268    fn reflog(
269        &self,
270        repo: &RepoRef,
271        refname: &str,
272        skip: usize,
273        limit: usize,
274    ) -> Result<gitpoulpi_core::domain::ReflogPage> {
275        reflog_ops::reflog(repo, refname, skip, limit)
276    }
277    fn config_section(&self, repo: &RepoRef, section: &str) -> Result<Vec<(String, String)>> {
278        journal_ops::config_section(repo, section)
279    }
280    fn remote_dependents(&self, repo: &RepoRef, remote: &str) -> Result<Vec<String>> {
281        journal_ops::remote_dependents(repo, remote)
282    }
283    fn set_config_section(
284        &self,
285        repo: &RepoRef,
286        section: &str,
287        entries: &[(String, String)],
288    ) -> Result<()> {
289        journal_ops::set_config_section(repo, section, entries)
290    }
291    fn stashes(&self, repo: &RepoRef) -> Result<Vec<Stash>> {
292        reads::stashes(repo)
293    }
294    fn remotes(&self, repo: &RepoRef) -> Result<Vec<Remote>> {
295        reads::remotes(repo)
296    }
297    fn worktrees(&self, repo: &RepoRef) -> Result<Vec<Worktree>> {
298        if cfg!(feature = "worktree") {
299            reads::worktrees(repo)
300        } else {
301            Err(gitpoulpi_core::Error::NotBuilt {
302                feature: "worktree",
303            })
304        }
305    }
306    fn submodules(&self, repo: &RepoRef) -> Result<Vec<Submodule>> {
307        #[cfg(feature = "submodule")]
308        {
309            reads::submodules(repo)
310        }
311        #[cfg(not(feature = "submodule"))]
312        {
313            let _ = repo;
314            Err(gitpoulpi_core::Error::NotBuilt {
315                feature: "submodule",
316            })
317        }
318    }
319    fn resolve(&self, repo: &RepoRef, rev: &str) -> Result<Oid> {
320        reads::resolve(repo, rev)
321    }
322    fn merge_base(&self, repo: &RepoRef, a: Oid, b: Oid) -> Result<Option<Oid>> {
323        reads::merge_base(repo, a, b)
324    }
325    fn ahead_behind(&self, repo: &RepoRef, tip: Oid, base: Oid) -> Result<(u32, u32)> {
326        reads::ahead_behind(repo, tip, base)
327    }
328    // libgit2 has no patch-id: the system git answers.
329    fn cherry_counts(&self, repo: &RepoRef, local: Oid, remote: Oid) -> Result<(u32, u32)> {
330        self.fallback.cherry_counts(repo, local, remote)
331    }
332    fn predict_merge_conflicts(
333        &self,
334        repo: &RepoRef,
335        ours: Oid,
336        theirs: Oid,
337    ) -> Result<Vec<String>> {
338        predict::predict_merge_conflicts(repo, ours, theirs)
339    }
340    fn read_blob(&self, repo: &RepoRef, path: &Path, source: &BlobSource) -> Result<Blob> {
341        reads::read_blob(repo, path, source)
342    }
343    fn read_blob_bytes(
344        &self,
345        repo: &RepoRef,
346        path: &Path,
347        source: &BlobSource,
348        max: u64,
349    ) -> Result<gitpoulpi_core::domain::BlobBytes> {
350        reads::read_blob_bytes(repo, path, source, max)
351    }
352    fn list_tree(&self, repo: &RepoRef, at: Oid) -> Result<Vec<PathBuf>> {
353        reads::list_tree(repo, at)
354    }
355    fn grep_tree(
356        &self,
357        repo: &RepoRef,
358        at: Oid,
359        terms: &[String],
360        max_hits: usize,
361    ) -> Result<Vec<gitpoulpi_core::domain::GrepHit>> {
362        reads::grep_tree(repo, at, terms, max_hits)
363    }
364    fn mailmap_resolve(
365        &self,
366        repo: &RepoRef,
367        idents: &[gitpoulpi_core::domain::rewrite::Ident],
368    ) -> Result<Vec<gitpoulpi_core::domain::rewrite::Ident>> {
369        reads::mailmap_resolve(repo, idents)
370    }
371    fn blame(&self, repo: &RepoRef, path: &Path, at: Oid) -> Result<Blame> {
372        reads::blame(repo, path, at)
373    }
374    /// libgit2 has no `--follow`; re-implementing git's rename-chasing walk
375    /// would make the backends disagree exactly where this feature matters,
376    /// so it is one `git log` process either way.
377    fn file_history(
378        &self,
379        repo: &RepoRef,
380        path: &Path,
381        start: Oid,
382        skip: usize,
383        limit: usize,
384    ) -> Result<gitpoulpi_core::domain::FileHistoryPage> {
385        self.fallback.file_history(repo, path, start, skip, limit)
386    }
387    /// File / Folder / All run on libgit2's index (no spawn, one index
388    /// write); Hunk / Line and every operation in an LFS repository (no
389    /// LFS clean filter in libgit2, ADR 0009) go to the system git.
390    fn stage(&self, repo: &RepoRef, target: &StageTarget) -> Result<()> {
391        if !staging::handles(target) || lfs::is_active(repo) {
392            return self.fallback.stage(repo, target);
393        }
394        match staging::stage(repo, target) {
395            Err(gitpoulpi_core::Error::Unsupported { .. }) => self.fallback.stage(repo, target),
396            other => other,
397        }
398    }
399    fn unstage(&self, repo: &RepoRef, target: &StageTarget) -> Result<()> {
400        if !staging::handles(target) || lfs::is_active(repo) {
401            return self.fallback.unstage(repo, target);
402        }
403        match staging::unstage(repo, target) {
404            Err(gitpoulpi_core::Error::Unsupported { .. }) => self.fallback.unstage(repo, target),
405            other => other,
406        }
407    }
408    fn commit(&self, repo: &RepoRef, message: &str, opts: &CommitOptions) -> Result<Oid> {
409        // A commit that concludes a merge / cherry-pick / revert has to
410        // read MERGE_HEAD / CHERRY_PICK_HEAD / REVERT_HEAD (second parent,
411        // picked author) and clear that state afterwards; the system git
412        // does exactly that, so these (rare) commits are delegated to it,
413        // the same way merge, cherry-pick and revert themselves are.
414        // The same goes for a repository with commit hooks: libgit2 runs
415        // none, so the system git commits (and honours `no_verify`).
416        if mutate::has_pending_sequencer_commit(repo) || mutate::has_commit_hooks(repo) {
417            return self.fallback.commit(repo, message, opts);
418        }
419        mutate::commit(repo, message, opts)
420    }
421    /// Writes the working tree, so in an LFS repository it goes to the
422    /// system git (which runs the smudge filter); libgit2 would write
423    /// pointer text (ADR 0009).
424    fn checkout(&self, repo: &RepoRef, target: &CheckoutTarget) -> Result<()> {
425        if lfs::is_active(repo) {
426            return self.fallback.checkout(repo, target);
427        }
428        match mutate::checkout(repo, target) {
429            Err(gitpoulpi_core::Error::Unsupported { .. }) => self.fallback.checkout(repo, target),
430            other => other,
431        }
432    }
433    // Native on the index (`staging::discard`), except in an LFS repository
434    // where the checkout needs the smudge filter.
435    fn discard(&self, repo: &RepoRef, paths: &[String]) -> Result<()> {
436        if lfs::is_active(repo) {
437            return self.fallback.discard(repo, paths);
438        }
439        staging::discard(repo, paths)
440    }
441    fn branch_create(&self, repo: &RepoRef, name: &str, at: Oid) -> Result<()> {
442        mutate::branch_create(repo, name, at)
443    }
444    fn branch_create_tracking(
445        &self,
446        repo: &RepoRef,
447        local_name: &str,
448        upstream: &str,
449    ) -> Result<()> {
450        if lfs::is_active(repo) {
451            return self
452                .fallback
453                .branch_create_tracking(repo, local_name, upstream);
454        }
455        mutate::branch_create_tracking(repo, local_name, upstream)
456    }
457    fn branch_delete(&self, repo: &RepoRef, name: &str) -> Result<()> {
458        mutate::branch_delete(repo, name)
459    }
460    fn branch_rename(&self, repo: &RepoRef, old_name: &str, new_name: &str) -> Result<()> {
461        mutate::branch_rename(repo, old_name, new_name)
462    }
463    fn branch_set_upstream(
464        &self,
465        repo: &RepoRef,
466        branch: &str,
467        upstream: Option<&str>,
468    ) -> Result<()> {
469        mutate::branch_set_upstream(repo, branch, upstream)
470    }
471    fn fast_forward(
472        &self,
473        repo: &RepoRef,
474        branch: &str,
475        target: Oid,
476    ) -> Result<FastForwardOutcome> {
477        if lfs::is_active(repo) {
478            return self.fallback.fast_forward(repo, branch, target);
479        }
480        mutate::fast_forward(repo, branch, target)
481    }
482    fn tag_create(
483        &self,
484        repo: &RepoRef,
485        name: &str,
486        at: Oid,
487        annotated_message: Option<&str>,
488    ) -> Result<()> {
489        mutate::tag_create(repo, name, at, annotated_message)
490    }
491    fn tag_delete(&self, repo: &RepoRef, name: &str) -> Result<()> {
492        mutate::tag_delete(repo, name)
493    }
494    fn tag_annotate(&self, repo: &RepoRef, name: &str, message: &str) -> Result<()> {
495        mutate::tag_annotate(repo, name, message)
496    }
497    fn tag_move(&self, repo: &RepoRef, name: &str, to: Oid, force: bool) -> Result<()> {
498        mutate::tag_move(repo, name, to, force)
499    }
500    fn tag_merge_branch(
501        &self,
502        repo: &RepoRef,
503        name: &str,
504        branch: &str,
505        message: Option<&str>,
506    ) -> Result<Oid> {
507        mutate::tag_merge_branch(repo, name, branch, message)
508    }
509    /// Forwarded, like every other network operation here.
510    ///
511    /// Pushing a tag also has to *record* the push in the remote-tag
512    /// mirror, and that bookkeeping is what makes the backends agree about
513    /// which tags are unpushed. The mirror therefore has exactly one
514    /// writer, in `gitpoulpi_cli_backend::tags`; this backend only *reads*
515    /// it (natively, in `reads::refs`).
516    async fn tag_push(
517        &self,
518        repo: &RepoRef,
519        remote: &str,
520        selection: &TagSelection,
521    ) -> Result<PushOutcome> {
522        self.fallback.tag_push(repo, remote, selection).await
523    }
524    fn tag_take_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
525        self.fallback.tag_take_remote(repo, remote, name)
526    }
527    async fn tag_force_push(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
528        self.fallback.tag_force_push(repo, remote, name).await
529    }
530    async fn tag_delete_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
531        self.fallback.tag_delete_remote(repo, remote, name).await
532    }
533    async fn tag_fetch(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
534        self.fallback.tag_fetch(repo, remote, name).await
535    }
536    async fn branch_delete_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
537        self.fallback.branch_delete_remote(repo, remote, name).await
538    }
539    async fn remote_ref_value(
540        &self,
541        repo: &RepoRef,
542        remote: &str,
543        full_ref: &str,
544    ) -> Result<Option<Oid>> {
545        self.fallback.remote_ref_value(repo, remote, full_ref).await
546    }
547    async fn remote_ref_update(
548        &self,
549        repo: &RepoRef,
550        remote: &str,
551        full_ref: &str,
552        new: Option<Oid>,
553        expect: Option<Oid>,
554    ) -> Result<()> {
555        self.fallback
556            .remote_ref_update(repo, remote, full_ref, new, expect)
557            .await
558    }
559    fn rebase_state(&self, repo: &RepoRef) -> Result<Option<RebaseState>> {
560        // Part of every refresh: answered natively in the (overwhelmingly
561        // common) no-rebase case; the system backend reads the state
562        // files when one is in progress.
563        if reads::provably_no_rebase(repo) {
564            return Ok(None);
565        }
566        self.fallback.rebase_state(repo)
567    }
568    /// `Soft` only moves the branch, so it stays native; `Mixed` and
569    /// `Hard` rewrite the index / working tree and go to the system git in
570    /// an LFS repository (ADR 0009).
571    fn reset(&self, repo: &RepoRef, target: Oid, mode: ResetMode) -> Result<()> {
572        if mode != ResetMode::Soft && lfs::is_active(repo) {
573            return self.fallback.reset(repo, target, mode);
574        }
575        mutate::reset(repo, target, mode)
576    }
577    fn reword(&self, repo: &RepoRef, commit: Oid, message: &str) -> Result<RewordOutcome> {
578        reword::reword(repo, commit, message)
579    }
580    fn amend_commit(
581        &self,
582        repo: &RepoRef,
583        commit: Oid,
584        amend: &gitpoulpi_core::domain::CommitAmend,
585    ) -> Result<RewordOutcome> {
586        reword::amend_commit(repo, commit, amend, "amend")
587    }
588    /// System git: the byte-faithful partial patches live in the CLI
589    /// backend's `patch.rs`, as for hunk and line staging.
590    fn split_source(&self, repo: &RepoRef, commit: Oid) -> Result<SplitSource> {
591        self.fallback.split_source(repo, commit)
592    }
593    fn split_commit(&self, repo: &RepoRef, req: &SplitCommit) -> Result<SplitOutcome> {
594        self.fallback.split_commit(repo, req)
595    }
596    // One engine for both backends (the split-commit precedent).
597    fn rewrite_preview(
598        &self,
599        repo: &RepoRef,
600        recipe: &Recipe,
601        progress: RewriteProgressSink<'_>,
602    ) -> Result<RewritePlan> {
603        self.fallback.rewrite_preview(repo, recipe, progress)
604    }
605    fn rewrite_apply(&self, repo: &RepoRef, plan: &RewritePlan) -> Result<RewriteOutcome> {
606        self.fallback.rewrite_apply(repo, plan)
607    }
608    fn rewrite_extract(
609        &self,
610        repo: &RepoRef,
611        plan: &RewritePlan,
612        target: &std::path::Path,
613    ) -> Result<RewriteOutcome> {
614        self.fallback.rewrite_extract(repo, plan, target)
615    }
616    fn rewrite_load(&self, repo: &RepoRef, run: &RunId) -> Result<Option<RewritePlan>> {
617        self.fallback.rewrite_load(repo, run)
618    }
619    fn rewrite_record(
620        &self,
621        repo: &RepoRef,
622        run: &RunId,
623    ) -> Result<gitpoulpi_core::domain::rewrite::RewriteRecord> {
624        self.fallback.rewrite_record(repo, run)
625    }
626    fn rewrite_maps(
627        &self,
628        repo: &RepoRef,
629        run: &RunId,
630        out: Option<&std::path::Path>,
631    ) -> Result<gitpoulpi_core::domain::rewrite::RewriteMaps> {
632        self.fallback.rewrite_maps(repo, run, out)
633    }
634    async fn push_rewritten(
635        &self,
636        repo: &RepoRef,
637        req: &gitpoulpi_core::domain::rewrite::PushRewritten,
638    ) -> Result<gitpoulpi_core::domain::rewrite::PushRewrittenOutcome> {
639        self.fallback.push_rewritten(repo, req).await
640    }
641    fn rewrite_purge(
642        &self,
643        repo: &RepoRef,
644        req: &gitpoulpi_core::domain::rewrite::PurgeRequest,
645        progress: gitpoulpi_core::domain::rewrite::PurgeProgressSink<'_>,
646    ) -> Result<gitpoulpi_core::domain::rewrite::PurgeOutcome> {
647        self.fallback.rewrite_purge(repo, req, progress)
648    }
649    fn rewrite_blob_diff(
650        &self,
651        repo: &RepoRef,
652        run: &RunId,
653        commit: Oid,
654        path: &str,
655    ) -> Result<gitpoulpi_core::domain::rewrite::BlobChange> {
656        self.fallback.rewrite_blob_diff(repo, run, commit, path)
657    }
658    fn rewrite_script_check(
659        &self,
660        repo: &RepoRef,
661        script: &gitpoulpi_core::domain::rewrite::ScriptRef,
662        policy: &gitpoulpi_core::domain::rewrite::ScriptPolicy,
663    ) -> Result<gitpoulpi_core::domain::rewrite::script::ScriptCheck> {
664        self.fallback.rewrite_script_check(repo, script, policy)
665    }
666    fn rewrite_script_test(
667        &self,
668        repo: &RepoRef,
669        script: &gitpoulpi_core::domain::rewrite::ScriptRef,
670        policy: &gitpoulpi_core::domain::rewrite::ScriptPolicy,
671        commits: &[Oid],
672    ) -> Result<Vec<gitpoulpi_core::domain::rewrite::script::ScriptTestRow>> {
673        self.fallback
674            .rewrite_script_test(repo, script, policy, commits)
675    }
676    fn rewrite_analyze(
677        &self,
678        repo: &RepoRef,
679        scope: &gitpoulpi_core::domain::rewrite::Scope,
680        top: u32,
681        progress: gitpoulpi_core::domain::rewrite::RewriteProgressSink<'_>,
682    ) -> Result<gitpoulpi_core::domain::rewrite::SizeAnalysis> {
683        self.fallback.rewrite_analyze(repo, scope, top, progress)
684    }
685    fn rewrite_scan_secrets(
686        &self,
687        repo: &RepoRef,
688        scope: &gitpoulpi_core::domain::rewrite::Scope,
689        progress: gitpoulpi_core::domain::rewrite::RewriteProgressSink<'_>,
690    ) -> Result<gitpoulpi_core::domain::rewrite::SecretScan> {
691        self.fallback.rewrite_scan_secrets(repo, scope, progress)
692    }
693    fn rewrite_discard(&self, repo: &RepoRef, run: &RunId) -> Result<()> {
694        self.fallback.rewrite_discard(repo, run)
695    }
696    /// Networking is CliFallback, like `fetch`: the system-git layer is where
697    /// the entry is applied.
698    fn set_network_auth(&self, repo: &RepoRef, auth: Option<NetworkAuth>) {
699        self.fallback.set_network_auth(repo, auth);
700    }
701    async fn remote_access_check(
702        &self,
703        repo: &RepoRef,
704        remote: &str,
705        opts: &RemoteAccessOptions,
706    ) -> Result<RemoteAccessReport> {
707        self.fallback.remote_access_check(repo, remote, opts).await
708    }
709    async fn fetch(
710        &self,
711        repo: &RepoRef,
712        remote: &str,
713        opts: &FetchOptions,
714    ) -> Result<FetchOutcome> {
715        self.fallback.fetch(repo, remote, opts).await
716    }
717    async fn fetch_all(&self, repo: &RepoRef, opts: &FetchOptions) -> Result<FetchOutcome> {
718        self.fallback.fetch_all(repo, opts).await
719    }
720    async fn fetch_ref_as_branch(
721        &self,
722        repo: &RepoRef,
723        remote: &str,
724        remote_ref: &str,
725        branch: &str,
726    ) -> Result<FetchOutcome> {
727        self.fallback
728            .fetch_ref_as_branch(repo, remote, remote_ref, branch)
729            .await
730    }
731    async fn fetch_refspec(
732        &self,
733        repo: &RepoRef,
734        remote: &str,
735        refspec: &str,
736    ) -> Result<FetchOutcome> {
737        self.fallback.fetch_refspec(repo, remote, refspec).await
738    }
739    async fn pull(&self, repo: &RepoRef, opts: &PullOptions) -> Result<PullOutcome> {
740        self.fallback.pull(repo, opts).await
741    }
742    async fn pull_fetch(&self, repo: &RepoRef, opts: &PullOptions) -> Result<()> {
743        self.fallback.pull_fetch(repo, opts).await
744    }
745    async fn pull_integrate(&self, repo: &RepoRef, opts: &PullOptions) -> Result<PullOutcome> {
746        self.fallback.pull_integrate(repo, opts).await
747    }
748    async fn push(&self, repo: &RepoRef, remote: &str, opts: &PushOptions) -> Result<PushOutcome> {
749        self.fallback.push(repo, remote, opts).await
750    }
751    async fn push_for_review(
752        &self,
753        repo: &RepoRef,
754        remote: &str,
755        branch: &str,
756        topic: Option<&str>,
757    ) -> Result<PushOutcome> {
758        self.fallback
759            .push_for_review(repo, remote, branch, topic)
760            .await
761    }
762    async fn clone(&self, url: &str, dest: &Path, opts: &CloneOptions) -> Result<RepoRef> {
763        self.fallback.clone(url, dest, opts).await
764    }
765    /// Forwarded rather than reimplemented on libgit2's own
766    /// `RemoteCallbacks::transfer_progress`: `clone` is already
767    /// `CliFallback`, and narrating through libgit2 would give the same
768    /// operation two progress vocabularies depending on the backend. If
769    /// `clone` ever becomes Native, the progress mapping moves with it.
770    async fn clone_with_progress(
771        &self,
772        url: &str,
773        dest: &Path,
774        opts: &CloneOptions,
775        progress: CloneProgressSink<'_>,
776    ) -> Result<RepoRef> {
777        self.fallback
778            .clone_with_progress(url, dest, opts, progress)
779            .await
780    }
781    fn remote_set_url(&self, repo: &RepoRef, name: &str, url: &str) -> Result<()> {
782        if !mutate::remote_has_url(repo, name)? {
783            return self.fallback.remote_set_url(repo, name, url);
784        }
785        mutate::remote_set_url(repo, name, url)
786    }
787    fn remote_set_push_url(&self, repo: &RepoRef, name: &str, url: Option<&str>) -> Result<()> {
788        if !mutate::remote_has_url(repo, name)? {
789            return self.fallback.remote_set_push_url(repo, name, url);
790        }
791        mutate::remote_set_push_url(repo, name, url)
792    }
793    fn ssh_command(&self, repo: &RepoRef) -> Result<Option<String>> {
794        mutate::ssh_command(repo)
795    }
796    fn set_ssh_command(&self, repo: &RepoRef, command: Option<&str>) -> Result<()> {
797        mutate::set_ssh_command(repo, command)
798    }
799    fn repo_config(&self, repo: &RepoRef, key: &str) -> Result<Option<String>> {
800        mutate::repo_config(repo, key)
801    }
802    // libgit2 has no sparse-checkout API (it cannot even write the skip-worktree
803    // bits back reliably), so all three are `git sparse-checkout`.
804    fn sparse_checkout_status(&self, repo: &RepoRef) -> Result<SparseState> {
805        self.fallback.sparse_checkout_status(repo)
806    }
807    fn sparse_checkout_set(&self, repo: &RepoRef, dirs: &[String]) -> Result<()> {
808        self.fallback.sparse_checkout_set(repo, dirs)
809    }
810    fn sparse_checkout_disable(&self, repo: &RepoRef) -> Result<()> {
811        self.fallback.sparse_checkout_disable(repo)
812    }
813    fn set_repo_config(&self, repo: &RepoRef, key: &str, value: Option<&str>) -> Result<()> {
814        mutate::set_repo_config(repo, key, value)
815    }
816    fn config_entries(&self, repo: &RepoRef, prefixes: &[&str]) -> Result<Vec<(String, String)>> {
817        mutate::config_entries(repo, prefixes)
818    }
819    fn lfs_files(&self, repo: &RepoRef, at: Option<Oid>) -> Result<Vec<LfsFile>> {
820        lfs::lfs_files(repo, at)
821    }
822    async fn lfs_locks(&self, repo: &RepoRef, remote: &str) -> Result<Vec<LfsLock>> {
823        self.fallback.lfs_locks(repo, remote).await
824    }
825    async fn lfs_lock(&self, repo: &RepoRef, remote: &str, path: &Path) -> Result<LfsLock> {
826        self.fallback.lfs_lock(repo, remote, path).await
827    }
828    async fn lfs_unlock(
829        &self,
830        repo: &RepoRef,
831        remote: &str,
832        path: &Path,
833        force: bool,
834    ) -> Result<()> {
835        self.fallback.lfs_unlock(repo, remote, path, force).await
836    }
837    async fn lfs_fetch(
838        &self,
839        repo: &RepoRef,
840        remote: &str,
841        opts: &LfsFetchOptions,
842        progress: LfsProgressSink<'_>,
843    ) -> Result<()> {
844        self.fallback.lfs_fetch(repo, remote, opts, progress).await
845    }
846    async fn lfs_pull(
847        &self,
848        repo: &RepoRef,
849        remote: &str,
850        progress: LfsProgressSink<'_>,
851    ) -> Result<()> {
852        self.fallback.lfs_pull(repo, remote, progress).await
853    }
854    async fn lfs_checkout(
855        &self,
856        repo: &RepoRef,
857        paths: &[PathBuf],
858        progress: LfsProgressSink<'_>,
859    ) -> Result<()> {
860        self.fallback.lfs_checkout(repo, paths, progress).await
861    }
862    async fn lfs_push(
863        &self,
864        repo: &RepoRef,
865        remote: &str,
866        opts: &LfsPushOptions,
867        progress: LfsProgressSink<'_>,
868    ) -> Result<()> {
869        self.fallback.lfs_push(repo, remote, opts, progress).await
870    }
871    fn conflicts(&self, repo: &RepoRef) -> Result<Vec<ConflictSet>> {
872        // Part of every refresh: an index with no unmerged entries has
873        // nothing for `git diff --diff-filter=U` to report, so skip the
874        // process spawn; anything else goes to git as before.
875        if reads::provably_no_conflicts(repo) {
876            return Ok(Vec::new());
877        }
878        self.fallback.conflicts(repo)
879    }
880    /// Native: libgit2 lists the index's unmerged entries without a
881    /// process or a blob read.
882    fn conflict_entries(&self, repo: &RepoRef) -> Result<Vec<ConflictEntry>> {
883        reads::conflict_entries(repo)
884    }
885    /// Native stage reads; the 3-way merge of them is `CliFallback`
886    /// (see `reads::merge_document`).
887    fn merge_document(&self, repo: &RepoRef, path: &Path) -> Result<MergeDocument> {
888        reads::merge_document(repo, path)
889    }
890
891    forward_to_fallback! {
892        /// `CliFallback`: the reachability walk is the CLI's own, one implementation.
893        fn lost_commits(
894            &self,
895            repo: &RepoRef,
896            opts: &gitpoulpi_core::domain::LostCommitOptions,
897        ) -> Result<gitpoulpi_core::domain::LostCommitsPage>;
898        /// `CliFallback`: libgit2 has no `reset --keep`; one implementation,
899        /// the CLI's.
900        fn move_head_keep(&self, repo: &RepoRef, branch: &str, from: Oid, to: Oid) -> Result<()>;
901        fn delete_files(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
902        /// `CliFallback`: plain file I/O over the shared `textconv` functions,
903        /// one implementation so both backends write the same bytes.
904        fn convert_files(
905            &self,
906            repo: &RepoRef,
907            paths: &[String],
908            op: gitpoulpi_core::textconv::ConvertOp,
909        ) -> Result<gitpoulpi_core::textconv::ConvertReport>;
910        fn gitignore_add(&self, repo: &RepoRef, pattern: &str, file: Option<&str>) -> Result<bool>;
911        /// `CliFallback`: the one implementation writes the attribute files and
912        /// asks `git check-attr`, so both backends answer alike.
913        fn gitattributes_treat(
914            &self,
915            repo: &RepoRef,
916            paths: &[String],
917            scope: gitpoulpi_core::domain::RuleScope,
918            file: Option<&str>,
919            treat: gitpoulpi_core::domain::Treat,
920        ) -> Result<gitpoulpi_core::domain::AttributesWrite>;
921        fn binary_paths(&self, repo: &RepoRef, paths: &[String]) -> Result<Vec<bool>>;
922        /// `CliFallback`: one `git log` counts the identities of a scope, and
923        /// the `.mailmap` edit is plain file I/O; one implementation each.
924        fn mailmap_identities(
925            &self,
926            repo: &RepoRef,
927            scope: &gitpoulpi_core::domain::rewrite::Scope,
928            options: &gitpoulpi_core::domain::rewrite::ScopeOptions,
929        ) -> Result<gitpoulpi_core::domain::rewrite::IdentityList>;
930        fn mailmap_add(
931            &self,
932            repo: &RepoRef,
933            canonical: &gitpoulpi_core::domain::rewrite::Ident,
934            from: &[gitpoulpi_core::domain::rewrite::Ident],
935            file: Option<&str>,
936        ) -> Result<gitpoulpi_core::domain::rewrite::MailmapAdded>;
937        fn patch_files(&self, repo: &RepoRef, patch: &Path) -> Result<Vec<String>>;
938        // `CliFallback` for the same reason hunk- and line-level staging are:
939        // it is a partial patch reverse-applied with `git apply`, and the
940        // patch builder that gets CRLF and a missing final newline right
941        // lives in the CLI backend (`patch.rs`) -- one builder, not two.
942        fn discard_part(&self, repo: &RepoRef, target: &DiscardTarget) -> Result<()>;
943        /// `CliFallback`: libgit2's `worktree_add` cannot start a worktree on
944        /// a new branch and a commit in one step, does not create missing
945        /// parent folders, and names the admin entry differently from `git
946        /// worktree add` -- three ways for the two backends to disagree about
947        /// the same worktree. One implementation, the CLI's.
948        /// `CliFallback`: `submodule init`/`update` clone and fetch through
949        /// git's own transports and credentials; libgit2's submodule update
950        /// needs callbacks for all of it. One implementation, the CLI's.
951        fn submodule_init(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
952        fn submodule_update(&self, repo: &RepoRef, opts: &SubmoduleUpdateOptions) -> Result<()>;
953        fn worktree_add(
954            &self,
955            repo: &RepoRef,
956            path: &Path,
957            opts: &WorktreeAddOptions,
958        ) -> Result<Worktree>;
959        fn worktree_changes(&self, repo: &RepoRef, path: &Path) -> Result<Vec<WorktreeChange>>;
960        fn worktree_remove(
961            &self,
962            repo: &RepoRef,
963            path: &Path,
964            opts: &WorktreeRemoveOptions,
965        ) -> Result<WorktreeRemoved>;
966        /// `CliFallback`: `git format-patch`/`git diff --binary`/`git apply`
967        /// are the sources of truth for a patch's exact bytes (base85 binary
968        /// hunks, CRLF preservation); one implementation, the CLI's.
969        fn patch_create(
970            &self,
971            repo: &RepoRef,
972            source: &PatchSource,
973            dest: &Path,
974        ) -> Result<PatchCreated>;
975        fn patch_apply(&self, repo: &RepoRef, patch: &Path) -> Result<PatchApplied>;
976        fn apply_commit_to_worktree(&self, repo: &RepoRef, commit: Oid) -> Result<PatchApplied>;
977        fn merge(&self, repo: &RepoRef, from: &Ref, opts: &MergeOptions) -> Result<MergeOutcome>;
978        fn rebase(&self, repo: &RepoRef, onto: &Ref, opts: &RebaseOptions) -> Result<RebaseOutcome>;
979        fn rebase_plan(&self, repo: &RepoRef, upstream: Option<Oid>) -> Result<RebasePlanDraft>;
980        fn rebase_interactive(
981            &self,
982            repo: &RepoRef,
983            req: &InteractiveRebase,
984        ) -> Result<RebaseOutcome>;
985        fn rebase_continue(&self, repo: &RepoRef) -> Result<RebaseOutcome>;
986        fn rebase_skip(&self, repo: &RepoRef) -> Result<RebaseOutcome>;
987        fn rebase_abort(&self, repo: &RepoRef) -> Result<()>;
988        fn cherry_pick(
989            &self,
990            repo: &RepoRef,
991            commits: &[Oid],
992            opts: &CherryPickOptions,
993        ) -> Result<CherryPickOutcome>;
994        fn revert(&self, repo: &RepoRef, commit: Oid, mainline: Option<u32>) -> Result<RevertOutcome>;
995        fn stash_push(
996            &self,
997            repo: &RepoRef,
998            message: Option<&str>,
999            include_untracked: bool,
1000        ) -> Result<Option<StashId>>;
1001        fn stash_push_paths(
1002            &self,
1003            repo: &RepoRef,
1004            message: Option<&str>,
1005            paths: &[String],
1006        ) -> Result<Option<StashId>>;
1007        fn stash_pop(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1008        fn stash_apply(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1009        fn stash_drop(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1010        fn stash_store(&self, repo: &RepoRef, commit: Oid, message: &str) -> Result<()>;
1011        fn stash_from_commit(
1012            &self,
1013            repo: &RepoRef,
1014            commit: Oid,
1015            message: Option<&str>,
1016        ) -> Result<Oid>;
1017        fn stash_paths(&self, repo: &RepoRef, commit: Oid) -> Result<Vec<String>>;
1018        fn remote_add(&self, repo: &RepoRef, name: &str, url: &str) -> Result<()>;
1019        fn remote_remove(&self, repo: &RepoRef, name: &str) -> Result<()>;
1020        fn leftover_remotes(&self, repo: &RepoRef) -> Result<Vec<String>>;
1021        /// Forwarded: a rename also has to move the remote-tag mirror, and
1022        /// the mirror has exactly one writer (see `tag_push`).
1023        fn remote_rename(&self, repo: &RepoRef, old_name: &str, new_name: &str) -> Result<()>;
1024        fn lfs_status(&self, repo: &RepoRef) -> Result<LfsRepoStatus>;
1025        fn rewrite_tools(&self, repo: &RepoRef, fresh: bool) -> Result<gitpoulpi_core::domain::rewrite::RewriteTools>;
1026        fn rewrite_check_signing(&self, repo: &RepoRef) -> Result<gitpoulpi_core::domain::rewrite::SigningCheck>;
1027        fn lfs_install(&self, repo: &RepoRef, scope: LfsInstallScope) -> Result<()>;
1028        fn lfs_track(
1029            &self,
1030            repo: &RepoRef,
1031            patterns: &[String],
1032            opts: &LfsTrackOptions,
1033        ) -> Result<Vec<LfsPattern>>;
1034        fn lfs_untrack(&self, repo: &RepoRef, patterns: &[String]) -> Result<Vec<LfsPattern>>;
1035        fn lfs_prune(&self, repo: &RepoRef) -> Result<()>;
1036        /// `CliFallback`: the resolution writes files, restores stages and
1037        /// shells the same `git` plumbing either way; one implementation
1038        /// is the identity guarantee.
1039        fn resolve_conflict(
1040            &self,
1041            repo: &RepoRef,
1042            path: &Path,
1043            resolution: ConflictResolution,
1044            opts: &ResolveOptions,
1045        ) -> Result<()>;
1046        fn unresolve_conflict(&self, repo: &RepoRef, path: &Path, entry: &ConflictEntry)
1047            -> Result<()>;
1048        fn operation_state(&self, repo: &RepoRef) -> Result<Option<OperationState>>;
1049        fn operation_abort(&self, repo: &RepoRef) -> Result<()>;
1050        fn am_continue(&self, repo: &RepoRef) -> Result<AmOutcome>;
1051        fn am_skip(&self, repo: &RepoRef) -> Result<AmOutcome>;
1052        fn am_abort(&self, repo: &RepoRef) -> Result<()>;
1053        fn index_lock(&self, repo: &RepoRef) -> Result<Option<IndexLock>>;
1054        fn index_lock_remove(&self, repo: &RepoRef) -> Result<()>;
1055        fn operation_skip(&self, repo: &RepoRef) -> Result<()>;
1056    }
1057}