Skip to content

Commit 4cb3f22

Browse files
committed
switch to nearest surviving branch
1 parent efa0a9e commit 4cb3f22

6 files changed

Lines changed: 187 additions & 30 deletions

File tree

‎cmd/sync.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ func runSync(cfg *config.Config, opts *syncOptions) error {
116116
// resolve a divergence, before rebasing and pushing so pulled branches
117117
// participate in the normal flow. Best-effort for stacks tracked on the
118118
// remote; a no-op otherwise.
119-
reconcileRes, err := reconcileRemoteStack(cfg, sf, s, gitDir, remote)
119+
reconcileRes, err := reconcileRemoteStack(cfg, sf, s, currentBranch, gitDir, remote)
120120
if err != nil {
121121
if errors.Is(err, errInterrupt) {
122122
return ErrSilent
@@ -133,6 +133,11 @@ func runSync(cfg *config.Config, opts *syncOptions) error {
133133
cfg.Infof("Sync aborted — no changes were made")
134134
return nil
135135
}
136+
// Reconciling "use remote as source of truth" may have moved us off a
137+
// branch that is no longer in the stack, so re-read the current branch.
138+
if cb, cbErr := git.CurrentBranch(); cbErr == nil {
139+
currentBranch = cb
140+
}
136141

137142
// --- Step 2: Fast-forward trunk ---
138143
trunk := s.Trunk.Branch

‎cmd/sync_test.go‎

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2182,8 +2182,70 @@ func TestSync_Divergent_UseRemote(t *testing.T) {
21822182
assert.Equal(t, "9", sf.Stacks[0].ID)
21832183
}
21842184

2185-
// TestSync_Divergent_UseRemote_DirtyBlocked refuses to replace the local stack
2186-
// when the working tree has uncommitted changes.
2185+
func TestNearestBranchAfterReplace(t *testing.T) {
2186+
newStack := func(branches ...string) *stack.Stack {
2187+
s := &stack.Stack{Trunk: stack.BranchRef{Branch: "main"}}
2188+
for _, b := range branches {
2189+
s.Branches = append(s.Branches, stack.BranchRef{Branch: b})
2190+
}
2191+
return s
2192+
}
2193+
tests := []struct {
2194+
name string
2195+
old []string
2196+
current string
2197+
newBranches []string
2198+
want string
2199+
}{
2200+
{"still in stack", []string{"b1", "b2", "b3"}, "b2", []string{"b1", "b2", "b4"}, "b2"},
2201+
{"dropped top prefers below", []string{"b1", "b2", "b3"}, "b3", []string{"b1", "b2", "b4"}, "b2"},
2202+
{"dropped middle prefers above", []string{"b1", "b2", "b3"}, "b2", []string{"b1", "b3"}, "b3"},
2203+
{"on trunk stays put", []string{"b1", "b2"}, "main", []string{"b1", "b2", "b4"}, "main"},
2204+
{"none survive falls back to top", []string{"x", "y", "z"}, "y", []string{"a", "b", "c"}, "c"},
2205+
{"empty new stack falls back to trunk", []string{"b1"}, "b1", nil, "main"},
2206+
}
2207+
for _, tt := range tests {
2208+
t.Run(tt.name, func(t *testing.T) {
2209+
assert.Equal(t, tt.want, nearestBranchAfterReplace(tt.old, tt.current, newStack(tt.newBranches...)))
2210+
})
2211+
}
2212+
}
2213+
2214+
// TestSync_Divergent_UseRemote_SwitchesOffDroppedBranch verifies that when the
2215+
// user is on a branch that the remote stack no longer contains, replacing the
2216+
// local stack with the remote moves them to the nearest surviving branch.
2217+
func TestSync_Divergent_UseRemote_SwitchesOffDroppedBranch(t *testing.T) {
2218+
tmpDir := t.TempDir()
2219+
divergentStack(t, tmpDir) // local [b1,b2,b3], remote [b1,b2,b4]; user on b3 (dropped)
2220+
2221+
ghMock := divergentRemoteMock()
2222+
current := "b3"
2223+
var checkouts []string
2224+
mock := newSyncMockNoRebase(tmpDir, "b3")
2225+
mock.CurrentBranchFn = func() (string, error) { return current, nil }
2226+
mock.CheckoutBranchFn = func(name string) error { current = name; checkouts = append(checkouts, name); return nil }
2227+
mock.BranchExistsFn = func(name string) bool { return name != "b4" }
2228+
mock.CreateBranchFn = func(string, string) error { return nil }
2229+
mock.SetUpstreamTrackingFn = func(string, string) error { return nil }
2230+
mock.HasUncommittedChangesFn = func() (bool, error) { return false, nil }
2231+
2232+
output, err := runSyncCfg(t, mock, func(cfg *config.Config) {
2233+
cfg.GitHubClientOverride = ghMock
2234+
cfg.ForceInteractive = true
2235+
cfg.SelectFn = func(_, _ string, _ []string) (int, error) { return 0, nil }
2236+
})
2237+
require.NoError(t, err)
2238+
2239+
assert.Contains(t, checkouts, "b2", "should switch off dropped branch b3 to nearest surviving branch b2")
2240+
assert.NotContains(t, checkouts, "b3", "should never check the dropped branch back out")
2241+
assert.Contains(t, output, "Switched to b2")
2242+
assert.Contains(t, output, "no longer in the stack")
2243+
assert.Equal(t, "b2", current, "should end on b2, not the dropped b3")
2244+
2245+
sf, err := stack.Load(tmpDir)
2246+
require.NoError(t, err)
2247+
assert.Equal(t, []string{"b1", "b2", "b4"}, sf.Stacks[0].BranchNames())
2248+
}
21872249
func TestSync_Divergent_UseRemote_DirtyBlocked(t *testing.T) {
21882250
tmpDir := t.TempDir()
21892251
divergentStack(t, tmpDir)

‎cmd/utils.go‎

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"errors"
55
"fmt"
66
"net/url"
7+
"slices"
78
"strconv"
89
"strings"
910
"sync"
@@ -1229,7 +1230,7 @@ const (
12291230
// a missing client, stacked PRs being unavailable, or any API error causes it
12301231
// to skip so the rest of sync still runs. Untracked stacks (s.ID == "") are
12311232
// left to the syncStack/reconcileUntrackedStack path.
1232-
func reconcileRemoteStack(cfg *config.Config, sf *stack.StackFile, s *stack.Stack, gitDir, remote string) (remoteReconcileResult, error) {
1233+
func reconcileRemoteStack(cfg *config.Config, sf *stack.StackFile, s *stack.Stack, currentBranch, gitDir, remote string) (remoteReconcileResult, error) {
12331234
var res remoteReconcileResult
12341235

12351236
if s.ID == "" {
@@ -1276,7 +1277,7 @@ func reconcileRemoteStack(cfg *config.Config, sf *stack.StackFile, s *stack.Stac
12761277
case remoteStackCleanAhead:
12771278
return pullRemoteAdditions(cfg, sf, s, gitDir, remote, prs)
12781279
default:
1279-
return resolveStackDivergence(cfg, client, sf, s, gitDir, remote, prs, remoteActive)
1280+
return resolveStackDivergence(cfg, client, sf, s, currentBranch, gitDir, remote, prs, remoteActive)
12801281
}
12811282
}
12821283

@@ -1414,7 +1415,7 @@ func pullRemoteAdditions(cfg *config.Config, sf *stack.StackFile, s *stack.Stack
14141415
// from the remote (neither is a prefix of the other). In an interactive
14151416
// terminal it prompts the user to resolve it; otherwise (or when the user
14161417
// cancels) it aborts the sync so nothing is pushed or updated.
1417-
func resolveStackDivergence(cfg *config.Config, client github.ClientOps, sf *stack.StackFile, s *stack.Stack, gitDir, remote string, prs []*github.PullRequest, remoteActive []string) (remoteReconcileResult, error) {
1418+
func resolveStackDivergence(cfg *config.Config, client github.ClientOps, sf *stack.StackFile, s *stack.Stack, currentBranch, gitDir, remote string, prs []*github.PullRequest, remoteActive []string) (remoteReconcileResult, error) {
14181419
cfg.Printf("")
14191420
cfg.Warningf("Your local stack has diverged from the stack on GitHub")
14201421
cfg.Printf(" Local: %s", s.DisplayChain())
@@ -1454,7 +1455,7 @@ func resolveStackDivergence(cfg *config.Config, client github.ClientOps, sf *sta
14541455

14551456
switch selected {
14561457
case 0:
1457-
return resolveDivergenceUseRemote(cfg, sf, s, gitDir, remote, prs)
1458+
return resolveDivergenceUseRemote(cfg, sf, s, currentBranch, gitDir, remote, prs)
14581459
case 1:
14591460
return resolveDivergenceUseLocal(cfg, client, sf, s, gitDir)
14601461
case 2:
@@ -1470,7 +1471,7 @@ func resolveStackDivergence(cfg *config.Config, client github.ClientOps, sf *sta
14701471
// destructive to stack tracking). Local-only branches remain as git refs but
14711472
// are no longer part of the stack. Returns the rebuilt stack pointer so the
14721473
// caller can continue with it (importRemoteStack reslices StackFile.Stacks).
1473-
func resolveDivergenceUseRemote(cfg *config.Config, sf *stack.StackFile, s *stack.Stack, gitDir, remote string, prs []*github.PullRequest) (remoteReconcileResult, error) {
1474+
func resolveDivergenceUseRemote(cfg *config.Config, sf *stack.StackFile, s *stack.Stack, currentBranch, gitDir, remote string, prs []*github.PullRequest) (remoteReconcileResult, error) {
14741475
var res remoteReconcileResult
14751476

14761477
if dirty, err := git.HasUncommittedChanges(); err == nil && dirty {
@@ -1481,13 +1482,26 @@ func resolveDivergenceUseRemote(cfg *config.Config, sf *stack.StackFile, s *stac
14811482

14821483
trunk := s.Trunk.Branch
14831484
remoteStackID := s.ID
1485+
oldBranches := s.BranchNames()
14841486

14851487
removeLocalStack(sf, s)
14861488
newStack, err := importRemoteStack(cfg, sf, gitDir, remote, trunk, prs, remoteStackID)
14871489
if err != nil {
14881490
res.skipStackObjectSync = true
14891491
return res, err
14901492
}
1493+
1494+
// If the user was on a branch that the remote stack no longer contains,
1495+
// move them to the nearest surviving branch so they don't end up detached
1496+
// from the stack.
1497+
if target := nearestBranchAfterReplace(oldBranches, currentBranch, newStack); target != currentBranch {
1498+
if err := git.CheckoutBranch(target); err != nil {
1499+
cfg.Warningf("Failed to switch from %s to %s: %v", currentBranch, target, err)
1500+
} else {
1501+
cfg.Printf("Switched to %s (original branch %s is no longer in the stack)", target, currentBranch)
1502+
}
1503+
}
1504+
14911505
if err := stack.Save(gitDir, sf); err != nil {
14921506
res.skipStackObjectSync = true
14931507
return res, handleSaveError(cfg, err)
@@ -1498,6 +1512,33 @@ func resolveDivergenceUseRemote(cfg *config.Config, sf *stack.StackFile, s *stac
14981512
return res, nil
14991513
}
15001514

1515+
// nearestBranchAfterReplace decides which branch to check out after the local
1516+
// stack has been replaced with the remote version. If currentBranch still
1517+
// exists in newStack (or the user was on the trunk / a non-stack branch), it is
1518+
// returned unchanged. Otherwise it delegates to stack.NearestSurvivingBranch to
1519+
// pick the nearest branch from the pre-replacement ordering (neighbor above,
1520+
// then below), falling back to the top of the new stack, or the trunk if the new
1521+
// stack has no branches. Mirrors the checkout behavior of `gh stack modify`.
1522+
func nearestBranchAfterReplace(oldBranches []string, currentBranch string, newStack *stack.Stack) string {
1523+
// Still in the new stack, or never a stack branch (e.g. the trunk): stay put.
1524+
if newStack.IndexOf(currentBranch) >= 0 || slices.Index(oldBranches, currentBranch) < 0 {
1525+
return currentBranch
1526+
}
1527+
1528+
if nearest := stack.NearestSurvivingBranch(oldBranches, currentBranch, func(name string) bool {
1529+
return newStack.IndexOf(name) >= 0
1530+
}); nearest != "" {
1531+
return nearest
1532+
}
1533+
1534+
// A dropped stack branch with no surviving neighbor — fall back to the top
1535+
// of the new stack, then the trunk.
1536+
if len(newStack.Branches) > 0 {
1537+
return newStack.Branches[len(newStack.Branches)-1].Branch
1538+
}
1539+
return newStack.Trunk.Branch
1540+
}
1541+
15011542
// resolveDivergenceUseLocal makes the remote match the local stack by deleting
15021543
// the diverged remote stack object and clearing the local ID. The normal
15031544
// syncStack step then recreates the stack from the local PR list (when two or

‎internal/modify/apply.go‎

Lines changed: 7 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -754,32 +754,17 @@ func adjacentSnapshotBranch(snapshot Snapshot, target string, direction int) str
754754
// still exists in the stack. Prefers the branch above (higher index), then below.
755755
// resolvedName translates snapshot names through any renames from the same operation.
756756
func nearestSurvivingBranch(snapshot Snapshot, dropped string, s *stack.Stack, resolvedName func(string) string) string {
757-
pos := -1
757+
order := make([]string, len(snapshot.Branches))
758758
for i, bs := range snapshot.Branches {
759-
if bs.Name == dropped {
760-
pos = i
761-
break
762-
}
759+
order[i] = bs.Name
763760
}
764-
if pos < 0 {
761+
raw := stack.NearestSurvivingBranch(order, dropped, func(name string) bool {
762+
return s.IndexOf(resolvedName(name)) >= 0
763+
})
764+
if raw == "" {
765765
return ""
766766
}
767-
768-
// Search above first (higher indices = away from trunk)
769-
for i := pos + 1; i < len(snapshot.Branches); i++ {
770-
name := resolvedName(snapshot.Branches[i].Name)
771-
if s.IndexOf(name) >= 0 {
772-
return name
773-
}
774-
}
775-
// Then below (lower indices = toward trunk)
776-
for i := pos - 1; i >= 0; i-- {
777-
name := resolvedName(snapshot.Branches[i].Name)
778-
if s.IndexOf(name) >= 0 {
779-
return name
780-
}
781-
}
782-
return ""
767+
return resolvedName(raw)
783768
}
784769

785770
// ContinueApply resumes a modify operation after the user resolves a rebase conflict.

‎internal/stack/stack.go‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,39 @@ func (s *Stack) IsFullyMerged() bool {
193193
return len(s.Branches) > 0
194194
}
195195

196+
// NearestSurvivingBranch returns the branch nearest to target within the ordered
197+
// branch-name list `order` for which `survives` reports true, preferring the
198+
// neighbor above (later in the slice, away from the trunk) and then the neighbor
199+
// below (earlier in the slice, toward the trunk).
200+
//
201+
// It returns "" when target is not present in order, or when no other branch in
202+
// order survives. Callers layer their own fallback and any name translation
203+
// around this search. It is shared by the checkout-branch selection in
204+
// `gh stack modify` and `gh stack sync`.
205+
func NearestSurvivingBranch(order []string, target string, survives func(string) bool) string {
206+
pos := -1
207+
for i, name := range order {
208+
if name == target {
209+
pos = i
210+
break
211+
}
212+
}
213+
if pos < 0 {
214+
return ""
215+
}
216+
for i := pos + 1; i < len(order); i++ {
217+
if survives(order[i]) {
218+
return order[i]
219+
}
220+
}
221+
for i := pos - 1; i >= 0; i-- {
222+
if survives(order[i]) {
223+
return order[i]
224+
}
225+
}
226+
return ""
227+
}
228+
196229
// StackFile represents the JSON file stored in .git/gh-stack.
197230
type StackFile struct {
198231
SchemaVersion int `json:"schemaVersion"`

‎internal/stack/stack_test.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,3 +625,34 @@ func TestIsFullyMerged_NotAffectedByQueued(t *testing.T) {
625625
assert.False(t, s.IsFullyMerged())
626626
})
627627
}
628+
629+
func TestNearestSurvivingBranch(t *testing.T) {
630+
// survivesIn returns a predicate reporting membership in the given set.
631+
survivesIn := func(names ...string) func(string) bool {
632+
set := make(map[string]bool, len(names))
633+
for _, n := range names {
634+
set[n] = true
635+
}
636+
return func(name string) bool { return set[name] }
637+
}
638+
639+
tests := []struct {
640+
name string
641+
order []string
642+
target string
643+
survives func(string) bool
644+
want string
645+
}{
646+
{"prefers neighbor above", []string{"a", "b", "c"}, "b", survivesIn("a", "c"), "c"},
647+
{"falls to neighbor below", []string{"a", "b", "c"}, "c", survivesIn("a", "b"), "b"},
648+
{"skips dead neighbors above", []string{"a", "b", "c", "d"}, "b", survivesIn("a", "d"), "d"},
649+
{"target not in order", []string{"a", "b"}, "z", survivesIn("a", "b"), ""},
650+
{"no other survives", []string{"a", "b", "c"}, "b", survivesIn("b"), ""},
651+
{"empty order", nil, "a", survivesIn("a"), ""},
652+
}
653+
for _, tt := range tests {
654+
t.Run(tt.name, func(t *testing.T) {
655+
assert.Equal(t, tt.want, NearestSurvivingBranch(tt.order, tt.target, tt.survives))
656+
})
657+
}
658+
}

0 commit comments

Comments
 (0)