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 it goes to the system git: it smudges LFS
422    /// files (ADR 0009) and, like every working-tree update here, leaves a
423    /// folder it cannot remove (another program holds it open, on Windows)
424    /// in place with a warning, where libgit2's checkout fails half done.
425    fn checkout(&self, repo: &RepoRef, target: &CheckoutTarget) -> Result<()> {
426        self.fallback.checkout(repo, target)
427    }
428    // Native on the index (`staging::discard`), except in an LFS repository
429    // where the checkout needs the smudge filter.
430    fn discard(&self, repo: &RepoRef, paths: &[String]) -> Result<()> {
431        if lfs::is_active(repo) {
432            return self.fallback.discard(repo, paths);
433        }
434        staging::discard(repo, paths)
435    }
436    fn branch_create(&self, repo: &RepoRef, name: &str, at: Oid) -> Result<()> {
437        mutate::branch_create(repo, name, at)
438    }
439    fn branch_create_tracking(
440        &self,
441        repo: &RepoRef,
442        local_name: &str,
443        upstream: &str,
444    ) -> Result<()> {
445        // Moves the working tree onto the new branch: system git (see
446        // `checkout`).
447        self.fallback
448            .branch_create_tracking(repo, local_name, upstream)
449    }
450    fn branch_delete(&self, repo: &RepoRef, name: &str) -> Result<()> {
451        mutate::branch_delete(repo, name)
452    }
453    fn branch_rename(&self, repo: &RepoRef, old_name: &str, new_name: &str) -> Result<()> {
454        mutate::branch_rename(repo, old_name, new_name)
455    }
456    fn branch_set_upstream(
457        &self,
458        repo: &RepoRef,
459        branch: &str,
460        upstream: Option<&str>,
461    ) -> Result<()> {
462        mutate::branch_set_upstream(repo, branch, upstream)
463    }
464    fn fast_forward(
465        &self,
466        repo: &RepoRef,
467        branch: &str,
468        target: Oid,
469    ) -> Result<FastForwardOutcome> {
470        // The checked-out branch updates the working tree: system git (see
471        // `checkout`). Any other branch moves by its ref alone, natively.
472        if lfs::is_active(repo) || mutate::is_checked_out(repo, branch) {
473            return self.fallback.fast_forward(repo, branch, target);
474        }
475        mutate::fast_forward(repo, branch, target)
476    }
477    fn tag_create(
478        &self,
479        repo: &RepoRef,
480        name: &str,
481        at: Oid,
482        annotated_message: Option<&str>,
483    ) -> Result<()> {
484        mutate::tag_create(repo, name, at, annotated_message)
485    }
486    fn tag_delete(&self, repo: &RepoRef, name: &str) -> Result<()> {
487        mutate::tag_delete(repo, name)
488    }
489    fn tag_annotate(&self, repo: &RepoRef, name: &str, message: &str) -> Result<()> {
490        mutate::tag_annotate(repo, name, message)
491    }
492    fn tag_move(&self, repo: &RepoRef, name: &str, to: Oid, force: bool) -> Result<()> {
493        mutate::tag_move(repo, name, to, force)
494    }
495    fn tag_merge_branch(
496        &self,
497        repo: &RepoRef,
498        name: &str,
499        branch: &str,
500        message: Option<&str>,
501    ) -> Result<Oid> {
502        mutate::tag_merge_branch(repo, name, branch, message)
503    }
504    /// Forwarded, like every other network operation here.
505    ///
506    /// Pushing a tag also has to *record* the push in the remote-tag
507    /// mirror, and that bookkeeping is what makes the backends agree about
508    /// which tags are unpushed. The mirror therefore has exactly one
509    /// writer, in `gitpoulpi_cli_backend::tags`; this backend only *reads*
510    /// it (natively, in `reads::refs`).
511    async fn tag_push(
512        &self,
513        repo: &RepoRef,
514        remote: &str,
515        selection: &TagSelection,
516    ) -> Result<PushOutcome> {
517        self.fallback.tag_push(repo, remote, selection).await
518    }
519    fn tag_take_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
520        self.fallback.tag_take_remote(repo, remote, name)
521    }
522    async fn tag_force_push(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
523        self.fallback.tag_force_push(repo, remote, name).await
524    }
525    async fn tag_delete_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
526        self.fallback.tag_delete_remote(repo, remote, name).await
527    }
528    async fn tag_fetch(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
529        self.fallback.tag_fetch(repo, remote, name).await
530    }
531    async fn branch_delete_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()> {
532        self.fallback.branch_delete_remote(repo, remote, name).await
533    }
534    async fn remote_ref_value(
535        &self,
536        repo: &RepoRef,
537        remote: &str,
538        full_ref: &str,
539    ) -> Result<Option<Oid>> {
540        self.fallback.remote_ref_value(repo, remote, full_ref).await
541    }
542    async fn remote_ref_update(
543        &self,
544        repo: &RepoRef,
545        remote: &str,
546        full_ref: &str,
547        new: Option<Oid>,
548        expect: Option<Oid>,
549    ) -> Result<()> {
550        self.fallback
551            .remote_ref_update(repo, remote, full_ref, new, expect)
552            .await
553    }
554    fn rebase_state(&self, repo: &RepoRef) -> Result<Option<RebaseState>> {
555        // Part of every refresh: answered natively in the (overwhelmingly
556        // common) no-rebase case; the system backend reads the state
557        // files when one is in progress.
558        if reads::provably_no_rebase(repo) {
559            return Ok(None);
560        }
561        self.fallback.rebase_state(repo)
562    }
563    /// `Soft` only moves the branch, so it stays native; `Mixed` and
564    /// `Hard` rewrite the index / working tree and go to the system git
565    /// (LFS smudge, ADR 0009; folders that cannot be removed, see
566    /// `checkout`).
567    fn reset(&self, repo: &RepoRef, target: Oid, mode: ResetMode) -> Result<()> {
568        if mode != ResetMode::Soft {
569            return self.fallback.reset(repo, target, mode);
570        }
571        mutate::reset(repo, target, mode)
572    }
573    fn reword(&self, repo: &RepoRef, commit: Oid, message: &str) -> Result<RewordOutcome> {
574        reword::reword(repo, commit, message)
575    }
576    fn amend_commit(
577        &self,
578        repo: &RepoRef,
579        commit: Oid,
580        amend: &gitpoulpi_core::domain::CommitAmend,
581    ) -> Result<RewordOutcome> {
582        reword::amend_commit(repo, commit, amend, "amend")
583    }
584    /// System git: the byte-faithful partial patches live in the CLI
585    /// backend's `patch.rs`, as for hunk and line staging.
586    fn split_source(&self, repo: &RepoRef, commit: Oid) -> Result<SplitSource> {
587        self.fallback.split_source(repo, commit)
588    }
589    fn split_commit(&self, repo: &RepoRef, req: &SplitCommit) -> Result<SplitOutcome> {
590        self.fallback.split_commit(repo, req)
591    }
592    // One engine for both backends (the split-commit precedent).
593    fn rewrite_preview(
594        &self,
595        repo: &RepoRef,
596        recipe: &Recipe,
597        progress: RewriteProgressSink<'_>,
598    ) -> Result<RewritePlan> {
599        self.fallback.rewrite_preview(repo, recipe, progress)
600    }
601    fn rewrite_apply(&self, repo: &RepoRef, plan: &RewritePlan) -> Result<RewriteOutcome> {
602        self.fallback.rewrite_apply(repo, plan)
603    }
604    fn rewrite_extract(
605        &self,
606        repo: &RepoRef,
607        plan: &RewritePlan,
608        target: &std::path::Path,
609    ) -> Result<RewriteOutcome> {
610        self.fallback.rewrite_extract(repo, plan, target)
611    }
612    fn rewrite_load(&self, repo: &RepoRef, run: &RunId) -> Result<Option<RewritePlan>> {
613        self.fallback.rewrite_load(repo, run)
614    }
615    fn rewrite_record(
616        &self,
617        repo: &RepoRef,
618        run: &RunId,
619    ) -> Result<gitpoulpi_core::domain::rewrite::RewriteRecord> {
620        self.fallback.rewrite_record(repo, run)
621    }
622    fn rewrite_maps(
623        &self,
624        repo: &RepoRef,
625        run: &RunId,
626        out: Option<&std::path::Path>,
627    ) -> Result<gitpoulpi_core::domain::rewrite::RewriteMaps> {
628        self.fallback.rewrite_maps(repo, run, out)
629    }
630    async fn push_rewritten(
631        &self,
632        repo: &RepoRef,
633        req: &gitpoulpi_core::domain::rewrite::PushRewritten,
634    ) -> Result<gitpoulpi_core::domain::rewrite::PushRewrittenOutcome> {
635        self.fallback.push_rewritten(repo, req).await
636    }
637    fn rewrite_purge(
638        &self,
639        repo: &RepoRef,
640        req: &gitpoulpi_core::domain::rewrite::PurgeRequest,
641        progress: gitpoulpi_core::domain::rewrite::PurgeProgressSink<'_>,
642    ) -> Result<gitpoulpi_core::domain::rewrite::PurgeOutcome> {
643        self.fallback.rewrite_purge(repo, req, progress)
644    }
645    fn rewrite_blob_diff(
646        &self,
647        repo: &RepoRef,
648        run: &RunId,
649        commit: Oid,
650        path: &str,
651    ) -> Result<gitpoulpi_core::domain::rewrite::BlobChange> {
652        self.fallback.rewrite_blob_diff(repo, run, commit, path)
653    }
654    fn rewrite_script_check(
655        &self,
656        repo: &RepoRef,
657        script: &gitpoulpi_core::domain::rewrite::ScriptRef,
658        policy: &gitpoulpi_core::domain::rewrite::ScriptPolicy,
659    ) -> Result<gitpoulpi_core::domain::rewrite::script::ScriptCheck> {
660        self.fallback.rewrite_script_check(repo, script, policy)
661    }
662    fn rewrite_script_test(
663        &self,
664        repo: &RepoRef,
665        script: &gitpoulpi_core::domain::rewrite::ScriptRef,
666        policy: &gitpoulpi_core::domain::rewrite::ScriptPolicy,
667        commits: &[Oid],
668    ) -> Result<Vec<gitpoulpi_core::domain::rewrite::script::ScriptTestRow>> {
669        self.fallback
670            .rewrite_script_test(repo, script, policy, commits)
671    }
672    fn rewrite_analyze(
673        &self,
674        repo: &RepoRef,
675        scope: &gitpoulpi_core::domain::rewrite::Scope,
676        top: u32,
677        progress: gitpoulpi_core::domain::rewrite::RewriteProgressSink<'_>,
678    ) -> Result<gitpoulpi_core::domain::rewrite::SizeAnalysis> {
679        self.fallback.rewrite_analyze(repo, scope, top, progress)
680    }
681    fn rewrite_scan_secrets(
682        &self,
683        repo: &RepoRef,
684        scope: &gitpoulpi_core::domain::rewrite::Scope,
685        progress: gitpoulpi_core::domain::rewrite::RewriteProgressSink<'_>,
686    ) -> Result<gitpoulpi_core::domain::rewrite::SecretScan> {
687        self.fallback.rewrite_scan_secrets(repo, scope, progress)
688    }
689    fn rewrite_discard(&self, repo: &RepoRef, run: &RunId) -> Result<()> {
690        self.fallback.rewrite_discard(repo, run)
691    }
692    /// Networking is CliFallback, like `fetch`: the system-git layer is where
693    /// the entry is applied.
694    fn set_network_auth(&self, repo: &RepoRef, auth: Option<NetworkAuth>) {
695        self.fallback.set_network_auth(repo, auth);
696    }
697    async fn remote_access_check(
698        &self,
699        repo: &RepoRef,
700        remote: &str,
701        opts: &RemoteAccessOptions,
702    ) -> Result<RemoteAccessReport> {
703        self.fallback.remote_access_check(repo, remote, opts).await
704    }
705    async fn fetch(
706        &self,
707        repo: &RepoRef,
708        remote: &str,
709        opts: &FetchOptions,
710    ) -> Result<FetchOutcome> {
711        self.fallback.fetch(repo, remote, opts).await
712    }
713    async fn fetch_all(&self, repo: &RepoRef, opts: &FetchOptions) -> Result<FetchOutcome> {
714        self.fallback.fetch_all(repo, opts).await
715    }
716    async fn fetch_ref_as_branch(
717        &self,
718        repo: &RepoRef,
719        remote: &str,
720        remote_ref: &str,
721        branch: &str,
722    ) -> Result<FetchOutcome> {
723        self.fallback
724            .fetch_ref_as_branch(repo, remote, remote_ref, branch)
725            .await
726    }
727    async fn fetch_refspec(
728        &self,
729        repo: &RepoRef,
730        remote: &str,
731        refspec: &str,
732    ) -> Result<FetchOutcome> {
733        self.fallback.fetch_refspec(repo, remote, refspec).await
734    }
735    async fn pull(&self, repo: &RepoRef, opts: &PullOptions) -> Result<PullOutcome> {
736        self.fallback.pull(repo, opts).await
737    }
738    async fn pull_fetch(&self, repo: &RepoRef, opts: &PullOptions) -> Result<()> {
739        self.fallback.pull_fetch(repo, opts).await
740    }
741    async fn pull_integrate(&self, repo: &RepoRef, opts: &PullOptions) -> Result<PullOutcome> {
742        self.fallback.pull_integrate(repo, opts).await
743    }
744    async fn push(&self, repo: &RepoRef, remote: &str, opts: &PushOptions) -> Result<PushOutcome> {
745        self.fallback.push(repo, remote, opts).await
746    }
747    async fn push_for_review(
748        &self,
749        repo: &RepoRef,
750        remote: &str,
751        branch: &str,
752        topic: Option<&str>,
753    ) -> Result<PushOutcome> {
754        self.fallback
755            .push_for_review(repo, remote, branch, topic)
756            .await
757    }
758    async fn clone(&self, url: &str, dest: &Path, opts: &CloneOptions) -> Result<RepoRef> {
759        self.fallback.clone(url, dest, opts).await
760    }
761    /// Forwarded rather than reimplemented on libgit2's own
762    /// `RemoteCallbacks::transfer_progress`: `clone` is already
763    /// `CliFallback`, and narrating through libgit2 would give the same
764    /// operation two progress vocabularies depending on the backend. If
765    /// `clone` ever becomes Native, the progress mapping moves with it.
766    async fn clone_with_progress(
767        &self,
768        url: &str,
769        dest: &Path,
770        opts: &CloneOptions,
771        progress: CloneProgressSink<'_>,
772    ) -> Result<RepoRef> {
773        self.fallback
774            .clone_with_progress(url, dest, opts, progress)
775            .await
776    }
777    fn remote_set_url(&self, repo: &RepoRef, name: &str, url: &str) -> Result<()> {
778        if !mutate::remote_has_url(repo, name)? {
779            return self.fallback.remote_set_url(repo, name, url);
780        }
781        mutate::remote_set_url(repo, name, url)
782    }
783    fn remote_set_push_url(&self, repo: &RepoRef, name: &str, url: Option<&str>) -> Result<()> {
784        if !mutate::remote_has_url(repo, name)? {
785            return self.fallback.remote_set_push_url(repo, name, url);
786        }
787        mutate::remote_set_push_url(repo, name, url)
788    }
789    fn ssh_command(&self, repo: &RepoRef) -> Result<Option<String>> {
790        mutate::ssh_command(repo)
791    }
792    fn set_ssh_command(&self, repo: &RepoRef, command: Option<&str>) -> Result<()> {
793        mutate::set_ssh_command(repo, command)
794    }
795    fn repo_config(&self, repo: &RepoRef, key: &str) -> Result<Option<String>> {
796        mutate::repo_config(repo, key)
797    }
798    // libgit2 has no sparse-checkout API (it cannot even write the skip-worktree
799    // bits back reliably), so all three are `git sparse-checkout`.
800    fn sparse_checkout_status(&self, repo: &RepoRef) -> Result<SparseState> {
801        self.fallback.sparse_checkout_status(repo)
802    }
803    fn sparse_checkout_set(&self, repo: &RepoRef, dirs: &[String]) -> Result<()> {
804        self.fallback.sparse_checkout_set(repo, dirs)
805    }
806    fn sparse_checkout_disable(&self, repo: &RepoRef) -> Result<()> {
807        self.fallback.sparse_checkout_disable(repo)
808    }
809    fn set_repo_config(&self, repo: &RepoRef, key: &str, value: Option<&str>) -> Result<()> {
810        mutate::set_repo_config(repo, key, value)
811    }
812    fn config_entries(&self, repo: &RepoRef, prefixes: &[&str]) -> Result<Vec<(String, String)>> {
813        mutate::config_entries(repo, prefixes)
814    }
815    fn lfs_files(&self, repo: &RepoRef, at: Option<Oid>) -> Result<Vec<LfsFile>> {
816        lfs::lfs_files(repo, at)
817    }
818    async fn lfs_locks(&self, repo: &RepoRef, remote: &str) -> Result<Vec<LfsLock>> {
819        self.fallback.lfs_locks(repo, remote).await
820    }
821    async fn lfs_lock(&self, repo: &RepoRef, remote: &str, path: &Path) -> Result<LfsLock> {
822        self.fallback.lfs_lock(repo, remote, path).await
823    }
824    async fn lfs_unlock(
825        &self,
826        repo: &RepoRef,
827        remote: &str,
828        path: &Path,
829        force: bool,
830    ) -> Result<()> {
831        self.fallback.lfs_unlock(repo, remote, path, force).await
832    }
833    async fn lfs_fetch(
834        &self,
835        repo: &RepoRef,
836        remote: &str,
837        opts: &LfsFetchOptions,
838        progress: LfsProgressSink<'_>,
839    ) -> Result<()> {
840        self.fallback.lfs_fetch(repo, remote, opts, progress).await
841    }
842    async fn lfs_pull(
843        &self,
844        repo: &RepoRef,
845        remote: &str,
846        progress: LfsProgressSink<'_>,
847    ) -> Result<()> {
848        self.fallback.lfs_pull(repo, remote, progress).await
849    }
850    async fn lfs_checkout(
851        &self,
852        repo: &RepoRef,
853        paths: &[PathBuf],
854        progress: LfsProgressSink<'_>,
855    ) -> Result<()> {
856        self.fallback.lfs_checkout(repo, paths, progress).await
857    }
858    async fn lfs_push(
859        &self,
860        repo: &RepoRef,
861        remote: &str,
862        opts: &LfsPushOptions,
863        progress: LfsProgressSink<'_>,
864    ) -> Result<()> {
865        self.fallback.lfs_push(repo, remote, opts, progress).await
866    }
867    fn conflicts(&self, repo: &RepoRef) -> Result<Vec<ConflictSet>> {
868        // Part of every refresh: an index with no unmerged entries has
869        // nothing for `git diff --diff-filter=U` to report, so skip the
870        // process spawn; anything else goes to git as before.
871        if reads::provably_no_conflicts(repo) {
872            return Ok(Vec::new());
873        }
874        self.fallback.conflicts(repo)
875    }
876    /// Native: libgit2 lists the index's unmerged entries without a
877    /// process or a blob read.
878    fn conflict_entries(&self, repo: &RepoRef) -> Result<Vec<ConflictEntry>> {
879        reads::conflict_entries(repo)
880    }
881    /// Native stage reads; the 3-way merge of them is `CliFallback`
882    /// (see `reads::merge_document`).
883    fn merge_document(&self, repo: &RepoRef, path: &Path) -> Result<MergeDocument> {
884        reads::merge_document(repo, path)
885    }
886
887    forward_to_fallback! {
888        /// `CliFallback`: the reachability walk is the CLI's own, one implementation.
889        fn lost_commits(
890            &self,
891            repo: &RepoRef,
892            opts: &gitpoulpi_core::domain::LostCommitOptions,
893        ) -> Result<gitpoulpi_core::domain::LostCommitsPage>;
894        /// `CliFallback`: libgit2 has no `reset --keep`; one implementation,
895        /// the CLI's.
896        fn move_head_keep(&self, repo: &RepoRef, branch: &str, from: Oid, to: Oid) -> Result<()>;
897        fn delete_files(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
898        /// `CliFallback`: plain file I/O over the shared `textconv` functions,
899        /// one implementation so both backends write the same bytes.
900        fn convert_files(
901            &self,
902            repo: &RepoRef,
903            paths: &[String],
904            op: gitpoulpi_core::textconv::ConvertOp,
905        ) -> Result<gitpoulpi_core::textconv::ConvertReport>;
906        fn gitignore_add(&self, repo: &RepoRef, pattern: &str, file: Option<&str>) -> Result<bool>;
907        /// `CliFallback`: the one implementation writes the attribute files and
908        /// asks `git check-attr`, so both backends answer alike.
909        fn gitattributes_treat(
910            &self,
911            repo: &RepoRef,
912            paths: &[String],
913            scope: gitpoulpi_core::domain::RuleScope,
914            file: Option<&str>,
915            treat: gitpoulpi_core::domain::Treat,
916        ) -> Result<gitpoulpi_core::domain::AttributesWrite>;
917        fn binary_paths(&self, repo: &RepoRef, paths: &[String]) -> Result<Vec<bool>>;
918        /// `CliFallback`: one `git log` counts the identities of a scope, and
919        /// the `.mailmap` edit is plain file I/O; one implementation each.
920        fn mailmap_identities(
921            &self,
922            repo: &RepoRef,
923            scope: &gitpoulpi_core::domain::rewrite::Scope,
924            options: &gitpoulpi_core::domain::rewrite::ScopeOptions,
925        ) -> Result<gitpoulpi_core::domain::rewrite::IdentityList>;
926        fn mailmap_add(
927            &self,
928            repo: &RepoRef,
929            canonical: &gitpoulpi_core::domain::rewrite::Ident,
930            from: &[gitpoulpi_core::domain::rewrite::Ident],
931            file: Option<&str>,
932        ) -> Result<gitpoulpi_core::domain::rewrite::MailmapAdded>;
933        fn patch_files(&self, repo: &RepoRef, patch: &Path) -> Result<Vec<String>>;
934        // `CliFallback` for the same reason hunk- and line-level staging are:
935        // it is a partial patch reverse-applied with `git apply`, and the
936        // patch builder that gets CRLF and a missing final newline right
937        // lives in the CLI backend (`patch.rs`) -- one builder, not two.
938        fn discard_part(&self, repo: &RepoRef, target: &DiscardTarget) -> Result<()>;
939        /// `CliFallback`: libgit2's `worktree_add` cannot start a worktree on
940        /// a new branch and a commit in one step, does not create missing
941        /// parent folders, and names the admin entry differently from `git
942        /// worktree add` -- three ways for the two backends to disagree about
943        /// the same worktree. One implementation, the CLI's.
944        /// `CliFallback`: `submodule init`/`update` clone and fetch through
945        /// git's own transports and credentials; libgit2's submodule update
946        /// needs callbacks for all of it. One implementation, the CLI's.
947        fn submodule_init(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
948        fn submodule_update(&self, repo: &RepoRef, opts: &SubmoduleUpdateOptions) -> Result<()>;
949        fn worktree_add(
950            &self,
951            repo: &RepoRef,
952            path: &Path,
953            opts: &WorktreeAddOptions,
954        ) -> Result<Worktree>;
955        fn worktree_changes(&self, repo: &RepoRef, path: &Path) -> Result<Vec<WorktreeChange>>;
956        fn worktree_remove(
957            &self,
958            repo: &RepoRef,
959            path: &Path,
960            opts: &WorktreeRemoveOptions,
961        ) -> Result<WorktreeRemoved>;
962        /// `CliFallback`: `git format-patch`/`git diff --binary`/`git apply`
963        /// are the sources of truth for a patch's exact bytes (base85 binary
964        /// hunks, CRLF preservation); one implementation, the CLI's.
965        fn patch_create(
966            &self,
967            repo: &RepoRef,
968            source: &PatchSource,
969            dest: &Path,
970        ) -> Result<PatchCreated>;
971        fn patch_apply(&self, repo: &RepoRef, patch: &Path) -> Result<PatchApplied>;
972        fn apply_commit_to_worktree(&self, repo: &RepoRef, commit: Oid) -> Result<PatchApplied>;
973        fn merge(&self, repo: &RepoRef, from: &Ref, opts: &MergeOptions) -> Result<MergeOutcome>;
974        fn rebase(&self, repo: &RepoRef, onto: &Ref, opts: &RebaseOptions) -> Result<RebaseOutcome>;
975        fn rebase_plan(&self, repo: &RepoRef, upstream: Option<Oid>) -> Result<RebasePlanDraft>;
976        fn rebase_interactive(
977            &self,
978            repo: &RepoRef,
979            req: &InteractiveRebase,
980        ) -> Result<RebaseOutcome>;
981        fn rebase_continue(&self, repo: &RepoRef) -> Result<RebaseOutcome>;
982        fn rebase_skip(&self, repo: &RepoRef) -> Result<RebaseOutcome>;
983        fn rebase_abort(&self, repo: &RepoRef) -> Result<()>;
984        fn cherry_pick(
985            &self,
986            repo: &RepoRef,
987            commits: &[Oid],
988            opts: &CherryPickOptions,
989        ) -> Result<CherryPickOutcome>;
990        fn revert(&self, repo: &RepoRef, commit: Oid, mainline: Option<u32>) -> Result<RevertOutcome>;
991        fn stash_push(
992            &self,
993            repo: &RepoRef,
994            message: Option<&str>,
995            include_untracked: bool,
996        ) -> Result<Option<StashId>>;
997        fn stash_push_paths(
998            &self,
999            repo: &RepoRef,
1000            message: Option<&str>,
1001            paths: &[String],
1002        ) -> Result<Option<StashId>>;
1003        fn stash_pop(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1004        fn stash_apply(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1005        fn stash_drop(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1006        fn stash_store(&self, repo: &RepoRef, commit: Oid, message: &str) -> Result<()>;
1007        fn stash_from_commit(
1008            &self,
1009            repo: &RepoRef,
1010            commit: Oid,
1011            message: Option<&str>,
1012        ) -> Result<Oid>;
1013        fn stash_paths(&self, repo: &RepoRef, commit: Oid) -> Result<Vec<String>>;
1014        fn remote_add(&self, repo: &RepoRef, name: &str, url: &str) -> Result<()>;
1015        fn remote_remove(&self, repo: &RepoRef, name: &str) -> Result<()>;
1016        fn leftover_remotes(&self, repo: &RepoRef) -> Result<Vec<String>>;
1017        /// Forwarded: a rename also has to move the remote-tag mirror, and
1018        /// the mirror has exactly one writer (see `tag_push`).
1019        fn remote_rename(&self, repo: &RepoRef, old_name: &str, new_name: &str) -> Result<()>;
1020        fn lfs_status(&self, repo: &RepoRef) -> Result<LfsRepoStatus>;
1021        fn rewrite_tools(&self, repo: &RepoRef, fresh: bool) -> Result<gitpoulpi_core::domain::rewrite::RewriteTools>;
1022        fn rewrite_check_signing(&self, repo: &RepoRef) -> Result<gitpoulpi_core::domain::rewrite::SigningCheck>;
1023        fn lfs_install(&self, repo: &RepoRef, scope: LfsInstallScope) -> Result<()>;
1024        fn lfs_track(
1025            &self,
1026            repo: &RepoRef,
1027            patterns: &[String],
1028            opts: &LfsTrackOptions,
1029        ) -> Result<Vec<LfsPattern>>;
1030        fn lfs_untrack(&self, repo: &RepoRef, patterns: &[String]) -> Result<Vec<LfsPattern>>;
1031        fn lfs_prune(&self, repo: &RepoRef) -> Result<()>;
1032        /// `CliFallback`: the resolution writes files, restores stages and
1033        /// shells the same `git` plumbing either way; one implementation
1034        /// is the identity guarantee.
1035        fn resolve_conflict(
1036            &self,
1037            repo: &RepoRef,
1038            path: &Path,
1039            resolution: ConflictResolution,
1040            opts: &ResolveOptions,
1041        ) -> Result<()>;
1042        fn unresolve_conflict(&self, repo: &RepoRef, path: &Path, entry: &ConflictEntry)
1043            -> Result<()>;
1044        fn operation_state(&self, repo: &RepoRef) -> Result<Option<OperationState>>;
1045        fn operation_abort(&self, repo: &RepoRef) -> Result<()>;
1046        fn am_continue(&self, repo: &RepoRef) -> Result<AmOutcome>;
1047        fn am_skip(&self, repo: &RepoRef) -> Result<AmOutcome>;
1048        fn am_abort(&self, repo: &RepoRef) -> Result<()>;
1049        fn index_lock(&self, repo: &RepoRef) -> Result<Option<IndexLock>>;
1050        fn index_lock_remove(&self, repo: &RepoRef) -> Result<()>;
1051        fn operation_skip(&self, repo: &RepoRef) -> Result<()>;
1052    }
1053}