diffler-core 0.20.0

Core review engine for diffler: diffs, sessions, comments, viewed marks
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! jj backend. Reads delegate to [`GitVcs`]: in a colocated repo git's HEAD
//! sits on `@-` and the worktree matches `@`; otherwise we open jj's own git
//! store and point its reads of HEAD at `@-`. Writes shell out to `jj`,
//! which owns the operation log and working-copy snapshot.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::diffalgo::{DiffAlgorithm, DiffSettings};
use crate::git::GitVcs;
use crate::model::{DiffModel, HunkId};
use crate::vcs::{
    BlameSpan, Bookmark, BranchInfo, ChangeInfo, ChangeOp, HeadInfo, JjView, LogEntry, NetworkOp,
    PullOutcome, PullTarget, StatusModel, Vcs, VcsError,
};

const NO_DESCRIPTION: &str = "(no description set)";
const FIELD_SEPARATOR: char = '\x1f';
const LIST_SEPARATOR: char = '\x1e';
const COMMIT_ID_TEMPLATE: &str = r#"commit_id ++ "\n""#;
/// The bookmarked commits nearest `@`, which name the line `@` sits on.
const NEAREST_BOOKMARKS: &str = "heads(::@ & (bookmarks() | remote_bookmarks()))";
/// The history whose change ids a view carries, matching what the log walks.
const HISTORY: &str = "::(@ | bookmarks() | remote_bookmarks() | tags())";

pub struct JjVcs {
    git: GitVcs,
    root: PathBuf,
    colocated: bool,
    view: RefCell<JjView>,
    /// Whether this handle has learned `@-` from jj, which a repo with no
    /// `.git` needs before its first read of HEAD.
    base_known: Cell<bool>,
}

impl JjVcs {
    pub fn open(root: &Path) -> Result<Self, VcsError> {
        Self::open_with_settings(root, &DiffSettings::default())
    }

    pub fn open_with_settings(root: &Path, settings: &DiffSettings) -> Result<Self, VcsError> {
        let colocated = root.join(".git").exists();
        let git = if colocated {
            GitVcs::open_with_settings(root, settings)?
        } else {
            GitVcs::open_jj_store(&store_git_dir(root)?, root, settings)?
        };
        Ok(Self {
            git,
            root: root.to_path_buf(),
            colocated,
            view: RefCell::default(),
            base_known: Cell::new(false),
        })
    }

    /// `jj log` over `revset` with `template`, which a jj repo answers
    /// without snapshotting the working copy.
    fn query(
        &self,
        revset: &str,
        template: &str,
        limit: Option<usize>,
    ) -> Result<String, VcsError> {
        let mut args = vec![
            "log".to_owned(),
            "--no-graph".to_owned(),
            "--ignore-working-copy".to_owned(),
            format!("--revisions={revset}"),
            format!("--template={template}"),
        ];
        if let Some(limit) = limit {
            args.push(format!("--limit={limit}"));
        }
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        self.run(&args)
    }

    /// `@`, its first parent and the nearest bookmark, plus every bookmark
    /// when the git store has none of its own.
    fn read_state(&self) -> Result<JjView, VcsError> {
        let revset = if self.colocated {
            format!("@ | {NEAREST_BOOKMARKS}")
        } else {
            "@ | bookmarks() | remote_bookmarks()".to_owned()
        };
        let marker = format!(
            r#"if(self.current_working_copy(), "@", if(self.contained_in("{NEAREST_BOOKMARKS}"), "^", "-"))"#
        );
        let template = line_template(&[
            &marker,
            "commit_id",
            "change_id.short(8)",
            "description.first_line()",
            &list_template("parents.map(|c| c.commit_id())"),
            &list_template("local_bookmarks.map(|b| b.name())"),
            &list_template(r#"remote_bookmarks.map(|b| b.name() ++ "@" ++ b.remote())"#),
            r#"committer.timestamp().format("%s")"#,
        ]);
        let out = self.query(&revset, &template, None)?;
        Ok(parse_state(&out, !self.colocated))
    }

    /// Short change id by commit id over the newest `limit` commits of
    /// [`HISTORY`].
    fn read_change_ids(&self, limit: usize) -> Result<HashMap<String, String>, VcsError> {
        let template = line_template(&["commit_id", "change_id.short(8)"]);
        let out = self.query(HISTORY, &template, Some(limit))?;
        Ok(out
            .lines()
            .filter_map(|line| line.split_once(FIELD_SEPARATOR))
            .map(|(oid, change)| (oid.to_owned(), change.to_owned()))
            .collect())
    }

    /// A repo with no `.git` learns `@-` from jj once per handle; a
    /// refresh's view moves it after that. Without it every read of HEAD
    /// would show an unborn repo, so a failing `jj` fails the read.
    fn ensure_base(&self) -> Result<(), VcsError> {
        if self.colocated || self.base_known.get() {
            return Ok(());
        }
        self.reread_state()
    }

    /// The state alone, keeping the change ids this handle already holds.
    fn reread_state(&self) -> Result<(), VcsError> {
        let state = self.read_state()?;
        let change_ids = std::mem::take(&mut self.view.borrow_mut().change_ids);
        self.adopt_jj_view(JjView {
            change_ids,
            ..state
        });
        Ok(())
    }

    /// Short change ids, jj's bookmarks and jj's wording for an empty
    /// description, and no `jj/keep/*` refs, which jj makes to keep commits
    /// from git's gc.
    fn decorated(&self, mut entries: Vec<LogEntry>) -> Vec<LogEntry> {
        let view = self.view.borrow();
        for entry in &mut entries {
            entry.change_id = view.change_ids.get(&entry.oid).cloned();
            if self.colocated {
                entry.refs.retain(|name| !name.starts_with("jj/keep/"));
            } else {
                entry.refs = view
                    .bookmarks
                    .iter()
                    .filter(|bookmark| bookmark.oid == entry.oid)
                    .map(|bookmark| bookmark.name.clone())
                    .collect();
            }
            if entry.subject.is_empty() {
                NO_DESCRIPTION.clone_into(&mut entry.subject);
            }
        }
        entries
    }

    /// The commit a jj bookmark (`name` or `name@remote`) sits on.
    fn bookmark_oid(&self, name: &str) -> Option<String> {
        self.view
            .borrow()
            .bookmarks
            .iter()
            .find(|bookmark| bookmark.name == name)
            .map(|bookmark| bookmark.oid.clone())
    }

    /// Exactly one commit `revision` names as a jj revset.
    fn resolve_revset(&self, revision: &str) -> Result<String, VcsError> {
        let out = self.query(revision, COMMIT_ID_TEMPLATE, Some(2))?;
        match out.lines().collect::<Vec<_>>().as_slice() {
            [oid] if is_root(oid) => Err(VcsError::Rejected(format!(
                "`{revision}` names jj's root commit, which git has no commit for; name another"
            ))),
            [oid] => Ok((*oid).to_owned()),
            [] => Err(VcsError::Rejected(format!(
                "`{revision}` matches no commit, name one that exists"
            ))),
            _ => Err(VcsError::Rejected(format!(
                "`{revision}` matches several commits, name one"
            ))),
        }
    }

    /// Run jj from the repo root, since jj resolves paths against the cwd. A
    /// failure carries jj's `Error:` line.
    fn run(&self, args: &[&str]) -> Result<String, VcsError> {
        let output = Command::new("jj")
            .current_dir(&self.root)
            .args(args)
            // we pass every message as an argument, so an editor jj opens
            // anyway would freeze the UI thread; we make it fail at once
            .env("JJ_EDITOR", "false")
            .output()
            .map_err(|err| match err.kind() {
                io::ErrorKind::NotFound => VcsError::Rejected(
                    "install jj (jujutsu) on PATH to read and change this repo".into(),
                ),
                _ => VcsError::Io(err),
            })?;
        if output.status.success() {
            return Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned());
        }
        let stderr = String::from_utf8_lossy(&output.stderr);
        let mut lines = stderr.lines().map(str::trim);
        let message = lines
            .clone()
            .find(|line| line.starts_with("Error:"))
            .or_else(|| lines.find(|line| !line.is_empty()))
            .unwrap_or("run the jj command in a shell to see why it failed")
            .to_owned();
        Err(VcsError::Rejected(message))
    }

    /// Colocation exports jj's state to git synchronously, so HEAD already
    /// names the commit a write made; a repo with no `.git` asks jj again.
    fn head_oid(&self) -> Result<String, VcsError> {
        if !self.colocated {
            self.reread_state()?;
        }
        self.git.resolve("HEAD")
    }

    /// `rev` for a jj argument. A commit id goes as the change it belongs
    /// to, since acting on a commit rewritten since would bring it back as a
    /// divergent copy.
    fn target(&self, rev: &str) -> Result<String, VcsError> {
        if is_working_copy_revset(rev) {
            return Ok(rev.to_owned());
        }
        let change = self.query(&quoted(rev), "change_id", Some(1))?;
        if change.is_empty() {
            return Err(VcsError::Rejected(format!(
                "`{rev}` names no commit; refresh and pick another"
            )));
        }
        Ok(format!("change_id({})", quoted(&change)))
    }

    /// jj snapshots edits before an undo or redo, and both would then act on
    /// that snapshot and drop the edits, so we refuse while it is the newest
    /// operation.
    fn refuse_over_snapshot(&self, verb: &str) -> Result<(), VcsError> {
        self.run(&["util", "snapshot"])?;
        let newest = self.run(&[
            "op",
            "log",
            "--ignore-working-copy",
            "--no-graph",
            "--limit=1",
            "--template=description",
        ])?;
        if newest.starts_with("snapshot working copy") {
            return Err(VcsError::Rejected(format!(
                "describe or commit your edits first; {verb} would drop them"
            )));
        }
        Ok(())
    }

    /// A bare squash opens an editor only when both sides are described, so
    /// we join the two descriptions ourselves then.
    fn squash(&self, rev: &str) -> Result<String, VcsError> {
        let target = self.target(rev)?;
        let source = self.query(&target, "description", Some(1))?;
        let destination = self.query(&format!("({target})-"), "description", Some(1))?;
        let revision = format!("--revision={target}");
        if source.is_empty() || destination.is_empty() {
            return self.run(&["squash", &revision]);
        }
        self.run(&[
            "squash",
            &revision,
            &format!("--message={destination}\n\n{source}"),
        ])
    }

    /// Read fresh, since a bookmark made a moment ago must count.
    fn nearest_bookmark(&self) -> Result<NearestBookmark, VcsError> {
        let template = line_template(&[
            r#"if(self.current_working_copy(), "@", if(self.contained_in("@-"), "-", "^"))"#,
            r#"if(immutable, "1", "0")"#,
            &list_template("local_bookmarks.map(|b| b.name())"),
        ]);
        let out = self.query("@- | heads(::@ & bookmarks())", &template, None)?;
        Ok(parse_nearest_bookmark(&out))
    }

    /// What `jj git push` sends: the nearest local bookmark when it sits on
    /// `@` or `@-`, else `@-` under a name jj makes from its change id. A
    /// bookmark further back that is still mutable would push without the
    /// newer work, so we ask for it to be moved.
    fn push_selection(&self) -> Result<String, VcsError> {
        let nearest = self.nearest_bookmark()?;
        match nearest.name {
            Some(name) if nearest.on_working_line => {
                return Ok(format!("--bookmark=exact:{}", quoted(&name)));
            }
            Some(name) if !nearest.immutable => {
                return Err(VcsError::Rejected(format!(
                    "move {name} to @- first (jj bookmark move {name} --to @-), then push"
                )));
            }
            _ => {}
        }
        if nearest.parent_immutable {
            return Err(VcsError::Rejected(
                "commit a change on top of @- first; there is nothing new to push".into(),
            ));
        }
        Ok("--change=@-".into())
    }
}

/// The git store a jj repo without `.git` keeps; `git_target` names it
/// relative to `.jj/repo/store`, and it may sit outside the repo.
fn store_git_dir(root: &Path) -> Result<PathBuf, VcsError> {
    // a secondary workspace's `.jj/repo` is a file naming the main one
    if root.join(".jj/repo").is_file() {
        return Err(VcsError::Rejected(
            "open the repository's main jj workspace; secondary workspaces aren't supported yet"
                .into(),
        ));
    }
    let store = root.join(".jj/repo/store");
    let target = fs::read_to_string(store.join("git_target"))?;
    Ok(store.join(target.trim()))
}

/// `fields` joined into one line per commit.
fn line_template(fields: &[&str]) -> String {
    let separator = format!(r#" ++ "\x{:02x}" ++ "#, u32::from(FIELD_SEPARATOR));
    format!(r#"{} ++ "\n""#, fields.join(&separator))
}

fn list_template(list: &str) -> String {
    format!(r#"{list}.join("\x{:02x}")"#, u32::from(LIST_SEPARATOR))
}

fn split_list(list: &str) -> impl Iterator<Item = &str> {
    list.split(LIST_SEPARATOR).filter(|item| !item.is_empty())
}

/// The `git` remote is jj's mirror of a colocated repo's local bookmarks.
fn real_remotes(list: &str) -> impl Iterator<Item = &str> {
    split_list(list).filter(|name| !name.ends_with("@git"))
}

/// [`JjVcs::read_state`]'s rows as a view with no change ids. `bookmarks`
/// lists every bookmark the rows carry.
fn parse_state(out: &str, bookmarks: bool) -> JjView {
    let mut view = JjView::default();
    let mut nearest = None;
    for line in out.lines() {
        let fields: Vec<&str> = line.split(FIELD_SEPARATOR).collect();
        let &[
            marker,
            oid,
            change_id,
            description,
            parents,
            local,
            remote,
            time,
        ] = fields.as_slice()
        else {
            continue;
        };
        let bookmark = || split_list(local).chain(real_remotes(remote)).next();
        if marker == "@" {
            view.base = split_list(parents)
                .next()
                .filter(|id| !is_root(id))
                .map(str::to_owned);
            view.change = Some(ChangeInfo {
                change_id: change_id.to_owned(),
                commit_id: oid.to_owned(),
                bookmark: bookmark().map(str::to_owned),
                description: description.to_owned(),
            });
        } else if marker == "^" && nearest.is_none() {
            nearest = bookmark();
        }
        if bookmarks {
            let tip_unix = time.parse().unwrap_or_default();
            let names = split_list(local)
                .map(|name| (name, false))
                .chain(real_remotes(remote).map(|name| (name, true)));
            view.bookmarks.extend(names.map(|(name, remote)| Bookmark {
                name: name.to_owned(),
                oid: oid.to_owned(),
                remote,
                tip_unix,
            }));
        }
    }
    if let Some(change) = view.change.as_mut()
        && change.bookmark.is_none()
    {
        change.bookmark = nearest.map(str::to_owned);
    }
    view
}

/// `revision` split before a trailing git ancestry suffix: `main~2` is
/// `("main", "~2")`, `v2` has none.
fn split_ancestry(revision: &str) -> (&str, &str) {
    let kept = revision
        .trim_end_matches(|c: char| matches!(c, '~' | '^') || c.is_ascii_digit())
        .len();
    revision
        .get(kept..)
        .and_then(|tail| tail.find(['~', '^']))
        .map(|offset| kept + offset)
        .filter(|&at| at > 0)
        .and_then(|at| revision.split_at_checked(at))
        .unwrap_or((revision, ""))
}

/// jj's root commit, which the git store never holds.
fn is_root(oid: &str) -> bool {
    oid.bytes().all(|byte| byte == b'0')
}

/// `@` and the revsets built on it, which only jj reads right: git reads a
/// bare `@` as HEAD.
fn is_working_copy_revset(revision: &str) -> bool {
    revision == "@" || revision.starts_with("@-") || revision.starts_with("@+")
}

/// `s` as a jj string literal, since git names like `fix(x)` and `u@v` parse
/// as fileset or revset expressions when passed bare.
fn quoted(s: &str) -> String {
    format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
}

/// `path` as a fileset naming exactly that repo-relative file.
fn root_file(path: &str) -> String {
    format!("root-file:{}", quoted(path))
}

/// The local bookmark nearest `@`, where it sits, and whether `@-` is
/// already immutable.
struct NearestBookmark {
    name: Option<String>,
    /// On `@` or `@-`, so a push sends what the reader is working on.
    on_working_line: bool,
    immutable: bool,
    parent_immutable: bool,
}

/// [`JjVcs::nearest_bookmark`]'s rows: marker, immutable flag, local names.
fn parse_nearest_bookmark(out: &str) -> NearestBookmark {
    let mut nearest = NearestBookmark {
        name: None,
        on_working_line: false,
        immutable: false,
        parent_immutable: false,
    };
    for line in out.lines() {
        let fields: Vec<&str> = line.split(FIELD_SEPARATOR).collect();
        let &[marker, immutable, names] = fields.as_slice() else {
            continue;
        };
        let immutable = immutable == "1";
        if marker == "-" && immutable {
            nearest.parent_immutable = true;
        }
        if nearest.name.is_none()
            && let Some(name) = split_list(names).next()
        {
            nearest.name = Some(name.to_owned());
            nearest.on_working_line = marker != "^";
            nearest.immutable = immutable;
        }
    }
    nearest
}

const EMPTY_MESSAGE: &str = "write a commit message first";
const NO_STAGING: &str = "commit the whole working copy; jj has no staging area";
const NO_STASH: &str = "start a new change from the change menu instead; jj has no stash";
const NO_PULL_MODE: &str = "pull with p p; jj rebases @ onto the fetched bookmark";

impl Vcs for JjVcs {
    fn has_index(&self) -> bool {
        false
    }

    fn native_git_checkout(&self) -> bool {
        false
    }

    fn git_dir(&self) -> Result<PathBuf, VcsError> {
        self.git.git_dir()
    }

    fn head(&self) -> Result<HeadInfo, VcsError> {
        self.ensure_base()?;
        let mut head = self.git.head()?;
        if head.oid7.is_empty() {
            head.branch = None;
        }
        Ok(head)
    }

    /// Change ids cover twice `log_limit`, since jj and git order a busy
    /// history differently.
    fn read_jj_view(&self, log_limit: usize) -> Result<Option<JjView>, VcsError> {
        let view = JjView {
            change_ids: self.read_change_ids(log_limit.saturating_mul(2))?,
            ..self.read_state()?
        };
        self.adopt_jj_view(view.clone());
        Ok(Some(view))
    }

    fn adopt_jj_view(&self, view: JjView) {
        if !self.colocated {
            self.base_known.set(true);
            // jj prints full hex ids, so the base always parses
            self.git.set_base(view.base.as_deref()).ok();
        }
        *self.view.borrow_mut() = view;
    }

    /// One diff pass of `@-` vs the working copy. jj marks a new file
    /// intent-to-add in the index, so git's three lists would count it twice.
    fn status(&self) -> Result<StatusModel, VcsError> {
        Ok(StatusModel {
            untracked: DiffModel::default(),
            unstaged: DiffModel::default(),
            staged: self.working_tree_diff()?,
        })
    }

    fn working_tree_diff(&self) -> Result<DiffModel, VcsError> {
        self.ensure_base()?;
        self.git.working_tree_diff()
    }

    fn tree_to_workdir_diff(&self, base_oid: &str) -> Result<DiffModel, VcsError> {
        self.git.tree_to_workdir_diff(base_oid)
    }

    fn commit_diff(&self, oid: &str) -> Result<DiffModel, VcsError> {
        self.git.commit_diff(oid)
    }

    fn range_diff(&self, oldest_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError> {
        self.git.range_diff(oldest_oid, newest_oid)
    }

    fn tree_diff(&self, base_oid: &str, newest_oid: &str) -> Result<DiffModel, VcsError> {
        self.git.tree_diff(base_oid, newest_oid)
    }

    fn merge_base(&self, a: &str, b: &str) -> Result<String, VcsError> {
        self.git.merge_base(a, b)
    }

    /// Git syntax (`main~2`, refs, oids, `HEAD` as `@-`) resolves through
    /// git, since a colocated repo's git refs are current where jj's import
    /// of them may lag. With no `.git` the store's refs are stale or absent,
    /// so jj's bookmarks name the commit there, and git applies the
    /// ancestry suffix. What git cannot read (`trunk()`, change ids) is a jj
    /// revset; a git suffix never goes to jj, which reads `~` as a set
    /// difference.
    fn resolve(&self, revision: &str) -> Result<String, VcsError> {
        if is_working_copy_revset(revision) {
            return self.resolve_revset(revision);
        }
        self.ensure_base()?;
        let (name, ancestry) = split_ancestry(revision);
        if !self.colocated
            && let Some(oid) = self.bookmark_oid(name)
        {
            return self.git.resolve(&format!("{oid}{ancestry}"));
        }
        let resolved = self.git.resolve(revision);
        // jj has no HEAD, so asking it would only cost a `jj` run
        if resolved.is_ok() || name == "HEAD" {
            return resolved;
        }
        if !ancestry.is_empty() {
            return Err(VcsError::Rejected(format!(
                "`{name}` names no bookmark, ref or commit; name one before `{ancestry}`"
            )));
        }
        self.resolve_revset(revision)
    }

    fn log(&self, limit: usize, all_branches: bool) -> Result<Vec<LogEntry>, VcsError> {
        self.ensure_base()?;
        let entries = {
            let view = self.view.borrow();
            let tips: Vec<&str> = view
                .bookmarks
                .iter()
                .map(|bookmark| bookmark.oid.as_str())
                .filter(|oid| !is_root(oid))
                .collect();
            self.git.log_from(limit, all_branches, &tips)?
        };
        Ok(self.decorated(entries))
    }

    fn default_branch(&self, remote: &str) -> Result<Option<String>, VcsError> {
        self.git.default_branch(remote)
    }

    fn commits_between(&self, base: &str, head: &str) -> Result<Vec<LogEntry>, VcsError> {
        self.ensure_base()?;
        Ok(self.decorated(self.git.commits_between(base, head)?))
    }

    fn unpushed(&self, limit: usize) -> Result<Option<Vec<LogEntry>>, VcsError> {
        self.ensure_base()?;
        Ok(self
            .git
            .unpushed(limit)?
            .map(|entries| self.decorated(entries)))
    }

    fn blame(&self, rel: &Path) -> Result<Vec<BlameSpan>, VcsError> {
        self.ensure_base()?;
        self.git.blame(rel)
    }

    fn read_at(&self, rev: &str, path: &str) -> Result<Option<String>, VcsError> {
        self.ensure_base()?;
        self.git.read_at(rev, path)
    }

    fn read_blob(&self, oid: &str) -> Result<Option<Vec<u8>>, VcsError> {
        self.git.read_blob(oid)
    }

    fn tracked_files(&self) -> Result<Vec<PathBuf>, VcsError> {
        self.ensure_base()?;
        self.git.tracked_files()
    }

    fn attr(&self, rel: &Path, name: &str) -> bool {
        self.git.attr(rel, name)
    }

    /// A repo with no `.git` lists jj's local bookmarks; the one `@` sits on
    /// or under counts as checked out.
    fn branches(&self) -> Result<Vec<BranchInfo>, VcsError> {
        if self.colocated {
            return self.git.branches();
        }
        let view = self.view.borrow();
        let here = view.change.as_ref().and_then(|c| c.bookmark.as_deref());
        Ok(view
            .bookmarks
            .iter()
            .filter(|bookmark| !bookmark.remote)
            .map(|bookmark| BranchInfo {
                name: bookmark.name.clone(),
                is_head: here == Some(bookmark.name.as_str()),
                tip_unix: bookmark.tip_unix,
                divergence: None,
            })
            .collect())
    }

    /// A repo with no `.git` measures a bookmark against its first remote
    /// namesake.
    fn divergence(&self, branch: &str) -> Result<Option<(usize, usize)>, VcsError> {
        if self.colocated {
            return self.git.divergence(branch);
        }
        let view = self.view.borrow();
        let local = view
            .bookmarks
            .iter()
            .find(|bookmark| !bookmark.remote && bookmark.name == branch);
        let upstream = view.bookmarks.iter().find(|bookmark| {
            bookmark.remote
                && bookmark
                    .name
                    .rsplit_once('@')
                    .is_some_and(|(name, _)| name == branch)
        });
        let (Some(local), Some(upstream)) = (local, upstream) else {
            return Ok(None);
        };
        self.git.ahead_behind(&local.oid, &upstream.oid).map(Some)
    }

    fn all_branches(&self) -> Result<Vec<String>, VcsError> {
        if self.colocated {
            return self.git.all_branches();
        }
        Ok(self
            .view
            .borrow()
            .bookmarks
            .iter()
            .map(|bookmark| bookmark.name.clone())
            .collect())
    }

    fn stage(&self, _rel: &Path) -> Result<(), VcsError> {
        Err(VcsError::Rejected(NO_STAGING.into()))
    }

    fn stage_everything(&self) -> Result<(), VcsError> {
        Err(VcsError::Rejected(NO_STAGING.into()))
    }

    fn unstage_everything(&self) -> Result<(), VcsError> {
        Err(VcsError::Rejected(NO_STAGING.into()))
    }

    fn stage_hunk(&self, _rel: &Path, _hunk: &HunkId) -> Result<(), VcsError> {
        Err(VcsError::Rejected(NO_STAGING.into()))
    }

    fn unstage(&self, _rel: &Path) -> Result<(), VcsError> {
        Err(VcsError::Rejected(NO_STAGING.into()))
    }

    fn unstage_hunk(&self, _rel: &Path, _hunk: &HunkId) -> Result<(), VcsError> {
        Err(VcsError::Rejected(NO_STAGING.into()))
    }

    fn discard(&self, rel: &Path) -> Result<(), VcsError> {
        self.run(&["restore", "--", &root_file(&rel.to_string_lossy())])?;
        Ok(())
    }

    fn commit_paths(&self, message: &str, paths: &[String]) -> Result<String, VcsError> {
        if message.trim().is_empty() {
            return Err(VcsError::Rejected(EMPTY_MESSAGE.into()));
        }
        let message = format!("--message={message}");
        // we pass `root:` so a selected folder commits its whole subtree
        let filesets: Vec<String> = paths
            .iter()
            .map(|path| format!("root:{}", quoted(path)))
            .collect();
        let mut args = vec!["commit", message.as_str(), "--"];
        args.extend(filesets.iter().map(String::as_str));
        self.run(&args)?;
        self.head_oid()
    }

    fn change(&self, op: &ChangeOp) -> Result<(), VcsError> {
        match op {
            ChangeOp::New(rev) => self.run(&["new", "--", &self.target(rev)?]),
            ChangeOp::Edit(rev) => self.run(&["edit", "--", &self.target(rev)?]),
            ChangeOp::Describe { rev, message } => self.run(&[
                "describe",
                &format!("--message={message}"),
                "--",
                &self.target(rev)?,
            ]),
            ChangeOp::Squash(rev) => self.squash(rev),
            ChangeOp::Abandon(rev) => self.run(&["abandon", "--", &self.target(rev)?]),
            ChangeOp::Undo => {
                self.refuse_over_snapshot("undo")?;
                self.run(&["undo"])
            }
            ChangeOp::Redo => {
                self.refuse_over_snapshot("redo")?;
                self.run(&["redo"])
            }
        }?;
        Ok(())
    }

    /// `origin` wins when the bookmark tracks several remotes.
    fn pull_target(&self) -> Result<Option<PullTarget>, VcsError> {
        let Some(bookmark) = self.nearest_bookmark()?.name else {
            return Ok(None);
        };
        let tracked = self.run(&[
            "bookmark",
            "list",
            "--ignore-working-copy",
            "--tracked",
            r#"--template=if(remote, remote ++ "\n")"#,
            "--",
            &format!("exact:{}", quoted(&bookmark)),
        ])?;
        let remotes: Vec<&str> = tracked.lines().filter(|r| *r != "git").collect();
        let remote = remotes
            .iter()
            .find(|r| **r == "origin")
            .or_else(|| remotes.first())
            .map(|r| (*r).to_owned());
        Ok(Some(PullTarget { bookmark, remote }))
    }

    fn rebase_onto_remote(&self, bookmark: &str, remote: &str) -> Result<PullOutcome, VcsError> {
        let onto = format!("{bookmark}@{remote}");
        let target = format!(
            "remote_bookmarks(exact:{}, exact:{})",
            quoted(bookmark),
            quoted(remote)
        );
        if self.query(&target, COMMIT_ID_TEMPLATE, Some(1))?.is_empty() {
            return Ok(PullOutcome::Gone { onto });
        }
        if !self
            .query(&format!("({target}) & ::@"), COMMIT_ID_TEMPLATE, Some(1))?
            .is_empty()
        {
            return Ok(PullOutcome::UpToDate { onto });
        }
        self.run(&["rebase", "--branch=@", &format!("--onto={target}")])?;
        let conflicts = self
            .query(
                &format!("({target})..@ & conflicts()"),
                COMMIT_ID_TEMPLATE,
                None,
            )?
            .lines()
            .count();
        let bookmark_conflicted = !self
            .run(&[
                "bookmark",
                "list",
                "--ignore-working-copy",
                "--conflicted",
                "--",
                &format!("exact:{}", quoted(bookmark)),
            ])?
            .is_empty();
        Ok(PullOutcome::Rebased {
            onto,
            conflicts,
            bookmark_conflicted,
        })
    }

    fn commit_message(&self, oid: &str) -> Result<String, VcsError> {
        self.git.commit_message(oid)
    }

    /// Messages go as `--message=<text>`: clap reads a separate value that
    /// starts with `-` as a flag.
    fn commit(&self, message: &str) -> Result<String, VcsError> {
        if message.trim().is_empty() {
            return Err(VcsError::Rejected(EMPTY_MESSAGE.into()));
        }
        self.run(&["commit", &format!("--message={message}")])?;
        self.head_oid()
    }

    fn head_message(&self) -> Result<String, VcsError> {
        self.ensure_base()?;
        self.git.head_message()
    }

    /// `None` squashes with `-u`, since a bare squash opens an editor when
    /// both sides are described. `Some` without `use_index` rewords `@-` alone.
    fn amend(&self, message: Option<&str>, use_index: bool) -> Result<String, VcsError> {
        if let Some(message) = message
            && message.trim().is_empty()
        {
            return Err(VcsError::Rejected(EMPTY_MESSAGE.into()));
        }
        match message {
            None => self.run(&["squash", "--use-destination-message"])?,
            Some(message) if use_index => self.run(&["squash", &format!("--message={message}")])?,
            Some(message) => {
                self.run(&["describe", "-r", "@-", &format!("--message={message}")])?
            }
        };
        self.head_oid()
    }

    /// Bookmarks `@`; `checkout` is moot since `@` is already checked out.
    fn create_branch(&self, name: &str, _checkout: bool) -> Result<(), VcsError> {
        self.run(&["bookmark", "create", "-r", "@", "--", name])?;
        Ok(())
    }

    /// `exact:`, since jj reads a bare name as a glob.
    fn delete_branch(&self, name: &str) -> Result<(), VcsError> {
        self.run(&[
            "bookmark",
            "delete",
            "--",
            &format!("exact:{}", quoted(name)),
        ])?;
        Ok(())
    }

    /// `jj new <rev>` works on top of the branch and keeps the change left
    /// behind; `jj edit` would rewrite the tip in place.
    fn checkout(&self, name: &str) -> Result<(), VcsError> {
        self.run(&["new", "--", &quoted(name)])?;
        Ok(())
    }

    fn stash_push(&self, _message: Option<&str>) -> Result<(), VcsError> {
        Err(VcsError::Rejected(NO_STASH.into()))
    }

    fn stash_pop(&self) -> Result<(), VcsError> {
        Err(VcsError::Rejected(NO_STASH.into()))
    }

    /// A push sends what [`JjVcs::push_selection`] picks, and jj tracks the
    /// remote bookmark it makes. A pull is the fetch alone;
    /// [`Vcs::rebase_onto_remote`] follows it.
    fn network_argv(&self, op: NetworkOp) -> Result<Vec<String>, VcsError> {
        let mut args = vec!["git".to_owned()];
        match op {
            NetworkOp::Fetch | NetworkOp::Pull => args.push("fetch".into()),
            NetworkOp::FetchAll => args.extend(["fetch".into(), "--all-remotes".into()]),
            NetworkOp::PullFrom { remote, .. } => {
                args.extend(["fetch".into(), format!("--remote={remote}")]);
            }
            NetworkOp::Push | NetworkOp::PushSetUpstream { .. } => {
                args.push("push".into());
                if let NetworkOp::PushSetUpstream { remote } = op {
                    args.push(format!("--remote={remote}"));
                }
                args.push(self.push_selection()?);
            }
            NetworkOp::PullRebase | NetworkOp::PullMerge => {
                return Err(VcsError::Rejected(NO_PULL_MODE.into()));
            }
        }
        Ok(std::iter::once("jj".to_owned()).chain(args).collect())
    }

    fn workdir(&self) -> Result<PathBuf, VcsError> {
        self.git.workdir()
    }

    fn remote_url(&self, name: &str) -> Result<Option<String>, VcsError> {
        self.git.remote_url(name)
    }

    fn remotes(&self) -> Result<Vec<String>, VcsError> {
        self.git.remotes()
    }

    fn set_diff_algorithm(&self, algorithm: DiffAlgorithm, indent_heuristic: bool) {
        self.git.set_diff_algorithm(algorithm, indent_heuristic);
    }
}