Skip to main content

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