kono-wt 1.9.0

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
//! `wt pr` — check out a GitHub PR into its own worktree, or list open PRs
//! (spec §7). PR operations go through the `gh` boundary (§4).

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

use crate::cli::{PrArgs, PrSub};
use crate::commands::{
    Nav, Session, finish_worktree, maybe_init_submodules_interactive, open_session, resolve_target,
    rollback_worktree,
};
use crate::copy::copy_ignored_files;
use crate::cx::Cx;
use crate::error::Result;
use crate::gh::GhClient;
use crate::git::cli::GitCli;
use crate::git::{branch_ref, ops, resolve_hex};
use crate::hooks::{HookContext, HookRunner, run_post_create};
use crate::slug::slugify_with_fallback;
use crate::time::{now_unix, parse_iso8601, relative};
use crate::worktree::{MetaUpdate, apply_meta, enumerate_worktrees, lock_repo};

/// Dispatches `pr list`, `pr <target>` (checkout), or `pr` (picker, TUI).
pub(crate) fn run(cx: &mut Cx, hooks: &dyn HookRunner, args: &PrArgs, json: bool) -> Result<u8> {
    // `wt pr` with no target and no sub: open the interactive PR picker (§7).
    // The picker opens its own session, so return before opening one here.
    if args.sub.is_none() && args.target.is_none() {
        return launch_pr_picker(cx);
    }

    // `wt pr open`: compose and open a PR for the current branch (issue #9). It
    // opens its own session, so dispatch before setting one up here.
    #[cfg(feature = "pr")]
    if let Some(PrSub::Open(open_args)) = &args.sub {
        return crate::commands::pr_open::run(cx, open_args, json);
    }
    #[cfg(not(feature = "pr"))]
    if matches!(&args.sub, Some(PrSub::Open(_))) {
        return Err(crate::error::Error::usage(
            "wt pr open requires a build with the `pr` feature",
        ));
    }

    let git = cx.git.clone();
    let gh = cx.gh.clone();
    let session = open_session(cx, git.as_ref())?;
    let dir = session
        .repo
        .current_workdir()
        .unwrap_or_else(|| session.primary_root.clone());

    if matches!(args.sub, Some(PrSub::List)) {
        return pr_list(cx, gh.as_ref(), &dir, json);
    }
    let target = args.target.clone().unwrap_or_default();
    pr_checkout(
        cx,
        git.as_ref(),
        gh.as_ref(),
        hooks,
        &session,
        &dir,
        &target,
        args,
        json,
    )
}

/// Launches the TUI PR picker; on a checkout, prints the chosen worktree path
/// (so the wrapper `cd`s). A cancelled picker prints nothing and exits `0`.
/// Without the TUI feature there is no picker: name a PR instead.
#[cfg(not(feature = "tui"))]
fn launch_pr_picker(_cx: &mut Cx) -> Result<u8> {
    Err(crate::error::Error::usage(
        "the interactive PR picker requires a build with the `tui` feature; pass a PR number or branch",
    ))
}

/// Launches the TUI PR picker; on a checkout, prints the chosen worktree path
/// (so the wrapper `cd`s). A cancelled picker prints nothing and exits `0`.
#[cfg(feature = "tui")]
fn launch_pr_picker(cx: &mut Cx) -> Result<u8> {
    match crate::tui::run_pr_picker(cx)? {
        Some(path) => {
            cx.out.line(&path.to_string_lossy())?;
            Ok(0)
        }
        None => Ok(0),
    }
}

/// `pr list` — print open PRs as a table or newline-delimited JSON.
fn pr_list(cx: &mut Cx, gh: &dyn GhClient, dir: &Path, json: bool) -> Result<u8> {
    let prs = gh.list_open_prs(dir)?;
    if json {
        for pr in &prs {
            let row = serde_json::json!({
                "number": pr.number,
                "title": pr.title,
                "author": pr.author.login,
                "state": pr.pr_state().as_str(),
                "head_ref": pr.head_ref_name,
                "created_at": pr.created_at,
            });
            cx.out.line(&serde_json::to_string(&row)?)?;
        }
        return Ok(0);
    }
    if prs.is_empty() {
        cx.err.line("no open pull requests")?;
        return Ok(0);
    }
    let now = now_unix();
    for pr in &prs {
        let age = parse_iso8601(&pr.created_at).map_or_else(String::new, |u| relative(now, u));
        cx.out.line(&format!(
            "#{}  {}  ({})  {}  {age}",
            pr.number,
            pr.title,
            pr.author.login,
            pr.pr_state().as_str()
        ))?;
    }
    Ok(0)
}

/// A PR worktree, ready to be navigated into.
pub(crate) struct PrCheckout {
    /// The worktree's absolute path.
    pub(crate) path: PathBuf,
    /// Whether the worktree already existed (vs. was created here).
    pub(crate) existed: bool,
    /// The `WT_*` context for the `post_create` hook and `--start`.
    pub(crate) ctx: HookContext,
}

/// `pr <target>` — fetch the PR head, create a worktree for it, then emit the
/// navigation result (path/JSON/note).
#[allow(clippy::too_many_arguments)]
fn pr_checkout(
    cx: &mut Cx,
    git: &dyn GitCli,
    gh: &dyn GhClient,
    hooks: &dyn HookRunner,
    session: &Session,
    dir: &Path,
    target: &str,
    args: &PrArgs,
    json: bool,
) -> Result<u8> {
    let checkout = checkout_pr_worktree(
        cx,
        git,
        gh,
        hooks,
        session,
        dir,
        target,
        args.no_hooks,
        // The CLI may prompt before initializing submodules; the TUI passes false.
        true,
    )?;
    let note = if checkout.existed {
        "worktree already exists at"
    } else {
        "checked out PR worktree at"
    };
    finish_worktree(
        cx,
        hooks,
        &checkout.path,
        &checkout.ctx,
        Nav {
            json,
            no_switch: args.no_switch,
            note,
            start: args.start.as_deref(),
        },
    )
}

/// Checks out `target` (a PR number, URL, or head branch) into a worktree,
/// recording its PR metadata (§7). Does not emit output — the caller decides how
/// to surface the [`PrCheckout`] (CLI navigation result, or TUI
/// switch). `prompt` enables the interactive submodule confirmation (issue #50):
/// the CLI passes `true`; the TUI passes `false`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn checkout_pr_worktree(
    cx: &mut Cx,
    git: &dyn GitCli,
    gh: &dyn GhClient,
    hooks: &dyn HookRunner,
    session: &Session,
    dir: &Path,
    target: &str,
    no_hooks: bool,
    prompt: bool,
) -> Result<PrCheckout> {
    let view = gh.view_pr(dir, target)?;
    let root = session.primary_root.clone();
    let branch = view.head_ref_name.clone();
    let base = view.base_ref_name.clone();
    let number = view.number;

    // If the PR's head branch is already a worktree, record/refresh its PR
    // metadata (§7) and switch to it. The worktree was not necessarily created
    // by `wt`, so this does not mark it "created by wt".
    let worktrees = enumerate_worktrees(&session.repo, git)?;
    if let Some(existing) = worktrees
        .iter()
        .find(|w| w.branch.as_deref() == Some(branch.as_str()))
    {
        let path = existing.path.clone();
        // The whole snapshot lands under the advisory repo lock (issue #99):
        // no other writer may see half of it.
        let lock = lock_repo(&root)?;
        apply_meta(git, &root, &branch, &pr_meta(&view, &base, false))?;
        drop(lock);
        let ctx = pr_hook_context(&path, &branch, &root, &base, number);
        return Ok(PrCheckout {
            path,
            existed: true,
            ctx,
        });
    }

    // Fetch the PR head (works for fork PRs too via the pull/<n>/head ref).
    ops::fetch_refspec(
        git,
        &root,
        &session.config.pr_default_remote,
        &format!("pull/{number}/head"),
    )?;
    let head_oid = git
        .run(&root, &["rev-parse", "FETCH_HEAD"])?
        .trim()
        .to_string();
    let short_hash = head_oid.get(..7).unwrap_or(&head_oid).to_string();
    let slug = slugify_with_fallback(&branch, &short_hash);
    // If a local branch of this name already exists (but has no worktree), check
    // it out as-is rather than failing on `-b` (mirrors `wt new`).
    let branch_exists = resolve_hex(session.repo.gix(), &branch_ref(&branch)).is_some();

    let lock = lock_repo(&root)?;
    let worktree_path = resolve_target(
        &session.config,
        &root,
        &branch,
        &slug,
        &short_hash,
        &cx.env,
        session.repo.is_bare(),
    )?;
    if let Some(parent) = worktree_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let target_str = worktree_path.to_string_lossy().into_owned();
    if branch_exists {
        ops::worktree_add(git, &root, &target_str, &branch, false)?;
    } else {
        ops::worktree_add_branch(git, &root, &branch, &target_str, "FETCH_HEAD", false, false)?;
    }

    // Record metadata + copy, rolling back on failure (§13). Only mark "created
    // by wt" when we actually created the branch here; a pre-existing branch
    // belongs to the user and must not be branch-deleted by a later `remove`
    // (spec §10).
    let copy_outcome = match (|| -> Result<crate::copy::CopyOutcome> {
        apply_meta(git, &root, &branch, &pr_meta(&view, &base, !branch_exists))?;
        let source = session
            .repo
            .current_workdir()
            .unwrap_or_else(|| root.clone());
        copy_ignored_files(git, &source, &worktree_path, &session.config.copy)
    })() {
        Ok(outcome) => outcome,
        Err(e) => {
            // Delete the branch only if we created it here, but always clear the
            // metadata this command wrote (§13).
            rollback_worktree(git, &root, &worktree_path, &branch, !branch_exists, true);
            return Err(e);
        }
    };
    // Everything from target resolution to the copy step is one mutation region
    // (issue #99). The lock is released before the `post_create` hook, which may
    // re-enter `wt` — exactly as `Workspace::create` does.
    drop(lock);
    crate::commands::log_copy_outcome(cx, &copy_outcome);

    let ctx = pr_hook_context(&worktree_path, &branch, &root, &base, number);
    run_post_create(
        hooks,
        cx,
        session.config.hooks_post_create.as_deref(),
        &ctx,
        no_hooks,
    )?;

    // Honor `[submodules] init` for PR worktrees too (issue #50), prompting
    // (default yes) at an interactive terminal when the policy is left at its
    // default; no per-invocation flag here. Non-fatal.
    maybe_init_submodules_interactive(
        cx,
        git,
        &worktree_path,
        session.config.submodules_init,
        None,
        prompt,
        session.config.submodules_seed.is_enabled(),
    )?;

    Ok(PrCheckout {
        path: worktree_path,
        existed: false,
        ctx,
    })
}

/// The `wt.*` metadata a PR checkout records for its head branch (§7): the
/// cached PR snapshot plus the base ref, and "created by wt" only when this
/// command created the branch.
fn pr_meta(view: &crate::gh::PrView, base: &str, created_here: bool) -> MetaUpdate {
    MetaUpdate {
        base_ref: Some(base.to_string()),
        pr_number: Some(view.number),
        pr_state: Some(view.pr_state().as_str().to_string()),
        pr_title: Some(view.title.clone()),
        pr_url: Some(view.url.clone()),
        created_by_wt: created_here,
        // A PR checkout records no issue link; `None` leaves any existing one
        // (e.g. from `wt issue`) untouched.
        ..MetaUpdate::default()
    }
}

/// The `WT_*` context for a PR worktree's `post_create` hook and `--start`
/// command: unlike `wt new`, the base ref and PR number are always known.
fn pr_hook_context(path: &Path, branch: &str, root: &Path, base: &str, number: u64) -> HookContext {
    HookContext {
        worktree_path: path.to_path_buf(),
        branch: branch.to_string(),
        repo_root: root.to_path_buf(),
        base_ref: Some(base.to_string()),
        pr_number: Some(number),
    }
}

#[cfg(test)]
mod tests {
    use crate::cli::{PrArgs, PrSub};
    use crate::gh::PrView;
    use crate::hooks::RealHookRunner;
    use crate::testutil::{FakeGh, TestRepo};
    use std::sync::Arc;

    fn pr_args(target: Option<&str>, sub: Option<PrSub>) -> PrArgs {
        PrArgs {
            target: target.map(str::to_string),
            no_switch: false,
            no_hooks: true,
            start: None,
            sub,
        }
    }

    fn view(number: u64, head: &str, base: &str) -> PrView {
        PrView {
            number,
            title: "Add login".into(),
            state: "OPEN".into(),
            is_draft: false,
            head_ref_name: head.into(),
            base_ref_name: base.into(),
            url: format!("https://github.com/o/r/pull/{number}"),
        }
    }

    /// Sets up a fetchable `pull/<n>/head` ref served by an `origin` remote
    /// pointing at the repo itself, returning the repo.
    fn repo_with_pr(number: u64) -> TestRepo {
        let repo = TestRepo::init();
        // A commit to serve as the PR head.
        repo.write("pr.txt", "from pr\n");
        repo.commit_all("pr commit");
        let pr_oid = repo.git(&["rev-parse", "HEAD"]).trim().to_string();
        repo.git(&["update-ref", &format!("refs/pull/{number}/head"), &pr_oid]);
        // Reset main back so the PR commit is "ahead".
        repo.git(&["reset", "-q", "--hard", "HEAD~1"]);
        repo.git(&["remote", "add", "origin", repo.root().to_str().unwrap()]);
        repo
    }

    /// `--start` runs in the PR worktree with the full `WT_*` context: unlike
    /// `new`/`checkout`, a PR worktree knows both its base ref and its PR number.
    #[test]
    fn start_runs_in_the_pr_worktree_with_pr_context() {
        let repo = repo_with_pr(123);
        let cd_dir = tempfile::tempdir().unwrap();
        let cd_file = cd_dir.path().join("cd");
        let mut t = crate::testutil::test_cx(
            &[("WT_CD_FILE", cd_file.to_str().unwrap())],
            repo.root().to_str().unwrap(),
        );
        t.cx.gh = Arc::new(FakeGh::with_view(view(123, "pr-feature", "main")));
        let mut a = pr_args(Some("123"), None);
        a.start = Some("printf '%s %s' \"$WT_PR_NUMBER\" \"$WT_BASE_REF\" > ctx.txt".into());
        let code = super::run(&mut t.cx, &RealHookRunner, &a, false).unwrap();

        assert_eq!(code, 0);
        assert!(t.out.contents().is_empty(), "stdout is the command's");
        let target = std::fs::read_to_string(&cd_file).unwrap();
        assert_eq!(
            std::fs::read_to_string(std::path::Path::new(&target).join("ctx.txt")).unwrap(),
            "123 main"
        );
    }

    #[test]
    fn checks_out_pr_into_worktree() {
        let repo = repo_with_pr(123);
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.gh = Arc::new(FakeGh::with_view(view(123, "pr-feature", "main")));
        let code = super::run(
            &mut t.cx,
            &RealHookRunner,
            &pr_args(Some("123"), None),
            false,
        )
        .unwrap();
        assert_eq!(code, 0);
        let path = t.out.contents().trim().to_string();
        assert!(std::path::Path::new(&path).is_dir());
        assert!(path.ends_with("pr-feature"));
        // The PR file is present (correct head fetched).
        assert!(std::path::Path::new(&path).join("pr.txt").exists());
        // Metadata recorded.
        assert_eq!(
            repo.git(&["config", "--get", "wt.pr-feature.prNumber"])
                .trim(),
            "123"
        );
        assert_eq!(
            repo.git(&["config", "--get", "wt.pr-feature.baseRef"])
                .trim(),
            "main"
        );
        assert_eq!(
            repo.git(&["config", "--get", "wt.pr-feature.prState"])
                .trim(),
            "open"
        );
        assert!(
            repo.git(&["config", "--get", "wt.pr-feature.prUrl"])
                .contains("pull/123")
        );
    }

    #[test]
    fn pr_checkout_releases_the_lock_before_the_post_create_hook() {
        // The `wt pr` mutation region takes the advisory repo lock (issue #99),
        // but a hook may re-enter `wt`, so the lock must be gone by the time it
        // runs. The hook itself proves the lock file is absent.
        let repo = repo_with_pr(77);
        repo.write(
            ".wt.toml",
            "[hooks]\npost_create = \"test ! -e \\\"$WT_REPO_ROOT/.git/wt-mutation.lock\\\" && touch unlocked\"\n",
        );
        repo.commit_all("config");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.gh = Arc::new(FakeGh::with_view(view(77, "pr-feature", "main")));
        let mut a = pr_args(Some("77"), None);
        a.no_hooks = false;
        let code = super::run(&mut t.cx, &RealHookRunner, &a, false).unwrap();
        assert_eq!(code, 0);
        // The marker proves the hook ran *and* saw no lock file; a failing hook
        // is non-fatal, so the exit code alone would not.
        let path = std::path::PathBuf::from(t.out.contents().trim());
        assert!(path.join("unlocked").exists(), "{}", t.err.contents());
        // ...and the lock is not left behind afterwards either.
        assert!(!repo.root().join(".git/wt-mutation.lock").exists());
    }

    #[test]
    fn pr_on_existing_worktree_records_metadata_without_marking_created() {
        // Re-running `wt pr <n>` on a branch that already has a worktree records
        // the PR metadata (§7) without marking the worktree as created by wt.
        let repo = repo_with_pr(55);
        repo.add_worktree("pr-feature", "../pf");
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.gh = Arc::new(FakeGh::with_view(view(55, "pr-feature", "main")));
        let code = super::run(
            &mut t.cx,
            &RealHookRunner,
            &pr_args(Some("55"), None),
            false,
        )
        .unwrap();
        assert_eq!(code, 0);
        assert_eq!(
            repo.git(&["config", "--get", "wt.pr-feature.prNumber"])
                .trim(),
            "55"
        );
        assert_eq!(
            repo.git(&["config", "--get", "wt.pr-feature.baseRef"])
                .trim(),
            "main"
        );
        assert!(
            repo.git(&["config", "--get", "wt.pr-feature.prUrl"])
                .contains("pull/55")
        );
        // Not marked created-by-wt (the worktree predates this command). Keys are
        // lowercased in `config --list`.
        assert!(
            !repo
                .git(&["config", "--list"])
                .contains("wt.pr-feature.createdbywt")
        );
    }

    #[test]
    fn pr_checks_out_existing_local_branch_without_a_worktree() {
        // A local branch of the PR head name exists but has no worktree: check it
        // out (no `-b`) rather than failing.
        let repo = repo_with_pr(77);
        repo.git(&["branch", "pr-feature"]);
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.gh = Arc::new(FakeGh::with_view(view(77, "pr-feature", "main")));
        let code = super::run(
            &mut t.cx,
            &RealHookRunner,
            &pr_args(Some("77"), None),
            false,
        )
        .unwrap();
        assert_eq!(code, 0);
        let path = t.out.contents().trim().to_string();
        assert!(std::path::Path::new(&path).is_dir());
        assert!(path.ends_with("pr-feature"));
        // The user's pre-existing branch is NOT marked created-by-wt (so a later
        // `remove` will not delete it).
        assert!(
            !repo
                .git(&["config", "--list"])
                .contains("wt.pr-feature.createdbywt")
        );
    }

    #[test]
    fn pr_rollback_on_existing_branch_keeps_branch_and_clears_metadata() {
        use crate::git::cli::{GitCli, GitOutput, RealGit};
        use std::path::Path as StdPath;
        // A git that fails the copy step's `ls-files` after the metadata writes
        // succeed, forcing a rollback on the pre-existing-branch path.
        struct FailLs(RealGit);
        impl GitCli for FailLs {
            fn run_raw(&self, repo: &StdPath, args: &[&str]) -> crate::error::Result<GitOutput> {
                if args.first() == Some(&"ls-files") {
                    return Ok(GitOutput {
                        success: false,
                        stdout: String::new(),
                        stderr: "boom".into(),
                    });
                }
                self.0.run_raw(repo, args)
            }
        }

        let repo = repo_with_pr(88);
        repo.git(&["branch", "pr-feature"]);
        // A copy pattern so the (failing) copy step runs.
        std::fs::write(repo.root().join(".wt.toml"), "copy = [\".env\"]\n").unwrap();
        repo.write(".env", "X=1\n");
        let mut t = crate::testutil::test_cx_with_git(
            &[],
            repo.root().to_str().unwrap(),
            Arc::new(FailLs(RealGit)),
        );
        t.cx.gh = Arc::new(FakeGh::with_view(view(88, "pr-feature", "main")));
        let err = super::run(
            &mut t.cx,
            &RealHookRunner,
            &pr_args(Some("88"), None),
            false,
        )
        .unwrap_err();
        assert!(err.to_string().contains("boom"));
        // The user's branch survives the rollback...
        assert!(
            !repo
                .git(&["branch", "--list", "pr-feature"])
                .trim()
                .is_empty(),
            "pre-existing branch must not be deleted on rollback"
        );
        // ...and the metadata written before the failure is cleared (no orphans).
        assert!(
            !repo.git(&["config", "--list"]).contains("wt.pr-feature."),
            "rollback must clear the wt.* metadata it wrote"
        );
    }

    #[test]
    fn pr_list_prints_open_prs() {
        use crate::gh::{Author, PrSummary};
        let repo = TestRepo::init();
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.gh = Arc::new(FakeGh::with_list(vec![PrSummary {
            number: 7,
            title: "Fix bug".into(),
            author: Author {
                login: "alice".into(),
            },
            state: "OPEN".into(),
            is_draft: false,
            head_ref_name: "fix".into(),
            created_at: String::new(),
        }]));
        super::run(
            &mut t.cx,
            &RealHookRunner,
            &pr_args(None, Some(PrSub::List)),
            false,
        )
        .unwrap();
        let out = t.out.contents();
        assert!(out.contains("#7"));
        assert!(out.contains("Fix bug"));
        assert!(out.contains("alice"));
    }

    #[test]
    fn pr_list_json() {
        use crate::gh::{Author, PrSummary};
        let repo = TestRepo::init();
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.gh = Arc::new(FakeGh::with_list(vec![PrSummary {
            number: 9,
            title: "T".into(),
            author: Author {
                login: "bob".into(),
            },
            state: "OPEN".into(),
            is_draft: true,
            head_ref_name: "wip".into(),
            created_at: String::new(),
        }]));
        super::run(
            &mut t.cx,
            &RealHookRunner,
            &pr_args(None, Some(PrSub::List)),
            true,
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(t.out.contents().trim()).unwrap();
        assert_eq!(v["number"], serde_json::json!(9));
        assert_eq!(v["state"], serde_json::json!("draft"));
    }

    #[test]
    fn gh_unavailable_is_actionable() {
        let repo = TestRepo::init();
        let mut t = crate::testutil::test_cx(&[], repo.root().to_str().unwrap());
        t.cx.gh = Arc::new(FakeGh::unavailable());
        let err = super::run(
            &mut t.cx,
            &RealHookRunner,
            &pr_args(None, Some(PrSub::List)),
            false,
        )
        .unwrap_err();
        assert!(matches!(err, crate::error::Error::GhUnavailable(_)));
    }
}