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::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}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct LogEntry {
39    pub oid: String,
40    pub oid7: String,
41    /// Shorthand names of references pointing at this commit.
42    pub refs: Vec<String>,
43    pub subject: String,
44    pub author: String,
45    pub time_unix: i64,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct BranchInfo {
50    pub name: String,
51    pub is_head: bool,
52}
53
54/// A network operation the binary runs by shelling out to the backend's CLI,
55/// so the user's existing auth (SSH agent, credential helper, tokens) applies
56/// without diffler holding any credentials.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum NetworkOp {
59    Fetch,
60    FetchAll,
61}
62
63/// Per-area views of the working tree, neogit-style sections.
64#[derive(Debug, Clone, Default)]
65pub struct StatusModel {
66    pub untracked: DiffModel,
67    pub unstaged: DiffModel,
68    pub staged: DiffModel,
69}
70
71pub trait Vcs: Send {
72    /// Resolved repository metadata directory. In a plain repo this is
73    /// `<root>/.git`; in a linked worktree `<root>/.git` is a gitlink file
74    /// and this resolves to the external gitdir it points at.
75    fn git_dir(&self) -> Result<PathBuf, VcsError>;
76    /// Current branch, commit, and upstream.
77    fn head(&self) -> Result<HeadInfo, VcsError>;
78    /// Untracked / unstaged / staged sections as separate diff models.
79    fn status(&self) -> Result<StatusModel, VcsError>;
80    /// HEAD vs workdir+index including untracked files: the review view.
81    fn working_tree_diff(&self) -> Result<DiffModel, VcsError>;
82    /// [`Vcs::working_tree_diff`] taken from an arbitrary base commit instead
83    /// of HEAD, so uncommitted work shows alongside the commits since `base`.
84    fn tree_to_workdir_diff(&self, base_oid: &str) -> Result<DiffModel, VcsError>;
85    /// Changes a single commit introduced over its first parent.
86    fn commit_diff(&self, oid: &str) -> Result<DiffModel, VcsError>;
87    /// Combined diff of a contiguous commit range, from the first parent of
88    /// `oldest` to `newest` (`git diff <oldest>^..<newest>` semantics). When
89    /// `oldest` is a root commit its first-parent tree is the empty tree, so
90    /// the range includes everything `oldest` introduced.
91    fn range_diff(&self, oldest_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError>;
92    /// Diff between two trees as-is (`git diff <base> <newest>` semantics);
93    /// with `base` a merge base this is a PR-style three-dot diff.
94    fn tree_diff(&self, base_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError>;
95    /// Best common ancestor of two commits.
96    fn merge_base(&self, a: &str, b: &str) -> Result<String, VcsError>;
97    /// Resolve a revision (oid, ref name, remote ref) to a full commit oid.
98    fn resolve(&self, revision: &str) -> Result<String, VcsError>;
99    /// History from HEAD, newest first.
100    fn log(&self, limit: usize) -> Result<Vec<LogEntry>, VcsError>;
101
102    /// The branch a pull request merges into by default; `None` when the
103    /// repository offers no answer.
104    fn default_branch(&self, remote: &str) -> Result<Option<String>, VcsError>;
105
106    /// Commits reachable from `head` but not `base`, newest first: what a
107    /// pull request from `head` would carry.
108    fn commits_between(&self, base: &str, head: &str) -> Result<Vec<LogEntry>, VcsError>;
109    /// Local branches.
110    fn branches(&self) -> Result<Vec<BranchInfo>, VcsError>;
111    /// Local and remote-tracking branch names, for pickers that name a
112    /// revision rather than check one out.
113    fn all_branches(&self) -> Result<Vec<String>, VcsError>;
114    /// Stage a whole file (worktree deletions become staged deletions).
115    fn stage(&self, rel: &Path) -> Result<(), VcsError>;
116    /// Stage one hunk out of the unstaged (or untracked) changes of a file.
117    fn stage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError>;
118    /// Reset a file's index entry back to HEAD, keeping the worktree.
119    fn unstage(&self, rel: &Path) -> Result<(), VcsError>;
120    /// Remove one staged hunk from the index, keeping the worktree.
121    fn unstage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError>;
122    /// Throw away worktree changes only; an untracked file is deleted.
123    /// Refused while the file has staged changes (unstage first).
124    fn discard(&self, rel: &Path) -> Result<(), VcsError>;
125    /// Commit the index; returns the new commit id.
126    fn commit(&self, message: &str) -> Result<String, VcsError>;
127    /// Full message of the HEAD commit, for amend/reword editor templates.
128    fn head_message(&self) -> Result<String, VcsError>;
129    /// Amend HEAD, returning the new commit id. `message` `None` reuses HEAD's
130    /// message (extend); `Some` rewords it. `use_index` true folds the staged
131    /// index into the new tree (extend/amend); false keeps HEAD's tree (a
132    /// pure reword). Local-only — no network.
133    fn amend(&self, message: Option<&str>, use_index: bool) -> Result<String, VcsError>;
134    fn create_branch(&self, name: &str, checkout: bool) -> Result<(), VcsError>;
135    /// Refused for the currently checked-out branch.
136    fn delete_branch(&self, name: &str) -> Result<(), VcsError>;
137    fn checkout(&self, name: &str) -> Result<(), VcsError>;
138    /// Stash tracked changes (staged + unstaged), reverting the worktree to
139    /// HEAD; untracked files are left in place, matching `git stash`. `message`
140    /// `None` lets the backend label it. Local-only — no network.
141    fn stash_push(&self, message: Option<&str>) -> Result<(), VcsError>;
142    /// Restore the most recent stash and drop it. Refused when there is no
143    /// stash or the pop would conflict.
144    fn stash_pop(&self) -> Result<(), VcsError>;
145    /// Argv to run for a network op, e.g. `["git", "push"]`. The binary runs
146    /// this in [`Vcs::workdir`] so the backend's own CLI handles credentials;
147    /// diffler never touches them. A future jj backend returns `["jj", …]`.
148    fn network_argv(&self, op: NetworkOp) -> Vec<String>;
149    /// Working directory to run [`Vcs::network_argv`] in.
150    fn workdir(&self) -> Result<PathBuf, VcsError>;
151    /// URL of the named remote (e.g. `origin`), if it exists. Used to detect the
152    /// CI provider's host without shelling out.
153    fn remote_url(&self, name: &str) -> Result<Option<String>, VcsError>;
154    /// Names of every configured remote, for multi-remote CI detection.
155    fn remotes(&self) -> Result<Vec<String>, VcsError>;
156}
157
158/// Three-dot diff of `rev` against the working tree: `merge-base(rev, HEAD)`
159/// vs index + worktree + untracked. Commits `rev` gained since the branch
160/// forked stay out of it; uncommitted work stays in.
161pub fn against_diff(vcs: &dyn Vcs, rev: &str) -> Result<DiffModel, VcsError> {
162    let head = vcs.resolve("HEAD")?;
163    let base = vcs.merge_base(&vcs.resolve(rev)?, &head)?;
164    vcs.tree_to_workdir_diff(&base)
165}