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