wtui 0.1.0

A terminal UI and CLI for managing Git worktrees across repositories
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
use std::ffi::OsStr;
use std::fs;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::thread;

#[test]
fn creates_all_modes_reports_status_and_validates_conflicts() {
    let fixture = Fixture::normal("creation");
    let existing = fixture.root.join("existing tree");
    let new_tree = fixture.root.join("nested/new tree");
    let detached = fixture.root.join("detached tree");
    git(&fixture.anchor, &["branch", "existing"]);

    assert_success(&fixture.wt(&[
        "worktree",
        "create",
        "project",
        existing.to_str().unwrap(),
        "--branch",
        "existing",
        "--yes",
    ]));
    let checked_out = fixture.wt(&[
        "worktree",
        "create",
        "project",
        fixture.root.join("duplicate").to_str().unwrap(),
        "--branch",
        "existing",
        "--yes",
    ]);
    assert_failure_contains(&checked_out, "already checked out");

    let missing_parent = fixture.wt(&[
        "worktree",
        "create",
        "project",
        new_tree.to_str().unwrap(),
        "--new-branch",
        "new/topic",
        "--start-point",
        "HEAD",
        "--yes",
    ]);
    assert_failure_contains(&missing_parent, "destination parent does not exist");
    assert_success(&fixture.wt(&[
        "worktree",
        "create",
        "project",
        new_tree.to_str().unwrap(),
        "--new-branch",
        "new/topic",
        "--start-point",
        "HEAD",
        "--create-parents",
        "--yes",
    ]));
    assert_success(&fixture.wt(&[
        "worktree",
        "create",
        "project",
        detached.to_str().unwrap(),
        "--detach",
        "HEAD",
        "--yes",
    ]));

    fs::write(new_tree.join("untracked file"), "change").unwrap();
    let inspect = fixture.wt(&["worktree", "inspect", "project", "new/topic"]);
    assert_success(&inspect);
    assert!(stdout(&inspect).contains("upstream\t-"));
    assert!(stdout(&inspect).contains("status\t0 staged, 0 unstaged, 1 untracked"));
    let list = fixture.wt(&["worktree", "list", "project"]);
    assert_success(&list);
    assert!(stdout(&list).contains(detached.to_str().unwrap()));
    assert!(stdout(&list).contains("detached:"));

    let invalid = fixture.wt(&[
        "worktree",
        "create",
        "project",
        fixture.root.join("bad").to_str().unwrap(),
        "--detach",
        "not-a-commit",
        "--yes",
    ]);
    assert_failure_contains(&invalid, "does not resolve to a commit");
    let missing_branch = fixture.wt(&[
        "worktree",
        "create",
        "project",
        fixture.root.join("missing").to_str().unwrap(),
        "--branch",
        "does-not-exist",
        "--yes",
    ]);
    assert_failure_contains(&missing_branch, "does not exist");
    let existing_new_branch = fixture.wt(&[
        "worktree",
        "create",
        "project",
        fixture.root.join("already").to_str().unwrap(),
        "--new-branch",
        "existing",
        "--yes",
    ]);
    assert_failure_contains(&existing_new_branch, "already exists");
    let collision = fixture.wt(&[
        "worktree",
        "create",
        "project",
        existing.to_str().unwrap(),
        "--detach",
        "HEAD",
        "--yes",
    ]);
    assert_failure_contains(&collision, "destination already exists");
}

#[test]
fn suggests_moves_locks_unlocks_and_repairs_worktrees() {
    let fixture = Fixture::normal_with_worktree_root("updates");
    git(&fixture.anchor, &["branch", "suggested/topic"]);
    assert!(!fixture.worktree_root.exists());
    assert_success(&fixture.wt(&[
        "worktree",
        "create",
        "project",
        "--branch",
        "suggested/topic",
        "--yes",
    ]));
    let suggested = fixture.worktree_root.join("suggested-topic");
    assert!(suggested.exists());

    let moved = fixture.root.join("moved tree");
    assert_success(&fixture.wt(&[
        "worktree",
        "move",
        "project",
        "suggested/topic",
        moved.to_str().unwrap(),
        "--yes",
    ]));
    assert!(!suggested.exists());
    assert!(moved.exists());

    assert_success(&fixture.wt(&[
        "worktree",
        "lock",
        "project",
        "suggested/topic",
        "--reason",
        "do not remove",
        "--yes",
    ]));
    let list = fixture.wt(&["worktree", "list", "project"]);
    assert!(stdout(&list).contains("locked=do not remove"));
    let removal = fixture.wt(&["worktree", "remove", "project", "suggested/topic", "--yes"]);
    assert_failure_contains(&removal, "worktree is locked: do not remove");
    assert_success(&fixture.wt(&["worktree", "unlock", "project", "suggested/topic", "--yes"]));

    let relocated = fixture.root.join("relocated outside git");
    fs::rename(&moved, &relocated).unwrap();
    assert_success(&fixture.wt(&[
        "worktree",
        "repair",
        "project",
        relocated.to_str().unwrap(),
        "--yes",
    ]));
    assert_success(&git_output(&relocated, &["status", "--short"]));
}

#[test]
fn missing_worktree_root_is_created_for_creates_and_moves() {
    let fixture = Fixture::normal_with_worktree_root("root creation");
    git(&fixture.anchor, &["branch", "nested/topic"]);
    assert!(!fixture.worktree_root.exists());

    let nested = fixture.worktree_root.join("team/nested-topic");
    assert_success(&fixture.wt(&[
        "worktree",
        "create",
        "project",
        nested.to_str().unwrap(),
        "--branch",
        "nested/topic",
        "--yes",
    ]));
    assert!(nested.join(".git").exists());

    let unmanaged = fixture.root.join("unmanaged/topic");
    let refusal = fixture.wt(&[
        "worktree",
        "create",
        "project",
        unmanaged.to_str().unwrap(),
        "--detach",
        "HEAD",
        "--yes",
    ]);
    assert_failure_contains(&refusal, "destination parent does not exist");
    assert!(!fixture.root.join("unmanaged").exists());

    let relocated = fixture.worktree_root.join("moved/nested-topic");
    assert_success(&fixture.wt(&[
        "worktree",
        "move",
        "project",
        "nested/topic",
        relocated.to_str().unwrap(),
        "--yes",
    ]));
    assert!(relocated.join(".git").exists());
}

#[test]
fn removal_safeguards_force_confirmation_and_branch_preservation() {
    let fixture = Fixture::normal("removal");
    let clean = fixture.root.join("clean");
    let dirty = fixture.root.join("dirty");
    let locked = fixture.root.join("locked");
    git(&fixture.anchor, &["branch", "clean-branch"]);
    git(&fixture.anchor, &["branch", "dirty-branch"]);
    git(&fixture.anchor, &["branch", "locked-branch"]);
    create_existing(&fixture, &clean, "clean-branch");
    create_existing(&fixture, &dirty, "dirty-branch");
    create_existing(&fixture, &locked, "locked-branch");

    let main_refusal = fixture.wt(&[
        "worktree",
        "remove",
        "project",
        fixture.anchor.to_str().unwrap(),
        "--yes",
    ]);
    assert_failure_contains(&main_refusal, "cannot remove the main worktree");

    let from_inside = fixture.wt_in(
        &dirty,
        &["worktree", "remove", "project", "dirty-branch", "--yes"],
    );
    assert_failure_contains(&from_inside, "containing the current directory");

    fs::write(dirty.join("untracked"), "local work").unwrap();
    let safe = fixture.wt(&["worktree", "remove", "project", "dirty-branch", "--yes"]);
    assert_failure_contains(&safe, "local changes");
    let wrong = fixture.wt(&[
        "worktree",
        "force-remove",
        "project",
        "dirty-branch",
        "--confirm",
        "wrong",
    ]);
    assert_failure_contains(&wrong, "typed confirmation must equal");
    let forced = fixture.wt(&[
        "worktree",
        "force-remove",
        "project",
        "dirty-branch",
        "--confirm",
        "dirty-branch",
    ]);
    assert_success(&forced);
    assert!(stderr(&forced).contains("0 staged, 0 unstaged, 1 untracked"));
    assert!(branch_exists(&fixture.anchor, "dirty-branch"));

    assert_success(&fixture.wt(&[
        "worktree",
        "lock",
        "project",
        "locked-branch",
        "--reason",
        "protected",
        "--yes",
    ]));
    assert_success(&fixture.wt(&[
        "worktree",
        "force-remove",
        "project",
        "locked-branch",
        "--confirm",
        "locked-branch",
    ]));
    assert!(branch_exists(&fixture.anchor, "locked-branch"));

    assert_success(&fixture.wt(&["worktree", "remove", "project", "clean-branch", "--yes"]));
    assert!(!clean.exists());
    assert!(branch_exists(&fixture.anchor, "clean-branch"));
}

#[test]
fn bare_repository_supports_crud_and_prune_preview_parity() {
    let fixture = Fixture::bare("bare");
    let bare_removal = fixture.wt(&["worktree", "remove", "project", "project.git", "--yes"]);
    assert_failure_contains(&bare_removal, "bare repository anchor");
    let tree = fixture.root.join("bare tree");
    assert_success(&fixture.wt(&[
        "worktree",
        "create",
        "project",
        tree.to_str().unwrap(),
        "--new-branch",
        "bare-topic",
        "--start-point",
        "main",
        "--yes",
    ]));
    assert_success(&fixture.wt(&["worktree", "lock", "project", "bare-topic", "--yes"]));
    assert_success(&fixture.wt(&["worktree", "unlock", "project", "bare-topic", "--yes"]));
    let moved = fixture.root.join("bare moved");
    assert_success(&fixture.wt(&[
        "worktree",
        "move",
        "project",
        "bare-topic",
        moved.to_str().unwrap(),
        "--yes",
    ]));
    let repaired = fixture.root.join("bare repaired");
    fs::rename(&moved, &repaired).unwrap();
    assert_success(&fixture.wt(&[
        "worktree",
        "repair",
        "project",
        repaired.to_str().unwrap(),
        "--yes",
    ]));
    assert_success(&git_output(&repaired, &["status", "--short"]));
    assert_success(&fixture.wt(&["worktree", "remove", "project", "bare-topic", "--yes"]));
    assert!(branch_exists(&fixture.anchor, "bare-topic"));

    let stale = fixture.root.join("stale tree");
    git(
        &fixture.anchor,
        &[
            "worktree",
            "add",
            "-b",
            "stale-topic",
            stale.to_str().unwrap(),
            "main",
        ],
    );
    let displaced = fixture.root.join("displaced tree");
    fs::rename(&stale, &displaced).unwrap();
    let preview = fixture.wt(&["worktree", "prune-preview", "project"]);
    assert_success(&preview);
    assert!(stdout(&preview).contains("gitdir file points to non-existent location"));
    let detail = fixture.wt(&["worktree", "inspect", "project", "stale-topic"]);
    assert_success(&detail);
    assert!(stdout(&detail).contains("prunable\tgitdir file points"));
    let prune = fixture.wt(&["worktree", "prune", "project", "--yes"]);
    assert_success(&prune);
    assert!(stderr(&prune).contains(&stdout(&preview)));
    let after = fixture.wt(&["worktree", "prune-preview", "project"]);
    assert_success(&after);
    assert!(stdout(&after).is_empty());
}

#[test]
fn remove_merged_previews_confirms_revalidates_and_preserves_branches() {
    let fixture = Fixture::normal("remove merged");
    let worktree = fixture.root.join("merged topic");
    git(&fixture.anchor, &["branch", "topic"]);
    create_existing(&fixture, &worktree, "topic");

    let (base, preview_server) = fake_github_server(1);
    git(
        &fixture.anchor,
        &[
            "remote",
            "add",
            "origin",
            &format!("{base}/base/project.git"),
        ],
    );
    git(&fixture.anchor, &["config", "github.token", "test-token"]);
    let cancelled = fixture.wt(&["worktree", "remove-merged", "project"]);
    preview_server.join().unwrap();
    assert_failure_contains(&cancelled, "operation cancelled");
    assert!(stderr(&cancelled).contains("eligible\trepository=project\tbranch=topic"));
    assert!(worktree.exists());

    let (base, removal_server) = fake_github_server(2);
    git(
        &fixture.anchor,
        &[
            "remote",
            "set-url",
            "origin",
            &format!("{base}/base/project.git"),
        ],
    );
    let removed = fixture.wt(&["worktree", "remove-merged", "project", "--yes"]);
    removal_server.join().unwrap();
    assert_success(&removed);
    assert!(stdout(&removed).contains("removed\t"));
    assert!(stderr(&removed).contains("result\tremoved=1\tskipped=1"));
    assert!(!worktree.exists());
    assert!(branch_exists(&fixture.anchor, "topic"));
}

#[test]
fn remove_merged_requires_exactly_one_scope_and_completes_all() {
    let fixture = Fixture::normal("remove merged scope");
    let missing = fixture.wt(&["worktree", "remove-merged", "--yes"]);
    assert_failure_contains(&missing, "required arguments were not provided");
    let conflicting = fixture.wt(&["worktree", "remove-merged", "project", "--all", "--yes"]);
    assert_failure_contains(&conflicting, "cannot be used with");
    let completion = fixture.wt(&["__complete", "worktree", "remove-merged", ""]);
    assert_success(&completion);
    assert!(stdout(&completion).lines().any(|line| line == "--all"));
    assert!(stdout(&completion).lines().any(|line| line == "project"));
}

#[test]
fn remove_merged_all_cleans_every_registered_repository() {
    let fixture = Fixture::normal("remove merged all");
    let first_worktree = fixture.root.join("first topic");
    git(&fixture.anchor, &["branch", "topic"]);
    create_existing(&fixture, &first_worktree, "topic");

    let second_anchor = fixture.root.join("second main");
    let second_worktree = fixture.root.join("second topic");
    git(
        &fixture.root,
        &["init", "-b", "main", second_anchor.to_str().unwrap()],
    );
    configure_identity(&second_anchor);
    git(
        &second_anchor,
        &["commit", "--allow-empty", "-m", "initial"],
    );
    git(&second_anchor, &["branch", "topic-two"]);
    assert_success(&fixture.wt(&[
        "repo",
        "add",
        second_anchor.to_str().unwrap(),
        "--label",
        "second",
    ]));
    assert_success(&fixture.wt(&[
        "worktree",
        "create",
        "second",
        second_worktree.to_str().unwrap(),
        "--branch",
        "topic-two",
        "--yes",
    ]));

    let (base, server) = fake_github_server(4);
    for anchor in [&fixture.anchor, &second_anchor] {
        git(
            anchor,
            &[
                "remote",
                "add",
                "origin",
                &format!("{base}/base/project.git"),
            ],
        );
        git(anchor, &["config", "github.token", "test-token"]);
    }
    let removed = fixture.wt(&["worktree", "remove-merged", "--all", "--yes"]);
    server.join().unwrap();
    assert_success(&removed);
    assert!(stderr(&removed).contains("result\tremoved=2\tskipped=2"));
    assert!(!first_worktree.exists());
    assert!(!second_worktree.exists());
    assert!(branch_exists(&fixture.anchor, "topic"));
    assert!(branch_exists(&second_anchor, "topic-two"));
}

fn fake_github_server(request_count: usize) -> (String, thread::JoinHandle<()>) {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let address = listener.local_addr().unwrap();
    let server = thread::spawn(move || {
        for stream in listener.incoming().take(request_count) {
            let mut stream = stream.unwrap();
            let mut request = Vec::new();
            let mut buffer = [0_u8; 4096];
            let header_end = loop {
                let read = stream.read(&mut buffer).unwrap();
                assert!(read > 0);
                request.extend_from_slice(&buffer[..read]);
                if let Some(index) = request.windows(4).position(|window| window == b"\r\n\r\n") {
                    break index + 4;
                }
            };
            let headers = String::from_utf8_lossy(&request[..header_end]);
            let content_length = headers
                .lines()
                .find_map(|line| {
                    let (name, value) = line.split_once(':')?;
                    name.eq_ignore_ascii_case("content-length")
                        .then(|| value.trim().parse::<usize>().ok())
                        .flatten()
                })
                .unwrap();
            while request.len() < header_end + content_length {
                let read = stream.read(&mut buffer).unwrap();
                assert!(read > 0);
                request.extend_from_slice(&buffer[..read]);
            }
            let request: serde_json::Value =
                serde_json::from_slice(&request[header_end..header_end + content_length]).unwrap();
            let head = request["variables"]["branch0"].as_str().unwrap();
            let body = serde_json::json!({
                "data": {
                    "repository": {
                        "branch0": {
                            "associatedPullRequests": {
                                "nodes": [{
                                    "number": 42,
                                    "title": "merged change",
                                    "url": "https://example.test/base/project/pull/42",
                                    "state": "MERGED",
                                    "isDraft": false,
                                    "mergedAt": "2026-08-01T00:00:00Z",
                                    "updatedAt": "2026-08-01T00:00:00Z",
                                    "reviewDecision": "APPROVED",
                                    "autoMergeRequest": null,
                                    "baseRefName": "main",
                                    "baseRefOid": "base",
                                    "baseRepository": {"nameWithOwner": "base/project"},
                                    "headRefName": "topic",
                                    "headRefOid": head,
                                    "headRepository": {"nameWithOwner": "base/project"},
                                    "commits": {"nodes": []}
                                }]
                            }
                        }
                    },
                    "rateLimit": {"remaining": 100, "resetAt": "2026-08-11T12:00:00Z"}
                }
            })
            .to_string();
            write!(
                stream,
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                body.len(),
                body
            )
            .unwrap();
        }
    });
    (format!("http://{address}"), server)
}

struct Fixture {
    _temporary: tempfile::TempDir,
    root: PathBuf,
    anchor: PathBuf,
    config: PathBuf,
    worktree_root: PathBuf,
}

impl Fixture {
    fn normal(name: &str) -> Self {
        Self::normal_inner(name, false)
    }

    fn normal_with_worktree_root(name: &str) -> Self {
        Self::normal_inner(name, true)
    }

    fn normal_inner(name: &str, configure_root: bool) -> Self {
        let temporary = tempfile::tempdir().unwrap();
        let root = temporary.path().join(name);
        fs::create_dir(&root).unwrap();
        let anchor = root.join("main");
        let config = root.join("config/wt.json");
        let worktree_root = root.join("managed trees");
        git(
            temporary.path(),
            &["init", "-b", "main", anchor.to_str().unwrap()],
        );
        configure_identity(&anchor);
        git(&anchor, &["commit", "--allow-empty", "-m", "initial"]);
        let fixture = Self {
            _temporary: temporary,
            root,
            anchor,
            config,
            worktree_root,
        };
        let mut arguments = vec![
            "repo",
            "add",
            fixture.anchor.to_str().unwrap(),
            "--label",
            "project",
        ];
        if configure_root {
            arguments.extend(["--worktree-root", fixture.worktree_root.to_str().unwrap()]);
        }
        assert_success(&fixture.wt(&arguments));
        fixture
    }

    fn bare(name: &str) -> Self {
        let temporary = tempfile::tempdir().unwrap();
        let root = temporary.path().join(name);
        fs::create_dir(&root).unwrap();
        let source = root.join("source");
        let anchor = root.join("project.git");
        let config = root.join("wt.json");
        let worktree_root = root.join("trees");
        git(
            temporary.path(),
            &["init", "-b", "main", source.to_str().unwrap()],
        );
        configure_identity(&source);
        git(&source, &["commit", "--allow-empty", "-m", "initial"]);
        git(
            temporary.path(),
            &["init", "--bare", "-b", "main", anchor.to_str().unwrap()],
        );
        git(
            &source,
            &["remote", "add", "origin", anchor.to_str().unwrap()],
        );
        git(&source, &["push", "origin", "main"]);
        let fixture = Self {
            _temporary: temporary,
            root,
            anchor,
            config,
            worktree_root,
        };
        assert_success(&fixture.wt(&[
            "repo",
            "add",
            fixture.anchor.to_str().unwrap(),
            "--label",
            "project",
            "--worktree-root",
            fixture.worktree_root.to_str().unwrap(),
        ]));
        fixture
    }

    fn wt(&self, arguments: &[&str]) -> Output {
        self.wt_in(&self.root, arguments)
    }

    fn wt_in(&self, directory: &Path, arguments: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_wt"))
            .current_dir(directory)
            .env("WT_CONFIG_PATH", &self.config)
            .args(arguments)
            .output()
            .unwrap()
    }
}

fn create_existing(fixture: &Fixture, path: &Path, branch: &str) {
    assert_success(&fixture.wt(&[
        "worktree",
        "create",
        "project",
        path.to_str().unwrap(),
        "--branch",
        branch,
        "--yes",
    ]));
}

fn configure_identity(repository: &Path) {
    git(repository, &["config", "user.email", "test@example.com"]);
    git(repository, &["config", "user.name", "Test User"]);
}

fn branch_exists(repository: &Path, branch: &str) -> bool {
    git_output(
        repository,
        &[
            "show-ref",
            "--verify",
            "--quiet",
            &format!("refs/heads/{branch}"),
        ],
    )
    .status
    .success()
}

fn git(directory: &Path, arguments: &[&str]) {
    assert_success(&git_output(directory, arguments));
}

fn git_output(directory: &Path, arguments: &[&str]) -> Output {
    Command::new("git")
        .arg("-C")
        .arg(directory)
        .args(arguments.iter().map(OsStr::new))
        .output()
        .unwrap()
}

fn assert_success(output: &Output) {
    assert!(
        output.status.success(),
        "command failed\nstdout: {}\nstderr: {}",
        stdout(output),
        stderr(output)
    );
}

fn assert_failure_contains(output: &Output, expected: &str) {
    assert!(!output.status.success(), "command unexpectedly succeeded");
    assert!(
        stderr(output).contains(expected),
        "stderr did not contain {expected:?}: {}",
        stderr(output)
    );
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}