diffler_core/vcs.rs
1//! Backend-agnostic VCS interface. Everything above this trait consumes
2//! `dyn Vcs`; only the `git` and `repo` modules (and test fixtures) may
3//! import git2.
4
5use std::path::{Path, PathBuf};
6
7use thiserror::Error;
8
9use crate::model::{DiffModel, HunkId};
10
11#[derive(Debug, Error)]
12pub enum VcsError {
13 // acceptable for M1; rework when a second backend lands
14 #[error(transparent)]
15 Git(#[from] git2::Error),
16 #[error("repository has no working directory")]
17 NoWorkdir,
18 /// Domain refusal, e.g. discarding a file with staged changes.
19 #[error("{0}")]
20 Rejected(String),
21 #[error(transparent)]
22 Io(#[from] std::io::Error),
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct HeadInfo {
27 /// Branch shorthand; `None` when HEAD is detached.
28 pub branch: Option<String>,
29 /// Abbreviated commit id; empty on an unborn branch.
30 pub oid7: String,
31 /// First line of the HEAD commit message; empty on an unborn branch.
32 pub subject: String,
33 /// Upstream branch shorthand, if configured.
34 pub upstream: Option<String>,
35 /// Commits on HEAD the upstream lacks, so work that exists only here is
36 /// visible without running `git status`. Zero without an upstream.
37 pub ahead: usize,
38 /// Commits on the upstream that HEAD lacks.
39 pub behind: usize,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct LogEntry {
44 pub oid: String,
45 pub oid7: String,
46 /// Shorthand names of references pointing at this commit.
47 pub refs: Vec<String>,
48 pub subject: String,
49 pub author: String,
50 pub time_unix: i64,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct BranchInfo {
55 pub name: String,
56 pub is_head: bool,
57 /// Tip commit's time as a Unix timestamp, so callers can sort branches
58 /// newest-first and render an age.
59 pub tip_unix: i64,
60 /// How far this branch stands from its upstream, as `(ahead, behind)`.
61 /// Resolving one costs a config read and a graph walk, so a listing leaves
62 /// it `None` and the caller asks [`Vcs::divergence`] for the branches it
63 /// actually shows.
64 pub divergence: Option<(usize, usize)>,
65}
66
67/// A network operation the binary runs by shelling out to the backend's CLI,
68/// so the user's existing auth (SSH agent, credential helper, tokens) applies
69/// without diffler holding any credentials.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum NetworkOp {
72 Fetch,
73 FetchAll,
74}
75
76/// A run of consecutive lines a single commit last touched.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct BlameSpan {
79 /// 1-based first line of the run in the blamed content.
80 pub start_line: u32,
81 pub line_count: u32,
82 pub oid: String,
83 pub oid7: String,
84 pub author: String,
85 pub time_unix: i64,
86 pub summary: String,
87 /// False for lines that exist only in the worktree, which no commit owns.
88 pub committed: bool,
89}
90
91/// Per-area views of the working tree, neogit-style sections.
92#[derive(Debug, Clone, Default)]
93pub struct StatusModel {
94 pub untracked: DiffModel,
95 pub unstaged: DiffModel,
96 pub staged: DiffModel,
97}
98
99pub trait Vcs: Send {
100 /// Resolved repository metadata directory. In a plain repo this is
101 /// `<root>/.git`; in a linked worktree `<root>/.git` is a gitlink file
102 /// and this resolves to the external gitdir it points at.
103 fn git_dir(&self) -> Result<PathBuf, VcsError>;
104 /// Current branch, commit, and upstream.
105 fn head(&self) -> Result<HeadInfo, VcsError>;
106 /// Untracked / unstaged / staged sections as separate diff models.
107 fn status(&self) -> Result<StatusModel, VcsError>;
108 /// HEAD vs workdir+index including untracked files: the review view.
109 fn working_tree_diff(&self) -> Result<DiffModel, VcsError>;
110 /// [`Vcs::working_tree_diff`] taken from an arbitrary base commit instead
111 /// of HEAD, so uncommitted work shows alongside the commits since `base`.
112 fn tree_to_workdir_diff(&self, base_oid: &str) -> Result<DiffModel, VcsError>;
113 /// Changes a single commit introduced over its first parent.
114 fn commit_diff(&self, oid: &str) -> Result<DiffModel, VcsError>;
115 /// Combined diff of a contiguous commit range, from the first parent of
116 /// `oldest` to `newest` (`git diff <oldest>^..<newest>` semantics). When
117 /// `oldest` is a root commit its first-parent tree is the empty tree, so
118 /// the range includes everything `oldest` introduced.
119 fn range_diff(&self, oldest_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError>;
120 /// Diff between two trees as-is (`git diff <base> <newest>` semantics);
121 /// with `base` a merge base this is a PR-style three-dot diff.
122 fn tree_diff(&self, base_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError>;
123 /// Best common ancestor of two commits.
124 fn merge_base(&self, a: &str, b: &str) -> Result<String, VcsError>;
125 /// Resolve a revision (oid, ref name, remote ref) to a full commit oid.
126 fn resolve(&self, revision: &str) -> Result<String, VcsError>;
127 /// History from HEAD, newest first.
128 fn log(&self, limit: usize) -> Result<Vec<LogEntry>, VcsError>;
129
130 /// The branch a pull request merges into by default; `None` when the
131 /// repository offers no answer.
132 fn default_branch(&self, remote: &str) -> Result<Option<String>, VcsError>;
133
134 /// Commits reachable from `head` but not `base`, newest first: what a
135 /// pull request from `head` would carry.
136 fn commits_between(&self, base: &str, head: &str) -> Result<Vec<LogEntry>, VcsError>;
137 /// Commits on HEAD that no remote-tracking branch contains, newest first,
138 /// at most `limit` of them: work that exists only on this machine. `None`
139 /// when the repository has no remote-tracking refs, where being pushed has
140 /// no meaning yet. Asking the remotes rather than the configured upstream
141 /// is what makes the answer true: an upstream may be another local branch,
142 /// or a stale ref from before the last fetch. `limit` bounds a walk that is
143 /// otherwise the whole history whenever no remote ref sits on it.
144 fn unpushed(&self, limit: usize) -> Result<Option<Vec<LogEntry>>, VcsError>;
145 /// Last commit to touch each line of `rel` as the worktree has it, in line
146 /// order. Lines the worktree added since the last commit come back as one
147 /// span of their own, owned by no commit.
148 fn blame(&self, rel: &Path) -> Result<Vec<BlameSpan>, VcsError>;
149
150 /// One file's content as recorded in `rev`'s tree, `None` when that tree
151 /// has no such path. Lets a review pinned to one tree (a commit, a
152 /// range's newest, a PR's head) resolve a walkthrough's anchors against
153 /// what it actually shows, rather than whatever the worktree holds now.
154 fn read_at(&self, rev: &str, path: &str) -> Result<Option<String>, VcsError>;
155
156 /// Every tracked file, repo-relative and sorted. This is the index, so a
157 /// staged new file is tracked and an untracked one is not.
158 fn tracked_files(&self) -> Result<Vec<PathBuf>, VcsError>;
159
160 /// Whether the repo's git attributes set `name` to true for `rel`.
161 /// Unreadable attribute files read as unset: the caller is refining a
162 /// guess, so there is nothing to report and nothing to recover.
163 fn attr(&self, rel: &Path, name: &str) -> bool;
164
165 /// Local branches, their divergence left unresolved.
166 fn branches(&self) -> Result<Vec<BranchInfo>, VcsError>;
167
168 /// How far `branch` stands from its upstream, as `(ahead, behind)`, or
169 /// `None` when it tracks nothing.
170 fn divergence(&self, branch: &str) -> Result<Option<(usize, usize)>, VcsError>;
171 /// Local and remote-tracking branch names, for pickers that name a
172 /// revision rather than check one out.
173 fn all_branches(&self) -> Result<Vec<String>, VcsError>;
174 /// Stage a whole file (worktree deletions become staged deletions).
175 fn stage(&self, rel: &Path) -> Result<(), VcsError>;
176
177 /// Stage every change in the worktree, deletions and untracked files
178 /// included. Resolved against the repository as it is now, so a file
179 /// edited since the caller last looked is still caught.
180 fn stage_everything(&self) -> Result<(), VcsError>;
181
182 /// Reset the whole index back to HEAD, keeping the worktree.
183 fn unstage_everything(&self) -> Result<(), VcsError>;
184 /// Stage one hunk out of the unstaged (or untracked) changes of a file.
185 fn stage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError>;
186 /// Reset a file's index entry back to HEAD, keeping the worktree.
187 fn unstage(&self, rel: &Path) -> Result<(), VcsError>;
188 /// Remove one staged hunk from the index, keeping the worktree.
189 fn unstage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError>;
190 /// Throw away worktree changes only; an untracked file is deleted.
191 /// Refused while the file has staged changes (unstage first).
192 fn discard(&self, rel: &Path) -> Result<(), VcsError>;
193 /// Commit the index; returns the new commit id.
194 fn commit(&self, message: &str) -> Result<String, VcsError>;
195 /// Full message of the HEAD commit, for amend/reword editor templates.
196 fn head_message(&self) -> Result<String, VcsError>;
197 /// Amend HEAD, returning the new commit id. `message` `None` reuses HEAD's
198 /// message (extend); `Some` rewords it. `use_index` true folds the staged
199 /// index into the new tree (extend/amend); false keeps HEAD's tree (a
200 /// pure reword). Local-only: no network.
201 fn amend(&self, message: Option<&str>, use_index: bool) -> Result<String, VcsError>;
202 fn create_branch(&self, name: &str, checkout: bool) -> Result<(), VcsError>;
203 /// Refused for the currently checked-out branch.
204 fn delete_branch(&self, name: &str) -> Result<(), VcsError>;
205 fn checkout(&self, name: &str) -> Result<(), VcsError>;
206 /// Stash tracked changes (staged + unstaged), reverting the worktree to
207 /// HEAD; untracked files are left in place, matching `git stash`. `message`
208 /// `None` lets the backend label it. Local-only: no network.
209 fn stash_push(&self, message: Option<&str>) -> Result<(), VcsError>;
210 /// Restore the most recent stash and drop it. Refused when there is no
211 /// stash or the pop would conflict.
212 fn stash_pop(&self) -> Result<(), VcsError>;
213 /// Argv to run for a network op, e.g. `["git", "push"]`. The binary runs
214 /// this in [`Vcs::workdir`] so the backend's own CLI handles credentials;
215 /// diffler never touches them. A future jj backend returns `["jj", …]`.
216 fn network_argv(&self, op: NetworkOp) -> Vec<String>;
217 /// Working directory to run [`Vcs::network_argv`] in.
218 fn workdir(&self) -> Result<PathBuf, VcsError>;
219 /// URL of the named remote (e.g. `origin`), if it exists. Used to detect the
220 /// CI provider's host without shelling out.
221 fn remote_url(&self, name: &str) -> Result<Option<String>, VcsError>;
222 /// Names of every configured remote, for multi-remote CI detection.
223 fn remotes(&self) -> Result<Vec<String>, VcsError>;
224}
225
226/// Three-dot diff of `rev` against the working tree: `merge-base(rev, HEAD)`
227/// vs index + worktree + untracked. Commits `rev` gained since the branch
228/// forked stay out of it; uncommitted work stays in.
229pub fn against_diff(vcs: &dyn Vcs, rev: &str) -> Result<DiffModel, VcsError> {
230 let head = vcs.resolve("HEAD")?;
231 let base = vcs.merge_base(&vcs.resolve(rev)?, &head)?;
232 vcs.tree_to_workdir_diff(&base)
233}