-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathutils.go
More file actions
399 lines (352 loc) · 11.4 KB
/
utils.go
File metadata and controls
399 lines (352 loc) · 11.4 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
package cmd
import (
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"github.com/AlecAivazis/survey/v2/terminal"
"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/stack"
)
// 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
)
// 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")
}
// loadStackResult holds everything returned by loadStack.
type loadStackResult struct {
GitDir string
StackFile *stack.StackFile
Stack *stack.Stack
CurrentBranch string
}
// loadStack is the standard way to obtain a Stack for the current (or given)
// branch. It resolves the git directory, loads the stack file, determines the
// branch, calls resolveStack (which may prompt for disambiguation), checks for
// a nil stack, and re-reads the current branch (in case disambiguation caused
// a checkout). Errors are printed via cfg and returned.
//
// 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) {
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)
}
branchFromArg := branch != ""
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
}
if s == nil {
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"))
return nil, fmt.Errorf("branch %q is not part of a stack", branch)
}
// Re-read current branch in case disambiguation caused a checkout.
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
}
// 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) {
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.
// For each branch, it queries GitHub for the most recent PR and updates the
// PullRequestRef including merge status. Branches with already-merged PRs are skipped.
func syncStackPRs(cfg *config.Config, s *stack.Stack) {
client, err := cfg.GitHubClient()
if err != nil {
return
}
for i := range s.Branches {
b := &s.Branches[i]
if b.IsMerged() {
continue
}
pr, err := client.FindAnyPRForBranch(b.Branch)
if err != nil || pr == nil {
continue
}
b.PullRequest = &stack.PullRequestRef{
Number: pr.Number,
ID: pr.ID,
URL: pr.URL,
Merged: pr.Merged,
}
}
}
// 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 {
s.Branches[p.index].Base = base
}
if head, ok := shaMap[p.branch]; ok {
s.Branches[p.index].Head = head
}
}
}
// 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
}
// resolvePR resolves a user-provided target to a stack and branch using
// waterfall logic: PR URL → PR number → branch name.
func resolvePR(sf *stack.StackFile, target string) (*stack.Stack, *stack.BranchRef, error) {
// Try parsing as a GitHub PR URL (e.g. https://github.com/owner/repo/pull/42).
if prNumber, ok := parsePRURL(target); ok {
s, b := sf.FindStackByPRNumber(prNumber)
if s != nil && b != nil {
return s, b, nil
}
}
// Try parsing as a PR number.
if prNumber, err := strconv.Atoi(target); err == nil && prNumber > 0 {
s, b := sf.FindStackByPRNumber(prNumber)
if s != nil && b != nil {
return s, b, nil
}
}
// Try matching as a branch name.
stacks := sf.FindAllStacksForBranch(target)
if len(stacks) > 0 {
s := stacks[0]
idx := s.IndexOf(target)
if idx >= 0 {
return s, &s.Branches[idx], nil
}
// Target matched as trunk — return the first active branch.
if len(s.Branches) > 0 {
return s, &s.Branches[0], nil
}
}
return nil, nil, fmt.Errorf(
"no locally tracked stack found for %q\n"+
"This command currently only works with stacks created locally.\n"+
"Server-side stack discovery will be available in a future release.",
target,
)
}
// parsePRURL extracts a PR number from a GitHub pull request URL.
// Returns the number and true if the URL matches, or 0 and false otherwise.
func parsePRURL(raw string) (int, bool) {
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return 0, false
}
// Match paths like /owner/repo/pull/123
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) < 4 || parts[2] != "pull" {
return 0, false
}
n, err := strconv.Atoi(parts[3])
if err != nil || n <= 0 {
return 0, false
}
return n, true
}
// ensureRerere checks whether git rerere is enabled and, if not, prompts the
// user for permission before enabling it. If the user previously declined,
// the prompt is suppressed. In non-interactive sessions the function is a
// no-op so commands can still run in CI/scripting.
//
// Returns errInterrupt if the user pressed Ctrl+C during the prompt.
func ensureRerere(cfg *config.Config) error {
enabled, err := git.IsRerereEnabled()
if err != nil || enabled {
return nil
}
declined, _ := git.IsRerereDeclined()
if declined {
return nil
}
if !cfg.IsInteractive() {
return nil
}
p := prompter.New(cfg.In, cfg.Out, cfg.Err)
ok, err := p.Confirm("Enable git rerere to remember conflict resolutions?", true)
if err != nil {
if isInterruptError(err) {
printInterrupt(cfg)
return errInterrupt
}
return nil
}
if ok {
_ = git.EnableRerere()
} else {
_ = git.SaveRerereDeclined()
}
return nil
}