Skip to content

Commit 5880261

Browse files
committed
Adopt equivalent server-rebased branches
Snapshot tracking refs before fetch so rebase and sync can distinguish remote rewrites from local work. Adopt only correctly stacked, same-order range-diff-equivalent commits, and stop safely when both sides changed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 30bcbf2a-5ef1-4bdb-a0fc-618294ae8ded
1 parent c7144b4 commit 5880261

13 files changed

Lines changed: 740 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ Pull from remote and do a cascading rebase across the stack.
193193
gh stack rebase [flags] [branch]
194194
```
195195

196-
Fetches the latest changes from `origin`, then ensures each branch in the stack has the tip of the previous layer in its commit history. Rebases branches in order from trunk upward. If a branch's PR has been merged, the rebase automatically switches to `--onto` mode to correctly replay commits on top of the merge target.
196+
Fetches the latest changes from `origin`, then ensures each branch in the stack has the tip of the previous layer in its commit history. Rebases branches in order from trunk upward. If GitHub already rebased the stack, matching rewritten remote tips are adopted locally when your branches have not changed since the previous fetch and contain the same ordered commits. If a branch's PR has been merged, the rebase automatically switches to `--onto` mode to correctly replay commits on top of the merge target.
197197

198198
If a rebase conflict occurs, the operation pauses and prints the conflicted files with line numbers. Resolve the conflicts, stage with `git add`, and continue with `--continue`. To undo the entire rebase, use `--abort` to restore all branches to their pre-rebase state.
199199

@@ -321,6 +321,8 @@ Performs a synchronization of the entire stack:
321321

322322
A clean remote-ahead update (PRs added on top of your local stack) is pulled down automatically without prompting, so `sync` is safe to run in automation. Sync only prompts when the stacks have truly diverged.
323323

324+
If GitHub already rebased the same stack branches, `sync` adopts those rewritten remote tips when your local tips have not changed since the previous fetch and `git range-diff` confirms the same commits in the same order. If local and remote commits both changed, sync stops rather than overwriting either side.
325+
324326
#### Diverged stacks
325327

326328
When neither stack is a clean prefix of the other — for example, you added a branch locally while separate PRs were added to the same stack on GitHub — sync cannot merge the two automatically. In an interactive terminal it offers three choices:

‎cmd/rebase.go‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ func RebaseCmd(cfg *config.Config) *cobra.Command {
5555
Ensures that each branch in the stack has the tip of the previous
5656
layer in its commit history, rebasing if necessary.
5757
58+
If the stack was already rebased on the remote, matching rewritten branch tips
59+
are adopted locally when the local branches have not changed since the previous
60+
fetch and the ordered commit ranges are equivalent.
61+
5862
Use --no-trunk to skip fetching and rebasing with the trunk branch.
5963
Only the inter-branch rebases are performed (branch 2 onto branch 1,
6064
branch 3 onto branch 2, etc.).`,
@@ -146,11 +150,24 @@ func runRebase(cfg *config.Config, opts *rebaseOptions) error {
146150
}
147151

148152
// Fast-forward stack branches that are behind their remote tracking branch.
153+
branchSnapshots := snapshotBranchTips(s, remote)
149154
if err := git.FetchBranches(remote, activeBranchNames(s)); err != nil {
150155
cfg.Errorf("failed to fetch stack branches from %s: %v", remote, err)
151156
return ErrSilent
152157
}
158+
adopted, err := adoptRemoteRebasedBranches(cfg, s, remote, currentBranch, branchSnapshots)
159+
if err != nil {
160+
cfg.Errorf("%v", err)
161+
return ErrSilent
162+
}
153163
fastForwardBranches(cfg, s, remote, currentBranch)
164+
if len(adopted) > 0 && !stackNeedsRebase(s, trunk.Ref) {
165+
updateBaseSHAs(s)
166+
_ = syncStackPRs(cfg, s)
167+
stack.SaveNonBlocking(gitDir, sf)
168+
cfg.Printf("Local branches now match the rebased stack on %s", remote)
169+
return nil
170+
}
154171
}
155172

156173
cfg.Printf("Stack detected: %s", s.DisplayChain())

‎cmd/rebase_test.go‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2258,3 +2258,103 @@ func TestIntegration_AdoptedBranchRebasesFromCommonAncestor(t *testing.T) {
22582258
assert.Equal(t, []string{"imported two", "imported one", "parent commit"}, subjects)
22592259
require.NoError(t, issue250GitMayFail(t, cloneDir, "merge-base", "--is-ancestor", "parent", "imported"))
22602260
}
2261+
2262+
type serverRebasedRepo struct {
2263+
dir string
2264+
gitDir string
2265+
oldImported string
2266+
newImported string
2267+
parentSHA string
2268+
}
2269+
2270+
func setupServerRebasedRepo(t *testing.T) serverRebasedRepo {
2271+
t.Helper()
2272+
remoteDir := filepath.Join(t.TempDir(), "remote.git")
2273+
localDir := filepath.Join(t.TempDir(), "local")
2274+
serverDir := filepath.Join(t.TempDir(), "server")
2275+
2276+
issue250Git(t, ".", "-c", "safe.bareRepository=all", "init", "--bare", "-b", "main", remoteDir)
2277+
issue250Git(t, ".", "clone", remoteDir, localDir)
2278+
issue250Git(t, localDir, "config", "user.name", "Test")
2279+
issue250Git(t, localDir, "config", "user.email", "test@example.com")
2280+
2281+
issue250WriteFile(t, localDir, "base.txt", "base\n")
2282+
issue250Git(t, localDir, "add", ".")
2283+
issue250Git(t, localDir, "commit", "-m", "base")
2284+
issue250Git(t, localDir, "push", "-u", "origin", "main")
2285+
mainSHA := issue250Git(t, localDir, "rev-parse", "main")
2286+
2287+
issue250Git(t, localDir, "checkout", "-b", "parent")
2288+
issue250WriteFile(t, localDir, "parent.txt", "parent\n")
2289+
issue250Git(t, localDir, "add", ".")
2290+
issue250Git(t, localDir, "commit", "-m", "parent commit")
2291+
issue250Git(t, localDir, "push", "-u", "origin", "parent")
2292+
parentSHA := issue250Git(t, localDir, "rev-parse", "parent")
2293+
2294+
issue250Git(t, localDir, "checkout", "-b", "imported", "main")
2295+
issue250WriteFile(t, localDir, "imported.txt", "imported\n")
2296+
issue250Git(t, localDir, "add", ".")
2297+
issue250Git(t, localDir, "commit", "-m", "imported commit")
2298+
issue250Git(t, localDir, "push", "-u", "origin", "imported")
2299+
oldImported := issue250Git(t, localDir, "rev-parse", "imported")
2300+
2301+
gitDir := filepath.Join(localDir, ".git")
2302+
writeStackFile(t, gitDir, stack.Stack{
2303+
Trunk: stack.BranchRef{Branch: "main", Head: mainSHA},
2304+
Branches: []stack.BranchRef{
2305+
{Branch: "parent", Head: parentSHA, Base: mainSHA},
2306+
{Branch: "imported", Head: oldImported, Base: mainSHA},
2307+
},
2308+
})
2309+
2310+
issue250Git(t, ".", "clone", remoteDir, serverDir)
2311+
issue250Git(t, serverDir, "config", "user.name", "Test")
2312+
issue250Git(t, serverDir, "config", "user.email", "test@example.com")
2313+
issue250Git(t, serverDir, "checkout", "parent")
2314+
issue250Git(t, serverDir, "checkout", "imported")
2315+
issue250Git(t, serverDir, "rebase", "--onto", "parent", "main", "imported")
2316+
issue250Git(t, serverDir, "push", "--force", "origin", "imported")
2317+
newImported := issue250Git(t, serverDir, "rev-parse", "imported")
2318+
2319+
issue250Git(t, localDir, "checkout", "imported")
2320+
2321+
return serverRebasedRepo{
2322+
dir: localDir,
2323+
gitDir: gitDir,
2324+
oldImported: oldImported,
2325+
newImported: newImported,
2326+
parentSHA: parentSHA,
2327+
}
2328+
}
2329+
2330+
func assertServerRebasedRepoAdopted(t *testing.T, repo serverRebasedRepo) {
2331+
t.Helper()
2332+
assert.Equal(t, repo.newImported, issue250Git(t, repo.dir, "rev-parse", "imported"))
2333+
assert.NotEqual(t, repo.oldImported, repo.newImported)
2334+
require.NoError(t, issue250GitMayFail(t, repo.dir, "merge-base", "--is-ancestor", "parent", "imported"))
2335+
2336+
sf, err := stack.Load(repo.gitDir)
2337+
require.NoError(t, err)
2338+
require.Len(t, sf.Stacks, 1)
2339+
require.Len(t, sf.Stacks[0].Branches, 2)
2340+
assert.Equal(t, repo.parentSHA, sf.Stacks[0].Branches[1].Base)
2341+
assert.Equal(t, repo.newImported, sf.Stacks[0].Branches[1].Head)
2342+
}
2343+
2344+
func TestIntegration_RebaseAdoptsServerRebasedBranches(t *testing.T) {
2345+
repo := setupServerRebasedRepo(t)
2346+
withIssue250Repo(t, repo.dir)
2347+
cfg := issue250TestConfig(t)
2348+
2349+
require.NoError(t, runRebase(cfg, &rebaseOptions{remote: "origin"}))
2350+
assertServerRebasedRepoAdopted(t, repo)
2351+
}
2352+
2353+
func TestIntegration_SyncAdoptsServerRebasedBranches(t *testing.T) {
2354+
repo := setupServerRebasedRepo(t)
2355+
withIssue250Repo(t, repo.dir)
2356+
cfg := issue250TestConfig(t)
2357+
2358+
require.NoError(t, runSync(cfg, &syncOptions{remote: "origin"}))
2359+
assertServerRebasedRepoAdopted(t, repo)
2360+
}

‎cmd/sync.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ GitHub and recreate it later with sync/submit, or cancel. Cancelling — or a
4848
divergence in a non-interactive terminal — aborts the sync without pushing
4949
branches or updating PRs.
5050
51+
When the same branches were rewritten by a server-side stack rebase, sync
52+
adopts the remote tips only if the local tips still match their pre-fetch
53+
tracking refs and the ordered commit ranges are equivalent. Otherwise it stops
54+
instead of overwriting either side.
55+
5156
If a rebase conflict is detected, all branches are restored to their
5257
original state and you are advised to run "gh stack rebase" to resolve
5358
conflicts interactively.
@@ -108,6 +113,7 @@ func runSync(cfg *config.Config, opts *syncOptions) error {
108113
// Fetch trunk + active branches so tracking refs are current for
109114
// fast-forward detection (Step 2) and --force-with-lease (Step 4).
110115
normalizeStackTrunk(cfg, s, remote)
116+
branchSnapshots := snapshotBranchTips(s, remote)
111117
if err := git.FetchBranches(remote, activeBranchNames(s)); err != nil {
112118
cfg.Errorf("failed to fetch stack branches from %s: %v", remote, err)
113119
return ErrSilent
@@ -147,6 +153,11 @@ func runSync(cfg *config.Config, opts *syncOptions) error {
147153
return err
148154
}
149155

156+
if _, err := adoptRemoteRebasedBranches(cfg, s, remote, currentBranch, branchSnapshots); err != nil {
157+
cfg.Errorf("%v", err)
158+
return ErrSilent
159+
}
160+
150161
// --- Step 2b: Fast-forward stack branches behind their remote tracking branch ---
151162
updatedBranches := fastForwardBranches(cfg, s, remote, currentBranch)
152163

‎cmd/utils.go‎

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -822,6 +822,203 @@ func activeBranchNames(s *stack.Stack) []string {
822822
return names
823823
}
824824

825+
type branchTipSnapshot struct {
826+
localSHA string
827+
remoteSHA string
828+
hasRemote bool
829+
}
830+
831+
// snapshotBranchTips captures local and remote-tracking tips before a fetch.
832+
// The old remote tip lets us distinguish a server rewrite from an unpushed
833+
// local rewrite after FetchBranches updates the tracking refs.
834+
func snapshotBranchTips(s *stack.Stack, remote string) map[string]branchTipSnapshot {
835+
snapshots := make(map[string]branchTipSnapshot)
836+
for _, br := range s.Branches {
837+
if br.IsMerged() {
838+
continue
839+
}
840+
localSHA, err := git.RevParse(br.Branch)
841+
if err != nil {
842+
continue
843+
}
844+
snapshot := branchTipSnapshot{localSHA: localSHA}
845+
if remoteSHA, err := git.RevParse(remote + "/" + br.Branch); err == nil {
846+
snapshot.remoteSHA = remoteSHA
847+
snapshot.hasRemote = true
848+
}
849+
snapshots[br.Branch] = snapshot
850+
}
851+
return snapshots
852+
}
853+
854+
type remoteRebaseUpdate struct {
855+
branch string
856+
localSHA string
857+
remoteSHA string
858+
remoteRef string
859+
}
860+
861+
// adoptRemoteRebasedBranches updates local branches after a remote stack
862+
// rebase when the pre-fetch tracking refs prove the local tips were unchanged
863+
// and range-diff proves each branch retained the same ordered commits.
864+
func adoptRemoteRebasedBranches(cfg *config.Config, s *stack.Stack, remote, currentBranch string, snapshots map[string]branchTipSnapshot) ([]string, error) {
865+
var updates []remoteRebaseUpdate
866+
for _, br := range s.Branches {
867+
if br.IsMerged() {
868+
continue
869+
}
870+
snapshot, ok := snapshots[br.Branch]
871+
if !ok {
872+
continue
873+
}
874+
localSHA, err := git.RevParse(br.Branch)
875+
if err != nil {
876+
return nil, fmt.Errorf("could not resolve local branch %s: %w", br.Branch, err)
877+
}
878+
if localSHA != snapshot.localSHA {
879+
return nil, fmt.Errorf("local branch %s changed while syncing", br.Branch)
880+
}
881+
882+
remoteRef := remote + "/" + br.Branch
883+
remoteSHA, err := git.RevParse(remoteRef)
884+
if err != nil || localSHA == remoteSHA {
885+
continue
886+
}
887+
888+
localBehind, err := git.IsAncestor(localSHA, remoteSHA)
889+
if err != nil {
890+
return nil, fmt.Errorf("could not compare %s with %s: %w", br.Branch, remoteRef, err)
891+
}
892+
if localBehind {
893+
// An ordinary fast-forward is handled by fastForwardBranches.
894+
continue
895+
}
896+
897+
if !snapshot.hasRemote {
898+
return nil, fmt.Errorf(
899+
"%s and %s have diverged, but no pre-fetch tracking tip is available; reconcile them manually",
900+
br.Branch, remoteRef,
901+
)
902+
}
903+
if snapshot.remoteSHA == remoteSHA {
904+
// Only the local branch changed; preserve it for the normal local
905+
// rebase and push flow.
906+
continue
907+
}
908+
if snapshot.localSHA != snapshot.remoteSHA {
909+
return nil, fmt.Errorf(
910+
"%s and %s both changed since the last fetch; reconcile them manually",
911+
br.Branch, remoteRef,
912+
)
913+
}
914+
915+
updates = append(updates, remoteRebaseUpdate{
916+
branch: br.Branch,
917+
localSHA: localSHA,
918+
remoteSHA: remoteSHA,
919+
remoteRef: remoteRef,
920+
})
921+
}
922+
if len(updates) == 0 {
923+
return nil, nil
924+
}
925+
926+
updateByBranch := make(map[string]remoteRebaseUpdate, len(updates))
927+
for _, update := range updates {
928+
updateByBranch[update.branch] = update
929+
}
930+
lastUpdateIndex := -1
931+
for i, br := range s.Branches {
932+
if _, ok := updateByBranch[br.Branch]; ok {
933+
lastUpdateIndex = i
934+
}
935+
}
936+
937+
localParent := s.Trunk.Branch
938+
remoteParent := remote + "/" + s.Trunk.Branch
939+
for i, br := range s.Branches {
940+
if i > lastUpdateIndex {
941+
break
942+
}
943+
if br.IsMerged() {
944+
continue
945+
}
946+
remoteBranch := remote + "/" + br.Branch
947+
stacked, err := git.IsAncestor(remoteParent, remoteBranch)
948+
if err != nil || !stacked {
949+
return nil, fmt.Errorf(
950+
"remote branch %s is not stacked on %s; refusing to replace local branches",
951+
remoteBranch, remoteParent,
952+
)
953+
}
954+
955+
if _, ok := updateByBranch[br.Branch]; ok {
956+
localBase := br.Base
957+
validBase := false
958+
if localBase != "" {
959+
validBase, _ = git.IsAncestor(localBase, br.Branch)
960+
}
961+
if !validBase {
962+
localBase, err = git.MergeBase(localParent, br.Branch)
963+
if err != nil {
964+
return nil, fmt.Errorf("could not determine the local commit range for %s: %w", br.Branch, err)
965+
}
966+
}
967+
equivalent, err := git.RangeDiffEquivalent(localBase, br.Branch, remoteParent, remoteBranch)
968+
if err != nil {
969+
return nil, fmt.Errorf("could not compare local and remote commits for %s: %w", br.Branch, err)
970+
}
971+
if !equivalent {
972+
return nil, fmt.Errorf(
973+
"%s was rewritten on the remote with different commits; reconcile it manually",
974+
br.Branch,
975+
)
976+
}
977+
}
978+
979+
localParent = br.Branch
980+
remoteParent = remoteBranch
981+
}
982+
983+
dirty, err := git.HasUncommittedChanges()
984+
if err != nil {
985+
return nil, fmt.Errorf("could not determine whether the working tree is clean: %w", err)
986+
}
987+
if dirty {
988+
return nil, errors.New("uncommitted changes prevent adopting the remote-rebased branches; commit or stash them first")
989+
}
990+
991+
var applied []remoteRebaseUpdate
992+
for _, update := range updates {
993+
var updateErr error
994+
if update.branch == currentBranch {
995+
updateErr = git.ResetHard(update.remoteRef)
996+
} else {
997+
updateErr = git.UpdateBranchRef(update.branch, update.remoteSHA)
998+
}
999+
if updateErr != nil {
1000+
for i := len(applied) - 1; i >= 0; i-- {
1001+
previous := applied[i]
1002+
if previous.branch == currentBranch {
1003+
_ = git.ResetHard(previous.localSHA)
1004+
} else {
1005+
_ = git.UpdateBranchRef(previous.branch, previous.localSHA)
1006+
}
1007+
}
1008+
return nil, fmt.Errorf("failed to update %s from %s: %w", update.branch, update.remoteRef, updateErr)
1009+
}
1010+
applied = append(applied, update)
1011+
}
1012+
1013+
names := make([]string, len(updates))
1014+
for i, update := range updates {
1015+
names[i] = update.branch
1016+
}
1017+
cfg.Successf("Adopted %d server-rebased %s from %s: %s",
1018+
len(names), plural(len(names), "branch", "branches"), remote, strings.Join(names, ", "))
1019+
return names, nil
1020+
}
1021+
8251022
// fastForwardBranches fast-forwards each active stack branch to its remote
8261023
// tracking branch when the local branch is strictly behind. Returns the names
8271024
// of branches that were updated. Branches that are up-to-date, diverged, or

0 commit comments

Comments
 (0)