git-barber 0.2.0

Trim stale merged git branches (classic + squash merges), with a TUI
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
//! End-to-end tests against real throwaway git repositories.
//!
//! Every repo lives in a tempdir and is fully hermetic: no system or user
//! git config is read, identity comes from environment variables.

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

use assert_cmd::Command as BarberCommand;
use tempfile::TempDir;

/// Strip every env var that could point git at the ambient repository or
/// config. Without this, `cargo test` inside a hook or `rebase -x` (which
/// export GIT_DIR) would run the deletion tests against the REAL repo.
fn hermetic(cmd: &mut Command, dir: &Path) {
    for var in [
        "GIT_DIR",
        "GIT_WORK_TREE",
        "GIT_INDEX_FILE",
        "GIT_COMMON_DIR",
    ] {
        cmd.env_remove(var);
    }
    cmd.env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", dir.join("no-such-gitconfig"))
        .env("HOME", dir)
        .env("XDG_CONFIG_HOME", dir);
}

/// Run git in `dir`, panicking on failure (test setup must not fail silently).
fn git(dir: &Path, args: &[&str]) -> String {
    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(dir)
        .args(args)
        .env("GIT_AUTHOR_NAME", "test")
        .env("GIT_AUTHOR_EMAIL", "test@localhost")
        .env("GIT_COMMITTER_NAME", "test")
        .env("GIT_COMMITTER_EMAIL", "test@localhost");
    hermetic(&mut cmd, dir);
    let out = cmd.output().expect("failed to run git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).into_owned()
}

fn commit_file(dir: &Path, name: &str, content: &str, message: &str) {
    std::fs::write(dir.join(name), content).unwrap();
    git(dir, &["add", "."]);
    git(dir, &["commit", "-m", message]);
}

/// A repo with an initial commit on `main`.
fn repo() -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().to_path_buf();
    git(&dir, &["init", "-b", "main"]);
    commit_file(&dir, "README.md", "hello", "initial");
    (tmp, dir)
}

/// The binary under test, pointed at `dir`, with hermetic git env.
fn barber(dir: &Path) -> BarberCommand {
    let mut cmd = BarberCommand::cargo_bin("git-barber").unwrap();
    cmd.arg("-C").arg(dir);
    for var in [
        "GIT_DIR",
        "GIT_WORK_TREE",
        "GIT_INDEX_FILE",
        "GIT_COMMON_DIR",
    ] {
        cmd.env_remove(var);
    }
    cmd.env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", dir.join("no-such-gitconfig"))
        .env("HOME", dir)
        .env("XDG_CONFIG_HOME", dir);
    cmd
}

fn list_json(dir: &Path) -> serde_json::Value {
    let out = barber(dir).arg("--json").assert().success();
    serde_json::from_slice(&out.get_output().stdout).expect("--json must emit valid JSON")
}

fn branch_kinds(json: &serde_json::Value) -> Vec<(String, String)> {
    json["branches"]
        .as_array()
        .unwrap()
        .iter()
        .map(|b| {
            (
                b["name"].as_str().unwrap().to_string(),
                b["kind"].as_str().unwrap().to_string(),
            )
        })
        .collect()
}

#[test]
fn merge_commit_branch_is_detected_as_merged() {
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "f.txt", "feature", "add feature");
    git(&dir, &["checkout", "main"]);
    git(
        &dir,
        &["merge", "--no-ff", "feature", "-m", "merge feature"],
    );

    assert_eq!(
        branch_kinds(&list_json(&dir)),
        vec![("feature".into(), "merged".into())]
    );
}

#[test]
fn squash_merged_branch_is_detected_as_squash() {
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "a.txt", "one", "step one");
    commit_file(&dir, "b.txt", "two", "step two");
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--squash", "feature"]);
    git(&dir, &["commit", "-m", "feature (squashed)"]);

    assert_eq!(
        branch_kinds(&list_json(&dir)),
        vec![("feature".into(), "squash".into())]
    );
}

#[test]
fn unmerged_branch_is_not_a_candidate() {
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "active"]);
    commit_file(&dir, "wip.txt", "wip", "work in progress");
    git(&dir, &["checkout", "main"]);

    let json = list_json(&dir);
    assert!(
        branch_kinds(&json).is_empty(),
        "unexpected candidates: {json}"
    );
}

/// Bare "origin" + clone. Returns (guard, origin_path, clone_path).
fn repo_with_origin() -> (TempDir, PathBuf, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let origin = tmp.path().join("origin.git");
    let clone = tmp.path().join("clone");
    std::fs::create_dir(&origin).unwrap();
    git(&origin, &["init", "--bare", "-b", "main"]);
    let seed = tmp.path().join("seed");
    std::fs::create_dir(&seed).unwrap();
    git(&seed, &["init", "-b", "main"]);
    commit_file(&seed, "README.md", "hello", "initial");
    git(
        &seed,
        &["remote", "add", "origin", origin.to_str().unwrap()],
    );
    git(&seed, &["push", "-u", "origin", "main"]);
    git(
        tmp.path(),
        &["clone", origin.to_str().unwrap(), clone.to_str().unwrap()],
    );
    (tmp, origin, clone)
}

#[test]
fn gone_upstream_branch_needs_explicit_consent() {
    let (_tmp, origin, dir) = repo_with_origin();
    git(&dir, &["checkout", "-b", "was-merged-remotely"]);
    commit_file(&dir, "f.txt", "feature", "add feature");
    git(&dir, &["push", "-u", "origin", "was-merged-remotely"]);
    git(&dir, &["checkout", "main"]);
    // Simulate GitHub's "delete branch after merge" without merging the
    // commits (e.g. squash with conflict resolution we cannot patch-id match).
    git(&origin, &["branch", "-D", "was-merged-remotely"]);
    git(&dir, &["fetch", "--prune"]);

    assert_eq!(
        branch_kinds(&list_json(&dir)),
        vec![("was-merged-remotely".into(), "gone".into())]
    );
}

#[test]
fn protected_branches_are_excluded() {
    let (_tmp, dir) = repo();
    for name in ["develop", "release/1.0", "qa-env"] {
        git(&dir, &["branch", name]); // same tip as main → all "merged"
    }
    git(&dir, &["config", "barber.protect", "qa-*"]);

    let out = barber(&dir)
        .args(["--protect", "release/*", "--json"])
        .assert()
        .success();
    let json: serde_json::Value = serde_json::from_slice(&out.get_output().stdout).unwrap();
    assert!(
        branch_kinds(&json).is_empty(),
        "develop (default), release/* (flag) and qa-* (config) must all be protected: {json}"
    );
}

#[test]
fn current_branch_is_excluded() {
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "same-as-main"]); // merged by definition, but checked out

    let json = list_json(&dir);
    assert!(
        branch_kinds(&json).is_empty(),
        "unexpected candidates: {json}"
    );
}

#[test]
fn list_is_default_outside_a_tty_and_never_deletes() {
    let (_tmp, dir) = repo();
    git(&dir, &["branch", "merged-branch"]);

    // stdin/stdout are pipes here, so no flags must still mean "list".
    barber(&dir)
        .assert()
        .success()
        .stdout(predicates::str::contains("merged-branch"));
    git(&dir, &["rev-parse", "--verify", "merged-branch"]); // still exists
}

#[test]
fn not_a_repo_exits_2() {
    let tmp = TempDir::new().unwrap();
    barber(tmp.path())
        // A TMPDIR nested inside some git repo must not break this test.
        .env("GIT_CEILING_DIRECTORIES", tmp.path().parent().unwrap())
        .assert()
        .code(2);
}

#[test]
fn rebase_merged_branch_is_detected_as_rebase() {
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "a.txt", "one", "step one");
    commit_file(&dir, "b.txt", "two", "step two");
    git(&dir, &["checkout", "main"]);
    // GitHub's "Rebase and merge": each commit replayed individually. A
    // distinct committer date keeps the replayed commits from being
    // byte-identical to the originals (same-second runs would otherwise
    // reproduce the same OIDs and turn this into a plain fast-forward).
    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(&dir)
        .args(["cherry-pick", "feature~1", "feature"])
        .env("GIT_AUTHOR_NAME", "test")
        .env("GIT_AUTHOR_EMAIL", "test@localhost")
        .env("GIT_COMMITTER_NAME", "test")
        .env("GIT_COMMITTER_EMAIL", "test@localhost")
        .env("GIT_COMMITTER_DATE", "2030-01-01T00:00:00Z");
    hermetic(&mut cmd, &dir);
    assert!(cmd.status().unwrap().success());

    assert_eq!(
        branch_kinds(&list_json(&dir)),
        vec![("feature".into(), "rebase".into())]
    );
    // ...and --yes deletes it (force, since the tip is not an ancestor).
    barber(&dir).arg("--yes").assert().success();
    let left = git(&dir, &["branch", "--format=%(refname:short)"]);
    assert_eq!(left.lines().collect::<Vec<_>>(), vec!["main"]);
}

#[test]
fn base_flag_with_full_refname_never_offers_the_base_itself() {
    let (_tmp, dir) = repo();
    git(&dir, &["branch", "release-2x"]); // same tip as main → trivially merged
    git(&dir, &["checkout", "-b", "somewhere-else"]);
    commit_file(&dir, "w.txt", "w", "unrelated work");

    let out = barber(&dir)
        .args(["--base", "refs/heads/release-2x", "--json"])
        .assert()
        .success();
    let json: serde_json::Value = serde_json::from_slice(&out.get_output().stdout).unwrap();
    let names: Vec<String> = json["branches"]
        .as_array()
        .unwrap()
        .iter()
        .map(|b| b["name"].as_str().unwrap().to_string())
        .collect();
    assert!(
        !names.contains(&"release-2x".to_string()),
        "the base itself must never be a candidate: {json}"
    );
}

#[test]
fn branch_moved_between_scan_and_delete_survives() {
    // Simulated via the CAS check: scan sees sha A, we advance to B before
    // the delete step by scripting the scan through --json first.
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "f.txt", "f", "feature work");
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--no-ff", "feature", "-m", "merge"]);

    // Race a new commit onto the branch between "scan" and "delete" by
    // moving the ref right before --yes runs... we cannot pause the binary
    // mid-flight, so instead verify the building block directly: advance
    // the branch, then check the recorded scan-time sha no longer matches.
    let scan_sha = list_json(&dir)["branches"][0]["sha"]
        .as_str()
        .unwrap()
        .to_string();
    git(&dir, &["checkout", "feature"]);
    commit_file(&dir, "g.txt", "g", "late work");
    git(&dir, &["checkout", "main"]);
    let new_sha = git(&dir, &["rev-parse", "feature"]).trim().to_string();
    assert_ne!(scan_sha, new_sha);

    // A fresh --yes rescans and sees the branch as unmerged → survives.
    barber(&dir).arg("--yes").assert().success();
    git(&dir, &["rev-parse", "--verify", "feature"]);
}

#[test]
fn worktree_branches_are_excluded() {
    let (_tmp, dir) = repo();
    git(&dir, &["branch", "held-elsewhere"]); // same tip as main → merged
    let wt = dir.join("wt-checkout");
    git(
        &dir,
        &["worktree", "add", wt.to_str().unwrap(), "held-elsewhere"],
    );

    let json = list_json(&dir);
    assert!(
        branch_kinds(&json).is_empty(),
        "a branch checked out in another worktree must not be offered: {json}"
    );
    // And --yes must therefore succeed with nothing to do.
    barber(&dir).arg("--yes").assert().success();
    git(&dir, &["rev-parse", "--verify", "held-elsewhere"]);
}

#[test]
fn list_conflicts_with_yes() {
    let (_tmp, dir) = repo();
    barber(&dir).args(["--yes", "--dry-run"]).assert().code(2);
    barber(&dir).args(["--yes", "--list"]).assert().code(2);
    barber(&dir).arg("--include-gone").assert().code(2); // requires --yes
}

#[test]
fn rebase_with_extra_empty_commit_is_not_classified() {
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "a.txt", "one", "real work 1");
    commit_file(&dir, "b.txt", "two", "real work 2");
    git(&dir, &["commit", "--allow-empty", "-m", "release marker"]);
    git(&dir, &["checkout", "main"]);
    // Only the real commits are replayed upstream; the empty marker is not.
    // (Two of them, so the combined squash diff matches no single patch.)
    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(&dir)
        .args(["cherry-pick", "feature~2", "feature~1"])
        .env("GIT_AUTHOR_NAME", "test")
        .env("GIT_AUTHOR_EMAIL", "test@localhost")
        .env("GIT_COMMITTER_NAME", "test")
        .env("GIT_COMMITTER_EMAIL", "test@localhost")
        .env("GIT_COMMITTER_DATE", "2030-01-01T00:00:00Z");
    hermetic(&mut cmd, &dir);
    assert!(cmd.status().unwrap().success());

    // Empty-diff commits emit no patch-id; without the count guard the
    // branch would read as fully rebase-merged and be force-deleted along
    // with its (not-upstream) release-marker commit.
    let json = list_json(&dir);
    assert!(
        branch_kinds(&json).is_empty(),
        "empty commit must block the rebase verdict: {json}"
    );
    barber(&dir).arg("--yes").assert().success();
    git(&dir, &["rev-parse", "--verify", "feature"]);
}

#[test]
fn squash_with_rename_is_detected_despite_diff_config() {
    let (_tmp, dir) = repo();
    // Hostile-but-common user config: porcelain diffs would render renames
    // and use a different algorithm; detection must be immune.
    git(&dir, &["config", "diff.renames", "true"]);
    git(&dir, &["config", "diff.algorithm", "histogram"]);
    git(&dir, &["config", "diff.context", "5"]);

    git(&dir, &["checkout", "-b", "refactor"]);
    git(&dir, &["mv", "README.md", "GUIDE.md"]);
    commit_file(&dir, "extra.txt", "x", "move readme and add extra");
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--squash", "refactor"]);
    git(&dir, &["commit", "-m", "refactor (squashed)"]);

    assert_eq!(
        branch_kinds(&list_json(&dir)),
        vec![("refactor".into(), "squash".into())]
    );
}

#[test]
fn leased_remote_delete_refuses_when_remote_moved() {
    let (_tmp, origin, dir) = repo_with_origin();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "f.txt", "f", "feature work");
    git(&dir, &["push", "-u", "origin", "feature"]);
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--no-ff", "feature", "-m", "merge"]);
    git(&dir, &["push", "origin", "main"]);

    // A colleague pushes to the branch AFTER our last fetch.
    let colleague = dir.parent().unwrap().join("colleague");
    git(
        dir.parent().unwrap(),
        &[
            "clone",
            "-q",
            origin.to_str().unwrap(),
            colleague.to_str().unwrap(),
        ],
    );
    git(&colleague, &["checkout", "feature"]);
    commit_file(&colleague, "late.txt", "late", "late work");
    git(&colleague, &["push", "origin", "feature"]);

    // Local deletion succeeds; the leased remote deletion must refuse and
    // the remote branch (with the colleague's commit) must survive.
    barber(&dir).args(["--yes", "--remote"]).assert().code(1);
    let remote_branches = git(&origin, &["branch", "--format=%(refname:short)"]);
    assert!(
        remote_branches.lines().any(|b| b == "feature"),
        "lease must protect the moved remote branch: {remote_branches}"
    );
}

#[test]
fn yes_json_reports_candidates_even_when_nothing_is_deleted() {
    let (_tmp, origin, dir) = repo_with_origin();
    git(&dir, &["checkout", "-b", "gone-one"]);
    commit_file(&dir, "g.txt", "g", "gone work");
    git(&dir, &["push", "-u", "origin", "gone-one"]);
    git(&dir, &["checkout", "main"]);
    git(&origin, &["branch", "-D", "gone-one"]);
    git(&dir, &["fetch", "--prune"]);

    let out = barber(&dir).args(["--yes", "--json"]).assert().success();
    let json: serde_json::Value = serde_json::from_slice(&out.get_output().stdout).unwrap();
    assert_eq!(json["branches"][0]["name"], "gone-one", "{json}");
    assert_eq!(json["branches"][0]["kind"], "gone");
    assert_eq!(json["results"].as_array().unwrap().len(), 0);
}

#[test]
fn read_only_object_store_can_still_list() {
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "s.txt", "s", "squashed work");
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--squash", "feature"]);
    git(&dir, &["commit", "-m", "squash"]);

    // Freeze the object store: detection must be pure reads.
    let objects = dir.join(".git").join("objects");
    let original = std::fs::metadata(&objects).unwrap().permissions();
    let mut readonly = original.clone();
    readonly.set_readonly(true);
    std::fs::set_permissions(&objects, readonly).unwrap();

    let result = std::panic::catch_unwind(|| {
        assert_eq!(
            branch_kinds(&list_json(&dir)),
            vec![("feature".into(), "squash".into())]
        );
    });

    // Restore the exact original mode so TempDir can clean up.
    std::fs::set_permissions(&objects, original).unwrap();
    result.unwrap();
}

#[test]
fn yes_deletes_merged_and_squash_but_not_gone_or_active() {
    let (_tmp, origin, dir) = repo_with_origin();
    // merged via merge commit
    git(&dir, &["checkout", "-b", "merged-one"]);
    commit_file(&dir, "m.txt", "m", "merged work");
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--no-ff", "merged-one", "-m", "merge"]);
    // squash-merged
    git(&dir, &["checkout", "-b", "squashed-one"]);
    commit_file(&dir, "s.txt", "s", "squashed work");
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--squash", "squashed-one"]);
    git(&dir, &["commit", "-m", "squash"]);
    git(&dir, &["push", "origin", "main"]);
    // gone upstream, unmerged content
    git(&dir, &["checkout", "-b", "gone-one"]);
    commit_file(&dir, "g.txt", "g", "gone work");
    git(&dir, &["push", "-u", "origin", "gone-one"]);
    git(&dir, &["checkout", "main"]);
    git(&origin, &["branch", "-D", "gone-one"]);
    git(&dir, &["fetch", "--prune"]);
    // active, untouched
    git(&dir, &["checkout", "-b", "active-one"]);
    commit_file(&dir, "a.txt", "a", "active work");
    git(&dir, &["checkout", "main"]);

    barber(&dir)
        .arg("--yes")
        .assert()
        .success()
        .stdout(predicates::str::contains("merged-one"))
        .stdout(predicates::str::contains("undo:"));

    let left = git(&dir, &["branch", "--format=%(refname:short)"]);
    let left: Vec<&str> = left.lines().collect();
    assert_eq!(
        left,
        vec!["active-one", "gone-one", "main"],
        "only merged+squash must go"
    );
}

#[test]
fn include_gone_extends_yes_to_gone_branches() {
    let (_tmp, origin, dir) = repo_with_origin();
    git(&dir, &["checkout", "-b", "gone-one"]);
    commit_file(&dir, "g.txt", "g", "gone work");
    git(&dir, &["push", "-u", "origin", "gone-one"]);
    git(&dir, &["checkout", "main"]);
    git(&origin, &["branch", "-D", "gone-one"]);
    git(&dir, &["fetch", "--prune"]);

    barber(&dir)
        .args(["--yes", "--include-gone"])
        .assert()
        .success();
    let left = git(&dir, &["branch", "--format=%(refname:short)"]);
    assert_eq!(left.lines().collect::<Vec<_>>(), vec!["main"]);
}

#[test]
fn remote_flag_deletes_the_remote_counterpart_too() {
    let (_tmp, origin, dir) = repo_with_origin();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "f.txt", "f", "feature work");
    git(&dir, &["push", "-u", "origin", "feature"]);
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--no-ff", "feature", "-m", "merge"]);
    git(&dir, &["push", "origin", "main"]);

    let out = barber(&dir)
        .args(["--yes", "--remote", "--json"])
        .assert()
        .success();
    let json: serde_json::Value = serde_json::from_slice(&out.get_output().stdout).unwrap();
    assert_eq!(json["results"][0]["remote"]["status"], "deleted");

    let remote_branches = git(&origin, &["branch", "--format=%(refname:short)"]);
    assert_eq!(
        remote_branches.lines().collect::<Vec<_>>(),
        vec!["main"],
        "gone from origin too"
    );
    let local = git(&dir, &["branch", "--format=%(refname:short)"]);
    assert_eq!(local.lines().collect::<Vec<_>>(), vec!["main"]);
}

#[test]
fn remote_only_merged_branch_is_listed_but_never_auto_deleted() {
    let (_tmp, origin, dir) = repo_with_origin();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "f.txt", "f", "feature work");
    git(&dir, &["push", "-u", "origin", "feature"]);
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--no-ff", "feature", "-m", "merge"]);
    git(&dir, &["push", "origin", "main"]);
    git(&dir, &["branch", "-D", "feature"]); // simulate a prior local cleanup

    let out = barber(&dir).args(["--list", "--json"]).assert().success();
    let json: serde_json::Value = serde_json::from_slice(&out.get_output().stdout).unwrap();
    let remote = json["branches"]
        .as_array()
        .unwrap()
        .iter()
        .find(|b| b["name"] == "origin/feature")
        .expect("remote-only branch must be listed");
    assert_eq!(remote["scope"], "remote_only");
    assert_eq!(remote["selected_by_default"], true);

    barber(&dir).args(["--yes", "--remote"]).assert().success();
    let remote_branches = git(&origin, &["branch", "--format=%(refname:short)"]);
    assert!(
        remote_branches.lines().any(|b| b == "feature"),
        "remote-only candidates require TUI selection"
    );
}

#[test]
fn gentle_delete_falls_back_to_verified_force_from_another_branch() {
    let (_tmp, _origin, dir) = repo_with_origin();
    // `other` diverges from the initial commit and never sees the merge.
    git(&dir, &["branch", "other", "main"]);
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "f.txt", "f", "feature work");
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--no-ff", "feature", "-m", "merge"]);
    git(&dir, &["push", "origin", "main"]);
    // From `other`, plain `git branch -d feature` refuses (not merged into
    // HEAD); the tool must verify against origin/main and force.
    git(&dir, &["checkout", "other"]);

    barber(&dir)
        .arg("--yes")
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "force-deleted (verified merged into base)",
        ));
    let left = git(&dir, &["branch", "--format=%(refname:short)"]);
    assert_eq!(left.lines().collect::<Vec<_>>(), vec!["main", "other"]);
}

#[test]
fn undo_hint_actually_restores_the_branch() {
    let (_tmp, dir) = repo();
    git(&dir, &["checkout", "-b", "feature"]);
    commit_file(&dir, "f.txt", "f", "feature work");
    git(&dir, &["checkout", "main"]);
    git(&dir, &["merge", "--no-ff", "feature", "-m", "merge"]);
    let sha = git(&dir, &["rev-parse", "feature"]).trim().to_string();

    let out = barber(&dir).args(["--yes", "--json"]).assert().success();
    let json: serde_json::Value = serde_json::from_slice(&out.get_output().stdout).unwrap();
    let undo = json["results"][0]["undo"][0].as_str().unwrap().to_string();
    let undo_args: Vec<&str> = undo.split_whitespace().skip(1).collect();

    git(&dir, &undo_args);
    assert_eq!(git(&dir, &["rev-parse", "feature"]).trim(), sha);
}