marver 0.0.11

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! A thin wrapper over the `git` CLI.
//!
//! Shelling out rather than linking libgit2: worktree support is the feature
//! marver leans on hardest, and the CLI is the reference implementation of it.
//!
//! Every call is local. Nothing here fetches, and `GIT_TERMINAL_PROMPT=0` is set
//! so a repo with a credential-requiring remote fails fast instead of hanging on
//! a prompt no TUI could answer.

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

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("could not run git: {0}")]
    Spawn(#[source] std::io::Error),
    #[error("git {args} failed in {repo}: {stderr}")]
    Failed {
        repo: PathBuf,
        args: String,
        stderr: String,
    },
    #[error("{0} has no default branch and no checked-out branch")]
    NoDefaultBranch(PathBuf),
}

pub type Result<T> = std::result::Result<T, Error>;

/// Branches tried, in order, when the remote does not advertise a default.
const FALLBACK_DEFAULTS: &[&str] = &["main", "master", "trunk", "develop"];

/// Run git and return `(succeeded, stdout)` without judging the exit status.
///
/// Some git commands report a difference with a non-zero exit while still
/// producing the output we want — `diff --no-index` is the notable one.
fn output<S: AsRef<OsStr>>(repo: &Path, args: &[S]) -> Result<(bool, String)> {
    let result = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(args)
        .env("GIT_TERMINAL_PROMPT", "0")
        .output()
        .map_err(Error::Spawn)?;
    Ok((
        result.status.success(),
        String::from_utf8_lossy(&result.stdout).into_owned(),
    ))
}

/// Run git in `repo` and return stdout exactly as produced.
///
/// Callers parsing machine-readable output must use this rather than [`run`]:
/// `status --porcelain` lines begin with a significant space, which trimming
/// would silently eat, shifting every path by one character.
pub fn run_raw<S: AsRef<OsStr>>(repo: &Path, args: &[S]) -> Result<String> {
    let result = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(args)
        .env("GIT_TERMINAL_PROMPT", "0")
        .output()
        .map_err(Error::Spawn)?;

    if !result.status.success() {
        return Err(Error::Failed {
            repo: repo.to_path_buf(),
            args: args
                .iter()
                .map(|a| a.as_ref().to_string_lossy().into_owned())
                .collect::<Vec<_>>()
                .join(" "),
            stderr: String::from_utf8_lossy(&result.stderr).trim().to_string(),
        });
    }
    Ok(String::from_utf8_lossy(&result.stdout).into_owned())
}

/// Run git in `repo` and return trimmed stdout.
///
/// Convenient for single-value answers such as a branch name or a hash. For
/// anything parsed line-by-line, use [`run_raw`].
pub fn run<S: AsRef<OsStr>>(repo: &Path, args: &[S]) -> Result<String> {
    Ok(run_raw(repo, args)?.trim().to_string())
}

/// Like [`run`], but a non-zero exit is reported as `false` rather than an error.
fn succeeds<S: AsRef<OsStr>>(repo: &Path, args: &[S]) -> Result<bool> {
    match run(repo, args) {
        Ok(_) => Ok(true),
        Err(Error::Failed { .. }) => Ok(false),
        Err(other) => Err(other),
    }
}

pub fn is_repo(path: &Path) -> bool {
    run(path, &["rev-parse", "--git-dir"]).is_ok()
}

/// Whether a local branch of this name exists.
pub fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
    succeeds(
        repo,
        &[
            "show-ref",
            "--verify",
            "--quiet",
            &format!("refs/heads/{branch}"),
        ],
    )
}

/// The branch currently checked out, or `None` when HEAD is detached.
pub fn head_branch(repo: &Path) -> Result<Option<String>> {
    match run(repo, &["symbolic-ref", "--short", "--quiet", "HEAD"]) {
        Ok(branch) if !branch.is_empty() => Ok(Some(branch)),
        Ok(_) => Ok(None),
        Err(Error::Failed { .. }) => Ok(None),
        Err(other) => Err(other),
    }
}

/// The repository's default branch.
///
/// Resolution order, all of it local:
///
/// 1. What the remote advertises, via `refs/remotes/origin/HEAD`. Set by
///    `git clone`, so it is right for most repos and costs nothing.
/// 2. The first conventional name that actually exists — a repo cloned before
///    `origin/HEAD` was recorded, or one with no remote at all.
/// 3. Whatever is checked out, as a last resort.
///
/// Deliberately never fetches. Task branches cut from a possibly-stale local
/// default, which is what `git checkout main` would have given you anyway.
pub fn default_branch(repo: &Path) -> Result<String> {
    if let Ok(head) = run(
        repo,
        &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
    ) && let Some(branch) = head.strip_prefix("origin/")
        && !branch.is_empty()
        && branch_exists(repo, branch)?
    {
        return Ok(branch.to_string());
    }

    for candidate in FALLBACK_DEFAULTS {
        if branch_exists(repo, candidate)? {
            return Ok((*candidate).to_string());
        }
    }

    head_branch(repo)?.ok_or_else(|| Error::NoDefaultBranch(repo.to_path_buf()))
}

/// Add a worktree at `path` on `branch`, creating it from `base` if it is new.
///
/// The existing-branch case is not an edge case. Stopping a task keeps its
/// branch by default, so the ordinary "stop it, keep the work, start it again"
/// path comes back here with the branch already present — and `-b` on an
/// existing branch is a hard error.
pub fn worktree_add(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
    let mut args = vec![OsStr::new("worktree"), OsStr::new("add")];
    if !branch_exists(repo, branch)? {
        args.push(OsStr::new("-b"));
        args.push(OsStr::new(branch));
        args.push(path.as_os_str());
        args.push(OsStr::new(base));
    } else {
        // Checking out a branch that already exists: no base, or git would try
        // to reset it and discard whatever is on it.
        args.push(path.as_os_str());
        args.push(OsStr::new(branch));
    }
    run(repo, &args)?;
    Ok(())
}

/// Remove a worktree. `force` discards uncommitted changes in it.
pub fn worktree_remove(repo: &Path, path: &Path, force: bool) -> Result<()> {
    let mut args = vec![OsStr::new("worktree"), OsStr::new("remove")];
    if force {
        args.push(OsStr::new("--force"));
    }
    args.push(path.as_os_str());
    run(repo, &args)?;
    Ok(())
}

/// Drop administrative records for worktrees whose directories are gone.
pub fn worktree_prune(repo: &Path) -> Result<()> {
    run(repo, &["worktree", "prune"])?;
    Ok(())
}

/// Paths of every worktree attached to this repo, including the main one.
pub fn worktree_list(repo: &Path) -> Result<Vec<PathBuf>> {
    let out = run(repo, &["worktree", "list", "--porcelain"])?;
    Ok(out
        .lines()
        .filter_map(|line| line.strip_prefix("worktree "))
        .map(PathBuf::from)
        .collect())
}

/// One entry from `git status --porcelain`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusEntry {
    /// Index status character. `?` means untracked.
    pub index: char,
    /// Working-tree status character.
    pub worktree: char,
    /// Path relative to the repository root.
    pub path: String,
    /// Where a renamed file came from.
    pub original: Option<String>,
}

impl StatusEntry {
    pub fn is_untracked(&self) -> bool {
        self.index == '?' && self.worktree == '?'
    }

    /// Whether there is something in the index to commit.
    pub fn is_staged(&self) -> bool {
        !self.is_untracked() && self.index != ' '
    }

    /// Whether the working tree differs from the index.
    pub fn is_unstaged(&self) -> bool {
        self.is_untracked() || self.worktree != ' '
    }

    /// Whether the file has an unresolved merge conflict.
    ///
    /// The codes git documents as unmerged: `DD`, `AU`, `UD`, `UA`, `DU`, `AA`,
    /// `UU`. A `U` in either column is the reliable marker, plus the two
    /// same-letter pairs that have no `U` at all.
    pub fn is_unmerged(&self) -> bool {
        self.index == 'U'
            || self.worktree == 'U'
            || matches!((self.index, self.worktree), ('D', 'D') | ('A', 'A'))
    }
}

/// Everything changed in a worktree, staged and not.
///
/// Uses `-z` rather than the human format: git quotes and escapes paths
/// containing spaces, quotes, or newlines in the default output, and unquoting
/// that correctly is harder than reading NUL-separated records. `-uall` lists
/// files inside new directories individually rather than collapsing them to the
/// directory, which would otherwise hide every file an agent created.
pub fn status(repo: &Path) -> Result<Vec<StatusEntry>> {
    let out = run_raw(repo, &["status", "--porcelain=v1", "-z", "-uall"])?;
    Ok(parse_status(&out))
}

fn parse_status(raw: &str) -> Vec<StatusEntry> {
    let mut entries = Vec::new();
    // Records are NUL-separated; a rename spends two records, the second being
    // the original path.
    let mut records = raw.split('\0').filter(|r| !r.is_empty());
    while let Some(record) = records.next() {
        let mut chars = record.chars();
        let (Some(index), Some(worktree)) = (chars.next(), chars.next()) else {
            continue;
        };
        let path = record.get(3..).unwrap_or_default().to_string();
        // Either column can carry the rename. `git status` documents " R" as
        // "renamed in work tree", which `git add -N` produces routinely — and
        // the second record is consumed either way. Checking only the index
        // column left the origin path to be read as the next entry, so a
        // phantom file appeared in the review list, reported itself as staged,
        // and errored on every attempt to stage or unstage it.
        let original = if matches!(index, 'R' | 'C') || matches!(worktree, 'R' | 'C') {
            records.next().map(str::to_string)
        } else {
            None
        };
        entries.push(StatusEntry {
            index,
            worktree,
            path,
            original,
        });
    }
    entries
}

/// One exact path, as a pathspec git will not interpret.
///
/// Everything after `--` is still a *pathspec*, not a filename: `a?.txt`
/// matches `ab.txt` as well, and a backslash escapes the next character. A
/// filename is a literal, and saying so is the only way to mean it — otherwise
/// staging one file stages its neighbours, and asking for one file's diff can
/// return another file's.
fn literal(path: &str) -> String {
    format!(":(literal){path}")
}

/// Unified diff for a worktree. `staged` reads the index instead of the tree.
pub fn diff(repo: &Path, path: Option<&str>, staged: bool) -> Result<String> {
    let mut args: Vec<String> = vec!["diff".into()];
    if staged {
        args.push("--cached".into());
    }
    // Never colour or page: this is parsed, not read by a human here.
    args.extend(["--no-color".to_string(), "--no-ext-diff".to_string()]);
    if let Some(path) = path {
        args.push("--".into());
        args.push(literal(path));
    }
    let args: Vec<&str> = args.iter().map(String::as_str).collect();
    run_raw(repo, &args)
}

/// Diff of an untracked file against nothing, so new files are reviewable.
///
/// `git diff` ignores untracked files entirely; `--no-index` against
/// `/dev/null` produces the same shape as any other addition.
pub fn diff_untracked(repo: &Path, path: &str) -> Result<String> {
    // --no-index exits 1 whenever the files differ, which is always the case
    // here, so the exit status is ignored and stdout is what matters.
    let (_, out) = output(
        repo,
        &["diff", "--no-color", "--no-index", "--", "/dev/null", path],
    )?;
    Ok(out)
}

pub fn stage(repo: &Path, path: &str) -> Result<()> {
    run(repo, &["add", "--", &literal(path)])?;
    Ok(())
}

pub fn stage_all(repo: &Path) -> Result<()> {
    run(repo, &["add", "-A"])?;
    Ok(())
}

/// Remove a path from the index, leaving the working tree untouched.
pub fn unstage(repo: &Path, path: &str) -> Result<()> {
    run(repo, &["restore", "--staged", "--", &literal(path)])?;
    Ok(())
}

pub fn has_staged_changes(repo: &Path) -> Result<bool> {
    // Exits 1 when there are differences, which is not a failure here.
    Ok(!succeeds(repo, &["diff", "--cached", "--quiet"])?)
}

/// Commit the index. Returns the new commit's short hash.
pub fn commit(repo: &Path, message: &str) -> Result<String> {
    run(repo, &["commit", "-m", message])?;
    run(repo, &["rev-parse", "--short", "HEAD"])
}

/// Delete a local branch. `force` deletes even if unmerged.
pub fn branch_delete(repo: &Path, branch: &str, force: bool) -> Result<()> {
    let flag = if force { "-D" } else { "-d" };
    run(repo, &["branch", flag, branch])?;
    Ok(())
}

#[cfg(test)]
pub(crate) mod testing {
    use super::*;
    use std::path::Path;

    /// Initialise a repo with one commit on `default_branch`.
    pub fn init_repo(path: &Path, default_branch: &str) {
        std::fs::create_dir_all(path).expect("create repo dir");
        let init = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(["init", "-q", "-b", default_branch])
            .output()
            .expect("git init");
        assert!(init.status.success(), "git init failed");

        run(path, &["config", "user.email", "test@marver.invalid"]).unwrap();
        run(path, &["config", "user.name", "marver tests"]).unwrap();
        std::fs::write(path.join("README.md"), "# test\n").expect("write file");
        run(path, &["add", "."]).unwrap();
        run(path, &["commit", "-q", "-m", "initial"]).unwrap();
    }

    /// Point `refs/remotes/origin/HEAD` at a branch, as `git clone` would.
    pub fn set_origin_head(path: &Path, branch: &str) {
        run(
            path,
            &[
                "update-ref",
                &format!("refs/remotes/origin/{branch}"),
                "HEAD",
            ],
        )
        .unwrap();
        run(
            path,
            &[
                "symbolic-ref",
                "refs/remotes/origin/HEAD",
                &format!("refs/remotes/origin/{branch}"),
            ],
        )
        .unwrap();
    }
}

#[cfg(test)]
mod tests {
    use super::testing::*;
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn detects_a_repo() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("r");
        init_repo(&repo, "main");
        assert!(is_repo(&repo));

        let plain = tmp.path().join("plain");
        std::fs::create_dir_all(&plain).unwrap();
        assert!(!is_repo(&plain));
    }

    #[test]
    fn reads_the_checked_out_branch() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "trunk");
        assert_eq!(head_branch(tmp.path()).unwrap().as_deref(), Some("trunk"));
    }

    #[test]
    fn branch_existence_is_reported_not_errored() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        assert!(branch_exists(tmp.path(), "main").unwrap());
        assert!(!branch_exists(tmp.path(), "nope").unwrap());
    }

    #[test]
    fn default_branch_prefers_what_the_remote_advertises() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        // A repo whose remote says "develop" even though main exists locally.
        run(tmp.path(), &["branch", "develop"]).unwrap();
        set_origin_head(tmp.path(), "develop");

        assert_eq!(default_branch(tmp.path()).unwrap(), "develop");
    }

    #[test]
    fn default_branch_falls_back_to_conventional_names() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "master");
        // No origin/HEAD at all, as in a repo created locally.
        assert_eq!(default_branch(tmp.path()).unwrap(), "master");
    }

    #[test]
    fn default_branch_falls_back_to_head_for_unconventional_names() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "shipping");
        assert_eq!(default_branch(tmp.path()).unwrap(), "shipping");
    }

    #[test]
    fn a_stale_origin_head_does_not_win() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        // origin/HEAD points at a branch that no longer exists locally.
        run(
            tmp.path(),
            &["update-ref", "refs/remotes/origin/gone", "HEAD"],
        )
        .unwrap();
        run(
            tmp.path(),
            &[
                "symbolic-ref",
                "refs/remotes/origin/HEAD",
                "refs/remotes/origin/gone",
            ],
        )
        .unwrap();
        run(
            tmp.path(),
            &["update-ref", "-d", "refs/remotes/origin/gone"],
        )
        .unwrap();

        assert_eq!(
            default_branch(tmp.path()).unwrap(),
            "main",
            "should skip a default that has no local branch"
        );
    }

    #[test]
    fn adds_and_removes_a_worktree() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        init_repo(&repo, "main");
        let wt = tmp.path().join("wt");

        worktree_add(&repo, &wt, "feature", "main").unwrap();
        assert!(wt.join("README.md").exists());
        assert!(branch_exists(&repo, "feature").unwrap());
        assert!(
            worktree_list(&repo)
                .unwrap()
                .iter()
                .any(|p| p.ends_with("wt"))
        );

        worktree_remove(&repo, &wt, false).unwrap();
        assert!(!wt.exists());
        assert!(
            branch_exists(&repo, "feature").unwrap(),
            "removing a worktree must not delete its branch"
        );
    }

    #[test]
    fn a_dirty_worktree_needs_force() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        init_repo(&repo, "main");
        let wt = tmp.path().join("wt");
        worktree_add(&repo, &wt, "feature", "main").unwrap();
        std::fs::write(wt.join("README.md"), "changed\n").unwrap();

        assert!(worktree_remove(&repo, &wt, false).is_err());
        worktree_remove(&repo, &wt, true).unwrap();
        assert!(!wt.exists());
    }

    #[test]
    fn a_duplicate_branch_is_an_error() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        init_repo(&repo, "main");
        worktree_add(&repo, &tmp.path().join("a"), "feature", "main").unwrap();

        let err = worktree_add(&repo, &tmp.path().join("b"), "feature", "main").unwrap_err();
        assert!(matches!(err, Error::Failed { .. }));
    }

    #[test]
    fn failures_carry_stderr() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        let err = run(tmp.path(), &["rev-parse", "does-not-exist"]).unwrap_err();
        let Error::Failed { stderr, args, .. } = err else {
            panic!("expected a command failure");
        };
        assert!(!stderr.is_empty(), "stderr should be captured");
        assert!(args.contains("rev-parse"));
    }

    #[test]
    fn status_keeps_the_leading_space_that_encodes_the_index() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        std::fs::write(tmp.path().join("README.md"), "changed\n").unwrap();

        let entries = status(tmp.path()).unwrap();
        assert_eq!(entries.len(), 1);
        // " M README.md": trimming stdout would eat the leading space and
        // shift every path by one character.
        assert_eq!(entries[0].index, ' ');
        assert_eq!(entries[0].worktree, 'M');
        assert_eq!(entries[0].path, "README.md");
        assert!(entries[0].is_unstaged() && !entries[0].is_staged());
    }

    #[test]
    fn status_distinguishes_staged_untracked_and_renamed() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        std::fs::write(tmp.path().join("staged.txt"), "s\n").unwrap();
        stage(tmp.path(), "staged.txt").unwrap();
        std::fs::write(tmp.path().join("loose.txt"), "l\n").unwrap();
        run(tmp.path(), &["mv", "README.md", "RENAMED.md"]).unwrap();

        let entries = status(tmp.path()).unwrap();
        let by_path = |p: &str| entries.iter().find(|e| e.path == p).cloned();

        let staged = by_path("staged.txt").expect("staged.txt");
        assert_eq!(staged.index, 'A');
        assert!(staged.is_staged());

        let loose = by_path("loose.txt").expect("loose.txt");
        assert!(loose.is_untracked());
        assert!(loose.is_unstaged() && !loose.is_staged());

        let renamed = by_path("RENAMED.md").expect("RENAMED.md");
        assert_eq!(renamed.index, 'R');
        assert_eq!(
            renamed.original.as_deref(),
            Some("README.md"),
            "a rename spends two NUL records; the second is where it came from"
        );

        // Looking entries up by path cannot see an entry that should not be
        // there. A desync produces exactly that, so the count is asserted too.
        assert_eq!(entries.len(), 3, "no phantom entries: {entries:?}");
    }

    #[test]
    fn a_rename_in_the_work_tree_does_not_desync_the_parser() {
        // `git add -N` on a moved file gives " R", with the rename in the
        // *worktree* column rather than the index. It still spends two NUL
        // records. Checking only the index column left the origin path to be
        // read as the next entry: a phantom file appeared in the review list,
        // claimed to be staged, and errored on every attempt to touch it.
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        std::fs::write(tmp.path().join("old.txt"), "one\n").unwrap();
        stage_all(tmp.path()).unwrap();
        run(tmp.path(), &["commit", "-q", "-m", "seed"]).unwrap();

        std::fs::rename(tmp.path().join("old.txt"), tmp.path().join("new.txt")).unwrap();
        run(tmp.path(), &["add", "-N", "new.txt"]).unwrap();

        let entries = status(tmp.path()).unwrap();
        assert_eq!(entries.len(), 1, "one rename, one entry: {entries:?}");
        assert_eq!(entries[0].path, "new.txt");
        assert_eq!(entries[0].worktree, 'R');
        assert_eq!(entries[0].original.as_deref(), Some("old.txt"));
    }

    #[test]
    fn staged_changes_are_detectable_and_committable() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        assert!(!has_staged_changes(tmp.path()).unwrap());

        std::fs::write(tmp.path().join("new.txt"), "n\n").unwrap();
        stage(tmp.path(), "new.txt").unwrap();
        assert!(has_staged_changes(tmp.path()).unwrap());

        let hash = commit(tmp.path(), "add new").unwrap();
        assert!(!hash.is_empty());
        assert!(!has_staged_changes(tmp.path()).unwrap());
        assert_eq!(
            run(tmp.path(), &["log", "-1", "--pretty=%s"]).unwrap(),
            "add new"
        );
    }

    #[test]
    fn unstaging_leaves_the_file_on_disk() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        std::fs::write(tmp.path().join("README.md"), "changed\n").unwrap();
        stage(tmp.path(), "README.md").unwrap();
        unstage(tmp.path(), "README.md").unwrap();

        assert!(!has_staged_changes(tmp.path()).unwrap());
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("README.md")).unwrap(),
            "changed\n",
            "unstaging must not discard the work"
        );
    }

    #[test]
    fn a_glob_in_a_filename_stages_only_that_file() {
        // Everything after `--` is a pathspec, not a filename. Staging
        // `a?.txt` used to stage `ab.txt` and `ax.txt` along with it, so a
        // commit carried changes the user never reviewed.
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        for name in ["a?.txt", "ab.txt", "ax.txt"] {
            std::fs::write(tmp.path().join(name), "content\n").unwrap();
        }

        stage(tmp.path(), "a?.txt").unwrap();

        let staged: Vec<String> = status(tmp.path())
            .unwrap()
            .into_iter()
            .filter(|e| e.is_staged())
            .map(|e| e.path)
            .collect();
        assert_eq!(staged, ["a?.txt"], "only the named file may be staged");
    }

    #[test]
    fn a_glob_in_a_filename_unstages_only_that_file() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        for name in ["a*.txt", "ab.txt"] {
            std::fs::write(tmp.path().join(name), "content\n").unwrap();
        }
        stage_all(tmp.path()).unwrap();

        unstage(tmp.path(), "a*.txt").unwrap();

        let staged: Vec<String> = status(tmp.path())
            .unwrap()
            .into_iter()
            .filter(|e| e.is_staged())
            .map(|e| e.path)
            .collect();
        assert_eq!(staged, ["ab.txt"], "the neighbour must stay staged");
    }

    #[test]
    fn a_glob_in_a_filename_diffs_only_that_file() {
        // The worst of the three: the review screen takes the first file out of
        // the diff, so the user read one file's changes and committed another's.
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        for name in ["a?.txt", "a0.txt"] {
            std::fs::write(tmp.path().join(name), "before\n").unwrap();
        }
        stage_all(tmp.path()).unwrap();
        run(tmp.path(), &["commit", "-q", "-m", "seed"]).unwrap();
        std::fs::write(tmp.path().join("a?.txt"), "QUESTION\n").unwrap();
        std::fs::write(tmp.path().join("a0.txt"), "ZERO\n").unwrap();

        let out = diff(tmp.path(), Some("a?.txt"), false).unwrap();
        assert!(out.contains("QUESTION"), "wanted the named file: {out}");
        assert!(
            !out.contains("ZERO"),
            "another file's changes must not appear: {out}"
        );
    }

    #[test]
    fn branches_can_be_deleted() {
        let tmp = TempDir::new().unwrap();
        init_repo(tmp.path(), "main");
        run(tmp.path(), &["branch", "scratch"]).unwrap();
        branch_delete(tmp.path(), "scratch", true).unwrap();
        assert!(!branch_exists(tmp.path(), "scratch").unwrap());
    }
}