Skip to main content

gitpoulpi_core/
backend.rs

1use std::path::{Path, PathBuf};
2
3use crate::domain::rewrite::{Recipe, RewriteOutcome, RewritePlan, RewriteProgressSink, RunId};
4use crate::domain::{
5    AmOutcome, Blame, Blob, BlobSource, CheckoutTarget, CherryPickOptions, CherryPickOutcome,
6    CloneOptions, CloneProgressSink, CommitAmend, CommitGraph, CommitMessages, CommitMessagesQuery,
7    CommitOptions, CommitStat, ConflictEntry, ConflictResolution, ConflictSet, DiffFileList,
8    DiffTarget, DiscardTarget, DiscoveredRepo, FastForwardOutcome, FetchOptions, FetchOutcome,
9    FileDiff, FileHistoryPage, IndexLock, InitOptions, InteractiveRebase, LfsFetchOptions, LfsFile,
10    LfsInstallScope, LfsLock, LfsPattern, LfsProgressSink, LfsPushOptions, LfsRepoStatus,
11    LfsTrackOptions, LogOptions, LostCommitOptions, LostCommitsPage, MergeDocument, MergeOptions,
12    MergeOutcome, NetworkAuth, Oid, OperationState, PatchApplied, PatchCreated, PatchSource,
13    PathHash, PullOptions, PullOutcome, PushOptions, PushOutcome, RebaseOptions, RebaseOutcome,
14    RebasePlanDraft, RebaseState, Ref, RefScope, RefSnapshot, RefUpdate, ReflogPage, Remote,
15    RemoteAccessOptions, RemoteAccessReport, RepoRef, ResetMode, ResolveOptions, RevertOutcome,
16    RewordOutcome, Snapshot, SparseState, SplitCommit, SplitOutcome, SplitSource, StageTarget,
17    Stash, StashId, Submodule, SubmoduleUpdateOptions, WorkingTree, Worktree, WorktreeAddOptions,
18    WorktreeChange, WorktreeRemoveOptions, WorktreeRemoved,
19};
20use crate::Result;
21
22/// A config section's name and its `(key, value)` pairs.
23pub type ConfigSection = (String, Vec<(String, String)>);
24
25/// The port every frontend (TUI/CLI/MCP, via the daemon) and every backend
26/// adapter (git2, system git) implements against.
27#[async_trait::async_trait]
28pub trait GitBackend: Send + Sync {
29    /// Short implementation name (`"git2"` or `"system"`), for diagnostics.
30    fn name(&self) -> &'static str;
31
32    // -- read --
33    /// Finds the repository enclosing `path` and describes it.
34    ///
35    /// Behind the seam so both backends agree on what "the repository at
36    /// this path" means, including a linked worktree (`.git` is a *file*),
37    /// a bare repository and an external `$GIT_DIR`.
38    ///
39    /// `path` may be the root, any subdirectory, or a file inside it. Both
40    /// fields of the returned [`RepoRef`] come from the root.
41    ///
42    /// A path that does not exist, and one inside no repository, are both
43    /// [`crate::Error::RepoNotFound`] (also the answer for a recent entry
44    /// whose directory has been deleted).
45    fn discover(&self, path: &Path) -> Result<DiscoveredRepo>;
46
47    /// Creates a new repository at `path` and returns the `RepoRef` every
48    /// later request for it will be keyed on.
49    ///
50    /// Pinned by the contract suite:
51    ///
52    /// - **A missing directory is created**, parents included, like
53    ///   `git init <path>`.
54    /// - **The returned `RepoRef` is what `discover` would return** for the
55    ///   same path.
56    /// - **An existing repository root is an error**, not a silent
57    ///   re-initialisation. A directory that merely contains files, or sits
58    ///   inside another repository, is fine (a legitimate nested
59    ///   repository).
60    ///
61    /// Synchronous: no network, and no repository to target yet.
62    fn init(&self, path: &Path, opts: &InitOptions) -> Result<RepoRef>;
63
64    fn status(&self, repo: &RepoRef) -> Result<WorkingTree>;
65    /// The commit graph. With `all_refs`, `opts.hidden` drops refs from the
66    /// walk (the commits only they reach go with them; `HEAD` always stays
67    /// while a filter is active); both backends take the tips from
68    /// `domain::visible_tips` and page that one walk with `skip`/`limit`.
69    fn log(&self, repo: &RepoRef, opts: &LogOptions) -> Result<CommitGraph>;
70    /// How many commits [`log`](Self::log) would return for `opts` if it
71    /// were not paged: the same refs (`all_refs`, `start_ref`, HEAD) and
72    /// path filter and `hidden` filter, `skip` and `limit` ignored. Counts without loading any
73    /// commit's text, so it stays cheap on a very large history. An unborn
74    /// repository is `0`. Read-only; nothing to journal.
75    fn count_commits(&self, repo: &RepoRef, opts: &LogOptions) -> Result<u64>;
76    fn diff(&self, repo: &RepoRef, target: DiffTarget) -> Result<Vec<FileDiff>>;
77    /// The files [`diff`](Self::diff) lists for the same `target` - same
78    /// paths, same statuses, same order - as cheaply as the backend can
79    /// produce them.
80    ///
81    /// The commit-detail pane shows the list from this and fills the hunks
82    /// in from `diff` a moment later.
83    ///
84    /// A backend for which the list costs what the whole diff costs
85    /// (system git: one `git diff` process either way) answers with the
86    /// whole diff and says so in [`DiffFileList::hunks_included`], so the
87    /// caller never pays twice.
88    fn diff_files(&self, repo: &RepoRef, target: DiffTarget) -> Result<DiffFileList>;
89    /// [`CommitStat`] for each of `ids`, in the order given, for the Log's
90    /// "Changes" column. Each is the commit against its first parent (a
91    /// root commit against nothing) without rename detection, so
92    /// `files` equals the length of `diff(CommitVsParent(id))`. A batch
93    /// so the system backend can answer it with one process instead of
94    /// one per commit. An empty `ids` is an empty answer; an unknown id
95    /// is an error.
96    fn commit_stats(&self, repo: &RepoRef, ids: &[Oid]) -> Result<Vec<CommitStat>>;
97    /// [`diff`](Self::diff) restricted to `paths`: the hunks of just those
98    /// files, so the Diff view can load one file's hunks when it is opened.
99    ///
100    /// Paths are literal (no globbing, no pathspec magic), repo-relative.
101    /// The answer holds the files of `diff(target)` whose path is in
102    /// `paths`, in the same order, with identical statuses and identical
103    /// hunks and hunk ids (ids number the hunks within one file, so
104    /// restricting never renumbers them). An empty `paths` is an empty
105    /// answer, not "everything". Untracked files are not part of any
106    /// `diff` target and are not here either.
107    fn diff_paths(
108        &self,
109        repo: &RepoRef,
110        target: DiffTarget,
111        paths: &[PathBuf],
112    ) -> Result<Vec<FileDiff>>;
113    fn refs(&self, repo: &RepoRef) -> Result<Vec<Ref>>;
114    /// Raw ref values (tag objects not peeled) under `scope`, plus HEAD
115    /// (symbolic, possibly unborn, or detached). A read; the undo
116    /// journal's source of truth for "what did this operation change".
117    /// The hidden `refs/gitpoulpi/` namespace is never listed.
118    fn ref_snapshot(&self, repo: &RepoRef, scope: &RefScope) -> Result<RefSnapshot>;
119    /// An atomic compare-and-swap ref transaction: every update applies
120    /// or none does. A ref that does not hold the expected value is
121    /// `Error::UndoRefused(UndoRefusal::RefMoved)`; a HEAD that is not
122    /// where `SetHead` expects is `HeadMoved`. `SetHead` re-points HEAD
123    /// without touching the index or any file. `reflog_message` is
124    /// written for every ref that moves.
125    fn update_refs(
126        &self,
127        repo: &RepoRef,
128        updates: &[RefUpdate],
129        reflog_message: &str,
130    ) -> Result<()>;
131    /// Moves the branch `branch` from `from` to `to` **and** carries the
132    /// index and working tree along, with `git reset --keep` semantics:
133    /// local changes survive unless the move would overwrite them, in
134    /// which case it is `UndoRefusal::WouldOverwrite` and nothing changed.
135    /// `branch` must be the checked-out branch (else `HeadMoved`) and must
136    /// hold `from` (else `RefMoved`). The undo journal's primitive for
137    /// fast-forwards of the checked-out branch.
138    fn move_head_keep(&self, repo: &RepoRef, branch: &str, from: Oid, to: Oid) -> Result<()>;
139    /// The `key = value` pairs of one repository-local config section,
140    /// full keys (`branch.x.remote`), in file order. Only the sections
141    /// `branch.<name>` and `remote.<name>` are accepted (an undo helper, not a
142    /// general config reader).
143    fn config_section(&self, repo: &RepoRef, section: &str) -> Result<Vec<(String, String)>>;
144    /// [`GitBackend::config_section`] for several sections at once, in the
145    /// order asked. The system-git backend answers with one process
146    /// instead of one per section (the undo journal reads a remote's
147    /// section and every dependent branch's together).
148    fn config_sections(&self, repo: &RepoRef, sections: &[String]) -> Result<Vec<ConfigSection>> {
149        sections
150            .iter()
151            .map(|s| Ok((s.clone(), self.config_section(repo, s)?)))
152            .collect()
153    }
154    /// The `branch.<name>` sections whose `remote` is `remote`, sorted:
155    /// what `git remote remove` deletes and `git remote rename` rewrites
156    /// besides the remote's own section.
157    fn remote_dependents(&self, repo: &RepoRef, remote: &str) -> Result<Vec<String>>;
158    /// Replaces the whole section with `entries` (empty removes it). Same
159    /// restriction as [`GitBackend::config_section`].
160    fn set_config_section(
161        &self,
162        repo: &RepoRef,
163        section: &str,
164        entries: &[(String, String)],
165    ) -> Result<()>;
166    /// The tree id of the index as it is right now (`git write-tree`):
167    /// what a staging operation's undo records before and after. Writes
168    /// tree objects (never the working tree); an index with unresolved
169    /// conflicts has no tree and is an error.
170    fn index_tree(&self, repo: &RepoRef) -> Result<Oid>;
171    /// Makes the index equal `tree` exactly (`git read-tree`). Never
172    /// touches the working tree. The undo journal's primitive for
173    /// stage/unstage; the caller has verified, under the repository's
174    /// write lock, that the index is what it expects.
175    fn index_restore(&self, repo: &RepoRef, tree: Oid) -> Result<()>;
176    /// A safety snapshot of every file under `paths` (repo-relative, `/`
177    /// separated; a directory means everything below it): the index entry
178    /// and the working-tree file, **including untracked files**, as raw
179    /// bytes (no clean filter), with the executable bit and symlinks. It
180    /// writes objects only: neither the index nor the working tree is
181    /// touched. Take it before a destructive operation and keep `tree`
182    /// reachable with a pin ref. Snapshot only what the operation will
183    /// touch, never the whole tree.
184    fn snapshot_create(&self, repo: &RepoRef, paths: &[String]) -> Result<Snapshot>;
185    /// Writes a snapshot's index and working-tree sides back for `paths`,
186    /// exactly: a file the snapshot holds is rewritten (content, mode,
187    /// symlink), and a file under `paths` that the snapshot does *not*
188    /// hold is removed from the index and the disk. Index and working
189    /// tree are restored independently of each other.
190    fn snapshot_restore(&self, repo: &RepoRef, snapshot: Oid, paths: &[String]) -> Result<()>;
191    /// The current [`PathHash`] of every file under `paths` that exists in
192    /// the index or the working tree, sorted by path. Equal to
193    /// `snapshot_create(paths).hashes` taken at the same instant. A read:
194    /// the undo preconditions.
195    fn path_hashes(&self, repo: &RepoRef, paths: &[String]) -> Result<Vec<PathHash>>;
196    /// The raw bytes of the blob `oid` (no filter, no decoding): what a
197    /// snapshot's [`FileHash`] names. "Restore only this" writes them next
198    /// to a file that changed since. A missing object is an error.
199    fn blob_bytes(&self, repo: &RepoRef, oid: Oid) -> Result<Vec<u8>>;
200    /// One page of a reflog, newest entry first. `refname` is `HEAD` or a
201    /// ref (`refs/heads/main`; a bare name is a local branch, see
202    /// [`crate::domain::reflog_refname`]). `old`/`new` are the values
203    /// git stored, `old` being all zeros for the first entry. A ref with
204    /// no reflog (a deleted branch, a tag, `core.logAllRefUpdates` off)
205    /// is an empty page, not an error. A read; shows moves made outside
206    /// GitPoulpi too.
207    fn reflog(
208        &self,
209        repo: &RepoRef,
210        refname: &str,
211        skip: usize,
212        limit: usize,
213    ) -> Result<ReflogPage>;
214    /// Commits no branch, tag, remote-tracking ref or stash reaches (the
215    /// reflogs and GitPoulpi's undo pins do not count as reaching), newest
216    /// first: what a deleted branch left behind (named by a reflog or only
217    /// by an undo pin), and with `opts.deep` the dangling commits of the
218    /// whole object database (what `git fsck --unreachable --no-reflogs`
219    /// lists). A read, bounded by `opts.budget_ms`.
220    fn lost_commits(&self, repo: &RepoRef, opts: &LostCommitOptions) -> Result<LostCommitsPage>;
221    /// Every commit's author, time, subject and body, for the workspace
222    /// search index: the commits reachable from the branches, remote
223    /// branches, tags and HEAD (not stashes, not GitPoulpi's own refs),
224    /// newest first, minus those reachable from `query.known_tips` (so an
225    /// index is brought up to date by asking for what is new). See
226    /// [`CommitMessages`] for `tips`, `replace` and `truncated`. A read.
227    fn commit_messages(
228        &self,
229        repo: &RepoRef,
230        query: &CommitMessagesQuery,
231    ) -> Result<CommitMessages>;
232    /// Deletes `paths` (files, or directories with everything below) from
233    /// the working tree; the index is not touched, so a tracked file shows
234    /// up as a deleted change, as with `rm`. A path that does not exist is
235    /// ignored; a path outside the repository or inside `.git` is an error. The daemon-side home of the
236    /// TUI's "Delete file", so it can be journaled and undone.
237    fn delete_files(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
238    /// Rewrites the bytes of the files `paths` (working tree only; the index
239    /// is not touched) as `op` says: another encoding, other line breaks or
240    /// other indentation (`textconv::convert_bytes`, the editor's own
241    /// functions). A binary file, a missing one, one the target encoding
242    /// cannot hold, is left alone and reported, never damaged; a path
243    /// outside the repository or inside `.git` is an error. The daemon-side
244    /// home of the right pane's "Convert" menu, so one call is one journal
245    /// entry.
246    fn convert_files(
247        &self,
248        repo: &RepoRef,
249        paths: &[String],
250        op: crate::textconv::ConvertOp,
251    ) -> Result<crate::textconv::ConvertReport>;
252    /// Appends `pattern` as its own line to the `.gitignore` named by
253    /// `file` (repo-relative, default `.gitignore`; its file name must be
254    /// `.gitignore`), creating the file and keeping an existing last line
255    /// intact. `Ok(false)` when the pattern is already a line of the file
256    /// (nothing written). The daemon-side home of the TUI's "Ignore" menu,
257    /// so it can be journaled and undone.
258    fn gitignore_add(&self, repo: &RepoRef, pattern: &str, file: Option<&str>) -> Result<bool>;
259    /// Writes the `.gitattributes` rule that makes git diff `paths` as
260    /// `treat` says (see [`crate::domain::Treat::attributes`]): one pattern
261    /// per path (`scope`: the file itself or its extension; `Folder`: the
262    /// path is a folder and the rule covers everything below), relative to
263    /// `file`'s folder. `file` is repo-relative: `None` is the root
264    /// `.gitattributes`, `Some(".git/info/attributes")` the per-clone file,
265    /// else a `.gitattributes` inside the repository (created when
266    /// missing). A rule already naming the same pattern is rewritten rather
267    /// than contradicted. The answer says what was written and whether git
268    /// now really treats `paths` that way (a rule closer to the file, or
269    /// in `.git/info/attributes`, can still override a root one). The
270    /// daemon-side home of "Treat as Binary/Text", journaled like
271    /// [`GitBackend::gitignore_add`], except for the per-clone file, which
272    /// lives outside the working tree.
273    fn gitattributes_treat(
274        &self,
275        repo: &RepoRef,
276        paths: &[String],
277        scope: crate::domain::RuleScope,
278        file: Option<&str>,
279        treat: crate::domain::Treat,
280    ) -> Result<crate::domain::AttributesWrite>;
281    /// Each of `idents` as the repository's `.mailmap` (and `mailmap.file`)
282    /// shows it, in the same order: the canonical name and email, or the
283    /// identity itself when nothing maps it. The system backend asks `git
284    /// check-mailmap`, `Git2Backend` libgit2's `Mailmap`; the contract suite
285    /// pins that they agree. A read.
286    fn mailmap_resolve(
287        &self,
288        repo: &RepoRef,
289        idents: &[crate::domain::rewrite::Ident],
290    ) -> Result<Vec<crate::domain::rewrite::Ident>>;
291    /// Every name and email that authored or committed a commit of `scope`,
292    /// with the counts, most commits first, and what the `.mailmap` already
293    /// maps each to. The Identities list of the history workbench. A read;
294    /// one `git log`, whatever the size of the history.
295    fn mailmap_identities(
296        &self,
297        repo: &RepoRef,
298        scope: &crate::domain::rewrite::Scope,
299        options: &crate::domain::rewrite::ScopeOptions,
300    ) -> Result<crate::domain::rewrite::IdentityList>;
301    /// Appends the lines that map each of `from` to `canonical` to the
302    /// `.mailmap` (`file`: repo-relative, default `.mailmap`; created when
303    /// missing), once each. Nothing is committed. Journaled like
304    /// [`GitBackend::gitignore_add`]: undo puts the previous file back.
305    fn mailmap_add(
306        &self,
307        repo: &RepoRef,
308        canonical: &crate::domain::rewrite::Ident,
309        from: &[crate::domain::rewrite::Ident],
310        file: Option<&str>,
311    ) -> Result<crate::domain::rewrite::MailmapAdded>;
312    /// For each of `paths`, in order: does `git diff` treat it as binary?
313    /// The `diff` attribute decides when a rule sets or unsets it (`binary`
314    /// unsets it); otherwise the content does, with git's own sniff (a NUL
315    /// in the first 8000 bytes of the working-tree file). A read.
316    fn binary_paths(&self, repo: &RepoRef, paths: &[String]) -> Result<Vec<bool>>;
317    /// The repo-relative paths a patch file would touch (every side of a
318    /// rename), without applying it: what to snapshot before
319    /// [`GitBackend::patch_apply`].
320    fn patch_files(&self, repo: &RepoRef, patch: &Path) -> Result<Vec<String>>;
321    fn stashes(&self, repo: &RepoRef) -> Result<Vec<Stash>>;
322    fn remotes(&self, repo: &RepoRef) -> Result<Vec<Remote>>;
323    /// The remote-tracking namespaces no remote is configured for: refs
324    /// under `refs/remotes/<name>/` (or a tag mirror under
325    /// [`crate::domain::REMOTE_TAG_MIRROR_PREFIX`]) whose `<name>` is not in
326    /// [`GitBackend::remotes`] - what a repository keeps after its remote
327    /// went (a fork that is not one any more). Names split like
328    /// [`crate::domain::split_remote_ref`] does (a configured `grp/sub`
329    /// owns its refs; the rest of `grp/` is the leftover `grp`), sorted.
330    /// [`GitBackend::remote_remove`] on such a name deletes those refs.
331    fn leftover_remotes(&self, repo: &RepoRef) -> Result<Vec<String>>;
332    /// Every worktree of `repo`, main one first (see [`Worktree`]).
333    fn worktrees(&self, repo: &RepoRef) -> Result<Vec<Worktree>>;
334    /// Every submodule `.gitmodules` declares, sorted by path, with its
335    /// state against what the superproject records. Top level only: a
336    /// submodule's own submodules are listed by that repository. An
337    /// uninitialized submodule is listed (state `Uninitialized`, no
338    /// `head`); a repository without `.gitmodules` answers an empty list
339    /// without spawning anything.
340    fn submodules(&self, repo: &RepoRef) -> Result<Vec<Submodule>>;
341    /// Registers submodules in `.git/config` (`git submodule init`), without
342    /// cloning anything. Empty `paths` is every submodule; an unknown path is
343    /// an error.
344    fn submodule_init(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
345    /// `git submodule update [--init] [--recursive] [-- paths]`: checks each
346    /// submodule out at the commit the superproject records, cloning it first
347    /// with `init`. May reach the network (the submodule's remote), so a
348    /// caller that cares about prompts applies `credentials.https_mode`
349    /// first, as the daemon does.
350    fn submodule_update(&self, repo: &RepoRef, opts: &SubmoduleUpdateOptions) -> Result<()>;
351    /// Turns any revision spelling git accepts (`HEAD`, `HEAD~2`, a
352    /// branch or tag name, a full or abbreviated sha) into the [`Oid`] of
353    /// the *commit* it names, peeling annotated tags on the way.
354    ///
355    /// The only sanctioned bridge from the strings CLI/MCP callers type to
356    /// the `Oid`s every mutating operation takes, so no frontend runs
357    /// `git rev-parse` outside the seam.
358    ///
359    /// An unresolvable revision is an `Err`, never a fallback to HEAD.
360    fn resolve(&self, repo: &RepoRef, rev: &str) -> Result<Oid>;
361
362    /// The best common ancestor of two commits (`git merge-base a b`), or
363    /// `None` when their histories share nothing. A read; the code review
364    /// view diffs `merge_base(base, head)..head`, which is what a host shows.
365    fn merge_base(&self, repo: &RepoRef, a: Oid, b: Oid) -> Result<Option<Oid>>;
366
367    /// `(ahead, behind)` of `tip` against `base`: the commits reachable from
368    /// `tip` but not from `base`, and the reverse (`rev-list --left-right
369    /// --count tip...base`). A read; the branching workflow's "behind its
370    /// parent by n".
371    fn ahead_behind(&self, repo: &RepoRef, tip: Oid, base: Oid) -> Result<(u32, u32)>;
372
373    /// Like [`Self::ahead_behind`] but patch-equivalent commits do not
374    /// count (`rev-list --cherry-pick --left-right --count local...remote`):
375    /// `(local_unmatched, remote_unmatched)`. A remote that only holds
376    /// older copies of rebased local commits reads `(n, 0)` here while
377    /// `ahead_behind` says it diverged. A read.
378    fn cherry_counts(&self, repo: &RepoRef, local: Oid, remote: Oid) -> Result<(u32, u32)>;
379
380    /// The paths a merge of `theirs` into `ours` would leave conflicted,
381    /// sorted and without duplicates, computed **without touching the work
382    /// tree, the index, HEAD or any ref** (proactive conflict detection).
383    /// Empty when the merge would go through, including when one commit
384    /// contains the other.
385    ///
386    /// `SystemGitBackend` runs `git merge-tree --write-tree --name-only -z`
387    /// (git 2.38 or later; an older git is `Error::Unsupported`) and
388    /// `Git2Backend` merges the two commits in memory. Both detect renames,
389    /// so rename/modify merges cleanly on both and the sets agree; a merge
390    /// can write the merged blobs and trees into the object database as
391    /// unreferenced objects, which `git gc` collects.
392    fn predict_merge_conflicts(
393        &self,
394        repo: &RepoRef,
395        ours: Oid,
396        theirs: Oid,
397    ) -> Result<Vec<String>>;
398
399    /// A file's *content* - as opposed to a diff of it - at a commit,
400    /// at the index, or on disk (see [`BlobSource`]).
401    ///
402    /// `path` is always relative to the repository root, with `/`
403    /// separators, matching every other path in the domain.
404    ///
405    /// A binary or oversized file is a successful [`Blob`] whose
406    /// [`crate::domain::BlobContent`] says so, not an `Err`: "this is a
407    /// 4 GiB PNG" is something a file viewer renders. Both backends learn
408    /// the size before reading anything, so an oversized file is never
409    /// pulled into memory just to be rejected. A path that does not
410    /// exist at `source` *is* an `Err`.
411    fn read_blob(&self, repo: &RepoRef, path: &Path, source: &BlobSource) -> Result<Blob>;
412
413    /// A file's **exact bytes** at `source` (same sources and path rules as
414    /// [`GitBackend::read_blob`]): no smudge filter, no decoding. What an
415    /// image viewer needs, since `read_blob` drops the bytes of a binary
416    /// file.
417    ///
418    /// The size is learned first; above `max` bytes the answer is
419    /// [`crate::domain::BlobBody::TooLarge`] and nothing is read. An LFS
420    /// pointer comes back as `BlobBody::Lfs`, carrying the real object when
421    /// it is in the local LFS store and within `max`. A path that does not
422    /// exist at `source` is an `Err`.
423    fn read_blob_bytes(
424        &self,
425        repo: &RepoRef,
426        path: &Path,
427        source: &BlobSource,
428        max: u64,
429    ) -> Result<crate::domain::BlobBytes>;
430
431    /// Every path present in the repository **at** `at`, sorted, with
432    /// `/` separators - the whole tree, not the subset a commit changed
433    /// (what the `View all files` toggle needs).
434    ///
435    /// Directories are not listed; a caller wanting a folder view derives
436    /// it from the path list.
437    fn list_tree(&self, repo: &RepoRef, at: Oid) -> Result<Vec<PathBuf>>;
438
439    /// The lines of the files **at** `at` that contain any of `terms`
440    /// (plain strings, case-sensitive), at most `max_hits` for each term,
441    /// sorted by path then line. A read: nothing is journaled.
442    ///
443    /// Binary files, LFS pointers and files over
444    /// [`crate::domain::MAX_GREP_FILE_BYTES`] are skipped; blank terms are
445    /// ignored (see [`crate::domain::grep_bytes`] for the rules both
446    /// backends share). An unknown revision is an `Err`.
447    fn grep_tree(
448        &self,
449        repo: &RepoRef,
450        at: Oid,
451        terms: &[String],
452        max_hits: usize,
453    ) -> Result<Vec<crate::domain::GrepHit>>;
454
455    /// Per-line attribution for `path` as of the commit `at`.
456    ///
457    /// Always a committed revision: blaming a dirty working tree would
458    /// attribute half the lines to git's "Not Committed Yet" pseudo-commit,
459    /// whose zero oid nothing downstream can click through to. Callers
460    /// that want "blame what I'm looking at" resolve a commit first.
461    ///
462    /// The returned lines are the same lines [`GitBackend::read_blob`]
463    /// would produce for `BlobSource::Commit(at)`, in the same order --
464    /// they share [`crate::domain::BlobContent::from_bytes`] - so a
465    /// blame gutter can be drawn beside file content without the two
466    /// disagreeing about where a line is.
467    ///
468    /// Whole-file renames are followed (blame's default): a line born
469    /// under an old name carries that name in `BlameLine::orig_path`.
470    /// Lines are not chased across files (no `-M`/`-C` line movement).
471    fn blame(&self, repo: &RepoRef, path: &Path, at: Oid) -> Result<Blame>;
472
473    /// The commits that changed `path`, newest first, **following renames**
474    /// (`git log --follow`), starting from `start` and returning at most
475    /// `limit` entries after skipping `skip`.
476    ///
477    /// - History is the default simplified history, not first-parent: a
478    ///   merge appears only when the file differs from every parent (a
479    ///   conflict resolution), and both sides of a kept merge are walked.
480    ///   A kept merge reports its change and line counts against its
481    ///   **first** parent.
482    /// - A file deleted then re-added shows the re-adding commit as
483    ///   `Added`, the deleting one as `Deleted`, and keeps going back.
484    /// - Lazy: the walk stops once `skip + limit + 1` entries are known
485    ///   (the extra one sets `FileHistoryPage::more`), so the first page
486    ///   of a huge history is cheap; deep pages cost their depth.
487    /// - A path that never existed at or before `start` is an empty page.
488    fn file_history(
489        &self,
490        repo: &RepoRef,
491        path: &Path,
492        start: Oid,
493        skip: usize,
494        limit: usize,
495    ) -> Result<FileHistoryPage>;
496
497    // -- staging (every granularity funnels through StageTarget) --
498    fn stage(&self, repo: &RepoRef, target: &StageTarget) -> Result<()>;
499    fn unstage(&self, repo: &RepoRef, target: &StageTarget) -> Result<()>;
500
501    // -- history mutation --
502    fn commit(&self, repo: &RepoRef, message: &str, opts: &CommitOptions) -> Result<Oid>;
503    fn checkout(&self, repo: &RepoRef, target: &CheckoutTarget) -> Result<()>;
504    /// Discards every uncommitted change to each of `paths` (relative to
505    /// the repository root, `/`-separated): a tracked path's index entry
506    /// and working-tree copy are both reset back to `HEAD`, and a path with
507    /// no `HEAD` entry (untracked, or staged but never committed) is
508    /// removed from the index if present and deleted from the working tree.
509    ///
510    /// Unlike [`CheckoutTarget::File`] (one already-tracked path from a
511    /// caller-supplied commit), this takes several paths and handles
512    /// untracked ones, which are not a `checkout` source at all.
513    ///
514    /// Empty `paths` is a no-op success. A missing path, or one with
515    /// nothing to discard, is not an error: discarding is idempotent, so a
516    /// caller racing another client's discard sees success.
517    fn discard(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
518    /// Reverts one hunk, or some changed lines of one hunk, of a file's
519    /// **unstaged** changes in the working tree - the
520    /// working-tree half of what [`GitBackend::unstage`] does to the index
521    /// with the same selection, and the "Discard Hunk" / "Discard
522    /// this line" actions.
523    ///
524    /// The target is resolved against a working-tree-vs-index diff the
525    /// backend computes itself, numbered as [`StageTarget::Hunk`] /
526    /// [`StageTarget::Line`] are when staging. The index is never touched:
527    /// a line that is staged *and* then edited again goes back to its
528    /// staged content, not to `HEAD`'s. Only the named lines change on
529    /// disk; every other change in the file, in that hunk or another,
530    /// survives.
531    ///
532    /// Selecting an added line removes it from the file; selecting a
533    /// removed line puts it back. An unknown hunk, or a selection whose
534    /// patch no longer applies (the file moved underneath the caller), is
535    /// an error and leaves the file exactly as it was.
536    fn discard_part(&self, repo: &RepoRef, target: &DiscardTarget) -> Result<()>;
537    fn branch_create(&self, repo: &RepoRef, name: &str, at: Oid) -> Result<()>;
538    /// Create the local branch `local_name` tracking the remote-tracking
539    /// branch `upstream` (spelled the way `RefKind::RemoteBranch` spells
540    /// it, `origin/feature/login`) and check it out - what
541    /// `git checkout -b <local_name> --track <upstream>` does, in one
542    /// operation.
543    ///
544    /// One call because the three steps are only ever wanted together, and
545    /// separate daemon round trips can interleave with another client's
546    /// mutation, leaving a branch created but not checked out.
547    ///
548    /// An existing `local_name` is an **error**, never a silent checkout of
549    /// that branch; callers wanting that call [`GitBackend::checkout`].
550    fn branch_create_tracking(
551        &self,
552        repo: &RepoRef,
553        local_name: &str,
554        upstream: &str,
555    ) -> Result<()>;
556    fn branch_delete(&self, repo: &RepoRef, name: &str) -> Result<()>;
557    fn branch_rename(&self, repo: &RepoRef, old_name: &str, new_name: &str) -> Result<()>;
558    /// Sets the local branch `branch`'s upstream to the remote-tracking
559    /// branch `upstream` (spelled `origin/feature`, as
560    /// `RefKind::RemoteBranch` joins it), or removes it with `None` --
561    /// `git branch --set-upstream-to` / `--unset-upstream`.
562    ///
563    /// The upstream must exist: pointing a branch at a remote branch
564    /// nobody has fetched is an error rather than config that silently
565    /// names nothing. Unsetting an upstream that is not set is a
566    /// success - the state asked for is the state reached.
567    fn branch_set_upstream(
568        &self,
569        repo: &RepoRef,
570        branch: &str,
571        upstream: Option<&str>,
572    ) -> Result<()>;
573
574    /// Moves the local branch `branch` forward to the commit `target`,
575    /// **only** when that is a fast-forward - the
576    /// `Fast-forward <branch> to <other>` action.
577    ///
578    /// - `branch`'s tip an ancestor of `target`: the branch moves there.
579    ///   If it is the branch checked out in *this* worktree, the index and
580    ///   working tree follow, as `git merge --ff-only` does; local changes
581    ///   that the move would overwrite refuse it, with nothing changed.
582    ///   Any other branch just has its ref moved (`git fetch . a:b`'s
583    ///   semantics) and no file is touched.
584    /// - `target` already contained in `branch` (the same commit, or
585    ///   behind it): [`FastForwardOutcome::UpToDate`], nothing moves.
586    /// - The two diverged: [`crate::Error::NotFastForward`], nothing moves.
587    ///
588    /// A branch checked out in *another* linked worktree is refused:
589    /// moving it would leave that worktree's files describing the old
590    /// commit, which is what `git fetch . a:b` refuses too.
591    fn fast_forward(&self, repo: &RepoRef, branch: &str, target: Oid)
592        -> Result<FastForwardOutcome>;
593
594    /// Adds a linked worktree at `path` (`git worktree add`), on the
595    /// branch or commit [`WorktreeAddOptions`] names, optionally on a
596    /// new branch created there, and returns its entry as
597    /// [`GitBackend::worktrees`] would list it.
598    ///
599    /// `path` must not exist, or be an empty directory - git's own rule.
600    /// Missing parent directories are created. A branch already checked
601    /// out in another worktree, a `new_branch` name already taken, and a
602    /// `WorktreeStart::Branch` that is not a local branch are errors, and
603    /// leave no worktree behind.
604    fn worktree_add(
605        &self,
606        repo: &RepoRef,
607        path: &Path,
608        opts: &WorktreeAddOptions,
609    ) -> Result<Worktree>;
610
611    /// The uncommitted changes of the worktree at `path` (tracked and
612    /// untracked, not ignored), in path order. Empty when it is clean.
613    fn worktree_changes(&self, repo: &RepoRef, path: &Path) -> Result<Vec<WorktreeChange>>;
614
615    /// Removes the linked worktree at `path` (`git worktree remove`).
616    ///
617    /// The main worktree is refused. A worktree with uncommitted changes
618    /// is refused unless `opts.force`, or unless `opts.commit` / `opts.stash`
619    /// first saves them (commit on the worktree's branch, or a
620    /// `stash push -u`); a refusal leaves the worktree untouched. A
621    /// locked worktree is refused. Not journaled: removing the folder
622    /// cannot be undone, but a commit or stash made first stays.
623    fn worktree_remove(
624        &self,
625        repo: &RepoRef,
626        path: &Path,
627        opts: &WorktreeRemoveOptions,
628    ) -> Result<WorktreeRemoved>;
629
630    /// Writes `source` out as a patch file at `dest` (`git format-patch`
631    /// for commits/ranges, `git diff HEAD --binary` for the working
632    /// tree).
633    ///
634    /// Refuses, writing nothing, when: `dest` already exists; `dest`'s
635    /// parent directory does not exist; the resulting patch would be
636    /// empty; a [`PatchSource::Commits`] entry is a merge commit or
637    /// names an unknown commit; or the working tree's `HEAD` is unborn
638    /// (`PatchSource::WorkingTree` on a repository with no commits).
639    fn patch_create(
640        &self,
641        repo: &RepoRef,
642        source: &PatchSource,
643        dest: &Path,
644    ) -> Result<PatchCreated>;
645
646    /// Applies `patch` (a file on disk, in `git apply`'s format) to the
647    /// working tree only - never the index - via `git apply`.
648    ///
649    /// Atomic: a patch that does not apply cleanly changes nothing.
650    fn patch_apply(&self, repo: &RepoRef, patch: &Path) -> Result<PatchApplied>;
651
652    /// Replays the changes `commit` made (its diff against its parent, or
653    /// against the empty tree for a root commit) onto the working tree
654    /// only - never the index, never HEAD. Binary files and line endings
655    /// come out as in the commit.
656    ///
657    /// All or nothing: when any file does not apply cleanly, nothing is
658    /// changed and the error says why. A merge commit is refused with
659    /// [`crate::Error::ApplyRefused`]. Returns the touched paths.
660    fn apply_commit_to_worktree(&self, repo: &RepoRef, commit: Oid) -> Result<PatchApplied>;
661
662    fn tag_create(
663        &self,
664        repo: &RepoRef,
665        name: &str,
666        at: Oid,
667        annotated_message: Option<&str>,
668    ) -> Result<()>;
669    fn tag_delete(&self, repo: &RepoRef, name: &str) -> Result<()>;
670
671    /// Replaces the existing tag `name` with an *annotated* tag carrying
672    /// `message`, at the same commit.
673    ///
674    /// Separate from `tag_create(.., force: true)` because it must *keep*
675    /// the tag where it is: both backends read the tag's own peeled commit
676    /// and put it back there (pinned by the contract). Annotating a tag
677    /// that does not exist is an error; annotating an already-annotated
678    /// one replaces its message.
679    fn tag_annotate(&self, repo: &RepoRef, name: &str, message: &str) -> Result<()>;
680
681    /// Moves the existing local tag `name` to the commit `to`, keeping its
682    /// kind: a lightweight tag stays a ref to the commit, an annotated one
683    /// is re-created with the **same message and tagger line verbatim** (see
684    /// [`crate::domain::retarget_tag_object`]), so only the object it points
685    /// at changes. A signed tag is refused (its signature would no longer
686    /// match), as is a tag of anything but a commit.
687    ///
688    /// Without `force` the move must be a fast-forward (the tag's commit is
689    /// an ancestor of `to`): otherwise [`crate::Error::NotFastForward`] and
690    /// nothing changes. Moving a tag onto the commit it already names is a
691    /// no-op. The update is checked against the tag's old value, so a tag
692    /// that moved meanwhile is an error, not a lost update.
693    ///
694    /// Local only. A remote's copy and the tag mirror are not touched, so a
695    /// tag the remote has becomes `differs`; the caller decides about a push.
696    fn tag_move(&self, repo: &RepoRef, name: &str, to: Oid, force: bool) -> Result<()>;
697
698    /// Merges the branch (or any revision) `branch` into the commit tag
699    /// `name` points at, then moves the tag onto the merge commit, whose
700    /// parents are the tag's old commit and `branch`'s tip. Returns the merge
701    /// commit.
702    ///
703    /// Detached: no branch moves, HEAD, the index and the working tree are
704    /// never touched. A merge that conflicts is
705    /// [`crate::Error::Conflict`] with nothing changed (the tag stays put);
706    /// a `branch` the tag's commit already contains is an error, since there
707    /// is nothing to merge. `message` defaults to
708    /// `Merge branch '<branch>' into tag '<name>'`. The tag keeps its kind
709    /// exactly as [`GitBackend::tag_move`] does.
710    fn tag_merge_branch(
711        &self,
712        repo: &RepoRef,
713        name: &str,
714        branch: &str,
715        message: Option<&str>,
716    ) -> Result<Oid>;
717
718    /// Sends tags to `remote` - one named tag, several, or every tag no
719    /// remote is known to have (see [`crate::domain::TagSelection`]).
720    ///
721    /// One operation so the frontends get one result, one broadcast and one
722    /// credential prompt for what the user did as one gesture.
723    ///
724    /// Both backends must also **record the push locally**, by writing the
725    /// mirror refs described at
726    /// [`crate::domain::REMOTE_TAG_MIRROR_PREFIX`]; otherwise the tag keeps
727    /// its "unpushed" marker until the next fetch.
728    ///
729    /// The returned [`PushOutcome::pushed_refs`] holds the tag names
730    /// actually sent, in the order they were sent. Pushing an empty
731    /// selection is a success reporting nothing.
732    async fn tag_push(
733        &self,
734        repo: &RepoRef,
735        remote: &str,
736        selection: &crate::domain::TagSelection,
737    ) -> Result<PushOutcome>;
738
739    /// Deletes tag `name` from `remote` (`git push --delete`), leaving
740    /// the local tag alone.
741    ///
742    /// [`GitBackend::tag_delete`] is the other half and must not touch the
743    /// remote either.
744    ///
745    /// Drops the tag's mirror ref on success, as `tag_push` writes one.
746    async fn tag_delete_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()>;
747
748    /// Fetches the single tag `name` from `remote` into `refs/tags/` - the
749    /// "Fetch this tag" of a remote-only tag. Never overwrites: a local
750    /// tag of that name at another commit is an error, not a silent loss.
751    /// Network. The remote tag mirror already knows the tag, so it is
752    /// not rewritten.
753    async fn tag_fetch(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()>;
754
755    /// Moves the local tag `name` to what `remote` has under that name, as
756    /// the tag mirror knows it (the last fetch or push): no network. The
757    /// mirror's object is taken as is, so an annotated tag becomes that very
758    /// tag object, never a lightweight tag at its commit. The "Use the
759    /// remote's version" of a tag that differs. An error when no mirror ref
760    /// names that tag on that remote, or when there is no local tag to move.
761    fn tag_take_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()>;
762
763    /// Force-pushes the local tag `name` to `remote`, leased on the value the
764    /// tag mirror says the remote has (`--force-with-lease=<ref>:<mirror>`):
765    /// a remote that moved since the last fetch is refused, typed
766    /// ([`crate::Error::PushRejected`] with `StaleLease`), and nothing is
767    /// overwritten. The mirror follows on success. An error when the mirror
768    /// has no such tag on that remote (use `tag_push` for a tag the remote
769    /// lacks) or there is no local tag. Network.
770    async fn tag_force_push(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()>;
771
772    /// Deletes branch `name` from `remote` (`push --delete`), leaving
773    /// any local branch of that name alone; the remote-tracking ref goes
774    /// with it. The remote twin of [`GitBackend::branch_delete`], which
775    /// must not touch the remote.
776    async fn branch_delete_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()>;
777
778    /// What `remote` holds at the fully qualified `full_ref` (`refs/heads/x`
779    /// or `refs/tags/v1`) right now, asked of the server (`ls-remote`);
780    /// `None` when it has no such ref. For an annotated tag, the tag object.
781    /// A network read, never answered from local tracking refs. It is the
782    /// value an undo of a remote deletion records and later checks.
783    async fn remote_ref_value(
784        &self,
785        repo: &RepoRef,
786        remote: &str,
787        full_ref: &str,
788    ) -> Result<Option<Oid>>;
789
790    /// Moves the branch or tag `full_ref` on `remote` from `expect` to `new`,
791    /// never forced: `Some(oid)` pushes that object there (it re-creates a
792    /// deleted ref when `expect` is `None`), `None` deletes the ref. The
793    /// remote must hold `expect` at that moment (a lease); if it moved on,
794    /// [`crate::Error::PushRejected`] with `StaleLease` comes back and
795    /// nothing changed. An object this repository no longer has is
796    /// [`crate::Error::UndoRefused`] with `RemoteObjectMissing`. Network.
797    /// The remote-tracking ref (branch) or remote-tag mirror (tag) follows.
798    async fn remote_ref_update(
799        &self,
800        repo: &RepoRef,
801        remote: &str,
802        full_ref: &str,
803        new: Option<Oid>,
804        expect: Option<Oid>,
805    ) -> Result<()>;
806    fn merge(&self, repo: &RepoRef, from: &Ref, opts: &MergeOptions) -> Result<MergeOutcome>;
807    fn rebase(&self, repo: &RepoRef, onto: &Ref, opts: &RebaseOptions) -> Result<RebaseOutcome>;
808
809    /// The range an interactive rebase from `upstream` would replay,
810    /// oldest first - what a frontend builds an [`InteractiveRebase`]
811    /// plan's `steps` from. `upstream: None` means the whole history
812    /// (`--root`). A read.
813    fn rebase_plan(&self, repo: &RepoRef, upstream: Option<Oid>) -> Result<RebasePlanDraft>;
814
815    /// Runs an interactive rebase from an explicit, pre-decided todo list
816    /// rather than an interactively edited one - the plan a frontend
817    /// built (possibly from [`GitBackend::rebase_plan`]), validated
818    /// again here regardless.
819    ///
820    /// Refuses (leaving the repository untouched) with
821    /// [`crate::Error::RebaseRefused`] when: another operation is in
822    /// progress, the working tree is dirty, `req.upstream` is not an
823    /// ancestor of HEAD, the range contains a merge commit, `req.steps`
824    /// is not exactly a permutation of the range, a `Squash`/`Fixup` step
825    /// is first, or a `Reword` step has no message.
826    ///
827    /// Never consults the user's `sequence.editor`/`core.editor`/
828    /// `rebase.autoSquash` config - the plan given here is authoritative.
829    fn rebase_interactive(&self, repo: &RepoRef, req: &InteractiveRebase) -> Result<RebaseOutcome>;
830
831    /// The state of a rebase (interactive or plain) currently in
832    /// progress, or `None` if none is. A read.
833    fn rebase_state(&self, repo: &RepoRef) -> Result<Option<RebaseState>>;
834
835    /// Resumes a rebase stopped by a conflict or an `edit` step
836    /// (`git rebase --continue`). [`crate::Error::RebaseRefused`] with
837    /// [`crate::domain::RebaseRefusal::NoRebaseInProgress`] if none is
838    /// running.
839    fn rebase_continue(&self, repo: &RepoRef) -> Result<RebaseOutcome>;
840
841    /// Skips the commit a rebase is stopped at (`git rebase --skip`).
842    fn rebase_skip(&self, repo: &RepoRef) -> Result<RebaseOutcome>;
843
844    /// Aborts a rebase in progress, restoring the branch and HEAD to
845    /// where they were before it started (`git rebase --abort`).
846    fn rebase_abort(&self, repo: &RepoRef) -> Result<()>;
847
848    fn cherry_pick(
849        &self,
850        repo: &RepoRef,
851        commits: &[Oid],
852        opts: &CherryPickOptions,
853    ) -> Result<CherryPickOutcome>;
854    /// Reverts `commit` with a new commit. A merge commit needs
855    /// `mainline`: the 1-based number of the parent whose side is kept
856    /// (`git revert -m`); `None` on a merge commit is an error.
857    fn revert(&self, repo: &RepoRef, commit: Oid, mainline: Option<u32>) -> Result<RevertOutcome>;
858    fn reset(&self, repo: &RepoRef, target: Oid, mode: ResetMode) -> Result<()>;
859
860    /// Gives `commit` the message `message`, keeping everything else.
861    ///
862    /// `commit` must be HEAD or an ancestor of HEAD. The commit is
863    /// re-created with the same tree, parents and author (name, email
864    /// *and date*); every commit between it and HEAD - the descendants
865    /// that are ancestors of HEAD - is then re-created on top of it,
866    /// again with its own tree, author and message, so merges among them
867    /// are kept as merges with their other parents untouched. Committer
868    /// is the current identity at the current time, as with `git rebase`
869    /// or `git commit --amend`. Finally the checked-out branch (or a
870    /// detached HEAD) moves to the new tip, with `ORIG_HEAD` and a reflog
871    /// entry recording the old one.
872    ///
873    /// Only messages change, so the rewrite cannot conflict and **the index
874    /// and working tree are never touched**: on HEAD this is an amend of
875    /// the message alone (staged changes stay staged, *not* folded in as
876    /// `git commit --amend` would), and a dirty working tree is no reason
877    /// to refuse. No rebase runs, so the repository is never left
878    /// mid-operation: either the branch moved or nothing did.
879    ///
880    /// The message is stored as [`crate::domain::normalize_reword_message`]
881    /// leaves it. Refusals are [`crate::Error::RewordRefused`]: the
882    /// commit is not on the current branch, a merge/rebase/... is in
883    /// progress, or the message is empty. Other branches or tags pointing
884    /// into the rewritten range are left where they are, as `git rebase`
885    /// leaves them.
886    fn reword(&self, repo: &RepoRef, commit: Oid, message: &str) -> Result<RewordOutcome>;
887
888    /// [`GitBackend::reword`] generalised to the commit's other
889    /// properties: whichever of `amend`'s message, author name/email/date
890    /// and committer name/email/date are `Some` replace the commit's; the
891    /// rest (tree, parents, every `None`) is kept. Same walk, same
892    /// descendants re-created on top (their own authors kept), same
893    /// guarantees (index and working tree untouched, no rebase) and the
894    /// same typed refusals, plus `InvalidIdentity` and `InvalidDate`;
895    /// [`crate::domain::CommitAmend::resolve`] runs first. Unless a
896    /// committer field says otherwise the committer is the current
897    /// identity, now. The reflog entry reads `amend: <oid> <summary>`.
898    fn amend_commit(
899        &self,
900        repo: &RepoRef,
901        commit: Oid,
902        amend: &CommitAmend,
903    ) -> Result<RewordOutcome>;
904
905    /// The pieces `commit` can be split into, numbered with `--no-renames`
906    /// (never from `diff(CommitVsParent)`, which honours `diff.renames`).
907    /// Text-modified files list hunks; binary, mode-only, added, deleted,
908    /// submodule and LFS files are whole-only. A read.
909    fn split_source(&self, repo: &RepoRef, commit: Oid) -> Result<SplitSource>;
910
911    /// Breaks `req.commit` into `req.parts` (oldest first) by plumbing, as
912    /// `reword` does: the last part carries the original tree, the
913    /// descendants are re-created on top, the index and working tree are
914    /// never touched. Refusals are [`crate::Error::SplitRefused`] and
915    /// [`crate::domain::validate_split`] runs first.
916    fn split_commit(&self, repo: &RepoRef, req: &SplitCommit) -> Result<SplitOutcome>;
917
918    // -- history rewrite (the history-rewrite design) --
919    /// Computes `recipe` into a temporary pack under the repository's
920    /// `gitpoulpi/rewrite/<run>/` directory and describes the result; no ref
921    /// and no object store moves. A read. The preview is the real run:
922    /// [`GitBackend::rewrite_apply`] indexes exactly that pack. `progress`
923    /// returning `Break` cancels and leaves nothing behind. Refusals are
924    /// [`crate::Error::RewriteRefused`];
925    /// [`crate::domain::rewrite::validate_recipe`] runs first.
926    fn rewrite_preview(
927        &self,
928        repo: &RepoRef,
929        recipe: &Recipe,
930        progress: RewriteProgressSink<'_>,
931    ) -> Result<RewritePlan>;
932
933    /// Indexes the previewed pack and moves every ref in one transaction with
934    /// compare-and-swap on the old values (a moved ref fails the whole run,
935    /// `RewriteRefusal::Stale`). Journaled by the daemon as one entry.
936    fn rewrite_apply(&self, repo: &RepoRef, plan: &RewritePlan) -> Result<RewriteOutcome>;
937
938    /// Applies a preview whose recipe extracts a subdirectory as a new
939    /// repository (`ExtractMode::Clone` or `Submodule`) instead of moving
940    /// this repository's refs: a `git clone --no-local` of this repository
941    /// into `target` (a folder that does not exist or is empty) is rewritten
942    /// there with the recipe, then cleaned of the old history. `Clone` leaves
943    /// this repository untouched and the outcome moves no ref here;
944    /// `Submodule` also adds one commit to the current branch that replaces
945    /// the folder by a submodule of `target` (the outcome's one ref change),
946    /// the old history stays. Journaled by the daemon (a submodule commit is
947    /// undone by moving the branch back). `Error::RewriteRefused` otherwise.
948    fn rewrite_extract(
949        &self,
950        _repo: &RepoRef,
951        _plan: &RewritePlan,
952        _target: &Path,
953    ) -> Result<RewriteOutcome> {
954        Err(crate::Error::Unsupported {
955            operation: "rewrite extract",
956        })
957    }
958
959    /// Deletes a preview's temporary objects. Idempotent.
960    fn rewrite_discard(&self, repo: &RepoRef, run: &RunId) -> Result<()>;
961
962    /// A previewed plan, without its rows, rebuilt from the run directory
963    /// the preview left (so a preview outlives its daemon). `None` when the
964    /// run is gone or its stored plan does not hash to its digest.
965    fn rewrite_load(&self, _repo: &RepoRef, _run: &RunId) -> Result<Option<RewritePlan>> {
966        Ok(None)
967    }
968
969    /// What an applied run moved, from the record its apply left in the run
970    /// directory (`moved.json`), with the directory the maps are in. This is
971    /// what the collaborator note and the push are built from; it outlives
972    /// the daemon. `RewriteRefusal::Stale` when the run was not applied here
973    /// or its directory was swept.
974    fn rewrite_record(
975        &self,
976        _repo: &RepoRef,
977        _run: &RunId,
978    ) -> Result<crate::domain::rewrite::RewriteRecord> {
979        Err(crate::Error::Unsupported {
980            operation: "rewrite record",
981        })
982    }
983
984    /// The run's `commit-map` and `ref-map` (git-filter-repo's format),
985    /// copied to `out` when given. A read.
986    fn rewrite_maps(
987        &self,
988        _repo: &RepoRef,
989        _run: &RunId,
990        _out: Option<&Path>,
991    ) -> Result<crate::domain::rewrite::RewriteMaps> {
992        Err(crate::Error::Unsupported {
993            operation: "rewrite maps",
994        })
995    }
996
997    /// Pushes the refs an applied run moved that were on a remote, each with
998    /// `--force-with-lease=<ref>:<the remote's id when the preview ran>`
999    /// (never a plain force), one `--atomic` push per remote where the
1000    /// server allows it. Protected refs are left out unless asked for. A
1001    /// rejection is a per-ref status in the answer, not an error. Not
1002    /// journaled and not undoable; the record of what was pushed lets a later
1003    /// undo of the rewrite warn.
1004    async fn push_rewritten(
1005        &self,
1006        _repo: &RepoRef,
1007        _req: &crate::domain::rewrite::PushRewritten,
1008    ) -> Result<crate::domain::rewrite::PushRewrittenOutcome> {
1009        Err(crate::Error::Unsupported {
1010            operation: "push rewritten",
1011        })
1012    }
1013
1014    /// Deletes the old history of rewrite journal entries from this
1015    /// repository for good: drops the entries' undo pins, expires the
1016    /// reflogs that name the old commits, removes the applied runs' folders,
1017    /// prunes the object store (`gc --prune=now`), then checks that every
1018    /// object reachable only from the old tips is gone. Anything that still
1019    /// holds the old history (a branch outside the rewrite's scope, a stash,
1020    /// another worktree's HEAD, a remote-tracking ref, a pin of an entry that
1021    /// is not part of the request, ...) is a typed
1022    /// [`crate::domain::rewrite::PurgeBlocker`] and the call changes
1023    /// **nothing** (`PurgeStatus::Blocked`). With `dry_run` it only reports
1024    /// (`Ready` or `Blocked`). Stashes are never expired. Not journaled and
1025    /// not undoable; the daemon marks the entries `Purged`. `progress` is told
1026    /// each step; there is no cancel.
1027    fn rewrite_purge(
1028        &self,
1029        _repo: &RepoRef,
1030        _req: &crate::domain::rewrite::PurgeRequest,
1031        _progress: crate::domain::rewrite::PurgeProgressSink<'_>,
1032    ) -> Result<crate::domain::rewrite::PurgeOutcome> {
1033        Err(crate::Error::Unsupported {
1034            operation: "rewrite purge",
1035        })
1036    }
1037
1038    /// What a content rule did to `path` in the preview's commit `commit`:
1039    /// the old and the new file, diffed (the new one is read back from the
1040    /// preview's temporary pack). Lines a secret rule removed are hidden. A
1041    /// read. `RewriteRefusal::Stale` when the run is gone.
1042    fn rewrite_blob_diff(
1043        &self,
1044        _repo: &RepoRef,
1045        _run: &RunId,
1046        _commit: Oid,
1047        _path: &str,
1048    ) -> Result<crate::domain::rewrite::BlobChange> {
1049        Err(crate::Error::Unsupported {
1050            operation: "rewrite blob diff",
1051        })
1052    }
1053
1054    /// Compiles a script (an inline text, or a file of the repository) and
1055    /// reports its header, the functions it defines and every problem. A
1056    /// syntax error is a problem in the answer, not an error. A read.
1057    /// `Error::Unsupported` without the `rewrite-scripts` feature.
1058    ///
1059    /// An external script (shell, Python, external Lua) is checked against
1060    /// `policy` first: its language switched off is
1061    /// `RewriteRefusal::ScriptsDisabled`, its interpreter missing
1062    /// `RewriteRefusal::ToolMissing`; the answer carries the script's content
1063    /// hash and whether `policy` trusts it (an untrusted script is an answer,
1064    /// not an error, and is not run); a trusted one gets a dry handshake.
1065    fn rewrite_script_check(
1066        &self,
1067        _repo: &RepoRef,
1068        _script: &crate::domain::rewrite::ScriptRef,
1069        _policy: &crate::domain::rewrite::ScriptPolicy,
1070    ) -> Result<crate::domain::rewrite::script::ScriptCheck> {
1071        Err(crate::Error::Unsupported {
1072            operation: "rewrite script check",
1073        })
1074    }
1075
1076    /// Runs a script on `commits` (their original data, in history order,
1077    /// state carried across them) and returns what it would change. Nothing
1078    /// is written. `RewriteRefusal::ScriptFailed` names the commit and the
1079    /// reason. A read. An external script that `policy` does not allow, whose
1080    /// interpreter is missing or that is not trusted is refused before it
1081    /// runs (`ScriptsDisabled`, `ToolMissing`, `ScriptNotTrusted`).
1082    fn rewrite_script_test(
1083        &self,
1084        _repo: &RepoRef,
1085        _script: &crate::domain::rewrite::ScriptRef,
1086        _policy: &crate::domain::rewrite::ScriptPolicy,
1087        _commits: &[Oid],
1088    ) -> Result<Vec<crate::domain::rewrite::script::ScriptTestRow>> {
1089        Err(crate::Error::Unsupported {
1090            operation: "rewrite script test",
1091        })
1092    }
1093
1094    /// Scans the history of `scope` for secrets (token prefixes, private
1095    /// keys, passwords in URLs, `password = value` with enough entropy):
1096    /// every unique blob is read once, text only. The answer holds each
1097    /// finding's rule, path, first and last commit, counts and a redacted
1098    /// preview, never its value; a finding's id is stable, and a content rule
1099    /// with `scan: true` names findings by id (the backend resolves them at
1100    /// preview time). `progress` reports and can cancel. A read.
1101    fn rewrite_scan_secrets(
1102        &self,
1103        _repo: &RepoRef,
1104        _scope: &crate::domain::rewrite::Scope,
1105        _progress: crate::domain::rewrite::RewriteProgressSink<'_>,
1106    ) -> Result<crate::domain::rewrite::SecretScan> {
1107        Err(crate::Error::Unsupported {
1108            operation: "rewrite scan secrets",
1109        })
1110    }
1111
1112    /// The size analysis of the history `scope` walks (slice S18): the
1113    /// `top` largest blobs with their paths, first and last commit and
1114    /// whether they are still in HEAD, the biggest folders (unique blob
1115    /// bytes), the paths deleted from HEAD but kept by the history, and the
1116    /// totals with what removing the history-only data would free (an
1117    /// estimate: after a purge and a `gc` only). One `log --raw` pass plus
1118    /// one `cat-file --batch-check`. `progress` reports and can cancel. A read.
1119    fn rewrite_analyze(
1120        &self,
1121        _repo: &RepoRef,
1122        _scope: &crate::domain::rewrite::Scope,
1123        _top: u32,
1124        _progress: crate::domain::rewrite::RewriteProgressSink<'_>,
1125    ) -> Result<crate::domain::rewrite::SizeAnalysis> {
1126        Err(crate::Error::Unsupported {
1127            operation: "rewrite analyze",
1128        })
1129    }
1130
1131    // -- stash --
1132    /// `None`: there was nothing to stash ("No local changes to save"), no
1133    /// stash was made and nothing changed - callers record no undo entry.
1134    fn stash_push(
1135        &self,
1136        repo: &RepoRef,
1137        message: Option<&str>,
1138        include_untracked: bool,
1139    ) -> Result<Option<StashId>>;
1140    /// Stashes only `paths` (`git stash push -- <paths>`), leaving every
1141    /// other change where it is. Untracked files among `paths` are
1142    /// stashed too (they were asked for by name). An empty `paths` stashes
1143    /// everything, untracked files included.
1144    fn stash_push_paths(
1145        &self,
1146        repo: &RepoRef,
1147        message: Option<&str>,
1148        paths: &[String],
1149    ) -> Result<Option<StashId>>;
1150    fn stash_pop(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1151    fn stash_apply(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1152    fn stash_drop(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1153    /// Puts the stash commit `commit` back on the stash list, at
1154    /// `stash@{0}` (`git stash store -m <message>`): how an undone drop or
1155    /// pop gets its stash back, with the very same commit. `commit` must
1156    /// be a stash commit (a merge of the base, the index and, maybe, the
1157    /// untracked files); anything else is an error and changes nothing.
1158    fn stash_store(&self, repo: &RepoRef, commit: Oid, message: &str) -> Result<()>;
1159    /// Builds a stash holding exactly the changes `commit` made (against
1160    /// its first parent, or the empty tree for a root commit) and puts it
1161    /// on top of the stash list, as `git stash store` would. The working
1162    /// tree, index and HEAD are not touched. `message` defaults to a text
1163    /// naming the commit. Returns the stash commit.
1164    fn stash_from_commit(&self, repo: &RepoRef, commit: Oid, message: Option<&str>) -> Result<Oid>;
1165    /// The repo-relative paths the stash commit `commit` holds changes
1166    /// for, untracked files included, sorted: what applying or popping it
1167    /// can touch. A read.
1168    fn stash_paths(&self, repo: &RepoRef, commit: Oid) -> Result<Vec<String>>;
1169
1170    // -- network (async: fetch/pull/push/clone hit the network) --
1171    /// Sets (or, with `None`, removes) how the network git processes of
1172    /// `repo` authenticate: they get `auth` instead of the process-wide
1173    /// credential mode and SSH key (ADR-0010). Held in memory, per
1174    /// repository, never persisted; no entry means the unchanged behaviour.
1175    /// Not a repository mutation: not journaled, not undoable. `Git2Backend`
1176    /// forwards it to its system-git fallback, which does all networking.
1177    fn set_network_auth(&self, repo: &RepoRef, auth: Option<NetworkAuth>);
1178    /// Connection test: `git ls-remote --heads` against `remote`'s fetch URL
1179    /// (its push URL with [`RemoteAccessOptions::push`]), with the
1180    /// repository's [`NetworkAuth`] applied like for any transfer. A failed
1181    /// connection is **not** an `Err`: it is a report with `ok: false` and a
1182    /// classified [`crate::ErrorDetail`]. `Err` is for a remote that does not
1183    /// exist or a git that cannot start. A read: nothing in the repository
1184    /// changes.
1185    async fn remote_access_check(
1186        &self,
1187        repo: &RepoRef,
1188        remote: &str,
1189        opts: &RemoteAccessOptions,
1190    ) -> Result<RemoteAccessReport>;
1191    async fn fetch(
1192        &self,
1193        repo: &RepoRef,
1194        remote: &str,
1195        opts: &FetchOptions,
1196    ) -> Result<FetchOutcome>;
1197    /// Fetches **every** configured remote (`git fetch --all`), with
1198    /// `--prune` when asked, and refreshes each remote's tag mirror the
1199    /// way [`GitBackend::fetch`] does for one.
1200    ///
1201    /// One operation rather than a frontend looping over `remotes()`:
1202    /// one result, one broadcast, and a remote added by another client a
1203    /// moment ago is included. `updated_refs` covers all remotes.
1204    async fn fetch_all(&self, repo: &RepoRef, opts: &FetchOptions) -> Result<FetchOutcome>;
1205    /// Fetches one `remote_ref` of `remote` that a normal fetch does not
1206    /// bring - a pull/merge request head such as `refs/pull/<n>/head` or
1207    /// `refs/merge-requests/<n>/head`, which is where a fork's commits
1208    /// live - and makes the local branch `branch` track it.
1209    ///
1210    /// The ref lands in `refs/remotes/<remote>/<branch>`; `branch` is
1211    /// created from it (with that as its upstream) or, when it already
1212    /// exists and is a strict ancestor, fast-forwarded. A branch with
1213    /// local commits of its own is left alone. Nothing is checked out
1214    /// (a *checked-out* `branch` is fast-forwarded in place); the caller
1215    /// checks it out. `remote_ref` must start with `refs/`.
1216    async fn fetch_ref_as_branch(
1217        &self,
1218        repo: &RepoRef,
1219        remote: &str,
1220        remote_ref: &str,
1221        branch: &str,
1222    ) -> Result<FetchOutcome>;
1223    /// Fetches one `[+]refs/<src>:refs/gitpoulpi/<dst>` spec from
1224    /// `remote` (a pull/merge request's head into `refs/gitpoulpi/pr/<n>`,
1225    /// for in-app review). Never a branch, tag or remote-tracking ref:
1226    /// the destination must sit strictly inside
1227    /// [`crate::domain::FETCH_REFSPEC_NAMESPACE`] and anything else is
1228    /// refused before git runs (see [`crate::domain::parse_fetch_refspec`]).
1229    /// Nothing is checked out, and the destination is force-updated (a
1230    /// request may be force-pushed). Not journaled and not undoable: it
1231    /// only refreshes a read-only cache ref no user workflow points at.
1232    /// Returns the destination ref in `updated_refs`.
1233    async fn fetch_refspec(
1234        &self,
1235        repo: &RepoRef,
1236        remote: &str,
1237        refspec: &str,
1238    ) -> Result<FetchOutcome>;
1239    /// Pulls into the checked-out branch, integrating as
1240    /// [`crate::domain::PullMode`] says - always explicitly, so the
1241    /// user's `pull.rebase` / `pull.ff` cannot change what was asked.
1242    ///
1243    /// A fast-forward-only pull of a diverged branch is
1244    /// [`crate::Error::NotFastForward`], with nothing changed.
1245    async fn pull(&self, repo: &RepoRef, opts: &PullOptions) -> Result<PullOutcome>;
1246    /// The download half of [`GitBackend::pull`]: fetches what the pull
1247    /// would integrate and touches nothing else (no index, working tree or
1248    /// `HEAD`), so the daemon can cancel it by dropping the future. The
1249    /// default does nothing: a backend without a separate download phase
1250    /// does it all in [`GitBackend::pull_integrate`].
1251    async fn pull_fetch(&self, _repo: &RepoRef, _opts: &PullOptions) -> Result<()> {
1252        Ok(())
1253    }
1254    /// The integrate half: merges, fast-forwards or rebases what
1255    /// [`GitBackend::pull_fetch`] downloaded, without touching the network,
1256    /// and gives `pull`'s outcome and errors. This is the point of no return
1257    /// of a pull: it rewrites the index and the working tree, so it must not
1258    /// be interrupted. The default is the whole `pull`.
1259    async fn pull_integrate(&self, repo: &RepoRef, opts: &PullOptions) -> Result<PullOutcome> {
1260        self.pull(repo, opts).await
1261    }
1262    /// Pushes a local branch (`opts.branch`, or the checked-out one) to
1263    /// the same-named branch on `remote`.
1264    ///
1265    /// A force push is only ever `--force-with-lease`. A rejection the
1266    /// user can act on - the remote diverged, or the lease found it
1267    /// moved - is the typed [`crate::Error::PushRejected`], never a
1268    /// string to parse.
1269    async fn push(&self, repo: &RepoRef, remote: &str, opts: &PushOptions) -> Result<PushOutcome>;
1270    /// Pushes `HEAD` to `refs/for/<branch>` on `remote` - how a Gerrit
1271    /// change is created - with the optional `%topic=<topic>` option.
1272    /// `branch` is the Gerrit target branch (`main`), not a local one. Never
1273    /// forced. Not journaled and not undoable: the change lives on the
1274    /// server (abandon it there). The default is `Unsupported`.
1275    async fn push_for_review(
1276        &self,
1277        _repo: &RepoRef,
1278        _remote: &str,
1279        _branch: &str,
1280        _topic: Option<&str>,
1281    ) -> Result<PushOutcome> {
1282        Err(crate::Error::Unsupported {
1283            operation: "push_for_review",
1284        })
1285    }
1286    async fn clone(&self, url: &str, dest: &Path, opts: &CloneOptions) -> Result<RepoRef>;
1287
1288    /// `clone`, reporting progress to `progress` as it goes.
1289    ///
1290    /// The default runs the plain `clone` and reports a single
1291    /// [`crate::domain::CloneProgress::done`] at the end, so a backend that
1292    /// cannot stream progress is still correct.
1293    ///
1294    /// Pinned by the contract suite: the last report is always `Done`/100,
1295    /// and `percent` never decreases within a phase.
1296    async fn clone_with_progress(
1297        &self,
1298        url: &str,
1299        dest: &Path,
1300        opts: &CloneOptions,
1301        progress: CloneProgressSink<'_>,
1302    ) -> Result<RepoRef> {
1303        let repo = self.clone(url, dest, opts).await?;
1304        progress(crate::domain::CloneProgress::done());
1305        Ok(repo)
1306    }
1307    fn remote_add(&self, repo: &RepoRef, name: &str, url: &str) -> Result<()>;
1308    /// Removes a remote (`git remote remove`) together with its remote-tracking
1309    /// branches and its tag mirror. On a *leftover* name (see
1310    /// [`GitBackend::leftover_remotes`]) there is no config to remove, so it
1311    /// deletes just those refs, never a configured sibling's (`<name>/sub`);
1312    /// a name that is neither is "no such remote".
1313    fn remote_remove(&self, repo: &RepoRef, name: &str) -> Result<()>;
1314    /// Renames a remote (`git remote rename`): its config section, its
1315    /// remote-tracking branches, every local branch's upstream that named
1316    /// it, *and* its tag mirror under
1317    /// [`crate::domain::REMOTE_TAG_MIRROR_PREFIX`] - or every tag it had
1318    /// would read as unpushed until the next fetch.
1319    fn remote_rename(&self, repo: &RepoRef, old_name: &str, new_name: &str) -> Result<()>;
1320    /// Sets a remote's fetch URL (`remote.<name>.url`).
1321    fn remote_set_url(&self, repo: &RepoRef, name: &str, url: &str) -> Result<()>;
1322    /// Sets a remote's separate push URL (`remote.<name>.pushurl`), or
1323    /// removes it with `None` so pushes go to the fetch URL again.
1324    /// [`crate::domain::Remote::push_url`] always reports the URL a push
1325    /// would actually use, so after `None` it equals the fetch URL.
1326    fn remote_set_push_url(&self, repo: &RepoRef, name: &str, url: Option<&str>) -> Result<()>;
1327
1328    /// The repository-local `core.sshCommand`, if one is set. Read-only
1329    /// companion of [`Self::set_ssh_command`].
1330    fn ssh_command(&self, repo: &RepoRef) -> Result<Option<String>>;
1331    /// Sets (or, with `None`, removes) the repository-local
1332    /// `core.sshCommand` - the opt-in way to make one repository use a
1333    /// profile's SSH key (ADR-0008). Clearing an unset value is not an
1334    /// error. Only `core.sshCommand` is reachable: this is deliberately
1335    /// not a general config write.
1336    fn set_ssh_command(&self, repo: &RepoRef, command: Option<&str>) -> Result<()>;
1337
1338    /// The repository-local value of `key` (the repo's own config file, not
1339    /// the global or system one), or `None` when unset. `key` must be on
1340    /// [`crate::repo_config::REPO_CONFIG_KEYS`] (`core.autocrlf`, `core.eol`).
1341    fn repo_config(&self, repo: &RepoRef, key: &str) -> Result<Option<String>>;
1342
1343    /// The entries of the repository-local config (`.git/config` only, not
1344    /// the global or system files) whose key starts, case-insensitively, with
1345    /// one of `prefixes` (`"gitflow."`, `"branch."`), as `(key, value)` in
1346    /// file order, keys spelled as `config --list` does (section and
1347    /// variable lower-cased, subsection as written). Not limited to the
1348    /// [`crate::repo_config::REPO_CONFIG_KEYS`] allow-list: it is read-only and
1349    /// meant for other tools' settings (git-flow, Git Town) and the recorded
1350    /// parent of a branch (`branch.<b>.gitpoulpi-parent`). An entry without a
1351    /// value is skipped.
1352    fn config_entries(&self, repo: &RepoRef, prefixes: &[&str]) -> Result<Vec<(String, String)>>;
1353    /// Sets (or, with `None`, removes) the repository-local `key`, so the
1354    /// repository inherits the global value again. Same allow-list as
1355    /// [`Self::repo_config`], and the value must be one the key accepts.
1356    /// Clearing an unset key is not an error.
1357    fn set_repo_config(&self, repo: &RepoRef, key: &str, value: Option<&str>) -> Result<()>;
1358
1359    // -- Sparse checkout (cone mode) --
1360    /// Whether the working tree is a sparse checkout, in which mode, and
1361    /// which directories are checked out. A repository that never enabled
1362    /// it reports `SparseState::default()` (disabled), never an error.
1363    fn sparse_checkout_status(&self, repo: &RepoRef) -> Result<SparseState>;
1364    /// Makes the checkout sparse (cone mode) showing exactly `dirs` plus
1365    /// the files at the root; replaces any earlier set, so directories left
1366    /// out disappear from the working tree and the new ones appear. `dirs`
1367    /// go through [`crate::domain::normalize_sparse_dirs`] (at least one,
1368    /// relative, no patterns). Not journaled: nothing is lost, "disable"
1369    /// brings every file back.
1370    fn sparse_checkout_set(&self, repo: &RepoRef, dirs: &[String]) -> Result<()>;
1371    /// Turns sparse checkout off: every file of the tree is checked out
1372    /// again. Disabling a repository that is not sparse is not an error.
1373    fn sparse_checkout_disable(&self, repo: &RepoRef) -> Result<()>;
1374
1375    // -- Git LFS (ADR 0009) --
1376    /// What is known about Git LFS in this repository: the `git-lfs`
1377    /// program's availability, whether the repository routes files
1378    /// through it, the tracked patterns, and whether its filters and hook
1379    /// are installed.
1380    ///
1381    /// A read that **never fails because `git-lfs` is missing**: that is
1382    /// `binary: LfsBinary::Missing` in the answer, so a frontend can
1383    /// explain it. Always re-probes the program (no stale cache).
1384    fn lfs_status(&self, repo: &RepoRef) -> Result<LfsRepoStatus>;
1385    /// Which external programs a history rewrite could use here (`gpg`,
1386    /// `ssh-keygen`, `gpgsm`, `git-lfs`, `python`, shells) and whether each
1387    /// works, with the install hint key for this OS. **The core rewrite
1388    /// actions need none of them** (see `RuleKind::required_tools`) and the
1389    /// embedded Lua is always there. Cached for a minute; `fresh` re-asks
1390    /// (the "Check again" button). Runs programs: never call it on a render
1391    /// thread. A read that never fails because a tool is missing.
1392    fn rewrite_tools(
1393        &self,
1394        repo: &RepoRef,
1395        fresh: bool,
1396    ) -> Result<crate::domain::rewrite::RewriteTools>;
1397    /// Signs a dummy payload once with the repository's signing setup
1398    /// (`gpg.format`, `user.signingkey`, `gpg.*.program`) and verifies it:
1399    /// the "Check signing" smoke test before a run that re-signs. May open a
1400    /// passphrase prompt. A broken setup is an `Ok` check with a `reason`,
1401    /// not an error. Runs programs: never on a render thread.
1402    fn rewrite_check_signing(&self, repo: &RepoRef)
1403        -> Result<crate::domain::rewrite::SigningCheck>;
1404    /// The LFS pointer files at a commit (`Some`) or in the index
1405    /// (`None`), each with whether its real object is in the local LFS
1406    /// store. Needs no `git-lfs` program. The index answer is empty for a
1407    /// repository that does not use LFS; a commit is scanned whatever the
1408    /// checked-out attributes say.
1409    fn lfs_files(&self, repo: &RepoRef, at: Option<Oid>) -> Result<Vec<LfsFile>>;
1410
1411    /// `git lfs install`: the clean / smudge filters and the LFS hooks,
1412    /// for this repository only (`Repository`, the default: `--local`) or
1413    /// the user's global git config (`User`). Needs the `git-lfs`
1414    /// program: [`crate::Error::LfsUnavailable`] otherwise, with nothing
1415    /// changed.
1416    fn lfs_install(&self, repo: &RepoRef, scope: LfsInstallScope) -> Result<()>;
1417    /// Routes `patterns` through LFS (`git lfs track`). Writes
1418    /// `.gitattributes` and leaves it **unstaged**, a visible working
1419    /// change. Returns every LFS pattern of the repository afterwards.
1420    /// With `opts.renormalize` the already-committed files that match are
1421    /// re-staged so their next commit stores pointers.
1422    fn lfs_track(
1423        &self,
1424        repo: &RepoRef,
1425        patterns: &[String],
1426        opts: &LfsTrackOptions,
1427    ) -> Result<Vec<LfsPattern>>;
1428    /// Stops routing `patterns` through LFS (`git lfs untrack`). Returns
1429    /// the LFS patterns left.
1430    fn lfs_untrack(&self, repo: &RepoRef, patterns: &[String]) -> Result<Vec<LfsPattern>>;
1431    /// `git lfs fetch <remote>`: download the LFS objects the current ref
1432    /// (or every ref with `opts.all_refs`) points at into the local LFS
1433    /// store, leaving the working tree alone. Network. Reports progress to
1434    /// `progress`; the last report is always `done: true`, and no
1435    /// direction's counters ever decrease (the contract suite pins both).
1436    /// Needs the `git-lfs` program ([`crate::Error::LfsUnavailable`]).
1437    async fn lfs_fetch(
1438        &self,
1439        repo: &RepoRef,
1440        remote: &str,
1441        opts: &LfsFetchOptions,
1442        progress: LfsProgressSink<'_>,
1443    ) -> Result<()>;
1444    /// `git lfs pull <remote>`: fetch, then replace the pointer files in
1445    /// the working tree with the real content. Network.
1446    async fn lfs_pull(
1447        &self,
1448        repo: &RepoRef,
1449        remote: &str,
1450        progress: LfsProgressSink<'_>,
1451    ) -> Result<()>;
1452    /// `git lfs checkout [paths]`: write the real content of every LFS
1453    /// pointer in the working tree (or only `paths`, relative to the
1454    /// root; empty means all) from the objects already in the local LFS
1455    /// store. Offline: it never downloads (that is `lfs_pull`). Installs
1456    /// the repository-local LFS filters first when they are missing, like
1457    /// `lfs_pull`. Not a journaled state change: it only expands pointers.
1458    /// Needs the `git-lfs` program ([`crate::Error::LfsUnavailable`]).
1459    async fn lfs_checkout(
1460        &self,
1461        repo: &RepoRef,
1462        paths: &[PathBuf],
1463        progress: LfsProgressSink<'_>,
1464    ) -> Result<()>;
1465    /// `git lfs push <remote>`: upload the LFS objects of the current
1466    /// branch (or of every ref with `opts.all_refs`). Network; a
1467    /// mutation of the remote.
1468    async fn lfs_push(
1469        &self,
1470        repo: &RepoRef,
1471        remote: &str,
1472        opts: &LfsPushOptions,
1473        progress: LfsProgressSink<'_>,
1474    ) -> Result<()>;
1475    /// The file locks held on the LFS server behind `remote`, each marked
1476    /// `ours` when the current user holds it. Network; a read (never
1477    /// broadcasts `RepoChanged`). Locking is a server feature reached with
1478    /// the remote's own credentials. A server without locking answers
1479    /// git-lfs's `locks` with an empty list, so that is what this returns;
1480    /// [`crate::Error::LfsLockingUnsupported`] comes from `lfs_lock`.
1481    async fn lfs_locks(&self, repo: &RepoRef, remote: &str) -> Result<Vec<LfsLock>>;
1482    /// Locks `path` on the server, so nobody else can lock or push
1483    /// changes to it. Network. A server without the locking API is
1484    /// [`crate::Error::LfsLockingUnsupported`].
1485    async fn lfs_lock(&self, repo: &RepoRef, remote: &str, path: &Path) -> Result<LfsLock>;
1486    /// Releases the lock on `path`. Somebody else's lock is refused unless
1487    /// `force` (which breaks it: destructive). Network.
1488    async fn lfs_unlock(
1489        &self,
1490        repo: &RepoRef,
1491        remote: &str,
1492        path: &Path,
1493        force: bool,
1494    ) -> Result<()>;
1495    /// `git lfs prune`: delete old, already-pushed objects from the local
1496    /// LFS store.
1497    fn lfs_prune(&self, repo: &RepoRef) -> Result<()>;
1498
1499    // -- conflicts --
1500    fn conflicts(&self, repo: &RepoRef) -> Result<Vec<ConflictSet>>;
1501    /// Every unmerged path with its stages' modes and oids and the kind of
1502    /// conflict they make, sorted by path. Reads no blob (the cheap form of
1503    /// [`GitBackend::conflicts`], for the refresh): 1 spawn on system git,
1504    /// none under git2. Empty when nothing is unmerged.
1505    fn conflict_entries(&self, repo: &RepoRef) -> Result<Vec<ConflictEntry>>;
1506    /// Everything the merge conflict editor needs for one unmerged `path`:
1507    /// the three stages read, git's own 3-way merge of them parsed into
1508    /// regions (see [`MergeDocument`]), the pane labels and the state of
1509    /// the file on disk. Text is decoded as `read_blob` does (the fallback
1510    /// encoding applies). A path that is not unmerged is an error.
1511    fn merge_document(&self, repo: &RepoRef, path: &Path) -> Result<MergeDocument>;
1512    /// Resolves the unmerged `path` as `resolution` says and, with
1513    /// `opts.stage`, stages the result. Refused (nothing written) with
1514    /// [`crate::domain::ConflictRefusal::Stale`] when `opts.expected` is
1515    /// not what the index holds, and
1516    /// [`crate::domain::ConflictRefusal::Unencodable`] for text a
1517    /// `UseEncoded` encoding cannot hold. A path that is not conflicted is
1518    /// written and staged like any file unless `expected` is given (then
1519    /// it is stale).
1520    fn resolve_conflict(
1521        &self,
1522        repo: &RepoRef,
1523        path: &Path,
1524        resolution: ConflictResolution,
1525        opts: &ResolveOptions,
1526    ) -> Result<()>;
1527    /// Puts a resolved path back in conflict: the stage 1/2/3 entries of
1528    /// `entry` return to the index (stage 0 goes) and the working tree
1529    /// file is rewritten the way git leaves it (the merge with conflict
1530    /// markers; the surviving side for a non-text conflict). Refused with
1531    /// [`crate::domain::ConflictRefusal::AlreadyConflicted`] when the path
1532    /// is still unmerged.
1533    fn unresolve_conflict(&self, repo: &RepoRef, path: &Path, entry: &ConflictEntry) -> Result<()>;
1534    /// The merge, cherry-pick, revert or rebase in progress, if any
1535    /// (rebase wins when several markers exist).
1536    fn operation_state(&self, repo: &RepoRef) -> Result<Option<OperationState>>;
1537    /// Abandons whatever [`GitBackend::operation_state`] reports
1538    /// (`merge`/`cherry-pick`/`revert`/`rebase --abort`): HEAD, the index
1539    /// and the working tree return to before the operation. Destructive
1540    /// for work done since. Without an operation: refused with
1541    /// [`crate::domain::ConflictRefusal::NoOperation`].
1542    fn operation_abort(&self, repo: &RepoRef) -> Result<()>;
1543    /// `git am --continue`: applies the patch the `am` stopped on (the
1544    /// caller resolved and staged it) and the rest. Without an `am` in
1545    /// progress: refused with [`crate::domain::ConflictRefusal::NoOperation`].
1546    fn am_continue(&self, repo: &RepoRef) -> Result<AmOutcome>;
1547    /// `git am --skip`: drops the patch the `am` stopped on and goes on.
1548    /// Same refusal as [`GitBackend::am_continue`].
1549    fn am_skip(&self, repo: &RepoRef) -> Result<AmOutcome>;
1550    /// `git am --abort`: back to the branch tip from before the `am`.
1551    /// Same refusal as [`GitBackend::am_continue`].
1552    fn am_abort(&self, repo: &RepoRef) -> Result<()>;
1553    /// The repository's `index.lock`, if the file exists. In a linked
1554    /// worktree it is the worktree's own (`.git/worktrees/<name>`).
1555    fn index_lock(&self, repo: &RepoRef) -> Result<Option<IndexLock>>;
1556    /// Deletes a stale `index.lock` (and nothing else). Refused with an
1557    /// error when there is none, or when it is younger than
1558    /// [`crate::domain::STALE_INDEX_LOCK_SECS`].
1559    fn index_lock_remove(&self, repo: &RepoRef) -> Result<()>;
1560    /// Skips what [`GitBackend::operation_state`] reports
1561    /// (`cherry-pick --skip`, `revert --skip`, `rebase --skip`): the
1562    /// stopped commit is given up on and HEAD, the index and the working
1563    /// tree return to HEAD. The way out of a pick or revert that became
1564    /// empty (the change is already applied; git refuses to commit it). A
1565    /// merge has nothing to skip: an `Error::Backend`, nothing changed.
1566    /// Without an operation: [`crate::domain::ConflictRefusal::NoOperation`].
1567    fn operation_skip(&self, repo: &RepoRef) -> Result<()>;
1568}