vcs-core 0.1.0

Unified facade over vcs-git and vcs-jj: repo detection and a backend-agnostic VCS handle.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! `vcs-core` — a unified facade over [`vcs-git`](vcs_git) and [`vcs-jj`](vcs_jj).
//!
//! Two pieces both downstream tools kept re-implementing:
//!
//! * [`detect`] — walk up from a directory to find a `.git`/`.jj` repository
//!   (jj wins when colocated), returning the [`BackendKind`] and root.
//! * [`Repo`] — a cwd-bound handle that dispatches the *common* VCS operations
//!   (status, diff stat, partial commit, worktree create/remove, …) to whichever
//!   backend is present, returning backend-agnostic DTOs. Open it
//!   once with [`Repo::open`]; re-anchor it to another directory with
//!   [`Repo::at`] without threading a `dir` argument through every call.
//!
//! Tool-specific operations stay on the underlying typed clients, reachable via
//! the [`Repo::git`] / [`Repo::jj`] escape hatches.
//!
//! ```no_run
//! use vcs_core::Repo;
//! # fn run() -> vcs_core::Result<()> {
//! let repo = Repo::open(".")?;
//! # let _ = repo.kind();
//! # Ok(()) }
//! ```
//!
//! The handle is generic over the [`ProcessRunner`] so tests can inject a fake;
//! [`Repo::open`] uses the real job-backed runner.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use processkit::{JobRunner, ProcessRunner};
use vcs_git::Git;
use vcs_jj::Jj;

mod dto;
mod error;
mod git_backend;
mod jj_backend;

pub use dto::{BackendKind, ChangeKind, CreateOutcome, DiffStat, FileChange, WorktreeInfo};
pub use error::{Error, Result};

// Re-export the underlying typed clients so a consumer depending only on
// `vcs-core` can still reach raw, tool-specific operations — and their types
// (`GitApi`, `JjApi`, `WorktreeAdd`, `JjFileset`, …) — without adding `vcs-git`
// / `vcs-jj` as separate dependencies. [`Repo::git`] / [`Repo::jj`] hand out
// borrows of these clients; the consumer decides, per call, whether to go
// through the facade or straight to the tool.
pub use vcs_git;
pub use vcs_jj;

/// The result of [`detect`]: which backend, and the repository root it was found
/// at.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Located {
    /// The detected backend.
    pub kind: BackendKind,
    /// The directory holding `.git`/`.jj` — the worktree root.
    pub root: PathBuf,
}

/// Walk up from `start` to the filesystem root looking for a repository. A `.jj`
/// directory wins over `.git` (colocated repos are driven through jj); `.git` may
/// be a directory or a gitlink file (a linked worktree/submodule). Pure
/// filesystem probing — no subprocess.
///
/// `start` is walked exactly as given via [`Path::parent`], so pass an **absolute**
/// path to search ancestors — a relative path like `"."` has no ancestor chain
/// and only its own directory is checked. ([`Repo::open`] absolutises for you.)
pub fn detect(start: &Path) -> Option<Located> {
    let mut current = Some(start);
    while let Some(dir) = current {
        if dir.join(".jj").is_dir() {
            return Some(Located {
                kind: BackendKind::Jj,
                root: dir.to_path_buf(),
            });
        }
        if dir.join(".git").exists() {
            return Some(Located {
                kind: BackendKind::Git,
                root: dir.to_path_buf(),
            });
        }
        current = dir.parent();
    }
    None
}

/// The per-tool client behind a [`Repo`]. Shared via `Arc` so [`Repo::at`] can
/// re-anchor the cwd cheaply without rebuilding the client.
enum Backend<R: ProcessRunner> {
    Git(Arc<Git<R>>),
    Jj(Arc<Jj<R>>),
}

impl<R: ProcessRunner> Backend<R> {
    fn shared(&self) -> Self {
        match self {
            Backend::Git(g) => Backend::Git(Arc::clone(g)),
            Backend::Jj(j) => Backend::Jj(Arc::clone(j)),
        }
    }
}

/// A cwd-bound, backend-agnostic VCS handle. Operations run against the bound
/// directory ([`cwd`](Repo::cwd)); use [`at`](Repo::at) to get a sibling handle
/// bound elsewhere.
pub struct Repo<R: ProcessRunner = JobRunner> {
    root: PathBuf,
    cwd: PathBuf,
    backend: Backend<R>,
}

impl Repo<JobRunner> {
    /// Detect the repository at or above `dir` and open a handle bound to `dir`,
    /// using the real job-backed runner. Errors with
    /// [`Error::NotARepository`] when no `.git`/`.jj` is found.
    pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
        // Absolutise first: `detect` walks parents, and a relative path like "."
        // has no real ancestor chain (`Path::new(".").parent()` is `""`, then
        // `None`), so a relative input would never find a repo above the cwd.
        let dir = std::path::absolute(dir.as_ref())?;
        let located = detect(&dir).ok_or_else(|| Error::NotARepository(dir.clone()))?;
        let backend = match located.kind {
            BackendKind::Git => Backend::Git(Arc::new(Git::new())),
            BackendKind::Jj => Backend::Jj(Arc::new(Jj::new())),
        };
        Ok(Repo {
            root: located.root,
            cwd: dir,
            backend,
        })
    }
}

impl<R: ProcessRunner> Repo<R> {
    /// Build a git-backed handle from an explicit client — for a custom runner
    /// (e.g. a test seam) or a pre-configured [`Git`].
    pub fn from_git(root: impl Into<PathBuf>, cwd: impl Into<PathBuf>, client: Git<R>) -> Self {
        Repo {
            root: root.into(),
            cwd: cwd.into(),
            backend: Backend::Git(Arc::new(client)),
        }
    }

    /// Build a jj-backed handle from an explicit client.
    pub fn from_jj(root: impl Into<PathBuf>, cwd: impl Into<PathBuf>, client: Jj<R>) -> Self {
        Repo {
            root: root.into(),
            cwd: cwd.into(),
            backend: Backend::Jj(Arc::new(client)),
        }
    }

    /// Which backend drives this handle.
    pub fn kind(&self) -> BackendKind {
        match &self.backend {
            Backend::Git(_) => BackendKind::Git,
            Backend::Jj(_) => BackendKind::Jj,
        }
    }

    /// The repository root detected at open time.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// The directory operations run against.
    pub fn cwd(&self) -> &Path {
        &self.cwd
    }

    /// A sibling handle bound to `dir`, sharing this handle's client and root.
    pub fn at(&self, dir: impl Into<PathBuf>) -> Self {
        Repo {
            root: self.root.clone(),
            cwd: dir.into(),
            backend: self.backend.shared(),
        }
    }

    /// The underlying [`Git`] client, or `None` when jj-backed — an escape hatch
    /// to git-only operations not on the common surface.
    pub fn git(&self) -> Option<&Git<R>> {
        match &self.backend {
            Backend::Git(g) => Some(g.as_ref()),
            Backend::Jj(_) => None,
        }
    }

    /// The underlying [`Jj`] client, or `None` when git-backed.
    pub fn jj(&self) -> Option<&Jj<R>> {
        match &self.backend {
            Backend::Jj(j) => Some(j.as_ref()),
            Backend::Git(_) => None,
        }
    }

    /// The current branch (git) or bookmark (jj); `None` when detached / no
    /// bookmark on the working copy.
    pub async fn current_branch(&self) -> Result<Option<String>> {
        match &self.backend {
            Backend::Git(g) => git_backend::current_branch(g, &self.cwd).await,
            Backend::Jj(j) => jj_backend::current_branch(j, &self.cwd).await,
        }
    }

    /// The trunk branch/bookmark; `None` when it can't be resolved.
    pub async fn trunk(&self) -> Result<Option<String>> {
        match &self.backend {
            Backend::Git(g) => git_backend::trunk(g, &self.cwd).await,
            Backend::Jj(j) => jj_backend::trunk(j, &self.cwd).await,
        }
    }

    /// Local branch (git) / bookmark (jj) names.
    pub async fn local_branches(&self) -> Result<Vec<String>> {
        match &self.backend {
            Backend::Git(g) => git_backend::local_branches(g, &self.cwd).await,
            Backend::Jj(j) => jj_backend::local_branches(j, &self.cwd).await,
        }
    }

    /// Whether a local branch/bookmark named `name` exists.
    pub async fn branch_exists(&self, name: &str) -> Result<bool> {
        match &self.backend {
            Backend::Git(g) => git_backend::branch_exists(g, &self.cwd, name).await,
            Backend::Jj(j) => jj_backend::branch_exists(j, &self.cwd, name).await,
        }
    }

    /// Whether the working copy has uncommitted changes (git: a non-empty
    /// `status`; jj: a non-empty working-copy change `@`).
    pub async fn has_uncommitted_changes(&self) -> Result<bool> {
        match &self.backend {
            Backend::Git(g) => git_backend::has_uncommitted_changes(g, &self.cwd).await,
            Backend::Jj(j) => jj_backend::has_uncommitted_changes(j, &self.cwd).await,
        }
    }

    /// Delete a local branch (git) / bookmark (jj). `force` applies to git only
    /// (`branch -D` vs `-d`); jj has no force and ignores it.
    pub async fn delete_branch(&self, name: &str, force: bool) -> Result<()> {
        match &self.backend {
            Backend::Git(g) => git_backend::delete_branch(g, &self.cwd, name, force).await,
            Backend::Jj(j) => jj_backend::delete_branch(j, &self.cwd, name).await,
        }
    }

    /// Rename a local branch (git) / bookmark (jj).
    pub async fn rename_branch(&self, old: &str, new: &str) -> Result<()> {
        match &self.backend {
            Backend::Git(g) => git_backend::rename_branch(g, &self.cwd, old, new).await,
            Backend::Jj(j) => jj_backend::rename_branch(j, &self.cwd, old, new).await,
        }
    }

    /// The working-copy changes (git `status` / jj `diff -r @ --summary`).
    pub async fn changed_files(&self) -> Result<Vec<FileChange>> {
        match &self.backend {
            Backend::Git(g) => git_backend::changed_files(g, &self.cwd).await,
            Backend::Jj(j) => jj_backend::changed_files(j, &self.cwd).await,
        }
    }

    /// Aggregate insertion/deletion counts for the working copy.
    pub async fn diff_stat(&self) -> Result<DiffStat> {
        match &self.backend {
            Backend::Git(g) => git_backend::diff_stat(g, &self.cwd).await,
            Backend::Jj(j) => jj_backend::diff_stat(j, &self.cwd).await,
        }
    }

    /// Commit exactly `paths` with `message` (git `commit --only`, jj
    /// `commit <filesets>`). Paths are repo-relative.
    pub async fn commit_paths(&self, paths: &[String], message: &str) -> Result<()> {
        match &self.backend {
            Backend::Git(g) => git_backend::commit_paths(g, &self.cwd, paths, message).await,
            Backend::Jj(j) => jj_backend::commit_paths(j, &self.cwd, paths, message).await,
        }
    }

    /// Fetch from the default remote (git `fetch` / jj `git fetch`).
    pub async fn fetch(&self) -> Result<()> {
        match &self.backend {
            Backend::Git(g) => git_backend::fetch(g, &self.cwd).await,
            Backend::Jj(j) => jj_backend::fetch(j, &self.cwd).await,
        }
    }

    /// List attached worktrees (git) / workspaces (jj).
    pub async fn list_worktrees(&self) -> Result<Vec<WorktreeInfo>> {
        match &self.backend {
            Backend::Git(g) => git_backend::list_worktrees(g, &self.cwd).await,
            Backend::Jj(j) => jj_backend::list_worktrees(j, &self.cwd).await,
        }
    }

    /// Create a worktree/workspace at `path` on a **new** `branch` based on
    /// `base`. Always [`CreateOutcome::Plain`]; a copy-on-write strategy stays in
    /// the consumer.
    ///
    /// `branch` must not already exist. The jj path is two steps (`workspace add`
    /// then `bookmark create`) and is not atomic: if the bookmark step fails, the
    /// freshly-added workspace is left in place for the caller to clean up. A
    /// consumer needing resume-existing or rollback semantics should drive the
    /// underlying client via [`jj`](Repo::jj) / [`git`](Repo::git).
    pub async fn create_worktree(
        &self,
        path: &Path,
        branch: &str,
        base: &str,
    ) -> Result<CreateOutcome> {
        match &self.backend {
            Backend::Git(g) => git_backend::create_worktree(g, &self.cwd, path, branch, base).await,
            Backend::Jj(j) => jj_backend::create_worktree(j, &self.cwd, path, branch, base).await,
        }
    }

    /// Remove the worktree/workspace at `path`. For jj this resolves the
    /// workspace name by matching `path`, deletes the directory, then forgets it.
    pub async fn remove_worktree(&self, path: &Path, force: bool) -> Result<()> {
        match &self.backend {
            Backend::Git(g) => git_backend::remove_worktree(g, &self.cwd, path, force).await,
            Backend::Jj(j) => jj_backend::remove_worktree(j, &self.cwd, path, force).await,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use processkit::{Reply, ScriptedRunner};

    // --- detect ------------------------------------------------------------

    /// A unique temp directory, removed on drop.
    struct TempDir(PathBuf);
    impl TempDir {
        fn new(tag: &str) -> Self {
            // Unique without a temp crate: process id + a monotonic counter, so
            // parallel tests never collide.
            use std::sync::atomic::{AtomicU64, Ordering};
            static COUNTER: AtomicU64 = AtomicU64::new(0);
            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
            let dir =
                std::env::temp_dir().join(format!("vcs-core-{tag}-{}-{n}", std::process::id()));
            std::fs::create_dir_all(&dir).expect("create temp dir");
            TempDir(dir)
        }
        fn path(&self) -> &Path {
            &self.0
        }
    }
    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn detect_finds_git_and_jj_and_prefers_jj() {
        let tmp = TempDir::new("detect");
        let root = tmp.path();

        // Plain git repo.
        std::fs::create_dir_all(root.join(".git")).unwrap();
        let located = detect(root).expect("git detected");
        assert_eq!(located.kind, BackendKind::Git);
        assert_eq!(located.root, root);

        // Colocated: adding .jj makes jj win.
        std::fs::create_dir_all(root.join(".jj")).unwrap();
        assert_eq!(detect(root).unwrap().kind, BackendKind::Jj);
    }

    #[test]
    fn detect_walks_up_to_ancestor() {
        let tmp = TempDir::new("walkup");
        let root = tmp.path();
        std::fs::create_dir_all(root.join(".git")).unwrap();
        let nested = root.join("a").join("b");
        std::fs::create_dir_all(&nested).unwrap();
        let located = detect(&nested).expect("found via ancestor walk");
        assert_eq!(located.kind, BackendKind::Git);
        assert_eq!(located.root, root);
    }

    #[test]
    fn detect_returns_none_outside_repo() {
        let tmp = TempDir::new("norepo");
        assert!(detect(tmp.path()).is_none());
    }

    // --- dispatch (hermetic, ScriptedRunner-backed) ------------------------

    fn git_repo(runner: ScriptedRunner) -> Repo<ScriptedRunner> {
        Repo::from_git("/repo", "/repo", Git::with_runner(runner))
    }

    fn jj_repo(runner: ScriptedRunner) -> Repo<ScriptedRunner> {
        Repo::from_jj("/repo", "/repo", Jj::with_runner(runner))
    }

    #[tokio::test]
    async fn kind_and_escape_hatches_reflect_backend() {
        let repo = git_repo(ScriptedRunner::new());
        assert_eq!(repo.kind(), BackendKind::Git);
        assert!(repo.git().is_some());
        assert!(repo.jj().is_none());
    }

    #[tokio::test]
    async fn current_branch_maps_detached_head_to_none() {
        let named = git_repo(ScriptedRunner::new().on(["rev-parse"], Reply::ok("main\n")));
        assert_eq!(
            named.current_branch().await.unwrap().as_deref(),
            Some("main")
        );
        let detached = git_repo(ScriptedRunner::new().on(["rev-parse"], Reply::ok("HEAD\n")));
        assert!(detached.current_branch().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn changed_files_maps_git_status() {
        let repo = git_repo(ScriptedRunner::new().on(
            ["status"],
            Reply::ok(" M a.rs\0?? b.rs\0R  new.rs\0old.rs\0"),
        ));
        let changes = repo.changed_files().await.unwrap();
        assert_eq!(changes.len(), 3);
        assert_eq!(changes[0].kind, ChangeKind::Modified);
        assert_eq!(changes[1].kind, ChangeKind::Added);
        assert_eq!(changes[2].kind, ChangeKind::Renamed);
        assert_eq!(changes[2].old_path.as_deref(), Some("old.rs"));
    }

    #[tokio::test]
    async fn local_branches_maps_git_branch_output() {
        let repo = git_repo(ScriptedRunner::new().on(["branch"], Reply::ok("* main\n  feat\n")));
        assert_eq!(repo.local_branches().await.unwrap(), ["main", "feat"]);
    }

    #[tokio::test]
    async fn branch_exists_reads_show_ref_exit() {
        let yes = git_repo(ScriptedRunner::new().on(["show-ref"], Reply::ok("")));
        assert!(yes.branch_exists("main").await.unwrap());
        let no = git_repo(ScriptedRunner::new().on(["show-ref"], Reply::fail(1, "")));
        assert!(!no.branch_exists("nope").await.unwrap());
    }

    #[tokio::test]
    async fn has_uncommitted_changes_reflects_status() {
        let dirty = git_repo(ScriptedRunner::new().on(["status"], Reply::ok(" M a.rs\0")));
        assert!(dirty.has_uncommitted_changes().await.unwrap());
        let clean = git_repo(ScriptedRunner::new().on(["status"], Reply::ok("")));
        assert!(!clean.has_uncommitted_changes().await.unwrap());
    }

    #[tokio::test]
    async fn at_rebinds_cwd_and_shares_backend() {
        let repo = git_repo(ScriptedRunner::new());
        let moved = repo.at("/repo/sub");
        assert_eq!(moved.cwd(), Path::new("/repo/sub"));
        assert_eq!(moved.root(), Path::new("/repo"));
        assert_eq!(moved.kind(), BackendKind::Git);
    }

    // --- dispatch: jj backend (hermetic) -----------------------------------

    #[tokio::test]
    async fn jj_kind_and_escape_hatches_reflect_backend() {
        let repo = jj_repo(ScriptedRunner::new());
        assert_eq!(repo.kind(), BackendKind::Jj);
        assert!(repo.jj().is_some() && repo.git().is_none());
    }

    #[tokio::test]
    async fn jj_current_branch_reads_bookmark() {
        let repo = jj_repo(ScriptedRunner::new().on(["log"], Reply::ok("main\n")));
        assert_eq!(
            repo.current_branch().await.unwrap().as_deref(),
            Some("main")
        );
    }

    #[tokio::test]
    async fn jj_local_branches_maps_bookmark_list() {
        let repo = jj_repo(ScriptedRunner::new().on(
            ["bookmark", "list"],
            Reply::ok("main: chg cmt desc\nfeat: c2 m2 d2\n"),
        ));
        assert_eq!(repo.local_branches().await.unwrap(), ["main", "feat"]);
    }

    #[tokio::test]
    async fn jj_branch_exists_scans_bookmarks() {
        let repo = jj_repo(
            ScriptedRunner::new().on(["bookmark", "list"], Reply::ok("main: chg cmt desc\n")),
        );
        assert!(repo.branch_exists("main").await.unwrap());
        let repo2 = jj_repo(
            ScriptedRunner::new().on(["bookmark", "list"], Reply::ok("main: chg cmt desc\n")),
        );
        assert!(!repo2.branch_exists("missing").await.unwrap());
    }

    #[tokio::test]
    async fn jj_has_uncommitted_changes_reads_empty_flag() {
        // CHANGE_TEMPLATE row: change_id \t commit_id \t empty \t description
        let dirty = jj_repo(ScriptedRunner::new().on(["log"], Reply::ok("kz\t38\tfalse\twip\n")));
        assert!(dirty.has_uncommitted_changes().await.unwrap());
        let clean = jj_repo(ScriptedRunner::new().on(["log"], Reply::ok("kz\t38\ttrue\t\n")));
        assert!(!clean.has_uncommitted_changes().await.unwrap());
    }

    #[tokio::test]
    async fn jj_changed_files_maps_diff_summary() {
        let repo = jj_repo(
            ScriptedRunner::new().on(["diff"], Reply::ok("M src/a.rs\nA b.rs\nD gone.rs\n")),
        );
        let changes = repo.changed_files().await.unwrap();
        assert_eq!(changes.len(), 3);
        assert_eq!(changes[0].kind, ChangeKind::Modified);
        assert_eq!(changes[1].kind, ChangeKind::Added);
        assert_eq!(changes[2].kind, ChangeKind::Deleted);
        assert!(changes.iter().all(|c| c.old_path.is_none()));
    }

    #[tokio::test]
    async fn jj_rename_branch_builds_bookmark_rename() {
        use processkit::RecordingRunner;
        let rec = RecordingRunner::replying(Reply::ok(""));
        let repo = Repo::from_jj("/repo", "/repo", Jj::with_runner(&rec));
        repo.rename_branch("old", "new").await.unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["bookmark", "rename", "old", "new"]
        );
    }
}