Skip to content

Commit 0c51c08

Browse files
authored
Fix to properly revert after aborting modify (#167)
* Add cherry-pick abort/quit/in-progress git primitives Introduce IsCherryPickInProgress() (detects .git/CHERRY_PICK_HEAD) and split the existing cherry-pick reset into two distinct operations: - CherryPickQuit() runs `git cherry-pick --quit`, clearing the sequencer state without touching the index (used to clear stale state before starting a fresh cherry-pick). - CherryPickAbort() now runs `git cherry-pick --abort`, which fully restores the working tree and index to the pre-cherry-pick state. The previous CherryPickAbort() ran --quit, which leaves an unmerged index and therefore cannot recover a conflicted fold-down. Integration tests cover the in-progress detection, the full abort restore, and the --quit-leaves-index behavior. * Fix modify --abort leaving a broken stack after a conflict When `gh stack modify` hit a rebase or cherry-pick conflict it saved state with phase "conflict" and told the user to run `gh stack modify --abort` to restore. But runModifyAbort had no case for PhaseConflict, so it fell into the default branch that merely printed "unexpected modify state phase" and deleted the state file without unwinding. The in-flight rebase/cherry-pick stayed active, branches were left partially rewritten, and the deleted state file also made --continue impossible: the stack was stuck in limbo. Fixes: - runModifyAbort now unwinds on PhaseConflict (same recovery as PhaseApplying), aborting the in-progress operation, resetting branch tips to their pre-modify SHAs, restoring stack metadata, and clearing state. - Unwind now also aborts an in-progress cherry-pick (fold-down conflicts), not just a rebase. Without this the restore checkouts would fail on the unmerged cherry-pick index. - ContinueApply now records a subsequent cascade-rebase conflict as ConflictType "rebase" instead of leaving a stale "cherry_pick", so the next --continue calls RebaseContinue rather than failing in CherryPickContinue. Adds coverage for the conflict-phase abort, pending-submit no-op abort, Unwind aborting an active cherry-pick, and the cherry-pick to rebase ConflictType transition. * Persist fold-branch removal when a post-fold cascade rebase conflicts ContinueApply removes the folded branch from the in-memory stack after a fold-down cherry-pick is resolved, but a subsequent cascade rebase conflict only saved the modify state file, not the stack metadata. On the next --continue the on-disk metadata (folded branch still present) was re-read, and because ConflictType is now "rebase" the fold-removal block was skipped, so the final save resurrected the folded branch as a phantom entry pointing at an orphaned tip. Persist the stack file alongside the state file on a cascade-rebase conflict, mirroring ApplyPlan's save-on-conflict, so the fold removal survives recovery. Adds an end-to-end regression test covering the fold-then-cascade-conflict path across two --continue calls.
1 parent ae5f889 commit 0c51c08

8 files changed

Lines changed: 601 additions & 83 deletions

File tree

‎cmd/modify.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,8 +219,12 @@ func runModifyAbort(cfg *config.Config) error {
219219
}
220220

221221
switch state.Phase {
222-
case modify.PhaseApplying:
223-
cfg.Printf("A modify session was interrupted during the apply phase")
222+
case modify.PhaseApplying, modify.PhaseConflict:
223+
if state.Phase == modify.PhaseConflict {
224+
cfg.Printf("Aborting the modify and discarding in-progress conflict resolution")
225+
} else {
226+
cfg.Printf("A modify session was interrupted during the apply phase")
227+
}
224228
cfg.Printf("Restoring stack to pre-modify state...")
225229
if err := modify.UnwindFromStateFile(cfg, gitDir); err != nil {
226230
cfg.Errorf("recovery failed: %s", err)

‎cmd/modify_test.go‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,3 +771,132 @@ func TestCheckModifyStateGuard_UnknownPhase(t *testing.T) {
771771
err := modify.CheckStateGuard(gitDir)
772772
assert.NoError(t, err, "guard only blocks on 'applying' phase")
773773
}
774+
775+
// ---------------------------------------------------------------------------
776+
// 6. runModifyAbort recovery
777+
// ---------------------------------------------------------------------------
778+
779+
// Regression test: aborting a modify that stopped at a conflict must actually
780+
// unwind the stack (abort the in-flight rebase, reset branch tips to their
781+
// pre-modify SHAs, restore metadata, clear state) — not fall into a default
782+
// branch that merely deletes the state file and strands the user.
783+
func TestRunModifyAbort_ConflictPhase_Unwinds(t *testing.T) {
784+
s := stack.Stack{
785+
Trunk: stack.BranchRef{Branch: "main"},
786+
Branches: []stack.BranchRef{
787+
{Branch: "A"},
788+
{Branch: "B"},
789+
},
790+
}
791+
792+
tmpDir := t.TempDir()
793+
writeStackFile(t, tmpDir, s)
794+
795+
meta, err := json.Marshal(s)
796+
require.NoError(t, err)
797+
798+
snapshot := modify.Snapshot{
799+
Branches: []modify.BranchSnapshot{
800+
{Name: "A", TipSHA: "sha-A-original", Position: 0},
801+
{Name: "B", TipSHA: "sha-B-original", Position: 1},
802+
},
803+
StackMetadata: meta,
804+
}
805+
806+
// The state ApplyPlan persists when a cascade rebase conflicts.
807+
state := &modify.StateFile{
808+
SchemaVersion: 1,
809+
StackName: "main",
810+
StackIndex: 0,
811+
Phase: modify.PhaseConflict,
812+
ConflictBranch: "B",
813+
ConflictType: "rebase",
814+
Snapshot: snapshot,
815+
}
816+
require.NoError(t, modify.SaveState(tmpDir, state))
817+
818+
var rebaseAborted bool
819+
var resetCalls []struct{ branch, sha string }
820+
current := ""
821+
mock := &git.MockOps{
822+
GitDirFn: func() (string, error) { return tmpDir, nil },
823+
IsRebaseInProgressFn: func() bool { return true },
824+
IsCherryPickInProgressFn: func() bool { return false },
825+
RebaseAbortFn: func() error { rebaseAborted = true; return nil },
826+
BranchExistsFn: func(string) bool { return true },
827+
CheckoutBranchFn: func(name string) error { current = name; return nil },
828+
ResetHardFn: func(sha string) error {
829+
resetCalls = append(resetCalls, struct{ branch, sha string }{current, sha})
830+
return nil
831+
},
832+
CreateBranchFn: func(string, string) error { return nil },
833+
}
834+
restore := git.SetOps(mock)
835+
defer restore()
836+
837+
cfg, _, errR := config.NewTestConfig()
838+
839+
err = runModifyAbort(cfg)
840+
841+
cfg.Out.Close()
842+
cfg.Err.Close()
843+
out, _ := io.ReadAll(errR)
844+
output := string(out)
845+
846+
require.NoError(t, err)
847+
848+
// The in-flight rebase must have been aborted.
849+
assert.True(t, rebaseAborted, "in-progress rebase should be aborted during recovery")
850+
851+
// The state file must be cleared because recovery ran (not left dangling,
852+
// and not deleted-without-unwind).
853+
assert.False(t, modify.StateExists(tmpDir), "state file should be cleared after a successful abort")
854+
855+
// Branch tips must be reset to their pre-modify snapshot SHAs.
856+
resetMap := map[string]string{}
857+
for _, r := range resetCalls {
858+
resetMap[r.branch] = r.sha
859+
}
860+
assert.Equal(t, "sha-A-original", resetMap["A"])
861+
assert.Equal(t, "sha-B-original", resetMap["B"])
862+
863+
// It must not fall into the old default branch.
864+
assert.NotContains(t, output, "unexpected modify state phase")
865+
assert.Contains(t, output, "Restoring stack to pre-modify state")
866+
}
867+
868+
// PendingSubmit abort is a no-op that guides the user to submit; it must not
869+
// try to unwind (the local changes already succeeded).
870+
func TestRunModifyAbort_PendingSubmit_NoUnwind(t *testing.T) {
871+
tmpDir := t.TempDir()
872+
873+
state := &modify.StateFile{
874+
SchemaVersion: 1,
875+
StackName: "main",
876+
StackIndex: 0,
877+
Phase: modify.PhasePendingSubmit,
878+
}
879+
require.NoError(t, modify.SaveState(tmpDir, state))
880+
881+
var resetCalled bool
882+
mock := &git.MockOps{
883+
GitDirFn: func() (string, error) { return tmpDir, nil },
884+
ResetHardFn: func(string) error { resetCalled = true; return nil },
885+
}
886+
restore := git.SetOps(mock)
887+
defer restore()
888+
889+
cfg, _, errR := config.NewTestConfig()
890+
891+
err := runModifyAbort(cfg)
892+
893+
cfg.Out.Close()
894+
cfg.Err.Close()
895+
out, _ := io.ReadAll(errR)
896+
output := string(out)
897+
898+
require.NoError(t, err)
899+
assert.False(t, resetCalled, "pending-submit abort must not unwind branches")
900+
assert.True(t, modify.StateExists(tmpDir), "pending-submit state should be preserved")
901+
assert.Contains(t, output, "gh stack submit")
902+
}

‎internal/git/git.go‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -399,10 +399,23 @@ func CherryPick(commits []string) error {
399399
return ops.CherryPick(commits)
400400
}
401401

402-
// CherryPickAbort clears any in-progress cherry-pick state.
403-
// Errors are silently ignored (no-op if no cherry-pick is in progress).
404-
func CherryPickAbort() {
405-
_ = ops.CherryPickAbort()
402+
// CherryPickQuit clears any in-progress cherry-pick sequencer state without
403+
// touching the working tree or index. Errors are silently ignored (no-op if no
404+
// cherry-pick is in progress).
405+
func CherryPickQuit() {
406+
_ = ops.CherryPickQuit()
407+
}
408+
409+
// CherryPickAbort cancels an in-progress cherry-pick, restoring the working
410+
// tree and index to the state before the cherry-pick began. Callers should
411+
// gate this with IsCherryPickInProgress, as it errors when none is in progress.
412+
func CherryPickAbort() error {
413+
return ops.CherryPickAbort()
414+
}
415+
416+
// IsCherryPickInProgress reports whether a cherry-pick is currently in progress.
417+
func IsCherryPickInProgress() bool {
418+
return ops.IsCherryPickInProgress()
406419
}
407420

408421
// CherryPickContinue continues an in-progress cherry-pick after conflicts are resolved.

‎internal/git/gitops.go‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,10 @@ type Ops interface {
6969
ValidateRefName(name string) error
7070
RenameBranch(oldName, newName string) error
7171
CherryPick(commits []string) error
72+
CherryPickQuit() error
7273
CherryPickAbort() error
7374
CherryPickContinue() error
75+
IsCherryPickInProgress() bool
7476
HasUncommittedChanges() (bool, error)
7577
LogMerges(base, head string) ([]CommitInfo, error)
7678
}
@@ -612,16 +614,40 @@ func (d *defaultOps) CherryPick(commits []string) error {
612614
return runSilent(args...)
613615
}
614616

615-
func (d *defaultOps) CherryPickAbort() error {
617+
// CherryPickQuit clears the in-progress cherry-pick sequencer state without
618+
// touching the working tree or index (git cherry-pick --quit). Used to clear
619+
// any stale sequencer state before starting a fresh cherry-pick.
620+
func (d *defaultOps) CherryPickQuit() error {
616621
return runSilent("cherry-pick", "--quit")
617622
}
618623

624+
// CherryPickAbort cancels an in-progress cherry-pick and restores the working
625+
// tree and index to the state before the cherry-pick began
626+
// (git cherry-pick --abort). Errors if no cherry-pick is in progress, so
627+
// callers should gate this with IsCherryPickInProgress.
628+
func (d *defaultOps) CherryPickAbort() error {
629+
return runSilent("cherry-pick", "--abort")
630+
}
631+
619632
func (d *defaultOps) CherryPickContinue() error {
620633
cmd := exec.Command("git", "cherry-pick", "--continue")
621634
cmd.Env = append(os.Environ(), "GIT_EDITOR=true")
622635
return cmd.Run()
623636
}
624637

638+
// IsCherryPickInProgress reports whether a cherry-pick is currently in progress
639+
// by checking for the CHERRY_PICK_HEAD marker in the git directory.
640+
func (d *defaultOps) IsCherryPickInProgress() bool {
641+
gitDir, err := GitDir()
642+
if err != nil {
643+
return false
644+
}
645+
if _, err := os.Stat(filepath.Join(gitDir, "CHERRY_PICK_HEAD")); err == nil {
646+
return true
647+
}
648+
return false
649+
}
650+
625651
func (d *defaultOps) HasUncommittedChanges() (bool, error) {
626652
out, err := run("status", "--porcelain")
627653
if err != nil {

‎internal/git/gitops_test.go‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -581,3 +581,89 @@ func TestIntegration_SaveAndGetRemote(t *testing.T) {
581581
_, err = GetSavedRemote()
582582
require.Error(t, err)
583583
}
584+
585+
// ---------------------------------------------------------------------------
586+
// Integration tests for cherry-pick in-progress detection and abort
587+
// ---------------------------------------------------------------------------
588+
589+
// A conflicting cherry-pick must be detected as in-progress, and CherryPickAbort
590+
// must fully restore the working tree/index so branch checkouts succeed again.
591+
// This underpins modify's --abort recovery for fold-down (cherry-pick) conflicts.
592+
func TestIntegration_CherryPickInProgressAndAbort(t *testing.T) {
593+
_, cloneDir := setupBareAndClone(t)
594+
restore := withGitDir(t, cloneDir)
595+
defer restore()
596+
597+
// Ensure runSilent-based git commands have a committer identity.
598+
gitExec(t, cloneDir, "config", "user.name", "Test")
599+
gitExec(t, cloneDir, "config", "user.email", "test@test.com")
600+
601+
// feature edits conflict.txt one way; main edits it another way.
602+
gitExec(t, cloneDir, "checkout", "-b", "feature")
603+
writeFile(t, cloneDir, "conflict.txt", "feature change\n")
604+
gitExec(t, cloneDir, "add", ".")
605+
gitExec(t, cloneDir, "commit", "-m", "feature edit")
606+
featureSHA := gitExec(t, cloneDir, "rev-parse", "feature")
607+
608+
gitExec(t, cloneDir, "checkout", "main")
609+
writeFile(t, cloneDir, "conflict.txt", "main change\n")
610+
gitExec(t, cloneDir, "add", ".")
611+
gitExec(t, cloneDir, "commit", "-m", "main edit")
612+
613+
// No cherry-pick in progress before we start.
614+
assert.False(t, IsCherryPickInProgress(), "no cherry-pick should be in progress initially")
615+
616+
// Cherry-picking feature onto main conflicts.
617+
err := CherryPick([]string{featureSHA})
618+
require.Error(t, err, "cherry-pick should conflict")
619+
assert.True(t, IsCherryPickInProgress(), "cherry-pick should be in progress after a conflict")
620+
621+
// While mid-conflict, a plain checkout must fail (unmerged index).
622+
_, coErr := gitExecMayFail(t, cloneDir, "checkout", "feature")
623+
require.Error(t, coErr, "checkout should fail while cherry-pick index is unmerged")
624+
625+
// Aborting must fully restore: no longer in progress, clean tree, checkout works.
626+
require.NoError(t, CherryPickAbort())
627+
assert.False(t, IsCherryPickInProgress(), "cherry-pick should not be in progress after abort")
628+
629+
status, err := gitExecMayFail(t, cloneDir, "status", "--porcelain")
630+
require.NoError(t, err)
631+
assert.Empty(t, status, "working tree should be clean after abort")
632+
633+
_, coErr = gitExecMayFail(t, cloneDir, "checkout", "feature")
634+
require.NoError(t, coErr, "checkout should succeed after abort restores a clean index")
635+
}
636+
637+
// CherryPickQuit clears the sequencer state but intentionally leaves the index
638+
// as-is, so a plain checkout still fails. This documents why Unwind uses the
639+
// full --abort rather than --quit.
640+
func TestIntegration_CherryPickQuitLeavesIndexUnmerged(t *testing.T) {
641+
_, cloneDir := setupBareAndClone(t)
642+
restore := withGitDir(t, cloneDir)
643+
defer restore()
644+
645+
gitExec(t, cloneDir, "config", "user.name", "Test")
646+
gitExec(t, cloneDir, "config", "user.email", "test@test.com")
647+
648+
gitExec(t, cloneDir, "checkout", "-b", "feature")
649+
writeFile(t, cloneDir, "conflict.txt", "feature change\n")
650+
gitExec(t, cloneDir, "add", ".")
651+
gitExec(t, cloneDir, "commit", "-m", "feature edit")
652+
featureSHA := gitExec(t, cloneDir, "rev-parse", "feature")
653+
654+
gitExec(t, cloneDir, "checkout", "main")
655+
writeFile(t, cloneDir, "conflict.txt", "main change\n")
656+
gitExec(t, cloneDir, "add", ".")
657+
gitExec(t, cloneDir, "commit", "-m", "main edit")
658+
659+
require.Error(t, CherryPick([]string{featureSHA}))
660+
require.True(t, IsCherryPickInProgress())
661+
662+
// --quit clears sequencer state (no longer "in progress") ...
663+
CherryPickQuit()
664+
assert.False(t, IsCherryPickInProgress(), "quit should clear cherry-pick sequencer state")
665+
666+
// ... but leaves the unmerged index behind, so checkout still fails.
667+
_, coErr := gitExecMayFail(t, cloneDir, "checkout", "feature")
668+
require.Error(t, coErr, "checkout should still fail after --quit because the index is unmerged")
669+
}

0 commit comments

Comments
 (0)