git-queue 0.1.1

Manage queues of dependent branches and their numbered pull requests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
//! Thin wrappers over the `git` executable.
//!
//! We shell out rather than link a git library: rebase/conflict semantics are
//! then exactly what the user would get by hand, and the dependency surface
//! stays tiny.

use anyhow::{anyhow, bail, Context, Result};
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

/// Env var set on child git processes while git-queue is requeueing, so our
/// own hooks can detect the reentry and skip (avoiding infinite recursion).
pub(crate) const GUARD_ENV: &str = "GIT_QUEUE_IN_REQUEUE";

/// Run `git <args>` and capture trimmed stdout. Errors if git exits non-zero.
pub(crate) fn out(args: &[&str]) -> Result<String> {
    let output = Command::new("git")
        .args(args)
        .output()
        .with_context(|| format!("failed to spawn `git {}`", args.join(" ")))?;
    if !output.status.success() {
        bail!(
            "`git {}` failed:\n{}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Run `git <args>` inheriting stdio, so progress (rebase, push) is visible.
/// Errors if git exits non-zero.
pub(crate) fn run(args: &[&str]) -> Result<()> {
    let status = Command::new("git")
        .args(args)
        .status()
        .with_context(|| format!("failed to spawn `git {}`", args.join(" ")))?;
    if !status.success() {
        bail!("`git {}` exited with {}", args.join(" "), status);
    }
    Ok(())
}

/// Run `git <args>`, returning whether it exited zero. Never errors on
/// non-zero (used for boolean probes like `merge-base --is-ancestor`).
pub(crate) fn ok(args: &[&str]) -> bool {
    Command::new("git")
        .args(args)
        .output()
        .is_ok_and(|o| o.status.success())
}

/// Fail early with a friendly message if we are not inside a git work tree.
pub(crate) fn ensure_repo() -> Result<()> {
    if !ok(&["rev-parse", "--git-dir"]) {
        bail!("not inside a git repository (run this from within your repo)");
    }
    Ok(())
}

pub(crate) fn current_branch() -> Result<String> {
    let b = out(&["rev-parse", "--abbrev-ref", "HEAD"])?;
    if b == "HEAD" {
        bail!("you are in a detached HEAD state; check out a branch first");
    }
    Ok(b)
}

pub(crate) fn rev_parse(rev: &str) -> Result<String> {
    out(&["rev-parse", "--verify", "--quiet", rev])
        .map_err(|_| anyhow!("cannot resolve revision `{rev}`"))
}

pub(crate) fn branch_exists(name: &str) -> bool {
    ok(&[
        "show-ref",
        "--verify",
        "--quiet",
        &format!("refs/heads/{name}"),
    ])
}

/// Is `ancestor` an ancestor of `descendant`?
pub(crate) fn is_ancestor(ancestor: &str, descendant: &str) -> bool {
    ok(&["merge-base", "--is-ancestor", ancestor, descendant])
}

pub(crate) fn merge_base(a: &str, b: &str) -> Result<String> {
    out(&["merge-base", a, b])
}

pub(crate) fn checkout(branch: &str) -> Result<()> {
    run(&["checkout", branch])
}

pub(crate) fn checkout_quiet(branch: &str) -> Result<()> {
    run(&["checkout", "-q", branch])
}

/// Snap index and worktree to HEAD. Discards local changes — callers must
/// ensure the worktree was clean before the refs moved under it.
pub(crate) fn reset_hard_head() -> Result<()> {
    run(&["reset", "-q", "--hard"])
}

/// Create `name` at `start_point` without checking it out.
pub(crate) fn create_branch(name: &str, start_point: &str) -> Result<()> {
    run(&["branch", name, start_point])
}

/// Subject line of the tip commit of `branch`.
pub(crate) fn tip_subject(branch: &str) -> Result<String> {
    out(&["log", "-1", "--format=%s", branch])
}

/// Number of commits in `base..branch` (i.e. unique to `branch`).
pub(crate) fn ahead_count(base: &str, branch: &str) -> Result<usize> {
    let s = out(&["rev-list", "--count", &format!("{base}..{branch}")])?;
    Ok(s.parse().unwrap_or(0))
}

/// Commits in `base..tip`, oldest first, as `(full_sha, subject)` pairs.
/// Commits in `base..tip`, oldest first: `(full sha, Stable-Commit-Id?, subject)`.
pub(crate) fn commits_between_with_ids(
    base: &str,
    tip: &str,
) -> Result<Vec<(String, Option<String>, String)>> {
    let raw = out(&[
        "log",
        "--reverse",
        &format!(
            "--format=%H%x09%(trailers:key={},valueonly,separator=%x20)%x09%s",
            crate::ident::TRAILER
        ),
        &format!("{base}..{tip}"),
    ])?;
    Ok(raw
        .lines()
        .filter_map(|l| {
            // `out()` trims the whole capture, so a trailing commit with an
            // empty subject loses its tab(s); parse defensively (missing
            // fields → empty) so such a commit is never silently dropped.
            let mut it = l.splitn(3, '\t');
            let sha = it.next()?.to_string();
            if sha.is_empty() {
                return None;
            }
            let id = it
                .next()
                .and_then(|s| s.split_whitespace().next())
                .map(str::to_string);
            let subject = it.next().unwrap_or("").to_string();
            Some((sha, id, subject))
        })
        .collect())
}

/// The patch a single commit introduces — its own diff against its parent,
/// with no colour and no message header. Handles a root commit (no parent).
/// Used by the TUI diff pane.
pub(crate) fn commit_diff(rev: &str) -> Result<String> {
    out(&["show", "--no-color", "--format=", "--patch", rev])
}

/// The full commit message of `rev` (subject + body + trailers). Used by the
/// TUI message pane.
pub(crate) fn commit_message(rev: &str) -> Result<String> {
    out(&["show", "--no-patch", "--format=%B", rev])
}

/// git's canonical empty tree object — the parent stand-in for a root commit.
const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

/// A commit's tree object sha.
pub(crate) fn tree_of(rev: &str) -> Result<String> {
    out(&["rev-parse", "--verify", &format!("{rev}^{{tree}}")])
}

/// The content of `path` at `rev`, or an empty string if it does not exist
/// there (e.g. a file added by `rev`, read at its parent).
pub(crate) fn file_at(rev: &str, path: &str) -> String {
    out(&["show", &format!("{rev}:{path}")]).unwrap_or_default()
}

/// Write `content` as a loose blob and return its sha.
fn hash_object(content: &str) -> Result<String> {
    let mut cmd = Command::new("git")
        .args(["hash-object", "-w", "--stdin"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .context("failed to spawn `git hash-object`")?;
    cmd.stdin
        .take()
        .ok_or_else(|| anyhow!("no stdin pipe for `git hash-object`"))?
        .write_all(content.as_bytes())
        .context("failed to write blob content")?;
    let out = cmd.wait_with_output()?;
    if !out.status.success() {
        bail!("`git hash-object` failed");
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// Build a new tree from `base_tree`, applying `changes`: `Some(content)` sets
/// a regular file (mode 100644), `None` removes it. Uses a temporary index so
/// the real index is untouched.
pub(crate) fn build_tree(base_tree: &str, changes: &[(String, Option<String>)]) -> Result<String> {
    let git_dir = out(&["rev-parse", "--git-dir"])?;
    let index_path = std::path::Path::new(&git_dir).join("git-queue-split-index");
    let index = index_path.to_string_lossy().to_string();
    let run_indexed = |args: &[&str]| -> Result<()> {
        let mut c = Command::new("git");
        c.args(args).env("GIT_INDEX_FILE", &index);
        quiet_git(&mut c);
        let status = c.status().context("failed to spawn `git`")?;
        if !status.success() {
            bail!("`git {}` failed", args.join(" "));
        }
        Ok(())
    };
    let result = (|| {
        run_indexed(&["read-tree", base_tree])?;
        for (path, content) in changes {
            match content {
                Some(text) => {
                    let blob = hash_object(text)?;
                    run_indexed(&[
                        "update-index",
                        "--add",
                        "--cacheinfo",
                        &format!("100644,{blob},{path}"),
                    ])?;
                }
                None => {
                    run_indexed(&["update-index", "--force-remove", path])?;
                }
            }
        }
        // write-tree with the temp index; capture its stdout.
        let mut c = Command::new("git");
        c.args(["write-tree"])
            .env("GIT_INDEX_FILE", &index)
            .env(GUARD_ENV, "1")
            .stderr(Stdio::null());
        let out = c.output().context("failed to spawn `git write-tree`")?;
        if !out.status.success() {
            bail!("`git write-tree` failed");
        }
        Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
    })();
    let _ = std::fs::remove_file(&index_path);
    result
}

/// Create a commit object from `tree` with parent `parent` and message
/// `message`, returning its sha. No ref is moved.
pub(crate) fn commit_tree(tree: &str, parent: &str, message: &str) -> Result<String> {
    let mut cmd = Command::new("git")
        .args(["commit-tree", tree, "-p", parent])
        .env(GUARD_ENV, "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .context("failed to spawn `git commit-tree`")?;
    cmd.stdin
        .take()
        .ok_or_else(|| anyhow!("no stdin pipe for `git commit-tree`"))?
        .write_all(message.as_bytes())
        .context("failed to write commit message")?;
    let out = cmd.wait_with_output()?;
    if !out.status.success() {
        bail!("`git commit-tree` failed");
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// Cherry-pick `sha` onto `base` (detaching HEAD there first), returning the
/// new commit's sha. Used to replay a split commit's descendants — which apply
/// cleanly because the new tip has the same tree. Aborts and errors on the
/// unexpected conflict.
pub(crate) fn cherry_pick_onto(base: &str, sha: &str) -> Result<String> {
    run(&["checkout", "-q", "--detach", base])?;
    let mut pick = Command::new("git");
    pick.args(["cherry-pick", "--allow-empty", sha]);
    quiet_git(&mut pick);
    let status = pick.status().context("failed to spawn `git cherry-pick`")?;
    if !status.success() {
        if cherry_pick_in_progress() {
            let _ = Command::new("git")
                .args(["cherry-pick", "--abort"])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
        bail!("replaying a split descendant unexpectedly conflicted");
    }
    out(&["rev-parse", "HEAD"])
}

/// True if `rev` introduces no change: its tree equals its (first) parent's,
/// or — for a root commit — the empty tree.
pub(crate) fn commit_is_empty(rev: &str) -> bool {
    let parent = out(&["rev-parse", "--verify", "--quiet", &format!("{rev}^")])
        .unwrap_or_else(|_| EMPTY_TREE.to_string());
    ok(&["diff", "--quiet", &parent, rev])
}

pub(crate) fn commits_between(base: &str, tip: &str) -> Result<Vec<(String, String)>> {
    let raw = out(&[
        "log",
        "--reverse",
        "--format=%H%x09%s",
        &format!("{base}..{tip}"),
    ])?;
    Ok(raw
        .lines()
        .filter_map(|l| {
            let (sha, subject) = l.split_once('\t')?;
            Some((sha.to_string(), subject.to_string()))
        })
        .collect())
}

/// True if the index has no staged changes and no tracked file is modified
/// (untracked files are allowed).
pub(crate) fn tracked_clean() -> bool {
    out(&["status", "--porcelain", "--untracked-files=no"]).is_ok_and(|s| s.is_empty())
}

/// True if the work tree and index are clean.
pub(crate) fn worktree_clean() -> bool {
    out(&["status", "--porcelain"]).is_ok_and(|s| s.is_empty())
}

/// Detach HEAD at its current commit (so no branch ref is "checked out").
pub(crate) fn detach_head() -> Result<()> {
    run(&["checkout", "-q", "--detach"])
}

/// True if a rebase (merge or apply backend) is currently in progress.
pub(crate) fn rebase_in_progress() -> bool {
    let dir = match out(&["rev-parse", "--git-dir"]) {
        Ok(d) => PathBuf::from(d),
        Err(_) => return false,
    };
    dir.join("rebase-merge").exists() || dir.join("rebase-apply").exists()
}

/// Fetch with `--prune`: stale remote-tracking refs for branches deleted on
/// the remote (e.g. auto-deleted when their PR merged) must not survive, or
/// sync would "pull" from ghost branches and push with dead leases.
pub(crate) fn fetch(remote: &str) -> Result<()> {
    run(&["fetch", "--prune", remote])
}

/// SHA of a remote-tracking branch `<remote>/<branch>`, if it exists.
pub(crate) fn remote_branch(remote: &str, branch: &str) -> Option<String> {
    let r = format!("{remote}/{branch}");
    out(&["rev-parse", "--verify", "--quiet", &r])
        .ok()
        .filter(|s| !s.is_empty())
}

/// Fast-forward the *currently checked-out* branch to `target` (updates the
/// work tree). Fails if it isn't a fast-forward.
pub(crate) fn merge_ff_only(target: &str) -> Result<()> {
    run(&["merge", "--ff-only", target])
}

/// Force-with-lease push, setting upstream. Shows git's own progress output.
pub(crate) fn push(remote: &str, branch: &str) -> Result<()> {
    run(&["push", "--force-with-lease", "-u", remote, branch])
}

/// Move a branch ref to `sha` without checking it out.
pub(crate) fn force_ref(branch: &str, sha: &str) -> Result<()> {
    run(&["update-ref", &format!("refs/heads/{branch}"), sha])
}

/// True if there are staged changes in the index.
pub(crate) fn staged_changes() -> bool {
    // `git diff --cached --quiet` exits 1 when there is something staged.
    !ok(&["diff", "--cached", "--quiet"])
}

/// The https URL of the GitHub repo behind `remote`, parsed from its URL
/// (ssh or https form), if it is a GitHub remote.
pub(crate) fn github_repo_url(remote: &str) -> Option<String> {
    let url = out(&["remote", "get-url", remote]).ok()?;
    let path = url
        .strip_prefix("git@github.com:")
        .or_else(|| url.strip_prefix("ssh://git@github.com/"))
        .or_else(|| url.strip_prefix("https://github.com/"))?;
    let path = path
        .strip_suffix(".git")
        .unwrap_or(path)
        .trim_end_matches('/');
    Some(format!("https://github.com/{path}"))
}

/// Paths in `rev`'s tree that contain conflict markers.
pub(crate) fn conflict_files(rev: &str) -> Vec<String> {
    out(&["grep", "-I", "-l", "-e", "^<<<<<<< ", rev])
        .map(|raw| {
            raw.lines()
                .filter_map(|l| l.split_once(':').map(|(_, p)| p.to_string()))
                .collect()
        })
        .unwrap_or_default()
}

/// True if the tree at `rev` contains textual conflict markers.
pub(crate) fn has_conflict_markers(rev: &str) -> bool {
    ok(&["grep", "-I", "-l", "-e", "^<<<<<<< ", rev])
}

/// Make a normal commit on the current branch.
pub(crate) fn commit(message: Option<&str>) -> Result<()> {
    // Suppress our own hooks during the internal commit; git-queue does the
    // requeue itself right after.
    let mut cmd = Command::new("git");
    cmd.env(GUARD_ENV, "1");
    match message {
        Some(m) => cmd.args(["commit", "-m", m]),
        None => cmd.args(["commit"]),
    };
    let status = cmd.status().context("failed to spawn `git commit`")?;
    if !status.success() {
        bail!("`git commit` failed");
    }
    Ok(())
}

/// `git history fixup <commit>` — fold staged changes into `commit`, atomically
/// updating every descendant branch. Returns `true` if it aborted because the
/// rewrite would conflict with a descendant (git history is atomic and cannot
/// persist markers). Any other failure is an error.
pub(crate) fn history_fixup(commit: &str) -> Result<bool> {
    let out = Command::new("git")
        .args(["history", "fixup", commit])
        .env(GUARD_ENV, "1")
        .output()
        .context("failed to spawn `git history fixup`")?;
    if out.status.success() {
        return Ok(false);
    }
    let err = String::from_utf8_lossy(&out.stderr);
    if err.contains("conflict") {
        return Ok(true);
    }
    bail!("`git history fixup` failed:\n{}", err.trim());
}

/// `git history reword <commit>` — rewrite a commit message (opens the editor),
/// atomically updating descendants. Returns `true` on conflict abort.
pub(crate) fn history_reword(commit: &str) -> Result<bool> {
    let status = Command::new("git")
        .args(["history", "reword", commit])
        .env(GUARD_ENV, "1")
        .status()
        .context("failed to spawn `git history reword`")?;
    // reword can only conflict via replay of descendants; a non-zero exit with
    // an unchanged repo means it aborted. Treat non-zero as conflict abort.
    Ok(!status.success())
}

/// Outcome of a `git replay` requeue attempt.
pub(crate) enum Replayed {
    Applied,
    /// Replay could not apply cleanly (typically a conflict); message is stderr.
    Failed(String),
}

/// Requeue every branch contained in `ranges` onto `onto` in one operation via
/// `git replay --contained`, applying the emitted ref updates atomically with
/// `git update-ref --stdin`. No worktree is touched.
pub(crate) fn replay_requeue(onto: &str, ranges: &[String]) -> Result<Replayed> {
    let mut args: Vec<String> = vec![
        "replay".into(),
        "--onto".into(),
        onto.into(),
        "--contained".into(),
    ];
    args.extend(ranges.iter().cloned());
    let argrefs: Vec<&str> = args.iter().map(std::string::String::as_str).collect();

    let out = Command::new("git")
        .args(&argrefs)
        .env(GUARD_ENV, "1")
        .output()
        .context("failed to spawn `git replay`")?;
    if !out.status.success() {
        return Ok(Replayed::Failed(
            String::from_utf8_lossy(&out.stderr).trim().to_string(),
        ));
    }
    if out.stdout.iter().all(u8::is_ascii_whitespace) {
        return Ok(Replayed::Applied); // nothing to update
    }

    let mut child = Command::new("git")
        .args(["update-ref", "--stdin"])
        .env(GUARD_ENV, "1")
        .stdin(Stdio::piped())
        .spawn()
        .context("failed to spawn `git update-ref --stdin`")?;
    child
        .stdin
        .take()
        .ok_or_else(|| anyhow!("no stdin pipe for `git update-ref --stdin`"))?
        .write_all(&out.stdout)
        .context("writing replay plan to update-ref")?;
    if !child.wait()?.success() {
        bail!("failed to apply replay ref updates");
    }
    Ok(Replayed::Applied)
}

/// Fallback requeue of a single branch that NEVER leaves an interactive
/// conflict state: on conflict it stages the marker-filled files, commits them,
/// and continues, so it always finishes. `--update-refs` moves any intermediate
/// branch refs in the rebased range. Detect persisted markers afterwards with
/// [`has_conflict_markers`].
pub(crate) fn rebase_persist(onto: &str, upstream: &str, branch: &str) -> Result<()> {
    let mut initial = Command::new("git");
    initial.args([
        "-c",
        "core.editor=true",
        "rebase",
        "--update-refs",
        "--onto",
        onto,
        upstream,
        branch,
    ]);
    quiet_git(&mut initial);
    let _ = initial.status().context("failed to spawn `git rebase`")?;
    drive_rebase_to_completion(branch)
}

/// Rewrite the whole line `base..top_branch` in place via an interactive
/// rebase whose todo we edit programmatically: the picks for `move_shas` are
/// relocated to directly follow `after` (or to the very front when `None`).
/// `--update-refs` carries every intermediate branch ref along, and conflicts
/// are persisted as markers exactly like [`rebase_persist`].
pub(crate) fn rebase_reorder_persist(
    base: &str,
    top_branch: &str,
    move_shas: &[String],
    after: Option<&str>,
) -> Result<()> {
    let exe = std::env::current_exe().context("cannot locate the git-queue executable")?;
    let mut initial = Command::new("git");
    initial.args([
        "-c",
        "core.editor=true",
        "rebase",
        "-i",
        "--update-refs",
        "--empty=keep",
        "--onto",
        base,
        base,
        top_branch,
    ]);
    quiet_git(&mut initial);
    // Our own binary rewrites the todo; the spec travels via the environment.
    initial
        .env(
            "GIT_SEQUENCE_EDITOR",
            format!("\"{}\" reorder-todo", exe.display()),
        )
        .env("GIT_QUEUE_MOVE_SHAS", move_shas.join(" "))
        .env("GIT_QUEUE_MOVE_AFTER", after.unwrap_or(""));
    let _ = initial.status().context("failed to spawn `git rebase`")?;
    drive_rebase_to_completion(top_branch)
}

/// The outcome of a TUI history-rewriting rebase.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Rewrite {
    /// The rebase finished; the line was rewritten.
    Clean,
    /// The rebase stopped at a conflict, leaving the standard mid-rebase state
    /// in place for the user to resolve (or for the caller to `--abort`).
    Conflict,
}

/// Rewrite the whole line `base..top_branch` with an interactive rebase driven
/// by a **caller-supplied todo** (`pick`/`update-ref` lines). The todo is
/// installed via a `cp`-based `GIT_SEQUENCE_EDITOR`, so this needs no external
/// helper binary and works when called in-process (unlike the CLI's
/// `reorder-todo` path, which re-invokes git-queue). Unlike
/// [`rebase_reorder_persist`] it **stops** at the first conflict (ADR-0002: the
/// TUI leaves the standard mid-rebase state rather than persisting markers).
pub(crate) fn rebase_with_todo_stop(base: &str, top_branch: &str, todo: &str) -> Result<Rewrite> {
    let git_dir = out(&["rev-parse", "--git-dir"])?;
    let todo_path = std::path::Path::new(&git_dir).join("git-queue-todo");
    std::fs::write(&todo_path, todo).context("failed to stage the rebase todo")?;

    // git invokes `$GIT_SEQUENCE_EDITOR <todofile>`, so `cp <our-todo>` becomes
    // `cp <our-todo> <todofile>` — overwriting git's generated todo with ours.
    let editor = format!("cp {}", shell_single_quote(&todo_path.to_string_lossy()));
    let mut cmd = Command::new("git");
    cmd.args([
        "rebase",
        "-i",
        "--update-refs",
        "--empty=keep",
        "--onto",
        base,
        base,
        top_branch,
    ]);
    cmd.stdout(Stdio::null())
        .stderr(Stdio::null())
        .env("GIT_EDITOR", "true")
        .env(GUARD_ENV, "1")
        .env("GIT_SEQUENCE_EDITOR", editor);
    let status = cmd.status().context("failed to spawn `git rebase`")?;
    let _ = std::fs::remove_file(&todo_path);
    if status.success() {
        Ok(Rewrite::Clean)
    } else if rebase_in_progress() {
        Ok(Rewrite::Conflict)
    } else {
        bail!("the rebase could not start (no rebase in progress)");
    }
}

/// Single-quote a string for a POSIX shell (git runs the sequence editor via
/// the shell). Embedded single quotes are escaped as `'\''`.
fn shell_single_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

/// Rewrite `base..top_branch` with a caller-supplied todo (one commit marked
/// `reword`) and supply the new commit message from `message`. Both are
/// installed via `cp`-based editors, so no helper binary is needed. A reword is
/// message-only and cannot conflict; a stop is treated as an error and aborted.
pub(crate) fn rebase_with_todo_message(
    base: &str,
    top_branch: &str,
    todo: &str,
    message: &str,
) -> Result<()> {
    let git_dir = out(&["rev-parse", "--git-dir"])?;
    let dir = std::path::Path::new(&git_dir);
    let todo_path = dir.join("git-queue-todo");
    let msg_path = dir.join("git-queue-msg");
    std::fs::write(&todo_path, todo).context("failed to stage the rebase todo")?;
    std::fs::write(&msg_path, message).context("failed to stage the commit message")?;

    let seq_editor = format!("cp {}", shell_single_quote(&todo_path.to_string_lossy()));
    let msg_editor = format!("cp {}", shell_single_quote(&msg_path.to_string_lossy()));
    let mut cmd = Command::new("git");
    cmd.args([
        "rebase",
        "-i",
        "--update-refs",
        "--onto",
        base,
        base,
        top_branch,
    ]);
    cmd.stdout(Stdio::null())
        .stderr(Stdio::null())
        .env(GUARD_ENV, "1")
        .env("GIT_SEQUENCE_EDITOR", seq_editor)
        .env("GIT_EDITOR", msg_editor);
    let status = cmd.status().context("failed to spawn `git rebase`")?;
    let _ = std::fs::remove_file(&todo_path);
    let _ = std::fs::remove_file(&msg_path);
    if status.success() {
        return Ok(());
    }
    if rebase_in_progress() {
        let _ = rebase_abort();
    }
    bail!("the reword did not apply cleanly");
}

/// Like [`rebase_with_todo_stop`] but also supplies the combined commit message
/// (for a todo containing a `squash`). Stops at a conflict (ADR-0002): on the
/// resolve path the user's own git supplies the message when they continue.
pub(crate) fn rebase_squash_stop(
    base: &str,
    top_branch: &str,
    todo: &str,
    message: &str,
) -> Result<Rewrite> {
    let git_dir = out(&["rev-parse", "--git-dir"])?;
    let dir = std::path::Path::new(&git_dir);
    let todo_path = dir.join("git-queue-todo");
    let msg_path = dir.join("git-queue-msg");
    std::fs::write(&todo_path, todo).context("failed to stage the rebase todo")?;
    std::fs::write(&msg_path, message).context("failed to stage the commit message")?;

    let seq_editor = format!("cp {}", shell_single_quote(&todo_path.to_string_lossy()));
    let msg_editor = format!("cp {}", shell_single_quote(&msg_path.to_string_lossy()));
    let mut cmd = Command::new("git");
    cmd.args([
        "rebase",
        "-i",
        "--update-refs",
        "--empty=keep",
        "--onto",
        base,
        base,
        top_branch,
    ]);
    cmd.stdout(Stdio::null())
        .stderr(Stdio::null())
        .env(GUARD_ENV, "1")
        .env("GIT_SEQUENCE_EDITOR", seq_editor)
        .env("GIT_EDITOR", msg_editor);
    let status = cmd.status().context("failed to spawn `git rebase`")?;
    let _ = std::fs::remove_file(&todo_path);
    let _ = std::fs::remove_file(&msg_path);
    if status.success() {
        Ok(Rewrite::Clean)
    } else if rebase_in_progress() {
        Ok(Rewrite::Conflict)
    } else {
        bail!("the squash could not start (no rebase in progress)");
    }
}

/// Abort an in-progress rebase, returning refs to their pre-rebase state.
pub(crate) fn rebase_abort() -> Result<()> {
    let mut cmd = Command::new("git");
    cmd.args(["rebase", "--abort"]);
    quiet_git(&mut cmd);
    let status = cmd
        .status()
        .context("failed to spawn `git rebase --abort`")?;
    if !status.success() {
        bail!("`git rebase --abort` failed");
    }
    Ok(())
}

/// Apply `shas` (front-first) on top of `branch` with conflict markers
/// persisted, leaving HEAD on `branch`. The cherry-pick analogue of
/// [`rebase_persist`].
pub(crate) fn cherry_pick_persist(branch: &str, shas: &[String]) -> Result<()> {
    run(&["checkout", "-q", branch])?;
    for sha in shas {
        let mut pick = Command::new("git");
        pick.args(["cherry-pick", "--allow-empty", sha]);
        quiet_git(&mut pick);
        let _ = pick.status().context("failed to spawn `git cherry-pick`")?;
        drive_cherry_pick_to_completion(branch)?;
    }
    Ok(())
}

fn cherry_pick_in_progress() -> bool {
    out(&["rev-parse", "--git-path", "CHERRY_PICK_HEAD"])
        .is_ok_and(|p| std::path::Path::new(&p).exists())
}

fn drive_cherry_pick_to_completion(what: &str) -> Result<()> {
    let mut guard = 0;
    while cherry_pick_in_progress() {
        guard += 1;
        if guard > 5000 {
            let _ = Command::new("git")
                .args(["cherry-pick", "--abort"])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
            bail!("cherry-pick onto `{what}` did not converge; aborted");
        }
        let mut add = Command::new("git");
        add.args(["add", "-A"]);
        quiet_git(&mut add);
        let _ = add.status();
        let sub: &[&str] = if staged_changes() {
            &["cherry-pick", "--continue"]
        } else {
            &["cherry-pick", "--skip"]
        };
        let mut step = Command::new("git");
        step.args(sub);
        quiet_git(&mut step);
        let _ = step.status();
    }
    Ok(())
}

/// Rewrite `upstream..branch` in place, stamping a `Stable-Commit-Id` trailer onto
/// the commits in `shas`: an interactive rebase whose todo marks those picks
/// as `reword`, with our own binary as the message editor (it appends the
/// trailer and exits). Content is untouched, so no conflicts can arise.
pub(crate) fn rebase_stamp_ids(upstream: &str, branch: &str, shas: &[String]) -> Result<()> {
    let exe = std::env::current_exe().context("cannot locate the git-queue executable")?;
    let exe = exe.display();
    let mut initial = Command::new("git");
    initial.args(["rebase", "-i", "--update-refs", upstream, branch]);
    initial
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .env(GUARD_ENV, "1")
        .env("GIT_SEQUENCE_EDITOR", format!("\"{exe}\" stamp-todo"))
        .env("GIT_EDITOR", format!("\"{exe}\" add-queue-id"))
        .env("GIT_QUEUE_REWORD_SHAS", shas.join(" "))
        .env("GIT_QUEUE_STAMP_ALL", "1");
    let _ = initial.status().context("failed to spawn `git rebase`")?;
    drive_rebase_to_completion(branch)
}

/// Silence git's rebase chatter (conflict hints etc.) — it would contradict
/// the "it succeeded" outcome. Our loud banner is the user-facing signal.
fn quiet_git(c: &mut Command) {
    c.stdout(Stdio::null())
        .stderr(Stdio::null())
        .env("GIT_EDITOR", "true")
        .env(GUARD_ENV, "1");
}

/// Keep stepping an in-progress rebase, staging conflict markers as the
/// "resolution" of each stop, until it finishes.
fn drive_rebase_to_completion(what: &str) -> Result<()> {
    let mut guard = 0;
    while rebase_in_progress() {
        guard += 1;
        if guard > 5000 {
            let _ = Command::new("git")
                .args(["rebase", "--abort"])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
            bail!("requeue of `{what}` did not converge; aborted the rebase");
        }
        // Stage the conflict markers as the "resolution".
        let mut add = Command::new("git");
        add.args(["add", "-A"]);
        quiet_git(&mut add);
        let _ = add.status();

        let sub: &[&str] = if staged_changes() {
            &["rebase", "--continue"]
        } else {
            &["rebase", "--skip"]
        };
        let mut step = Command::new("git");
        step.args(sub);
        quiet_git(&mut step);
        let _ = step.status();
    }
    Ok(())
}

/// Concatenated commit messages (`%B`) of `range` — used to find Stable-Commit-Ids
/// embedded in squash-merge bodies.
pub(crate) fn log_messages(range: &str) -> Result<String> {
    out(&["log", "--format=%B", range])
}

/// Append a `Stable-Commit-Id` trailer to the commit-message file at `path`, unless
/// one is already present. `git interpret-trailers` handles placement.
pub(crate) fn add_trailer_to_file(path: &std::path::Path, id: &str) -> Result<()> {
    run(&[
        "interpret-trailers",
        "--if-exists",
        "doNothing",
        "--trailer",
        &format!("{}: {id}", crate::ident::TRAILER),
        "--in-place",
        &path.to_string_lossy(),
    ])
}

/// The `Stable-Commit-Id` of each commit in `range`, front-first: `(sha, id?)`.
pub(crate) fn queue_ids(range: &str) -> Result<Vec<(String, Option<String>)>> {
    let raw = out(&[
        "log",
        "--reverse",
        &format!(
            "--format=%H%x09%(trailers:key={},valueonly,separator=%x20)",
            crate::ident::TRAILER
        ),
        range,
    ])?;
    Ok(raw
        .lines()
        .map(|l| {
            let (sha, id) = l.split_once('\t').unwrap_or((l, ""));
            let id = id.split_whitespace().next().map(str::to_string);
            (sha.to_string(), id)
        })
        .collect())
}

/// Commits in `range`, NEWEST first, as `(Stable-Commit-Id?, subject)` pairs.
pub(crate) fn commits_with_ids(range: &str) -> Result<Vec<(Option<String>, String)>> {
    // The leading `|` anchors each record: `out()` trims the whole capture,
    // which would otherwise eat the leading tab of an id-less first commit.
    let raw = out(&[
        "log",
        &format!(
            "--format=|%(trailers:key={},valueonly,separator=%x20)%x09%s",
            crate::ident::TRAILER
        ),
        range,
    ])?;
    Ok(raw
        .lines()
        .filter_map(|l| {
            let (id, subject) = l.strip_prefix('|')?.split_once('\t')?;
            let id = id.split_whitespace().next().map(str::to_string);
            Some((id, subject.to_string()))
        })
        .collect())
}

/// The `Stable-Commit-Id` of `rev`'s commit message, if any.
pub(crate) fn queue_id_of(rev: &str) -> Option<String> {
    out(&[
        "log",
        "-1",
        &format!(
            "--format=%(trailers:key={},valueonly,separator=%x20)",
            crate::ident::TRAILER
        ),
        rev,
    ])
    .ok()
    .and_then(|s| s.split_whitespace().next().map(str::to_string))
}

/// Rewrite HEAD's message to add a `Stable-Commit-Id` trailer (content untouched).
pub(crate) fn amend_head_add_queue_id(id: &str) -> Result<()> {
    let msg = out(&["log", "-1", "--format=%B", "HEAD"])?;
    let tmp = std::env::temp_dir().join(format!("git-queue-msg-{}", std::process::id()));
    std::fs::write(&tmp, msg + "\n").context("writing temp commit message")?;
    add_trailer_to_file(&tmp, id)?;
    let res = run(&[
        "commit",
        "--amend",
        "--no-verify",
        "--allow-empty",
        "-q",
        "-F",
        &tmp.to_string_lossy(),
    ]);
    let _ = std::fs::remove_file(&tmp);
    res
}

/// Patch-equivalence of `head` commits against `upstream`, via `git cherry`:
/// the SHAs (front-first) of commits in `head` whose patch is NOT already
/// present in `upstream`.
pub(crate) fn cherry_fresh(upstream: &str, head: &str) -> Result<Vec<String>> {
    let raw = out(&["cherry", upstream, head])?;
    Ok(raw
        .lines()
        .filter_map(|l| l.strip_prefix("+ ").map(str::to_string))
        .collect())
}

/// True if `sha` is a position `branch` has previously been at, per the
/// branch's reflog. Used to tell "the remote has new work" apart from "the
/// remote is just our own stale, pre-rewrite state".
pub(crate) fn was_previous_position(branch: &str, sha: &str) -> bool {
    out(&[
        "reflog",
        "show",
        "--format=%H",
        &format!("refs/heads/{branch}"),
    ])
    .is_ok_and(|log| log.lines().any(|l| l == sha))
}

/// The remote-tracking ref for the trunk, e.g. `origin/main`, if it exists.
pub(crate) fn remote_trunk(remote: &str, trunk: &str) -> Option<String> {
    let r = format!("{remote}/{trunk}");
    if ok(&[
        "show-ref",
        "--verify",
        "--quiet",
        &format!("refs/remotes/{r}"),
    ]) {
        Some(r)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]
    #[test]
    fn github_urls_parse_from_both_remote_forms() {
        // Pure parsing check via the same logic, exercised on literals.
        for (input, want) in [
            (
                "git@github.com:freshtonic/git-queue.git",
                "https://github.com/freshtonic/git-queue",
            ),
            (
                "https://github.com/freshtonic/git-queue",
                "https://github.com/freshtonic/git-queue",
            ),
            ("ssh://git@github.com/o/r.git", "https://github.com/o/r"),
        ] {
            let path = input
                .strip_prefix("git@github.com:")
                .or_else(|| input.strip_prefix("ssh://git@github.com/"))
                .or_else(|| input.strip_prefix("https://github.com/"))
                .unwrap();
            let path = path
                .strip_suffix(".git")
                .unwrap_or(path)
                .trim_end_matches('/');
            assert_eq!(format!("https://github.com/{path}"), want);
        }
    }
}