kono-wt 1.8.1

A single-binary CLI + TUI for managing Git worktrees and their GitHub pull requests.
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
//! Test-only helpers shared across the crate's unit tests.
//!
//! Provides an in-memory [`SharedBuf`] writer whose contents can be inspected
//! after a command runs, and [`test_cx`] which wires a [`Cx`] to two such
//! buffers plus a fixed environment.

use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex};

use tempfile::TempDir;

use std::collections::VecDeque;

use crate::agent::{AgentClient, AgentKind, AgentOptions, AgentRun, AgentVersion, DetectedAgent};
use crate::cx::{Cx, Env, Input, Stream};
use crate::error::Error;
use crate::gh::{GhClient, IssueSummary, IssueView, OpenPr, PrSummary, PrView, RealGh};
use crate::git::cli::{GitCli, RealGit};

/// A fake [`GhClient`] returning canned PR data or simulating an unavailable
/// `gh`. Records `create_pr`/`edit_pr` args so submit tests can assert them.
#[derive(Default)]
pub(crate) struct FakeGh {
    list: Vec<PrSummary>,
    view: Option<PrView>,
    available: bool,
    default_branch: Option<String>,
    existing_pr: Option<OpenPr>,
    create_stdout: String,
    edit_stdout: String,
    create_args: Arc<Mutex<Vec<Vec<String>>>>,
    edit_args: Arc<Mutex<Vec<Vec<String>>>>,
    issue_list: Vec<IssueSummary>,
    issue: Option<IssueView>,
}

#[allow(dead_code)]
impl FakeGh {
    /// A fake that returns `view` from `view_pr`.
    pub(crate) fn with_view(view: PrView) -> Self {
        FakeGh {
            view: Some(view),
            available: true,
            ..Default::default()
        }
    }

    /// A fake that returns `list` from `list_open_prs`.
    pub(crate) fn with_list(list: Vec<PrSummary>) -> Self {
        FakeGh {
            list,
            available: true,
            ..Default::default()
        }
    }

    /// A fake whose `create_pr`/`edit_pr` succeed and return `stdout`.
    pub(crate) fn sender(stdout: &str) -> Self {
        FakeGh {
            available: true,
            create_stdout: stdout.to_string(),
            edit_stdout: stdout.to_string(),
            ..Default::default()
        }
    }

    /// A fake that returns `issue` from `view_issue`.
    pub(crate) fn with_issue(issue: IssueView) -> Self {
        FakeGh {
            issue: Some(issue),
            available: true,
            ..Default::default()
        }
    }

    /// Sets the issues returned by `list_open_issues`.
    pub(crate) fn with_issue_list(mut self, list: Vec<IssueSummary>) -> Self {
        self.issue_list = list;
        self.available = true;
        self
    }

    /// A fake simulating a missing/unauthenticated `gh`.
    pub(crate) fn unavailable() -> Self {
        FakeGh::default()
    }

    /// Sets the default branch returned by `default_branch`.
    pub(crate) fn with_default_branch(mut self, name: &str) -> Self {
        self.default_branch = Some(name.to_string());
        self
    }

    /// Sets the existing open PR returned by `find_pr_for_branch`.
    pub(crate) fn with_existing_pr(mut self, pr: OpenPr) -> Self {
        self.existing_pr = Some(pr);
        self
    }

    /// The recorded `create_pr` arg lists (one per call).
    pub(crate) fn created_args(&self) -> Vec<Vec<String>> {
        self.create_args.lock().expect("lock poisoned").clone()
    }

    /// The recorded `edit_pr` arg lists (one per call).
    pub(crate) fn edited_args(&self) -> Vec<Vec<String>> {
        self.edit_args.lock().expect("lock poisoned").clone()
    }
}

impl GhClient for FakeGh {
    fn list_open_issues(&self, _dir: &std::path::Path) -> crate::error::Result<Vec<IssueSummary>> {
        if self.available {
            Ok(self.issue_list.clone())
        } else {
            Err(Error::GhUnavailable("gh unavailable".into()))
        }
    }

    fn view_issue(&self, _dir: &std::path::Path, _target: &str) -> crate::error::Result<IssueView> {
        if !self.available {
            return Err(Error::GhUnavailable("gh unavailable".into()));
        }
        self.issue
            .clone()
            .ok_or_else(|| Error::operation("no issue configured"))
    }

    fn list_open_prs(&self, _dir: &std::path::Path) -> crate::error::Result<Vec<PrSummary>> {
        if self.available {
            Ok(self.list.clone())
        } else {
            Err(Error::GhUnavailable("gh unavailable".into()))
        }
    }

    fn view_pr(&self, _dir: &std::path::Path, _target: &str) -> crate::error::Result<PrView> {
        if !self.available {
            return Err(Error::GhUnavailable("gh unavailable".into()));
        }
        self.view
            .clone()
            .ok_or_else(|| Error::operation("no PR configured"))
    }

    fn default_branch(&self, _dir: &std::path::Path) -> crate::error::Result<Option<String>> {
        // Mirror RealGh: non-fatal, so an unavailable `gh` yields None here.
        Ok(self.default_branch.clone())
    }

    fn find_pr_for_branch(
        &self,
        _dir: &std::path::Path,
        _branch: &str,
    ) -> crate::error::Result<Option<OpenPr>> {
        if !self.available {
            return Err(Error::GhUnavailable("gh unavailable".into()));
        }
        Ok(self.existing_pr.clone())
    }

    fn create_pr(&self, _dir: &std::path::Path, args: &[String]) -> crate::error::Result<String> {
        if !self.available {
            return Err(Error::GhUnavailable("gh unavailable".into()));
        }
        self.create_args
            .lock()
            .expect("lock poisoned")
            .push(args.to_vec());
        Ok(self.create_stdout.clone())
    }

    fn edit_pr(&self, _dir: &std::path::Path, args: &[String]) -> crate::error::Result<String> {
        if !self.available {
            return Err(Error::GhUnavailable("gh unavailable".into()));
        }
        self.edit_args
            .lock()
            .expect("lock poisoned")
            .push(args.to_vec());
        Ok(self.edit_stdout.clone())
    }
}

/// What a [`FakeAgent`] does when driven.
pub(crate) enum AgentBehavior {
    /// Agent present; `run` returns a successful [`AgentRun`] with this result text.
    Draft(String),
    /// Agent present; `run` returns an [`AgentRun`] flagged `is_error` with this text.
    Erroring(String),
    /// Agent absent: `detect` returns `Ok(None)` and `run` returns `AgentUnavailable`.
    Unavailable,
    /// Agent present but unresponsive: `run` returns `AgentTimeout`, as the real
    /// client does once a run exceeds its deadline.
    TimingOut,
}

/// A fake [`AgentClient`] for tests: returns a canned draft, simulates an
/// absent agent, or an erroring run, and records the [`AgentOptions`] of the
/// last `run` so tests can assert the selected model/effort were threaded.
pub(crate) struct FakeAgent {
    behavior: AgentBehavior,
    last_opts: Mutex<Option<AgentOptions>>,
}

#[allow(dead_code)]
impl FakeAgent {
    fn new(behavior: AgentBehavior) -> Self {
        FakeAgent {
            behavior,
            last_opts: Mutex::new(None),
        }
    }

    /// A present agent whose `run` returns `result` (a successful draft).
    pub(crate) fn drafting(result: &str) -> Self {
        FakeAgent::new(AgentBehavior::Draft(result.to_string()))
    }

    /// A present agent whose `run` returns an error-flagged result.
    pub(crate) fn erroring(result: &str) -> Self {
        FakeAgent::new(AgentBehavior::Erroring(result.to_string()))
    }

    /// An absent agent (`detect` → `None`, `run` → `AgentUnavailable`).
    pub(crate) fn unavailable() -> Self {
        FakeAgent::new(AgentBehavior::Unavailable)
    }

    /// A present but unresponsive agent (`run` → `AgentTimeout`).
    pub(crate) fn timing_out() -> Self {
        FakeAgent::new(AgentBehavior::TimingOut)
    }

    /// The [`AgentOptions`] passed to the most recent `run`, if any.
    pub(crate) fn last_opts(&self) -> Option<AgentOptions> {
        *self.last_opts.lock().expect("lock")
    }
}

impl AgentClient for FakeAgent {
    fn detect(&self, kind: AgentKind) -> crate::error::Result<Option<DetectedAgent>> {
        match self.behavior {
            AgentBehavior::Unavailable => Ok(None),
            _ => Ok(Some(DetectedAgent {
                kind,
                binary: kind.as_str().to_string(),
                version: AgentVersion {
                    version: None,
                    raw: String::new(),
                },
            })),
        }
    }

    fn run(
        &self,
        kind: AgentKind,
        _prompt: &str,
        _dir: &Path,
        opts: &AgentOptions,
    ) -> crate::error::Result<AgentRun> {
        *self.last_opts.lock().expect("lock") = Some(*opts);
        match &self.behavior {
            AgentBehavior::Draft(result) => Ok(AgentRun {
                kind,
                is_error: false,
                result: result.clone(),
                raw: serde_json::Value::Null,
            }),
            AgentBehavior::Erroring(result) => Ok(AgentRun {
                kind,
                is_error: true,
                result: result.clone(),
                raw: serde_json::Value::Null,
            }),
            AgentBehavior::Unavailable => Err(Error::AgentUnavailable("claude unavailable".into())),
            AgentBehavior::TimingOut => Err(Error::AgentTimeout {
                binary: kind.as_str().to_string(),
                seconds: 120,
            }),
        }
    }
}

/// An [`Input`] that returns queued lines (then empty strings), for testing
/// confirmation prompts.
#[derive(Default)]
pub(crate) struct CannedInput(VecDeque<String>);

impl CannedInput {
    /// Builds a canned input from the given responses (newlines are appended).
    #[cfg_attr(not(feature = "cli"), allow(dead_code))]
    pub(crate) fn new(lines: &[&str]) -> Self {
        CannedInput(lines.iter().map(|l| format!("{l}\n")).collect())
    }
}

impl Input for CannedInput {
    fn read_line(&mut self) -> crate::error::Result<String> {
        Ok(self.0.pop_front().unwrap_or_default())
    }
}

/// A cloneable in-memory writer whose contents can be inspected after writes.
///
/// Clones share the same underlying buffer, so a clone handed to a [`Stream`]
/// can be read back through the original handle.
#[derive(Clone, Default)]
pub(crate) struct SharedBuf(Arc<Mutex<Vec<u8>>>);

impl SharedBuf {
    /// Creates an empty buffer.
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Returns the bytes written so far, decoded as UTF-8 (lossy).
    pub(crate) fn contents(&self) -> String {
        let guard = self.0.lock().expect("buffer lock poisoned");
        String::from_utf8_lossy(&guard).into_owned()
    }
}

impl Write for SharedBuf {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0
            .lock()
            .expect("buffer lock poisoned")
            .extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// A [`Cx`] wired to in-memory buffers, with handles to inspect what was
/// written to stdout (`out`) and stderr (`err`).
pub(crate) struct TestCx {
    /// The context under test.
    pub cx: Cx,
    /// Captures everything written to stdout.
    pub out: SharedBuf,
    /// Captures everything written to stderr.
    pub err: SharedBuf,
}

/// Builds a [`TestCx`] over in-memory buffers, the given environment pairs, and
/// working directory, using the real `git` handle. Both streams report
/// themselves as non-TTYs.
pub(crate) fn test_cx(env: &[(&str, &str)], cwd: &str) -> TestCx {
    test_cx_with_git(env, cwd, Arc::new(RealGit))
}

/// Like [`test_cx`] but with an injected `git` handle (e.g. a fake).
pub(crate) fn test_cx_with_git(
    env: &[(&str, &str)],
    cwd: &str,
    git: Arc<dyn GitCli + Send + Sync>,
) -> TestCx {
    let out = SharedBuf::new();
    let err = SharedBuf::new();
    let env_map: HashMap<String, String> = env
        .iter()
        .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
        .collect();
    let cx = Cx::new(
        Stream::new(Box::new(out.clone()), false),
        Stream::new(Box::new(err.clone()), false),
        Env::from_map(env_map),
        PathBuf::from(cwd),
        git,
        Arc::new(RealGh),
        Arc::new(FakeAgent::unavailable()),
        Box::new(CannedInput::default()),
    );
    TestCx { cx, out, err }
}

/// A real, throwaway Git repository for integration tests. Worktrees are created
/// as siblings of the repo *inside* the same temp dir, so they are cleaned up
/// when the [`TestRepo`] is dropped. Git runs with an isolated config so the
/// host's `~/.gitconfig` cannot affect tests.
pub(crate) struct TestRepo {
    _dir: TempDir,
    root: PathBuf,
}

// The fixture grows across stages; not every helper is used by every stage.
#[allow(dead_code)]
impl TestRepo {
    /// Initializes a normal repo on branch `main` with one initial commit.
    pub(crate) fn init() -> TestRepo {
        Self::init_in(tempfile::tempdir().expect("tempdir"))
    }

    /// Initializes a repo like [`init`](Self::init), but on a filesystem that
    /// supports reflinks — or `None` when no such filesystem is reachable.
    ///
    /// The system temp dir is very often tmpfs, which has no reflink support, so
    /// a plain `init()` would make every copy-on-write test skip without saying
    /// so. Falling back to `target/` puts the fixture on whatever filesystem the
    /// checkout lives on, which is where these tests actually run.
    pub(crate) fn init_cow() -> Option<TestRepo> {
        if let Ok(dir) = tempfile::tempdir()
            && crate::util::reflink::is_supported(dir.path())
        {
            return Some(Self::init_in(dir));
        }
        let target = Path::new(env!("CARGO_MANIFEST_DIR")).join("target");
        std::fs::create_dir_all(&target).ok()?;
        let dir = tempfile::tempdir_in(&target).ok()?;
        crate::util::reflink::is_supported(dir.path()).then(|| Self::init_in(dir))
    }

    /// Builds the standard fixture inside an already-chosen temp directory.
    fn init_in(dir: TempDir) -> TestRepo {
        let root = dir.path().join("repo");
        std::fs::create_dir_all(&root).expect("mkdir repo");
        run_git(&root, &["init", "-q", "-b", "main"]);
        std::fs::write(root.join("README.md"), "init\n").expect("write readme");
        run_git(&root, &["add", "-A"]);
        run_git(&root, &["commit", "-q", "-m", "init"]);
        TestRepo { _dir: dir, root }
    }

    /// Initializes a bare repository on branch `main`.
    pub(crate) fn init_bare() -> TestRepo {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path().join("bare.git");
        std::fs::create_dir_all(&root).expect("mkdir bare");
        run_git(&root, &["init", "-q", "--bare", "-b", "main"]);
        TestRepo { _dir: dir, root }
    }

    /// The primary worktree (or bare repo) root.
    pub(crate) fn root(&self) -> &Path {
        &self.root
    }

    /// Runs an arbitrary `git` command in the repo and returns stdout.
    pub(crate) fn git(&self, args: &[&str]) -> String {
        run_git(&self.root, args)
    }

    /// Creates a linked worktree for a new branch at `rel_path` (relative to the
    /// repo root).
    pub(crate) fn add_worktree(&self, branch: &str, rel_path: &str) {
        run_git(
            &self.root,
            &["worktree", "add", "-q", "-b", branch, rel_path],
        );
    }

    /// Writes a file (creating parent directories) in the repo's working tree.
    pub(crate) fn write(&self, rel: &str, content: &str) {
        let path = self.root.join(rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("mkdir");
        }
        std::fs::write(path, content).expect("write file");
    }

    /// Stages all changes and commits them.
    pub(crate) fn commit_all(&self, message: &str) {
        run_git(&self.root, &["add", "-A"]);
        run_git(&self.root, &["commit", "-q", "-m", message]);
    }

    /// Adds a submodule at `path` sourced from a throwaway sibling repo, commits
    /// it, and returns the source repo path. The source lives inside this repo's
    /// temp dir, so it is cleaned up on drop. File-protocol submodules are blocked
    /// by default, so the `add` opts in via `protocol.file.allow=always`; the
    /// source's objects then live under `.git/modules`, which lets a later
    /// `git submodule update --init` reuse them (no second file-protocol clone) —
    /// the production command never needs that opt-in.
    pub(crate) fn add_submodule(&self, path: &str) -> PathBuf {
        let src = self
            .root
            .parent()
            .expect("temp dir")
            .join(format!("{}-src", path.replace('/', "-")));
        std::fs::create_dir_all(&src).expect("mkdir submodule src");
        run_git(&src, &["init", "-q", "-b", "main"]);
        std::fs::write(src.join("sub.txt"), "submodule\n").expect("write sub file");
        run_git(&src, &["add", "-A"]);
        run_git(&src, &["commit", "-q", "-m", "submodule init"]);
        let src_str = src.to_string_lossy().into_owned();
        run_git(
            &self.root,
            &[
                "-c",
                "protocol.file.allow=always",
                "submodule",
                "add",
                &src_str,
                path,
            ],
        );
        self.commit_all("add submodule");
        src
    }

    /// Adds a submodule at `outer` that itself contains a submodule at `inner`
    /// (relative to `outer`), and returns the outer source repo path.
    ///
    /// Nesting is what distinguishes recursive submodule handling from the
    /// single-level kind, and it is fiddly to build: the inner submodule has to
    /// be committed into the *source* repo before the outer one is added, or the
    /// superproject records a commit that has no nested gitlink.
    pub(crate) fn add_nested_submodule(&self, outer: &str, inner: &str) -> PathBuf {
        let parent = self.root.parent().expect("temp dir");
        let deep = parent.join(format!("{}-deep-src", outer.replace('/', "-")));
        std::fs::create_dir_all(&deep).expect("mkdir deep src");
        run_git(&deep, &["init", "-q", "-b", "main"]);
        std::fs::write(deep.join("deep.txt"), "deep\n").expect("write deep file");
        run_git(&deep, &["add", "-A"]);
        run_git(&deep, &["commit", "-q", "-m", "deep init"]);

        let outer_src = parent.join(format!("{}-src", outer.replace('/', "-")));
        std::fs::create_dir_all(&outer_src).expect("mkdir outer src");
        run_git(&outer_src, &["init", "-q", "-b", "main"]);
        std::fs::write(outer_src.join("sub.txt"), "submodule\n").expect("write sub file");
        run_git(&outer_src, &["add", "-A"]);
        run_git(&outer_src, &["commit", "-q", "-m", "submodule init"]);
        run_git(
            &outer_src,
            &[
                "-c",
                "protocol.file.allow=always",
                "submodule",
                "add",
                &deep.to_string_lossy(),
                inner,
            ],
        );
        run_git(&outer_src, &["add", "-A"]);
        run_git(&outer_src, &["commit", "-q", "-m", "add nested submodule"]);

        run_git(
            &self.root,
            &[
                "-c",
                "protocol.file.allow=always",
                "submodule",
                "add",
                &outer_src.to_string_lossy(),
                outer,
            ],
        );
        self.commit_all("add submodule");
        // Populate the nested level too, so the fixture mirrors a fully
        // initialized checkout.
        run_git(
            &self.root,
            &[
                "-c",
                "protocol.file.allow=always",
                "submodule",
                "update",
                "--init",
                "--recursive",
            ],
        );
        outer_src
    }

    /// Deinitializes the submodule at `path`: empties its working tree and clears
    /// its configured URL so it reports as uninitialized, while keeping its
    /// objects under `.git/modules` so it can be re-initialized without another
    /// file-protocol clone.
    pub(crate) fn deinit_submodule(&self, path: &str) {
        run_git(&self.root, &["submodule", "deinit", "-q", "-f", path]);
    }
}

/// Creates a wt-managed worktree on `branch` via the real `new` command, in a
/// throwaway context. Shared by the prune/remove/checkout test modules.
#[cfg(feature = "cli")]
pub(crate) fn make_wt(repo: &TestRepo, branch: &str) {
    let mut t = test_cx(&[], repo.root().to_str().unwrap());
    crate::commands::new::run(
        &mut t.cx,
        &crate::hooks::RealHookRunner,
        &crate::cli::NewArgs {
            branch: branch.to_string(),
            from: None,
            track: None,
            no_track: false,
            no_switch: true,
            no_hooks: true,
            start: None,
            copy_from: None,
            init_submodules: false,
            no_init_submodules: false,
            no_seed_submodules: false,
            reflink: false,
            no_reflink: false,
        },
        false,
    )
    .unwrap();
}

/// The path `wt new <branch>` produces for `repo` — the
/// `<repo>.worktrees/<repo>-<branch>` sibling — without creating it.
#[cfg_attr(not(feature = "cli"), allow(dead_code))]
pub(crate) fn wt_dir(repo: &TestRepo, branch: &str) -> PathBuf {
    let repo_name = repo.root().file_name().unwrap().to_string_lossy();
    repo.root()
        .parent()
        .unwrap()
        .join(format!("{repo_name}.worktrees/{repo_name}-{branch}"))
}

/// Gives `branch` an upstream at its current tip (ahead/behind 0), so the
/// no-upstream "unpushed" guard does not apply.
#[cfg_attr(not(feature = "cli"), allow(dead_code))]
pub(crate) fn give_upstream(repo: &TestRepo, branch: &str) {
    repo.git(&[
        "update-ref",
        &format!("refs/remotes/origin/{branch}"),
        &format!("refs/heads/{branch}"),
    ]);
    repo.git(&["config", &format!("branch.{branch}.remote"), "origin"]);
    repo.git(&[
        "config",
        &format!("branch.{branch}.merge"),
        &format!("refs/heads/{branch}"),
    ]);
}

/// Runs `git -C <dir> <args>` with isolated config and identity, asserting
/// success, and returns stdout.
///
/// Inherited `GIT_*` location variables are scrubbed first. Git honours
/// `GIT_DIR`/`GIT_WORK_TREE`/`GIT_INDEX_FILE` over the `-C <dir>` argument, so if
/// these are present in the environment — as they are when the suite runs from
/// inside a git hook (e.g. the `pre-push` hook git invokes with `GIT_DIR` set) —
/// every `TestRepo` mutation would operate on the developer's real repository
/// instead of the throwaway temp repo, silently corrupting it. Removing them
/// makes `-C <dir>` authoritative so the fixture stays sandboxed.
pub(crate) fn run_git(dir: &Path, args: &[&str]) -> String {
    let output = Command::new("git")
        .env_remove("GIT_DIR")
        .env_remove("GIT_WORK_TREE")
        .env_remove("GIT_INDEX_FILE")
        .env_remove("GIT_OBJECT_DIRECTORY")
        .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES")
        .env_remove("GIT_COMMON_DIR")
        .env_remove("GIT_NAMESPACE")
        .env_remove("GIT_CEILING_DIRECTORIES")
        .env_remove("GIT_PREFIX")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .env("GIT_AUTHOR_NAME", "wt Test")
        .env("GIT_AUTHOR_EMAIL", "test@example.com")
        .env("GIT_COMMITTER_NAME", "wt Test")
        .env("GIT_COMMITTER_EMAIL", "test@example.com")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .expect("spawn git");
    assert!(
        output.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).into_owned()
}