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