-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.go
More file actions
1157 lines (1006 loc) · 40.8 KB
/
sync.go
File metadata and controls
1157 lines (1006 loc) · 40.8 KB
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
package cmd
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"github.com/javoire/stackinator/internal/git"
"github.com/javoire/stackinator/internal/github"
"github.com/javoire/stackinator/internal/spinner"
"github.com/javoire/stackinator/internal/stack"
"github.com/javoire/stackinator/internal/ui"
"github.com/spf13/cobra"
)
// errAlreadyPrinted is a sentinel error indicating the error message was already displayed
var errAlreadyPrinted = errors.New("")
var (
syncForce bool
syncResume bool
syncAbort bool
syncCherryPick bool
// stdinReader allows tests to inject mock input for prompts
stdinReader io.Reader = os.Stdin
)
// Git config keys for sync state persistence
const (
configSyncStashed = "stack.sync.stashed"
configSyncOriginalBranch = "stack.sync.originalBranch"
)
var syncCmd = &cobra.Command{
Use: "sync [remote]",
Short: "Sync all stack branches with their parents and update PRs",
Long: `Perform a full sync of the stack:
1. Fetch latest changes from the base remote
2. Rebase each stack branch onto its parent (in bottom-to-top order)
3. Force push each branch to origin
4. Update PR base branches to match the stack (if PRs exist)
This ensures your stack is up-to-date and all PRs have the correct base branches.
If a parent PR has been merged, the child branches will be rebased to point to
the merged parent's parent.
Uncommitted changes are automatically stashed and reapplied (using --autostash).
The optional [remote] argument specifies which remote to fetch base branches from.
This is useful in fork workflows where 'origin' is your fork and 'upstream' is
the main repo. If not specified, the remote is auto-detected:
1. Git config 'stack.fetchRemote' if set
2. 'upstream' if it exists as a remote
3. 'origin' (default)
Stack branches are always pushed to 'origin'.`,
Args: cobra.MaximumNArgs(1),
Example: ` # Sync all branches and update PRs
stack sync
# Sync fetching base branches from upstream (fork workflow)
stack sync upstream
# Preview what would happen
stack sync --dry-run
# Show detailed git/gh commands
stack sync --verbose
# Force push even if branches have diverged
stack sync --force
# Resume after resolving rebase conflicts
stack sync --resume
# Abort an interrupted sync
stack sync --abort
# Common workflow after updating main
git checkout main && git pull
stack sync`,
Run: func(cmd *cobra.Command, args []string) {
gitClient := git.NewGitClient()
syncRemote := determineSyncRemote(gitClient, args)
repo := github.ParseRepoFromURL(gitClient.GetRemoteURL(syncRemote))
githubClient := github.NewGitHubClient(repo)
if err := runSync(gitClient, githubClient, syncRemote); err != nil {
// Don't print if error was already displayed with detailed message
if !errors.Is(err, errAlreadyPrinted) {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
os.Exit(1)
}
},
}
// determineSyncRemote determines which remote to use for fetching base branches.
// Priority: CLI arg > git config stack.fetchRemote > auto-detect upstream > origin
func determineSyncRemote(gitClient git.GitClient, args []string) string {
if len(args) > 0 {
return args[0]
}
if configured := gitClient.GetConfig("stack.fetchRemote"); configured != "" {
return configured
}
if gitClient.RemoteExists("upstream") {
fmt.Println("Using 'upstream' remote for base branches (detected automatically)")
return "upstream"
}
return "origin"
}
func init() {
syncCmd.Flags().BoolVarP(&syncForce, "force", "f", false, "Use --force instead of --force-with-lease for push (bypasses safety checks)")
syncCmd.Flags().BoolVarP(&syncResume, "resume", "r", false, "Resume a sync after resolving rebase conflicts")
syncCmd.Flags().BoolVarP(&syncAbort, "abort", "a", false, "Abort an interrupted sync and clean up state")
syncCmd.Flags().BoolVar(&syncCherryPick, "cherry-pick", false, "Rebuild polluted branches by cherry-picking unique commits (creates backup)")
}
func runSync(gitClient git.GitClient, githubClient github.GitHubClient, syncRemote string) error {
// Track state for stash handling
var originalBranch string
stashed := false
rebaseConflict := false
originalBranchMerged := false
// Check for existing sync state (from previous interrupted sync)
savedStashed := gitClient.GetConfig(configSyncStashed)
savedOriginalBranch := gitClient.GetConfig(configSyncOriginalBranch)
hasSavedState := savedStashed == "true" || savedOriginalBranch != ""
if syncAbort {
// Check if there's actually anything to abort
hasCherryPick := gitClient.IsCherryPickInProgress()
hasRebase := gitClient.IsRebaseInProgress()
if !hasSavedState && !hasCherryPick && !hasRebase {
return fmt.Errorf("no interrupted sync to abort\n\nUse 'stack sync' to start a new sync")
}
fmt.Println("Aborting sync and cleaning up...")
fmt.Println()
// Abort cherry-pick if one is in progress
if hasCherryPick {
if err := gitClient.AbortCherryPick(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to abort cherry-pick: %v\n", err)
} else {
fmt.Println(ui.Success("Aborted cherry-pick"))
}
} else if git.Verbose {
fmt.Fprintf(os.Stderr, "Note: no cherry-pick in progress\n")
}
// Abort rebase if one is in progress
if hasRebase {
if err := gitClient.AbortRebase(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to abort rebase: %v\n", err)
} else {
fmt.Println(ui.Success("Aborted rebase"))
}
} else if git.Verbose {
fmt.Fprintf(os.Stderr, "Note: no rebase in progress\n")
}
// Restore stashed changes if any
if savedStashed == "true" {
fmt.Println("Restoring stashed changes...")
if err := gitClient.StashPop(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to restore stashed changes: %v\n", err)
fmt.Fprintf(os.Stderr, "Run '%s' manually to restore your changes\n", ui.Command("git stash pop"))
} else {
fmt.Println(ui.Success("Restored stashed changes"))
}
}
// Return to original branch if we have one saved
if savedOriginalBranch != "" {
currentBranch, err := gitClient.GetCurrentBranch()
if err == nil && currentBranch != savedOriginalBranch {
fmt.Printf("Returning to %s...\n", ui.Branch(savedOriginalBranch))
if err := gitClient.CheckoutBranch(savedOriginalBranch); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to return to original branch: %v\n", err)
} else {
fmt.Println(ui.Success(fmt.Sprintf("Returned to %s", ui.Branch(savedOriginalBranch))))
}
}
}
// Clean up sync state
_ = gitClient.UnsetConfig(configSyncStashed)
_ = gitClient.UnsetConfig(configSyncOriginalBranch)
fmt.Println()
fmt.Println(ui.Success("Sync aborted and state cleaned up"))
return nil
}
if syncResume {
// Resuming after conflict resolution
if !hasSavedState {
return fmt.Errorf("no interrupted sync to resume\n\nUse 'stack sync' to start a new sync")
}
stashed = true
originalBranch = savedOriginalBranch
fmt.Println("Resuming sync...")
fmt.Println()
} else {
// Starting a fresh sync
if hasSavedState {
fmt.Fprintf(os.Stderr, "Warning: found state from a previous interrupted sync\n")
fmt.Fprintf(os.Stderr, "If you resolved rebase conflicts, run 'stack sync --resume'\n")
fmt.Fprintf(os.Stderr, "\nStart fresh? [y/N] ")
reader := bufio.NewReader(stdinReader)
input, err := reader.ReadString('\n')
if err != nil {
return fmt.Errorf("failed to read input: %w", err)
}
input = strings.TrimSpace(strings.ToLower(input))
if input != "y" && input != "yes" {
fmt.Println("Aborted. Use 'stack sync --resume' or 'stack sync --abort' to handle the interrupted sync.")
return nil
}
fmt.Println("Cleaning up stale state and starting fresh...")
fmt.Println()
// Clean up stale state
_ = gitClient.UnsetConfig(configSyncStashed)
_ = gitClient.UnsetConfig(configSyncOriginalBranch)
}
// Get current branch so we can return to it
var err error
originalBranch, err = gitClient.GetCurrentBranch()
if err != nil {
return fmt.Errorf("failed to get current branch: %w", err)
}
// Save original branch state for potential --abort
if err := gitClient.SetConfig(configSyncOriginalBranch, originalBranch); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to save sync state: %v\n", err)
}
// Check if working tree is clean and stash if needed
clean, err := gitClient.IsWorkingTreeClean()
if err != nil {
return fmt.Errorf("failed to check working tree status: %w", err)
}
if !clean {
fmt.Println("Stashing uncommitted changes...")
if err := gitClient.Stash("stack-sync-autostash"); err != nil {
return fmt.Errorf("failed to stash changes: %w", err)
}
stashed = true
// Mark that we stashed changes
if err := gitClient.SetConfig(configSyncStashed, "true"); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to save sync state: %v\n", err)
}
fmt.Println()
}
}
// Track if we complete successfully
success := false
// Ensure stash is popped on error (if we don't complete successfully)
// But NOT if we hit a rebase conflict - user needs to resolve and --resume
defer func() {
if stashed && !success && !rebaseConflict {
fmt.Println("\nRestoring stashed changes...")
if err := gitClient.StashPop(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to restore stashed changes: %v\n", err)
fmt.Fprintf(os.Stderr, "Run 'git stash pop' manually to restore your changes\n")
}
// Clean up sync state since we're restoring the stash
_ = gitClient.UnsetConfig(configSyncStashed)
_ = gitClient.UnsetConfig(configSyncOriginalBranch)
}
}()
// Check if current branch is in a stack BEFORE doing any network operations
// This allows us to prompt the user immediately if needed
baseBranch := stack.GetBaseBranch(gitClient)
parent := gitClient.GetConfig(fmt.Sprintf("branch.%s.stackparent", originalBranch))
if parent == "" && originalBranch != baseBranch {
// Auto-add branch to stack with base branch as parent
configKey := fmt.Sprintf("branch.%s.stackparent", originalBranch)
if err := gitClient.SetConfig(configKey, baseBranch); err != nil {
return fmt.Errorf("failed to set parent: %w", err)
}
fmt.Println(ui.Success(fmt.Sprintf("Added '%s' to stack with parent '%s'", ui.Branch(originalBranch), ui.Branch(baseBranch))))
}
// Start git fetch in parallel (the slowest network operation)
var wg sync.WaitGroup
var fetchErr error
var originFetchErr error
wg.Add(1)
go func() {
defer wg.Done()
fetchErr = gitClient.FetchRemote(syncRemote)
// If fetching from a non-origin remote, also fetch origin to get its branches
if syncRemote != "origin" {
originFetchErr = gitClient.Fetch()
}
}()
// While network operations run in background, do local work
// Get only branches in the current branch's stack
chain, err := stack.GetStackChain(gitClient, originalBranch)
if err != nil {
return fmt.Errorf("failed to get stack chain: %w", err)
}
if len(chain) == 0 {
// Wait for parallel operations before returning
wg.Wait()
if fetchErr != nil {
return fmt.Errorf("failed to fetch: %w", fetchErr)
}
fmt.Println("No stack branches found.")
if originalBranch == baseBranch {
fmt.Printf("Updating %s from origin...\n", ui.Branch(baseBranch))
if err := gitClient.FastForwardToRemote(baseBranch); err != nil {
return fmt.Errorf("failed to update %s: %w", baseBranch, err)
}
fmt.Println(ui.Success(fmt.Sprintf("Updated %s", ui.Branch(baseBranch))))
}
return nil
}
// Build set of branches in current stack
chainSet := make(map[string]bool)
for _, b := range chain {
chainSet[b] = true
}
// Get all stack branches and filter to current stack only
allStackBranches, err := stack.GetStackBranches(gitClient)
if err != nil {
return fmt.Errorf("failed to get stack branches: %w", err)
}
var stackBranches []stack.StackBranch
for _, b := range allStackBranches {
if chainSet[b.Name] {
stackBranches = append(stackBranches, b)
}
}
// Detect branches in chain that don't have stackparent configured
// and auto-configure them with inferred parents
existingBranchNames := make(map[string]bool)
for _, b := range stackBranches {
existingBranchNames[b.Name] = true
}
// Walk the chain and add missing branches
for i, branchName := range chain {
if branchName == baseBranch {
continue // Skip base branch
}
if existingBranchNames[branchName] {
continue // Already in stackBranches
}
// Infer parent from chain (previous branch in the chain)
var inferredParent string
if i > 0 {
inferredParent = chain[i-1]
} else {
inferredParent = baseBranch
}
// Check if branch exists locally before adding
if gitClient.BranchExists(branchName) {
stackBranches = append(stackBranches, stack.StackBranch{
Name: branchName,
Parent: inferredParent,
})
existingBranchNames[branchName] = true
// Configure stackparent so future syncs work correctly
configKey := fmt.Sprintf("branch.%s.stackparent", branchName)
if err := gitClient.SetConfig(configKey, inferredParent); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to set stackparent for %s: %v\n", branchName, err)
} else {
fmt.Printf("Auto-configured %s with parent %s\n", branchName, inferredParent)
}
}
}
// Sort branches in topological order (bottom to top)
sorted, err := stack.TopologicalSort(stackBranches)
if err != nil {
return fmt.Errorf("failed to sort branches: %w", err)
}
// Check if any branches in the current stack are in worktrees
worktrees, err := gitClient.GetWorktreeBranches()
if err != nil {
// Non-fatal, continue without worktree detection
worktrees = make(map[string]string)
}
// Get current worktree path to check if we're already in the right place
currentWorktreePath, err := gitClient.GetCurrentWorktreePath()
if err != nil {
// Non-fatal, continue without worktree path detection
currentWorktreePath = ""
}
worktreeSkipSet := make(map[string]string)
for _, branch := range sorted {
if worktreePath, inWorktree := worktrees[branch.Name]; inWorktree {
if currentWorktreePath != worktreePath {
worktreeSkipSet[branch.Name] = worktreePath
}
}
}
if len(worktreeSkipSet) > 0 {
for name, path := range worktreeSkipSet {
fmt.Fprintf(os.Stderr, "%s Skipping %s (checked out in worktree at %s)\n", ui.WarningIcon(), ui.Branch(name), path)
}
fmt.Println()
}
// Collect all branches we need PR info for (stack branches + their parents)
prBranchSet := make(map[string]bool)
for _, branch := range sorted {
prBranchSet[branch.Name] = true
prBranchSet[branch.Parent] = true
}
var prBranches []string
for b := range prBranchSet {
prBranches = append(prBranches, b)
}
// Wait for git fetch and fetch PRs in parallel for stack branches only
var prCache map[string]*github.PRInfo
fetchMsg := fmt.Sprintf("Fetching from %s and loading PRs...", syncRemote)
fetchDoneMsg := fmt.Sprintf("Fetched from %s and loaded PRs", syncRemote)
if err := spinner.WrapWithSuccess(fetchMsg, fetchDoneMsg, func() error {
wg.Wait()
prCache = githubClient.GetPRsForBranches(prBranches)
return nil
}); err != nil {
return err
}
// Check for fetch errors
if fetchErr != nil {
return fmt.Errorf("failed to fetch from %s: %w", syncRemote, fetchErr)
}
if originFetchErr != nil {
return fmt.Errorf("failed to fetch from origin: %w", originFetchErr)
}
// Get all remote branches in one call (more efficient than checking each branch individually)
remoteBranches := gitClient.GetRemoteBranchesSet()
// Build a set of stack branch names for quick lookup
stackBranchSet := make(map[string]bool)
for _, sb := range stackBranches {
stackBranchSet[sb.Name] = true
}
// Process each branch
for i, branch := range sorted {
progress := ui.Progress(i+1, len(sorted))
// Skip branches checked out in other worktrees
if worktreePath, skip := worktreeSkipSet[branch.Name]; skip {
fmt.Printf("%s Skipping %s (checked out in %s)\n\n", progress, ui.Branch(branch.Name), worktreePath)
continue
}
// Check if this branch has a merged PR - if so, remove from stack tracking
if pr, exists := prCache[branch.Name]; exists && pr.State == "MERGED" {
fmt.Printf("%s Skipping %s (PR #%d is %s)...\n", progress, ui.Branch(branch.Name), pr.Number, ui.PRState(pr.State))
fmt.Printf(" Removing from stack tracking...\n")
configKey := fmt.Sprintf("branch.%s.stackparent", branch.Name)
if err := gitClient.UnsetConfig(configKey); err != nil {
fmt.Fprintf(os.Stderr, " Warning: failed to remove stack config: %v\n", err)
} else {
fmt.Printf(" %s Removed. You can delete this branch with: %s\n", ui.SuccessIcon(), ui.Command(fmt.Sprintf("git branch -d %s", branch.Name)))
}
if branch.Name == originalBranch {
originalBranchMerged = true
}
fmt.Println()
continue
} else if _, exists := prCache[branch.Name]; !exists {
// No PR found - check if branch was merged via git history
remoteBase := syncRemote + "/" + baseBranch
if merged, err := gitClient.IsAncestor(branch.Name, remoteBase); err == nil && merged {
fmt.Printf("%s Skipping %s (merged into %s, detected via git history)...\n", progress, ui.Branch(branch.Name), ui.Branch(baseBranch))
fmt.Printf(" Removing from stack tracking...\n")
configKey := fmt.Sprintf("branch.%s.stackparent", branch.Name)
if err := gitClient.UnsetConfig(configKey); err != nil {
fmt.Fprintf(os.Stderr, " Warning: failed to remove stack config: %v\n", err)
} else {
fmt.Printf(" %s Removed. You can delete this branch with: %s\n", ui.SuccessIcon(), ui.Command(fmt.Sprintf("git branch -d %s", branch.Name)))
}
if branch.Name == originalBranch {
originalBranchMerged = true
}
fmt.Println()
continue
}
}
fmt.Printf("\n%s %s\n", progress, ui.Branch(branch.Name))
// Check if parent PR is merged
oldParent := "" // Track old parent for --onto rebase
parentPR := prCache[branch.Parent]
parentMergedViaGit := false
if parentPR != nil && parentPR.State == "MERGED" {
fmt.Printf(" Parent PR #%d has been merged\n", parentPR.Number)
oldParent = branch.Parent
} else if parentPR == nil && branch.Parent != baseBranch {
// No PR found for parent - check if parent was merged via git history
remoteBase := syncRemote + "/" + baseBranch
if merged, err := gitClient.IsAncestor(branch.Parent, remoteBase); err == nil && merged {
fmt.Printf(" Parent %s appears merged into %s (detected via git history)\n", ui.Branch(branch.Parent), ui.Branch(baseBranch))
oldParent = branch.Parent
parentMergedViaGit = true
}
}
if oldParent != "" {
// Save old parent for --onto rebase
// Update parent to grandparent
grandparent := gitClient.GetConfig(fmt.Sprintf("branch.%s.stackparent", branch.Parent))
if grandparent == "" {
grandparent = stack.GetBaseBranch(gitClient)
}
fmt.Printf(" %s Updated parent from %s to %s\n", ui.SuccessIcon(), ui.Branch(branch.Parent), ui.Branch(grandparent))
configKey := fmt.Sprintf("branch.%s.stackparent", branch.Name)
if err := gitClient.SetConfig(configKey, grandparent); err != nil {
fmt.Fprintf(os.Stderr, " Warning: failed to update parent config: %v\n", err)
} else {
branch.Parent = grandparent
}
// If parent was detected as merged via git (no PR), also remove it from stack tracking
if parentMergedViaGit {
parentConfigKey := fmt.Sprintf("branch.%s.stackparent", oldParent)
if err := gitClient.UnsetConfig(parentConfigKey); err != nil {
if git.Verbose {
fmt.Fprintf(os.Stderr, " Note: could not remove stack config for %s: %v\n", oldParent, err)
}
}
}
}
// Checkout the branch
if err := gitClient.CheckoutBranch(branch.Name); err != nil {
return fmt.Errorf("failed to checkout %s: %w", branch.Name, err)
}
// Sync with remote branch if it exists (unless --force is set)
remoteBranch := "origin/" + branch.Name
// Check if we have a local tracking ref for the remote branch
hasLocalRef := remoteBranches[branch.Name]
// Branch exists on remote if we have local tracking ref OR if there's a PR for it
// (PR existence proves branch is on origin, even if local ref is missing)
branchExistsOnRemote := hasLocalRef || prCache[branch.Name] != nil
// If branch is on remote but we don't have the local tracking ref, fetch it
if branchExistsOnRemote && !hasLocalRef {
if git.Verbose {
fmt.Printf(" Fetching remote branch (local tracking ref missing)...\n")
}
if err := gitClient.FetchBranch(branch.Name); err != nil {
// If fetch fails, the branch might have been deleted on remote
// Fall back to treating it as a new branch
if git.Verbose {
fmt.Printf(" Could not fetch remote branch, treating as new branch\n")
}
branchExistsOnRemote = false
}
}
if branchExistsOnRemote && !syncForce {
// Check if local and remote have diverged
localHash, err := gitClient.GetCommitHash(branch.Name)
if err != nil {
return fmt.Errorf("failed to get local commit hash: %w", err)
}
remoteHash, err := gitClient.GetCommitHash(remoteBranch)
if err != nil {
return fmt.Errorf("failed to get remote commit hash: %w", err)
}
if localHash != remoteHash {
// Check merge base to determine relationship
mergeBase, err := gitClient.GetMergeBase(branch.Name, remoteBranch)
if err != nil {
return fmt.Errorf("failed to get merge base: %w", err)
}
if mergeBase == remoteHash {
// Local is ahead of remote (we have new commits)
if git.Verbose {
fmt.Printf(" Local branch is ahead of origin (has new commits)\n")
}
} else if mergeBase == localHash {
// Local is behind remote (safe to fast-forward)
fmt.Printf(" Fast-forwarding to origin/%s...\n", branch.Name)
if err := gitClient.ResetToRemote(branch.Name); err != nil {
return fmt.Errorf("failed to fast-forward: %w", err)
}
} else {
// Branches have diverged - this is normal after rebasing onto an updated parent
// --force-with-lease will safely handle this during push
if git.Verbose {
fmt.Printf(" Local and remote have diverged (normal after rebase)\n")
}
}
} else if git.Verbose {
fmt.Printf(" Local branch is up-to-date with origin/%s\n", branch.Name)
}
} else if syncForce && branchExistsOnRemote {
if git.Verbose {
fmt.Printf(" Skipping divergence check (--force enabled)\n")
}
} else {
if git.Verbose {
fmt.Printf(" Remote branch origin/%s doesn't exist yet (new branch)\n", branch.Name)
}
}
// Determine rebase target: <remote>/<parent> for base branches, local for stack branches
rebaseTarget := branch.Parent
if !stackBranchSet[branch.Parent] {
// Parent is not a stack branch, so it's a base branch - use <syncRemote>/<parent>
rebaseTarget = syncRemote + "/" + branch.Parent
// Explicitly fetch the base branch to ensure tracking ref is up to date
// This is needed because 'git fetch <remote>' may not always update tracking refs
// reliably (e.g., repos with limited refspecs or certain git configurations)
if err := gitClient.FetchBranchFromRemote(syncRemote, branch.Parent); err != nil {
// Non-fatal: continue with potentially stale ref, rebase will still work
// but might not include latest changes from the base branch
if git.Verbose {
fmt.Printf(" Note: could not fetch %s from %s: %v\n", branch.Parent, syncRemote, err)
}
}
}
// Rebase onto parent
// If parent was just merged (oldParent set), use --onto to exclude old parent's commits
if err := spinner.WrapWithSuccessIndented(
" ",
fmt.Sprintf("Rebasing onto %s...", rebaseTarget),
fmt.Sprintf("Rebased onto %s", rebaseTarget),
func() error {
if oldParent != "" {
// Parent was merged - use --onto to handle squash merge
// This excludes commits from oldParent that are now in rebaseTarget
fmt.Printf(" Using --onto to handle squash merge (excluding commits from %s)\n", oldParent)
return gitClient.RebaseOnto(rebaseTarget, oldParent, branch.Name)
}
// Get unique commits in this branch by comparing patch content (not just SHAs)
// This detects duplicate changes even if commits were rebased with different SHAs
uniqueCommits, err := gitClient.GetUniqueCommitsByPatch(rebaseTarget, branch.Name)
if err != nil {
// If we can't get unique commits, fall back to regular rebase
if git.Verbose {
fmt.Printf(" Could not get unique commits by patch, using regular rebase: %v\n", err)
}
return gitClient.Rebase(rebaseTarget)
}
// If no unique commits by patch comparison, just do a simple rebase.
// The branch might still need to incorporate new commits from the target.
// Rebase will be a no-op if truly up-to-date.
if len(uniqueCommits) == 0 {
if git.Verbose {
fmt.Printf(" No unique patches found, rebasing to incorporate target updates\n")
}
return gitClient.Rebase(rebaseTarget)
}
if git.Verbose {
fmt.Printf(" Found %d unique commit(s) by patch comparison\n", len(uniqueCommits))
}
// Get merge-base to understand the history
mergeBase, err := gitClient.GetMergeBase(branch.Name, rebaseTarget)
if err != nil {
// If we can't find merge-base, fall back to regular rebase
if git.Verbose {
fmt.Printf(" Could not find merge-base, using regular rebase: %v\n", err)
}
return gitClient.Rebase(rebaseTarget)
}
rebaseTargetHash, err := gitClient.GetCommitHash(rebaseTarget)
if err == nil && mergeBase == rebaseTargetHash {
// Parent hasn't changed since we branched, regular rebase is fine
return gitClient.Rebase(rebaseTarget)
}
// Count commits from merge-base to current branch (total commits in branch history)
allCommits, err := gitClient.GetUniqueCommits(mergeBase, branch.Name)
if err == nil && len(allCommits) > len(uniqueCommits)*2 {
// Branch has polluted history: many more commits than unique patches
// This usually means branch diverged from parent's history (e.g., based on old backup)
if syncCherryPick {
// Automated cherry-pick rebuild with backup
tempBranch := branch.Name + "-rebuild"
// Find available backup branch name
backupBranch := branch.Name + "-backup"
for i := 2; gitClient.BranchExists(backupBranch); i++ {
backupBranch = fmt.Sprintf("%s-backup-%d", branch.Name, i)
}
fmt.Printf("\n")
fmt.Printf("⚠ Detected polluted branch history (%d commits, %d unique patches)\n", len(allCommits), len(uniqueCommits))
fmt.Printf(" Creating backup: %s\n", backupBranch)
// Create backup branch from current branch (without checkout)
if err := gitClient.CreateBranch(backupBranch, branch.Name); err != nil {
return fmt.Errorf("failed to create backup branch: %w", err)
}
fmt.Printf(" Rebuilding with %d unique commit(s)...\n", len(uniqueCommits))
// Checkout parent branch
if err := gitClient.CheckoutBranch(rebaseTarget); err != nil {
return fmt.Errorf("failed to checkout parent %s: %w", rebaseTarget, err)
}
// Create temp branch from parent
if err := gitClient.CreateBranchAndCheckout(tempBranch, rebaseTarget); err != nil {
return fmt.Errorf("failed to create temp branch: %w", err)
}
// Cherry-pick each unique commit
for _, commit := range uniqueCommits {
if git.Verbose {
fmt.Printf(" Cherry-picking %s\n", commit[:8])
}
if err := gitClient.CherryPick(commit); err != nil {
// Cherry-pick conflict - let user resolve
rebaseConflict = true
fmt.Fprintf(os.Stderr, "\n Cherry-pick conflict on %s. To continue:\n", commit[:8])
fmt.Fprintf(os.Stderr, " 1. Resolve the conflicts\n")
fmt.Fprintf(os.Stderr, " 2. Run 'git add <resolved files>'\n")
fmt.Fprintf(os.Stderr, " 3. Run 'git cherry-pick --continue'\n")
fmt.Fprintf(os.Stderr, " 4. Complete remaining cherry-picks manually\n")
fmt.Fprintf(os.Stderr, " 5. Run 'git branch -D %s && git branch -m %s'\n", branch.Name, branch.Name)
fmt.Fprintf(os.Stderr, " 6. Run 'stack sync --resume'\n")
fmt.Fprintf(os.Stderr, "\n Backup saved as: %s\n", backupBranch)
return fmt.Errorf("cherry-pick conflict: %w", err)
}
}
// Delete original branch and rename temp to original
if err := gitClient.DeleteBranchForce(branch.Name); err != nil {
return fmt.Errorf("failed to delete original branch: %w", err)
}
// We're on tempBranch, rename it to the original branch name
if err := gitClient.RenameBranch(tempBranch, branch.Name); err != nil {
return fmt.Errorf("failed to rename temp branch: %w", err)
}
// Restore stackparent config (git branch -D deletes the branch's config section)
configKey := fmt.Sprintf("branch.%s.stackparent", branch.Name)
if err := gitClient.SetConfig(configKey, branch.Parent); err != nil {
return fmt.Errorf("failed to restore stackparent config: %w", err)
}
fmt.Printf(" %s Rebuilt %s (backup saved as %s)\n", ui.SuccessIcon(), ui.Branch(branch.Name), ui.Branch(backupBranch))
fmt.Printf(" To delete backup later: %s\n", ui.Command(fmt.Sprintf("git branch -D %s", backupBranch)))
// Branch is now clean - no need to rebase, just return nil
return nil
}
// No --cherry-pick flag: show warning and suggest the flag
rebaseConflict = true
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "⚠ Detected polluted branch history:\n")
fmt.Fprintf(os.Stderr, " - %d commits in branch history\n", len(allCommits))
fmt.Fprintf(os.Stderr, " - Only %d unique patch(es)\n", len(uniqueCommits))
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "This usually means your branch diverged from the parent's history.\n")
fmt.Fprintf(os.Stderr, "Rebasing may result in many conflicts.\n")
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "Recommended: Run 'stack sync --cherry-pick' to auto-rebuild\n")
fmt.Fprintf(os.Stderr, " (Creates backup branch before rebuilding)\n")
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "Or rebuild manually:\n")
fmt.Fprintf(os.Stderr, " 1. git checkout %s\n", branch.Parent)
fmt.Fprintf(os.Stderr, " 2. git checkout -b %s-clean\n", branch.Name)
for i, commit := range uniqueCommits {
if i < 5 { // Show first 5 commits
fmt.Fprintf(os.Stderr, " 3. git cherry-pick %s\n", commit[:8])
}
}
if len(uniqueCommits) > 5 {
fmt.Fprintf(os.Stderr, " ... (%d more commits)\n", len(uniqueCommits)-5)
}
fmt.Fprintf(os.Stderr, " 4. git branch -D %s\n", branch.Name)
fmt.Fprintf(os.Stderr, " 5. git branch -m %s\n", branch.Name)
fmt.Fprintf(os.Stderr, " 6. git push --force-with-lease\n")
fmt.Fprintf(os.Stderr, "\n")
return fmt.Errorf("branch history is polluted, manual cleanup recommended")
}
// Use --onto to only replay commits unique to this branch
// This prevents conflicts from duplicate commits when parent was rebased
if git.Verbose {
fmt.Printf(" Using --onto with merge-base %s to handle rebased parent\n", mergeBase[:8])
}
return gitClient.RebaseOnto(rebaseTarget, mergeBase, branch.Name)
},
); err != nil {
rebaseConflict = true
fmt.Fprintf(os.Stderr, "\n Rebase conflict detected. To continue:\n")
fmt.Fprintf(os.Stderr, " 1. Resolve the conflicts\n")
fmt.Fprintf(os.Stderr, " 2. Run 'git add <resolved files>'\n")
fmt.Fprintf(os.Stderr, " 3. Run 'git rebase --continue'\n")
fmt.Fprintf(os.Stderr, " 4. Run 'stack sync --resume'\n")
fmt.Fprintf(os.Stderr, "\n Or to abort the sync:\n")
fmt.Fprintf(os.Stderr, " Run 'stack sync --abort'\n")
if stashed {
fmt.Fprintf(os.Stderr, "\n Note: Your uncommitted changes have been stashed and will be restored when you run --resume or --abort\n")
}
return fmt.Errorf("failed to rebase: %w", errAlreadyPrinted)
}
// Push to origin - only if the branch already exists remotely
if branchExistsOnRemote {
pushErr := spinner.WrapWithSuccessIndented(
" ",
"Pushing to origin...",
"Pushed to origin",
func() error {
if syncForce {
// Use regular --force (bypasses --force-with-lease safety checks)
if git.Verbose {
fmt.Printf(" Using --force (bypassing safety checks)\n")
}
return gitClient.ForcePush(branch.Name)
}
// Fetch one more time right before push to get the current remote SHA
if git.Verbose {
fmt.Printf(" Refreshing remote tracking ref before push...\n")
}
if err := gitClient.FetchBranch(branch.Name); err != nil {
// Non-fatal, continue with push using plain --force-with-lease
if git.Verbose {
fmt.Fprintf(os.Stderr, " Note: could not refresh tracking ref: %v\n", err)
}
return gitClient.Push(branch.Name, true)
}
// Get the remote SHA to use with explicit --force-with-lease
// This avoids "stale info" errors that can occur with plain --force-with-lease
remoteSha, err := gitClient.GetCommitHash("origin/" + branch.Name)
if err != nil {
// Fall back to plain --force-with-lease
if git.Verbose {
fmt.Fprintf(os.Stderr, " Note: could not get remote SHA, using plain force-with-lease: %v\n", err)
}
return gitClient.Push(branch.Name, true)
}
return gitClient.PushWithExpectedRemote(branch.Name, remoteSha)
},
)
if pushErr != nil {
if !syncForce {
fmt.Fprintf(os.Stderr, "\nPossible cause:\n")
fmt.Fprintf(os.Stderr, " Remote branch was updated after fetch - try running 'stack sync' again\n")
}
return fmt.Errorf("push failed for %s", branch.Name)
}
} else {
fmt.Printf(" Skipping push (branch not yet on origin)\n")
}
// Check if PR exists and update base if needed
pr := prCache[branch.Name]
if pr != nil {
if pr.Base != branch.Parent {
fmt.Printf(" Updating PR #%d base from %s to %s...\n", pr.Number, ui.Branch(pr.Base), ui.Branch(branch.Parent))
if err := githubClient.UpdatePRBase(pr.Number, branch.Parent); err != nil {
fmt.Fprintf(os.Stderr, " Warning: failed to update PR base: %v\n", err)
} else {
fmt.Printf(" %s PR #%d updated\n", ui.SuccessIcon(), pr.Number)
}
} else {
fmt.Printf(" %s PR #%d base is already correct (%s)\n", ui.SuccessIcon(), pr.Number, ui.Branch(pr.Base))
}
} else {
fmt.Printf(" No PR found (create one with '%s')\n", ui.Command("gh pr create"))
}
}
// Return to original branch if needed
currentBranch, err := gitClient.GetCurrentBranch()
if originalBranchMerged {
if currentBranch != baseBranch {
if err := gitClient.CheckoutBranch(baseBranch); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to switch to %s: %v\n", baseBranch, err)
}
}
fmt.Printf("Switched to %s (%s was merged)\n", ui.Branch(baseBranch), ui.Branch(originalBranch))
} else if err == nil && currentBranch != originalBranch {
fmt.Printf("Returning to %s...\n", ui.Branch(originalBranch))
if err := gitClient.CheckoutBranch(originalBranch); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to return to original branch: %v\n", err)
}
}
// Display the updated stack status (reuse prCache to avoid redundant API call)
fmt.Println()
if err := displayStatusAfterSync(gitClient, githubClient, prCache); err != nil {
// Don't fail if we can't display status, just warn
fmt.Fprintf(os.Stderr, "Warning: failed to display stack status: %v\n", err)
}
// Mark as successful so defer doesn't restore stash
success = true
// Restore stashed changes before success message
if stashed {
fmt.Println()
fmt.Println("Restoring stashed changes...")
if err := gitClient.StashPop(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to restore stashed changes: %v\n", err)
fmt.Fprintf(os.Stderr, "Run 'git stash pop' manually to restore your changes\n")
}
}
// Clean up sync state (both stash flag and original branch)
_ = gitClient.UnsetConfig(configSyncStashed)
_ = gitClient.UnsetConfig(configSyncOriginalBranch)
// Run post-sync install if a package manager is detected
runPostSyncInstall(gitClient)
fmt.Println()
fmt.Println(ui.Success("Sync complete!"))
return nil
}
// packageManager maps a lockfile name to its install command.
type packageManager struct {
lockfile string
command string
args []string
}
var packageManagers = []packageManager{
{"pnpm-lock.yaml", "pnpm", []string{"install"}},
{"yarn.lock", "yarn", []string{"install"}},
{"bun.lockb", "bun", []string{"install"}},
{"bun.lock", "bun", []string{"install"}},
{"package-lock.json", "npm", []string{"install"}},
}
// detectPackageManager checks for lockfiles in the given directory and returns
// the matching package manager, or nil if none found.
func detectPackageManager(repoRoot string) *packageManager {
for _, pm := range packageManagers {