Skip to main content

diffler_core/
vcs.rs

1//! Backend-agnostic VCS interface. Only the `git` and `repo` modules and test
2//! fixtures may import git2.
3
4use std::collections::HashMap;
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    #[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. Zero without an upstream.
36    pub ahead: usize,
37    /// Commits on the upstream that HEAD lacks.
38    pub behind: usize,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct LogEntry {
43    pub oid: String,
44    pub oid7: String,
45    /// Shorthand names of references pointing at this commit.
46    pub refs: Vec<String>,
47    /// Full parent oids, first parent first.
48    pub parents: Vec<String>,
49    pub subject: String,
50    pub author: String,
51    pub time_unix: i64,
52    /// Short jj change id; `None` outside a jj repo.
53    pub change_id: Option<String>,
54}
55
56impl LogEntry {
57    /// The id a reader names the commit by: the change id in a jj repo.
58    pub fn short_id(&self) -> &str {
59        self.change_id.as_deref().unwrap_or(&self.oid7)
60    }
61}
62
63/// The jj working-copy change `@`, shown on a jj repo's head line.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct ChangeInfo {
66    pub change_id: String,
67    /// `@`'s commit id when the view was read; a snapshot rewrites it.
68    pub commit_id: String,
69    /// A bookmark on `@`, else on its nearest bookmarked ancestor.
70    pub bookmark: Option<String>,
71    /// First line of the description; empty when none is set.
72    pub description: String,
73}
74
75/// A jj verb on one change. A `rev` is `@`, or a full commit id that names
76/// the change it belongs to, so a change rewritten since keeps its target.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum ChangeOp {
79    New(String),
80    Edit(String),
81    /// An empty message clears the description.
82    Describe {
83        rev: String,
84        message: String,
85    },
86    /// Into its parent. Both descriptions survive: the parent's, then the
87    /// change's, when both are set.
88    Squash(String),
89    Abandon(String),
90    Undo,
91    Redo,
92}
93
94/// The local bookmark nearest `@` and the remote it tracks, which a jj pull
95/// fetches and rebases onto.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct PullTarget {
98    pub bookmark: String,
99    /// `None` when the bookmark tracks no remote bookmark.
100    pub remote: Option<String>,
101}
102
103/// What a jj pull did after its fetch.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum PullOutcome {
106    /// The remote no longer has `onto` (`name@remote`).
107    Gone { onto: String },
108    /// `@` already descends from `onto`.
109    UpToDate { onto: String },
110    /// `@`'s branch now sits on `onto`; `conflicts` of its changes conflict,
111    /// and the local bookmark conflicts with the remote's when it moved on
112    /// both sides.
113    Rebased {
114        onto: String,
115        conflicts: usize,
116        bookmark_conflicted: bool,
117    },
118}
119
120/// What a jj-only verb answers in a git repo.
121pub const JJ_ONLY: &str = "edit changes in a jj repo; this one is plain git";
122
123/// A jj bookmark: `name` for a local one, `name@remote` for a remote one.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct Bookmark {
126    pub name: String,
127    pub oid: String,
128    pub remote: bool,
129    pub tip_unix: i64,
130}
131
132/// What jj knows beyond the git store, read through the `jj` CLI.
133#[derive(Debug, Clone, Default, PartialEq, Eq)]
134pub struct JjView {
135    /// `@`, `None` when jj's answer named no working copy.
136    pub change: Option<ChangeInfo>,
137    /// The first parent of `@`, which colocated git's HEAD sits on; `None`
138    /// when that is jj's root commit.
139    pub base: Option<String>,
140    /// Every bookmark; filled only where the git store lacks them, which is
141    /// a repo with no `.git`.
142    pub bookmarks: Vec<Bookmark>,
143    /// Short change id by full commit id, over recent history.
144    pub change_ids: HashMap<String, String>,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct BranchInfo {
149    pub name: String,
150    pub is_head: bool,
151    pub tip_unix: i64,
152    /// `(ahead, behind)` against the upstream. Resolving one costs a graph
153    /// walk, so listings leave it `None` and callers ask
154    /// [`Vcs::divergence`] for the branches they show.
155    pub divergence: Option<(usize, usize)>,
156}
157
158/// A network operation we run through the backend's CLI, so the user's own
159/// auth applies and diffler holds no credentials.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub enum NetworkOp {
162    Fetch,
163    FetchAll,
164    Push,
165    PushSetUpstream { remote: String },
166    Pull,
167    PullFrom { remote: String, branch: String },
168    PullRebase,
169    PullMerge,
170}
171
172/// A run of consecutive lines a single commit last touched.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub struct BlameSpan {
175    /// 1-based first line of the run in the blamed content.
176    pub start_line: u32,
177    pub line_count: u32,
178    pub oid: String,
179    pub oid7: String,
180    pub author: String,
181    pub time_unix: i64,
182    pub summary: String,
183    /// False for lines that exist only in the worktree, which no commit owns.
184    pub committed: bool,
185}
186
187/// Per-area views of the working tree, neogit-style sections.
188#[derive(Debug, Clone, Default)]
189pub struct StatusModel {
190    pub untracked: DiffModel,
191    pub unstaged: DiffModel,
192    pub staged: DiffModel,
193}
194
195pub trait Vcs: Send {
196    /// Resolved metadata directory. In a linked worktree this is the gitdir
197    /// the `.git` file points at.
198    fn git_dir(&self) -> Result<PathBuf, VcsError>;
199    fn head(&self) -> Result<HeadInfo, VcsError>;
200    /// jj's view, covering `log_limit` commits of history; `None` outside a
201    /// jj repo. It costs two `jj` runs, so callers ask from a worker, and
202    /// this handle adopts it.
203    fn read_jj_view(&self, _log_limit: usize) -> Result<Option<JjView>, VcsError> {
204        Ok(None)
205    }
206    /// Take a view another handle read, with no subprocess.
207    fn adopt_jj_view(&self, _view: JjView) {}
208    /// Whether this backend has a staging area. jj has none, so its whole
209    /// working copy reads as [`StatusModel::staged`].
210    fn has_index(&self) -> bool;
211    fn status(&self) -> Result<StatusModel, VcsError>;
212    /// HEAD vs index + worktree, untracked files included.
213    fn working_tree_diff(&self) -> Result<DiffModel, VcsError>;
214    /// [`Vcs::working_tree_diff`] taken from `base_oid`.
215    fn tree_to_workdir_diff(&self, base_oid: &str) -> Result<DiffModel, VcsError>;
216    /// Changes a single commit introduced over its first parent.
217    fn commit_diff(&self, oid: &str) -> Result<DiffModel, VcsError>;
218    /// `git diff <oldest>^..<newest>`. A root `oldest` diffs from the empty
219    /// tree.
220    fn range_diff(&self, oldest_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError>;
221    /// `git diff <base> <newest>`; with `base` a merge base this is a
222    /// three-dot diff.
223    fn tree_diff(&self, base_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError>;
224    fn merge_base(&self, a: &str, b: &str) -> Result<String, VcsError>;
225    /// Resolve a revision (oid, ref name, remote ref) to a full commit oid.
226    fn resolve(&self, revision: &str) -> Result<String, VcsError>;
227    /// History from HEAD, or from every branch, remote branch and tag with
228    /// `all_branches`, newest first and each commit before its parents.
229    fn log(&self, limit: usize, all_branches: bool) -> Result<Vec<LogEntry>, VcsError>;
230
231    /// The branch a pull request merges into by default, if the repo says.
232    fn default_branch(&self, remote: &str) -> Result<Option<String>, VcsError>;
233
234    /// Commits reachable from `head` but not `base`, newest first.
235    fn commits_between(&self, base: &str, head: &str) -> Result<Vec<LogEntry>, VcsError>;
236    /// Commits on HEAD that no remote-tracking branch contains, newest first,
237    /// at most `limit`. `None` when the repo has no remote-tracking refs. We
238    /// ask the remotes since a configured upstream may be a local branch or a
239    /// stale ref.
240    fn unpushed(&self, limit: usize) -> Result<Option<Vec<LogEntry>>, VcsError>;
241    /// Last commit to touch each line of `rel` as the worktree has it, in line
242    /// order. Uncommitted lines come back as spans owned by no commit.
243    fn blame(&self, rel: &Path) -> Result<Vec<BlameSpan>, VcsError>;
244
245    /// One file's content in `rev`'s tree, `None` when the tree lacks it.
246    fn read_at(&self, rev: &str, path: &str) -> Result<Option<String>, VcsError>;
247
248    /// A blob's raw bytes by its hex id (a [`crate::model::BlobIds`] side),
249    /// `None` when the object store has no such blob.
250    fn read_blob(&self, oid: &str) -> Result<Option<Vec<u8>>, VcsError>;
251
252    /// Every tracked file, repo-relative and sorted. This is the index, so a
253    /// staged new file is tracked and an untracked one is not.
254    fn tracked_files(&self) -> Result<Vec<PathBuf>, VcsError>;
255
256    /// Whether the repo's git attributes set `name` to true for `rel`.
257    /// Unreadable attribute files read as unset.
258    fn attr(&self, rel: &Path, name: &str) -> bool;
259
260    /// Local branches, their divergence left unresolved.
261    fn branches(&self) -> Result<Vec<BranchInfo>, VcsError>;
262
263    /// `(ahead, behind)` against the upstream, `None` when `branch` tracks
264    /// nothing.
265    fn divergence(&self, branch: &str) -> Result<Option<(usize, usize)>, VcsError>;
266    /// Local and remote-tracking branch names.
267    fn all_branches(&self) -> Result<Vec<String>, VcsError>;
268    /// Stage a whole file (worktree deletions become staged deletions).
269    fn stage(&self, rel: &Path) -> Result<(), VcsError>;
270
271    /// Stage every change in the worktree, deletions and untracked files
272    /// included.
273    fn stage_everything(&self) -> Result<(), VcsError>;
274
275    /// Reset the whole index back to HEAD, keeping the worktree.
276    fn unstage_everything(&self) -> Result<(), VcsError>;
277    /// Stage one hunk out of the unstaged (or untracked) changes of a file.
278    fn stage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError>;
279    /// Reset a file's index entry back to HEAD, keeping the worktree.
280    fn unstage(&self, rel: &Path) -> Result<(), VcsError>;
281    /// Remove one staged hunk from the index, keeping the worktree.
282    fn unstage_hunk(&self, rel: &Path, hunk: &HunkId) -> Result<(), VcsError>;
283    /// Throw away worktree changes only; an untracked file is deleted.
284    /// Refused while the file has staged changes (unstage first).
285    fn discard(&self, rel: &Path) -> Result<(), VcsError>;
286    /// Commit the index; returns the new commit id.
287    fn commit(&self, message: &str) -> Result<String, VcsError>;
288    /// Commit only `paths` (files or folders) of the working copy, which jj
289    /// can do with no index; returns the new commit id.
290    fn commit_paths(&self, _message: &str, _paths: &[String]) -> Result<String, VcsError> {
291        Err(VcsError::Rejected(
292            "stage the files you want, then commit".into(),
293        ))
294    }
295    /// A jj change verb; git has none.
296    fn change(&self, _op: &ChangeOp) -> Result<(), VcsError> {
297        Err(VcsError::Rejected(JJ_ONLY.into()))
298    }
299    /// What a jj pull fetches and rebases onto, read fresh; `None` outside
300    /// jj or with no local bookmark under `@`.
301    fn pull_target(&self) -> Result<Option<PullTarget>, VcsError> {
302        Ok(None)
303    }
304    /// After a fetch, rebase `@`'s branch onto `bookmark@remote` when that
305    /// moved.
306    fn rebase_onto_remote(&self, _bookmark: &str, _remote: &str) -> Result<PullOutcome, VcsError> {
307        Err(VcsError::Rejected(JJ_ONLY.into()))
308    }
309    /// Full message of the commit `oid`.
310    fn commit_message(&self, oid: &str) -> Result<String, VcsError>;
311    /// Full message of the HEAD commit, for amend/reword editor templates.
312    fn head_message(&self) -> Result<String, VcsError>;
313    /// Amend HEAD, returning the new commit id. `message` `None` reuses HEAD's
314    /// message (extend); `Some` rewords it. `use_index` true folds the staged
315    /// index into the new tree; false keeps HEAD's tree (a pure reword).
316    fn amend(&self, message: Option<&str>, use_index: bool) -> Result<String, VcsError>;
317    fn create_branch(&self, name: &str, checkout: bool) -> Result<(), VcsError>;
318    /// Refused for the currently checked-out branch.
319    fn delete_branch(&self, name: &str) -> Result<(), VcsError>;
320    fn checkout(&self, name: &str) -> Result<(), VcsError>;
321    /// Whether a raw `git`/forge CLI command may check out a branch. False for
322    /// jj, whose operation log would miss the write, so we go through
323    /// [`Vcs::checkout`] there.
324    fn native_git_checkout(&self) -> bool;
325    /// Stash tracked changes, leaving untracked files in place like
326    /// `git stash`. `message` `None` lets the backend label it.
327    fn stash_push(&self, message: Option<&str>) -> Result<(), VcsError>;
328    /// Restore the most recent stash and drop it. Refused when there is no
329    /// stash or the pop would conflict.
330    fn stash_pop(&self) -> Result<(), VcsError>;
331    /// Argv for a network op, run in [`Vcs::workdir`] so the backend's own CLI
332    /// handles credentials. jj pushes bookmarks with `jj git push` and pulls
333    /// with `jj git fetch`, then [`Vcs::rebase_onto_remote`].
334    fn network_argv(&self, op: NetworkOp) -> Result<Vec<String>, VcsError>;
335    fn workdir(&self) -> Result<PathBuf, VcsError>;
336    fn remote_url(&self, name: &str) -> Result<Option<String>, VcsError>;
337    fn remotes(&self) -> Result<Vec<String>, VcsError>;
338
339    /// Set the line-diff algorithm for every later diff of this instance.
340    fn set_diff_algorithm(&self, algorithm: DiffAlgorithm, indent_heuristic: bool);
341}
342
343/// The status screen's commit sections.
344#[derive(Debug, Clone, Default, PartialEq, Eq)]
345pub struct CommitLists {
346    /// [`Vcs::unpushed`]'s answer.
347    pub unpushed: Option<Vec<LogEntry>>,
348    /// HEAD's history with the unpushed commits left out.
349    pub recent: Vec<LogEntry>,
350}
351
352/// `recent` leaves out what `unpushed` holds, so a caller applies both or
353/// neither, or a commit goes missing from both sections.
354pub fn commit_lists(
355    vcs: &dyn Vcs,
356    recent_limit: usize,
357    unpushed_limit: usize,
358) -> Result<CommitLists, VcsError> {
359    let unpushed = vcs.unpushed(unpushed_limit)?;
360    let ahead = unpushed.as_deref().unwrap_or_default();
361    let mut recent = vcs.log(recent_limit + ahead.len(), false)?;
362    recent.retain(|entry| !ahead.iter().any(|local| local.oid == entry.oid));
363    recent.truncate(recent_limit);
364    Ok(CommitLists { unpushed, recent })
365}
366
367/// Three-dot diff of `rev` against the working tree: `merge-base(rev, HEAD)`
368/// vs index + worktree + untracked. Commits `rev` gained since the branch
369/// forked stay out of it; uncommitted work stays in.
370pub fn against_diff(vcs: &dyn Vcs, rev: &str) -> Result<DiffModel, VcsError> {
371    let head = vcs.resolve("HEAD")?;
372    let base = vcs.merge_base(&vcs.resolve(rev)?, &head)?;
373    vcs.tree_to_workdir_diff(&base)
374}