-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathutils.go
More file actions
1942 lines (1745 loc) · 62.8 KB
/
Copy pathutils.go
File metadata and controls
1942 lines (1745 loc) · 62.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 (
"errors"
"fmt"
"net/url"
"slices"
"strconv"
"strings"
"sync"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/cli/go-gh/v2/pkg/api"
"github.com/cli/go-gh/v2/pkg/prompter"
"github.com/github/gh-stack/internal/config"
"github.com/github/gh-stack/internal/git"
"github.com/github/gh-stack/internal/github"
"github.com/github/gh-stack/internal/stack"
"github.com/github/gh-stack/internal/theme"
)
// ErrSilent indicates the error has already been printed to the user.
// Execute() will exit with code 1 but will not print the error again.
var ErrSilent = &ExitError{Code: 1}
// Typed exit errors for programmatic detection by scripts and agents.
var (
ErrNotInStack = &ExitError{Code: 2} // branch/stack not found
ErrConflict = &ExitError{Code: 3} // rebase conflict
ErrAPIFailure = &ExitError{Code: 4} // GitHub API error
ErrInvalidArgs = &ExitError{Code: 5} // invalid arguments or flags
ErrDisambiguate = &ExitError{Code: 6} // multiple stacks/remotes, can't auto-select
ErrRebaseActive = &ExitError{Code: 7} // rebase already in progress
ErrLockFailed = &ExitError{Code: 8} // could not acquire stack file lock
ErrStacksUnavailable = &ExitError{Code: 9} // stacked PRs not available for this repository
ErrModifyRecovery = &ExitError{Code: 10} // modify session interrupted, recovery required
)
// ExitError is returned by commands to indicate a specific exit code.
// Execute() extracts the code and passes it to os.Exit.
type ExitError struct {
Code int
}
func (e *ExitError) Error() string {
return fmt.Sprintf("exit status %d", e.Code)
}
func (e *ExitError) Is(target error) bool {
t, ok := target.(*ExitError)
if !ok {
return false
}
return e.Code == t.Code
}
// errInterrupt is a sentinel returned when a prompt is cancelled via Ctrl+C.
// Callers should exit silently (the friendly message is already printed).
var errInterrupt = errors.New("interrupt")
// isInterruptError reports whether err is (or wraps) the survey interrupt,
// which is raised when the user presses Ctrl+C during a prompt.
func isInterruptError(err error) bool {
return errors.Is(err, terminal.InterruptErr)
}
// printInterrupt prints a friendly message and should be called exactly once
// per interrupted operation. The leading newline ensures the message starts
// on its own line even if the cursor was mid-prompt.
func printInterrupt(cfg *config.Config) {
fmt.Fprintln(cfg.Err)
cfg.Infof("Received interrupt, aborting operation")
}
// warnStacksUnavailable prints a warning when a stacks API call returns 404,
// indicating stacked PRs are not enabled for the repository.
func warnStacksUnavailable(cfg *config.Config) {
cfg.Warningf("Stacked PRs are not enabled for this repository")
}
// stackLabel returns a " (stack #N)" suffix for appending to user-facing
// messages when the human-facing stack number is known, or an empty string
// otherwise.
func stackLabel(number int) string {
if number <= 0 {
return ""
}
return fmt.Sprintf(" (stack #%d)", number)
}
// stackNumberByID resolves an internal stack ID (as stored in the local stack
// file) to its human-facing stack number by consulting the remote stack list.
// Returns ok=false when no remote stack matches the ID (e.g. it was deleted).
func stackNumberByID(client github.ClientOps, id string) (number int, ok bool, err error) {
if id == "" {
return 0, false, nil
}
stacks, err := client.ListStacks()
if err != nil {
return 0, false, err
}
for _, rs := range stacks {
if strconv.Itoa(rs.ID) == id {
return rs.Number, true, nil
}
}
return 0, false, nil
}
// ensureStackNumber returns the stack number for s, resolving and caching it
// from the remote stack list by internal ID when the local model predates the
// Number field (older stack files stored only the ID). Returns 0 when the stack
// number can't be determined.
func ensureStackNumber(client github.ClientOps, s *stack.Stack) (int, error) {
if s.Number != 0 {
return s.Number, nil
}
number, found, err := stackNumberByID(client, s.ID)
if err != nil {
return 0, err
}
if found {
s.Number = number
}
return number, nil
}
// promptInput prompts the user for a single line of text input. The user's
// input is rendered in the accent (cyan) color for visual distinction from the
// prompt message.
func promptInput(cfg *config.Config, prompt string) (string, error) {
if cfg.InputFn != nil {
return cfg.InputFn(prompt)
}
stdio := terminal.Stdio{In: cfg.In, Out: cfg.Out, Err: cfg.Err}
rr := terminal.NewRuneReader(stdio)
if err := rr.SetTermMode(); err != nil {
return "", fmt.Errorf("failed to set terminal mode: %w", err)
}
defer func() { _ = rr.RestoreTermMode() }()
// Render the prompt in survey style: green "?" + message
icon := "?"
useColor := cfg.Terminal.IsColorEnabled()
if useColor {
icon = theme.Success("?")
}
fmt.Fprintf(cfg.Out, "%s %s ", icon, prompt)
// Color the user's echoed input with the accent (cyan) color.
cyanStart, cyanReset := theme.FgSeqs(theme.ColorAccent)
if useColor {
fmt.Fprint(cfg.Out, cyanStart)
}
line, err := rr.ReadLine(0)
// Reset color after input
if useColor {
fmt.Fprint(cfg.Out, cyanReset)
}
if err != nil {
return "", err
}
return string(line), nil
}
// selectPromptPageSize matches the PageSize used by the go-gh prompter.
const selectPromptPageSize = 20
// clearSelectPrompt erases the rendered Select prompt from the terminal.
// survey/v2 does not call Cleanup on interrupt, leaving the question and
// option lines visible. This function moves the cursor up past those lines
// and clears to the end of the screen.
func clearSelectPrompt(cfg *config.Config, numOptions int) {
visible := numOptions
if visible > selectPromptPageSize {
visible = selectPromptPageSize
}
// 1 line for the question/filter + visible option lines
lines := 1 + visible
fmt.Fprintf(cfg.Out, "\033[%dA\033[J", lines)
}
// loadStackResult holds everything returned by loadStack.
type loadStackResult struct {
GitDir string
StackFile *stack.StackFile
Stack *stack.Stack
CurrentBranch string
PRDetails map[string]*github.PRDetails
}
// loadStack is the standard way to obtain a Stack for the current (or given)
// branch. It delegates to loadStackOptional, reports when the branch is not in
// a stack, and returns an error in that case.
//
// loadStack does NOT acquire the stack file lock. The lock is acquired
// automatically by stack.Save() when writing.
func loadStack(cfg *config.Config, branch string) (*loadStackResult, error) {
result, err := loadStackOptional(cfg, branch)
if err != nil {
return nil, err
}
if result.Stack == nil {
reportBranchNotInStack(cfg, result.CurrentBranch, branch != "")
return nil, fmt.Errorf("branch %q is not part of a stack", result.CurrentBranch)
}
return result, nil
}
// loadStackOptional performs the same lookup as loadStack, but returns a
// result with a nil Stack when the branch is not tracked instead of reporting
// an error. Other lookup failures are still reported and returned.
func loadStackOptional(cfg *config.Config, branch string) (*loadStackResult, error) {
gitDir, err := git.GitDir()
if err != nil {
cfg.Errorf("not a git repository")
return nil, fmt.Errorf("not a git repository")
}
sf, err := stack.Load(gitDir)
if err != nil {
cfg.Errorf("failed to load stack state: %s", err)
return nil, fmt.Errorf("failed to load stack state: %w", err)
}
if branch == "" {
branch, err = git.CurrentBranch()
if err != nil {
cfg.Errorf("failed to get current branch: %s", err)
return nil, fmt.Errorf("failed to get current branch: %w", err)
}
}
s, err := resolveStack(sf, branch, cfg)
if err != nil {
if errors.Is(err, errInterrupt) {
return nil, errInterrupt
}
cfg.Errorf("%s", err)
return nil, err
}
// Re-read current branch in case disambiguation caused a checkout.
currentBranch := branch
if s != nil {
currentBranch, err = git.CurrentBranch()
if err != nil {
cfg.Errorf("failed to get current branch: %s", err)
return nil, fmt.Errorf("failed to get current branch: %w", err)
}
}
return &loadStackResult{
GitDir: gitDir,
StackFile: sf,
Stack: s,
CurrentBranch: currentBranch,
}, nil
}
func reportBranchNotInStack(cfg *config.Config, branch string, branchFromArg bool) {
if branchFromArg {
cfg.Errorf("branch %q is not part of a stack", branch)
} else {
cfg.Errorf("current branch %q is not part of a stack", branch)
}
cfg.Printf("Checkout an existing stack using `%s` or create a new stack using `%s`",
cfg.ColorCyan("gh stack checkout"), cfg.ColorCyan("gh stack init"))
}
// lookupStackByNumber looks up the locally tracked stack whose stack number
// matches the given value, without printing a "not tracked" error. It returns
// ok=false (with a nil error) when no local stack resolves to that number —
// including when there is no git repository, since a stack cannot be tracked
// locally without one — so callers can fall back to a remote-only operation. A
// non-nil error signals a real failure (the stack file could not be loaded) that
// has already been reported via cfg.
//
// Stack files created before the number was tracked store only the internal ID
// (Number == 0); such legacy stacks are resolved by mapping their ID to a remote
// stack number so they can still be targeted by number. That mapping contacts
// GitHub (ListStacks), so it is only attempted when allowRemote is true — callers
// that must stay purely local (e.g. `--local`) pass false, and legacy stacks
// whose number isn't recorded locally are reported as not tracked.
func lookupStackByNumber(cfg *config.Config, number int, allowRemote bool) (result *loadStackResult, ok bool, err error) {
gitDir, err := git.GitDir()
if err != nil {
// Not a git repository — nothing can be tracked locally.
return nil, false, nil
}
sf, err := stack.Load(gitDir)
if err != nil {
cfg.Errorf("failed to load stack state: %s", err)
return nil, false, fmt.Errorf("failed to load stack state: %w", err)
}
// Direct match on the tracked stack number.
if result := stackResultByNumber(sf, gitDir, number); result != nil {
return result, true, nil
}
// No direct match — backfill legacy stacks' numbers from the remote and
// retry, so `gh stack unstack <number>` also works for stacks tracked
// before the number was recorded locally. This reaches GitHub, so it is
// skipped when the caller requires a purely local lookup.
if allowRemote && backfillLegacyStackNumbers(cfg, sf, gitDir) {
if result := stackResultByNumber(sf, gitDir, number); result != nil {
return result, true, nil
}
}
return nil, false, nil
}
// stackResultByNumber returns a loadStackResult for the locally tracked stack
// whose Number matches, or nil when none does.
func stackResultByNumber(sf *stack.StackFile, gitDir string, number int) *loadStackResult {
for i := range sf.Stacks {
if sf.Stacks[i].Number == number {
currentBranch, _ := git.CurrentBranch()
return &loadStackResult{
GitDir: gitDir,
StackFile: sf,
Stack: &sf.Stacks[i],
CurrentBranch: currentBranch,
}
}
}
return nil
}
// backfillLegacyStackNumbers fills in the human-facing Number for locally
// tracked stacks that predate it (Number == 0 but ID set) by mapping their
// internal ID to the remote stack list, persisting any updates. Returns true
// when at least one number was filled in. Best-effort: returns false on any
// client or API error rather than failing the caller.
func backfillLegacyStackNumbers(cfg *config.Config, sf *stack.StackFile, gitDir string) bool {
needsResolve := false
for i := range sf.Stacks {
if sf.Stacks[i].Number == 0 && sf.Stacks[i].ID != "" {
needsResolve = true
break
}
}
if !needsResolve {
return false
}
client, err := cfg.GitHubClient()
if err != nil {
return false
}
stacks, err := client.ListStacks()
if err != nil {
return false
}
numberByID := make(map[string]int, len(stacks))
for _, rs := range stacks {
numberByID[strconv.Itoa(rs.ID)] = rs.Number
}
changed := false
for i := range sf.Stacks {
if sf.Stacks[i].Number != 0 || sf.Stacks[i].ID == "" {
continue
}
if n, ok := numberByID[sf.Stacks[i].ID]; ok && n != 0 {
sf.Stacks[i].Number = n
changed = true
}
}
if changed {
if err := stack.Save(gitDir, sf); err != nil {
// Non-fatal: the in-memory backfill still lets us resolve the target.
cfg.Warningf("could not persist stack numbers: %v", err)
}
}
return changed
}
// handleSaveError translates a stack.Save error into the appropriate user
// message and exit error. Lock contention and stale-file detection both
// return ErrLockFailed (exit 8); other write failures return ErrSilent (exit 1).
func handleSaveError(cfg *config.Config, err error) error {
var lockErr *stack.LockError
if errors.As(err, &lockErr) {
cfg.Errorf("another process is currently editing the stack — try again later")
return ErrLockFailed
}
var staleErr *stack.StaleError
if errors.As(err, &staleErr) {
cfg.Errorf("stack file was modified by another process — please re-run the command")
return ErrLockFailed
}
cfg.Errorf("failed to save stack state: %s", err)
return ErrSilent
}
// resolveStack finds the stack for the given branch, handling ambiguity when
// a branch (typically a trunk) belongs to multiple stacks. If exactly one
// stack matches, it is returned directly. If multiple stacks match, the user
// is prompted to select one and the working tree is switched to the top branch
// of the selected stack. Returns nil with no error if no stack contains the
// branch.
func resolveStack(sf *stack.StackFile, branch string, cfg *config.Config) (*stack.Stack, error) {
stacks := sf.FindAllStacksForBranch(branch)
switch len(stacks) {
case 0:
return nil, nil
case 1:
return stacks[0], nil
}
if !cfg.IsInteractive() {
return nil, fmt.Errorf("branch %q belongs to multiple stacks; use an interactive terminal to select one", branch)
}
cfg.Warningf("Branch %q is the trunk of multiple stacks", branch)
options := make([]string, len(stacks))
for i, s := range stacks {
options[i] = s.DisplayChain()
}
p := prompter.New(cfg.In, cfg.Out, cfg.Err)
selected, err := p.Select("Which stack would you like to use?", "", options)
if err != nil {
if isInterruptError(err) {
clearSelectPrompt(cfg, len(options))
printInterrupt(cfg)
return nil, errInterrupt
}
return nil, fmt.Errorf("stack selection: %w", err)
}
s := stacks[selected]
if len(s.Branches) == 0 {
return nil, fmt.Errorf("selected stack %q has no branches", s.DisplayChain())
}
// Switch to the top branch of the selected stack so future commands
// resolve unambiguously.
topBranch := s.Branches[len(s.Branches)-1].Branch
if topBranch != branch {
if err := git.CheckoutBranch(topBranch); err != nil {
return nil, fmt.Errorf("failed to checkout branch %s: %w", topBranch, err)
}
cfg.Successf("Switched to %s", topBranch)
}
return s, nil
}
// syncStackPRs discovers and updates pull request metadata for branches in a stack.
// It also collects PRDetails for each branch, returned as a map keyed by branch name.
// The returned map is consumed by LoadBranchNodes to avoid redundant API calls.
//
// When the stack has a remote ID, the stack API is the source of truth: the
// authoritative PR list is fetched from the server and matched to local
// branches by head branch name. PRs remain associated even if closed.
//
// When no remote stack exists, branch-name-based discovery is used:
//
// 1. No tracked PR — look for an OPEN PR by head branch name.
// 2. Tracked PR (not merged) — refresh status by number; if closed,
// clear the association and fall through to path 1.
// 3. Tracked PR (merged) — skip; the merged state is final.
//
// The transient Queued flag is also populated from the API response.
//
// API calls for different branches are made concurrently to reduce latency.
func syncStackPRs(cfg *config.Config, s *stack.Stack) map[string]*github.PRDetails {
client, err := cfg.GitHubClient()
if err != nil {
return nil
}
// When the stack has a remote ID, the stack API is the source of truth.
if s.ID != "" {
if details, ok := syncStackPRsFromRemote(client, s); ok {
return details
}
}
// No remote stack (or remote sync failed) — local discovery.
// Each branch is processed concurrently; results are collected and applied sequentially.
type branchResult struct {
index int
pullRequest *stack.PullRequestRef
queued bool
details *github.PRDetails
skip bool // true means keep existing data, don't update
}
results := make([]branchResult, len(s.Branches))
// Fetch PR data for all branches concurrently using a WaitGroup for
// completion and a semaphore channel to cap the number of in-flight
// API requests (see maxAPIConcurrency).
var wg sync.WaitGroup
sem := make(chan struct{}, maxAPIConcurrency)
for i := range s.Branches {
b := s.Branches[i]
if b.IsMerged() {
results[i] = branchResult{index: i, skip: true}
// Provide PRDetails for merged branches from existing tracked PR
if b.PullRequest != nil && b.PullRequest.Number != 0 {
results[i].details = &github.PRDetails{
Number: b.PullRequest.Number,
State: "MERGED",
URL: b.PullRequest.URL,
Merged: true,
}
}
continue
}
wg.Add(1)
go func(idx int, branch stack.BranchRef) {
defer wg.Done()
// Acquire a semaphore slot to limit concurrent API calls.
sem <- struct{}{}
defer func() { <-sem }()
res := branchResult{index: idx}
trackedResolved := false
if branch.PullRequest != nil && branch.PullRequest.Number != 0 {
// Tracked PR — refresh its state.
pr, err := client.FindPRByNumber(branch.PullRequest.Number)
if err != nil {
// API error — keep existing tracked PR
res.skip = true
res.details = prDetailsFromTracked(branch.PullRequest)
results[idx] = res
return
}
if pr != nil && pr.State != "CLOSED" {
// PR is open or merged — keep it
res.pullRequest = &stack.PullRequestRef{
Number: pr.Number,
ID: pr.ID,
URL: pr.URL,
Merged: pr.Merged,
}
res.queued = pr.IsQueued()
res.details = prDetailsFromPR(pr)
results[idx] = res
trackedResolved = true
}
// Otherwise PR not found or closed — fall through to open-PR lookup
}
if trackedResolved {
return
}
// No tracked PR (or cleared) — only adopt OPEN PRs.
pr, err := client.FindPRForBranch(branch.Branch)
if err != nil || pr == nil {
results[idx] = res
return
}
res.pullRequest = &stack.PullRequestRef{
Number: pr.Number,
ID: pr.ID,
URL: pr.URL,
}
res.queued = pr.IsQueued()
// FindPRForBranch only returns OPEN PRs
res.details = &github.PRDetails{
Number: pr.Number,
State: "OPEN",
URL: pr.URL,
Title: pr.Title,
Body: pr.Body,
IsDraft: pr.IsDraft,
Merged: false,
IsQueued: pr.IsQueued(),
}
results[idx] = res
}(i, b)
}
wg.Wait()
// Apply results sequentially to preserve deterministic behavior.
details := make(map[string]*github.PRDetails)
for _, res := range results {
if res.details != nil {
details[s.Branches[res.index].Branch] = res.details
}
if res.skip {
continue
}
b := &s.Branches[res.index]
if res.pullRequest != nil {
b.PullRequest = res.pullRequest
b.Queued = res.queued
} else if !b.IsMerged() {
// Clear if we didn't find anything (and original was cleared during discovery)
if b.PullRequest != nil && res.pullRequest == nil {
b.PullRequest = nil
b.Queued = false
}
}
}
return details
}
// maxAPIConcurrency limits the number of concurrent API calls to avoid hitting secondary rate limits.
const maxAPIConcurrency = 6
// prDetailsFromPR builds PRDetails from a PullRequest returned by FindPRByNumber.
func prDetailsFromPR(pr *github.PullRequest) *github.PRDetails {
if pr == nil {
return nil
}
return &github.PRDetails{
Number: pr.Number,
State: pr.State,
URL: pr.URL,
Title: pr.Title,
Body: pr.Body,
IsDraft: pr.IsDraft,
Merged: pr.Merged,
IsQueued: pr.IsQueued(),
}
}
// prDetailsFromTracked builds minimal PRDetails from a tracked PullRequestRef.
func prDetailsFromTracked(ref *stack.PullRequestRef) *github.PRDetails {
if ref == nil {
return nil
}
state := "OPEN"
if ref.Merged {
state = "MERGED"
}
return &github.PRDetails{
Number: ref.Number,
State: state,
URL: ref.URL,
Merged: ref.Merged,
}
}
// enrichPRContent fills in the Title and Body of any existing PR whose details
// were built without them (e.g. merged branches, which skip the live refresh in
// syncStackPRs). It is used before the submit TUI renders an existing PR's
// read-only card so it shows the real PR title and description. PRs that already
// have a title (the common open/draft/queued case) are left untouched.
func enrichPRContent(client github.ClientOps, details map[string]*github.PRDetails) {
if client == nil {
return
}
var wg sync.WaitGroup
sem := make(chan struct{}, maxAPIConcurrency)
for _, d := range details {
if d == nil || d.Number == 0 || strings.TrimSpace(d.Title) != "" {
continue
}
wg.Add(1)
go func(d *github.PRDetails) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
if pr, err := client.FindPRByNumber(d.Number); err == nil && pr != nil {
d.Title = pr.Title
d.Body = pr.Body
}
}(d)
}
wg.Wait()
}
// syncStackPRsFromRemote uses the stack API to sync PR state. The remote
// stack's PR list is the source of truth — PRs stay associated even if
// closed. Returns the PRDetails map and true if sync succeeded, or nil and
// false if we should fall back to local discovery.
func syncStackPRsFromRemote(client github.ClientOps, s *stack.Stack) (map[string]*github.PRDetails, bool) {
stacks, err := client.ListStacks()
if err != nil {
return nil, false
}
// Find our stack in the remote list.
var remotePRNumbers []int
for _, rs := range stacks {
if strconv.Itoa(rs.ID) == s.ID {
remotePRNumbers = rs.PRNumbers()
// Backfill the human-facing stack number for stack files created
// before it was tracked, so callers (view, submit TUI) can display
// it. Persisted by whichever command later saves the stack file.
if s.Number == 0 {
s.Number = rs.Number
}
break
}
}
if remotePRNumbers == nil {
return nil, false
}
// Fetch each remote PR concurrently. Results are written to an ordered
// slice (one slot per PR number) so that when we build the branch map
// below, later entries win on duplicate HeadRefNames — matching the
// sequential behavior of the old code.
prResults := make([]*github.PullRequest, len(remotePRNumbers))
var wg sync.WaitGroup
sem := make(chan struct{}, maxAPIConcurrency) // limits concurrent API calls
for i, num := range remotePRNumbers {
wg.Add(1)
go func(idx, prNum int) {
defer wg.Done()
// Acquire a semaphore slot to limit concurrent API calls.
sem <- struct{}{}
defer func() { <-sem }()
pr, err := client.FindPRByNumber(prNum)
if err != nil || pr == nil {
return
}
// Each goroutine writes to its own index — no lock needed.
prResults[idx] = pr
}(i, num)
}
wg.Wait()
// Build map sequentially to preserve order semantics.
prByBranch := make(map[string]*github.PullRequest, len(remotePRNumbers))
for _, pr := range prResults {
if pr != nil {
prByBranch[pr.HeadRefName] = pr
}
}
// Match remote PRs to local branches and collect PRDetails.
details := make(map[string]*github.PRDetails)
for i := range s.Branches {
b := &s.Branches[i]
pr, ok := prByBranch[b.Branch]
if !ok {
continue
}
b.PullRequest = &stack.PullRequestRef{
Number: pr.Number,
ID: pr.ID,
URL: pr.URL,
Merged: pr.Merged,
}
b.Queued = pr.IsQueued()
details[b.Branch] = prDetailsFromPR(pr)
}
return details, true
}
// updateBaseSHAs refreshes the Base and Head SHAs for all active branches
// in a stack. Call this after any operation that may have moved branch refs
// (rebase, push, etc.).
func updateBaseSHAs(s *stack.Stack) {
// Collect all refs we need to resolve, then batch into one git call.
var refs []string
type refPair struct {
index int
parent string
branch string
}
var pairs []refPair
seen := make(map[string]bool)
for i := range s.Branches {
if s.Branches[i].IsMerged() {
continue
}
parent := s.ActiveBaseBranch(s.Branches[i].Branch)
branch := s.Branches[i].Branch
pairs = append(pairs, refPair{i, parent, branch})
if !seen[parent] {
refs = append(refs, parent)
seen[parent] = true
}
if !seen[branch] {
refs = append(refs, branch)
seen[branch] = true
}
}
if len(refs) == 0 {
return
}
shaMap, err := git.RevParseMap(refs)
if err != nil {
return
}
for _, p := range pairs {
if base, ok := shaMap[p.parent]; ok && canUpdateBase(base, p.branch, s.Branches[p.index].Base) {
s.Branches[p.index].Base = base
}
if head, ok := shaMap[p.branch]; ok {
s.Branches[p.index].Head = head
}
}
}
// canUpdateBase reports whether parentSHA can replace a branch's recorded base.
// Once a base is known, only a parent tip the branch actually contains may
// replace it; otherwise an amended parent would corrupt the next rebase
// boundary. Empty bases retain the historical best-effort behavior.
func canUpdateBase(parentSHA, branch, currentBase string) bool {
if currentBase == "" || currentBase == parentSHA {
return true
}
isAncestor, err := git.IsAncestor(parentSHA, branch)
return err == nil && isAncestor
}
// activeBranchNames returns the branch names for all non-merged branches in a stack.
func activeBranchNames(s *stack.Stack) []string {
active := s.ActiveBranches()
names := make([]string, len(active))
for i, b := range active {
names[i] = b.Branch
}
return names
}
// fastForwardBranches fast-forwards each active stack branch to its remote
// tracking branch when the local branch is strictly behind. Returns the names
// of branches that were updated. Branches that are up-to-date, diverged, or
// have no remote tracking branch are silently skipped.
func fastForwardBranches(cfg *config.Config, s *stack.Stack, remote, currentBranch string) []string {
var updated []string
for _, br := range s.Branches {
if br.IsSkipped() {
continue
}
remoteRef := remote + "/" + br.Branch
refs, err := git.RevParseMulti([]string{br.Branch, remoteRef})
if err != nil {
// Remote tracking branch doesn't exist — skip.
continue
}
localSHA, remoteSHA := refs[0], refs[1]
if localSHA == remoteSHA {
continue
}
isAncestor, err := git.IsAncestor(localSHA, remoteSHA)
if err != nil || !isAncestor {
// Diverged or error — skip. This commonly happens after a
// local rebase and is handled by the push step.
continue
}
// Local is behind remote — fast-forward.
if currentBranch == br.Branch {
if err := git.MergeFF(remoteRef); err != nil {
cfg.Warningf("Failed to fast-forward %s from remote: %v", br.Branch, err)
continue
}
} else {
if err := git.UpdateBranchRef(br.Branch, remoteSHA); err != nil {
cfg.Warningf("Failed to fast-forward %s from remote: %v", br.Branch, err)
continue
}
}
cfg.Successf("Fast-forwarded %s to %s", br.Branch, short(remoteSHA))
updated = append(updated, br.Branch)
}
return updated
}
// resolveOriginalRefs builds a map from branch name to current SHA for all
// branches in the stack. Merged branches that no longer exist locally are
// backfilled from the stack metadata. This map is used as the "before" state
// for cascade rebases and conflict recovery.
func resolveOriginalRefs(s *stack.Stack) (map[string]string, error) {
branchNames := make([]string, 0, len(s.Branches))
for _, b := range s.Branches {
if b.IsMerged() && !git.BranchExists(b.Branch) {
continue
}
branchNames = append(branchNames, b.Branch)
}
originalRefs, err := git.RevParseMap(branchNames)
if err != nil {
return nil, fmt.Errorf("resolving branch SHAs: %w", err)
}
// Backfill merged branches that were deleted locally.
for _, b := range s.Branches {
if b.IsMerged() && !git.BranchExists(b.Branch) {
if b.Head != "" {
originalRefs[b.Branch] = b.Head
}
}
}
return originalRefs, nil
}
// ensureLocalTrunk ensures the trunk branch exists locally. If it does not,
// it fetches the branch from the remote and creates a local tracking branch.
// This handles the case where a user started their stack after renaming their
// initial branch (e.g. `git branch -m newbranch`), leaving no local trunk.
func ensureLocalTrunk(cfg *config.Config, trunk, remote string) error {
if git.BranchExists(trunk) {
return nil
}
if err := git.FetchBranches(remote, []string{trunk}); err != nil {
return fmt.Errorf("could not fetch trunk branch %s from %s: %w", trunk, remote, err)
}
remoteTrunk := remote + "/" + trunk
if err := git.CreateBranch(trunk, remoteTrunk); err != nil {
return fmt.Errorf("could not create local trunk branch %s from %s: %w", trunk, remoteTrunk, err)
}
cfg.Successf("Created local trunk branch %s from %s", trunk, remoteTrunk)
return nil
}
func normalizeTrunkBranch(trunk, remote string) string {
if remote == "" || git.BranchExists(trunk) {
return trunk
}
if stripped, ok := strings.CutPrefix(trunk, remote+"/"); ok && stripped != "" {
return stripped
}
return trunk
}
func normalizeStackTrunk(cfg *config.Config, s *stack.Stack, remote string) {
trunk := normalizeTrunkBranch(s.Trunk.Branch, remote)
if trunk == s.Trunk.Branch {
return
}
cfg.Warningf("Stack trunk %q is remote-qualified — using %q", s.Trunk.Branch, trunk)
s.Trunk.Branch = trunk
}
type trunkTarget struct {
Branch string
Ref string
SHA string
Moved bool
}
func (t trunkTarget) Describe() string {
return fmt.Sprintf("%s (%s)", t.Ref, short(t.SHA))
}
// resolveTrunkTarget fetches the trunk explicitly, then returns the ref the
// cascade must use. Updating the local trunk is best-effort; the fetched remote
// ref remains the source of truth when the local branch is stale or immovable.
func resolveTrunkTarget(cfg *config.Config, s *stack.Stack, remote, currentBranch string) (trunkTarget, error) {
normalizeStackTrunk(cfg, s, remote)
trunk := s.Trunk.Branch
remoteRef := remote + "/" + trunk
if err := git.FetchBranch(remote, trunk); err != nil {
if errors.Is(err, git.ErrRemoteBranchNotFound) {
return trunkWithoutRemote(cfg, trunk, remote)
}
cfg.Errorf("failed to fetch trunk branch %s from %s: %v", trunk, remote, err)
return trunkTarget{}, ErrSilent
}
remoteSHA, err := git.RevParse(remoteRef)
if err != nil {
cfg.Errorf("could not resolve fetched trunk %s: %v", remoteRef, err)
return trunkTarget{}, ErrSilent
}
cfg.Successf("Fetched latest %s from %s", trunk, remote)
if !git.BranchExists(trunk) {
if err := git.CreateBranch(trunk, remoteRef); err != nil {
cfg.Errorf("could not create local trunk branch %s from %s: %v", trunk, remoteRef, err)
return trunkTarget{}, ErrSilent
}
cfg.Successf("Created local trunk branch %s from %s", trunk, remoteRef)
return trunkTarget{Branch: trunk, Ref: trunk, SHA: remoteSHA, Moved: true}, nil
}