-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathinit.go
More file actions
358 lines (323 loc) · 10.5 KB
/
init.go
File metadata and controls
358 lines (323 loc) · 10.5 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
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/cli/go-gh/v2/pkg/prompter"
"github.com/github/gh-stack/internal/branch"
"github.com/github/gh-stack/internal/config"
"github.com/github/gh-stack/internal/git"
"github.com/github/gh-stack/internal/stack"
"github.com/spf13/cobra"
)
type initOptions struct {
branches []string
base string
adopt bool
prefix string
numbered bool
}
func InitCmd(cfg *config.Config) *cobra.Command {
opts := &initOptions{}
cmd := &cobra.Command{
Use: "init [branches...]",
Short: "Initialize a new stack",
Long: `Initialize a stack object in the local repo.
Unless specified, prompts user to create/select branch for first layer of the stack.
Trunk defaults to default branch, unless specified otherwise.`,
Example: ` $ gh stack init
$ gh stack init myBranch
$ gh stack init --adopt branch1 branch2 branch3
$ gh stack init --base integrationBranch firstBranch`,
RunE: func(cmd *cobra.Command, args []string) error {
opts.branches = args
return runInit(cfg, opts)
},
}
cmd.Flags().StringVarP(&opts.base, "base", "b", "", "Trunk branch for stack (defaults to default branch)")
cmd.Flags().BoolVarP(&opts.adopt, "adopt", "a", false, "Track existing branches as part of a stack")
cmd.Flags().StringVarP(&opts.prefix, "prefix", "p", "", "Branch name prefix for the stack")
cmd.Flags().BoolVarP(&opts.numbered, "numbered", "n", false, "Use auto-incrementing numbered branch names (requires --prefix)")
return cmd
}
func runInit(cfg *config.Config, opts *initOptions) error {
gitDir, err := git.GitDir()
if err != nil {
cfg.Errorf("not a git repository")
return ErrNotInStack
}
// Determine trunk branch
trunk := opts.base
// Enable git rerere so conflict resolutions are remembered.
if err := ensureRerere(cfg); errors.Is(err, errInterrupt) {
return ErrSilent
}
if trunk == "" {
trunk, err = git.DefaultBranch()
if err != nil {
cfg.Errorf("unable to determine default branch\nUse -b to specify the trunk branch")
return ErrNotInStack
}
}
// Load existing stack file
sf, err := stack.Load(gitDir)
if err != nil {
cfg.Errorf("failed to load stack state: %s", err)
return ErrNotInStack
}
// Set repository context
repo, err := cfg.Repo()
if err == nil {
sf.Repository = repo.Host + ":" + repo.Owner + "/" + repo.Name
}
currentBranch, _ := git.CurrentBranch()
// Don't allow initializing a stack if the current branch is a non-trunk
// member of another stack. Trunk branches (e.g. "main") can be shared
// across multiple stacks.
if currentBranch != "" {
for _, s := range sf.FindAllStacksForBranch(currentBranch) {
if s.IndexOf(currentBranch) >= 0 {
cfg.Errorf("current branch %q is already part of a stack", currentBranch)
return ErrInvalidArgs
}
}
}
var branches []string
// --adopt takes existing branches as-is; --prefix and --numbered don't apply.
if opts.adopt && (opts.prefix != "" || opts.numbered) {
cfg.Errorf("--adopt cannot be combined with --prefix or --numbered")
return ErrInvalidArgs
}
// Validate --numbered requires a prefix (either from flag or interactive input,
// but for non-interactive paths we can check early).
if opts.numbered && opts.prefix == "" && !cfg.IsInteractive() {
cfg.Errorf("--numbered requires --prefix")
return ErrInvalidArgs
}
// Prompt for prefix interactively if not provided via flag and we're
// in interactive mode (not adopt, not explicit branches).
if opts.prefix == "" && !opts.adopt && len(opts.branches) == 0 && cfg.IsInteractive() {
p := prompter.New(cfg.In, cfg.Out, cfg.Err)
if opts.numbered {
// --numbered requires a prefix; prompt specifically for one
prefixInput, err := p.Input("Enter a branch prefix (required for --numbered)", "")
if err != nil {
if isInterruptError(err) {
printInterrupt(cfg)
return ErrSilent
}
cfg.Errorf("failed to read prefix: %s", err)
return ErrSilent
}
opts.prefix = strings.TrimSpace(prefixInput)
if opts.prefix == "" {
cfg.Errorf("--numbered requires a prefix")
return ErrInvalidArgs
}
} else {
prefixInput, err := p.Input("Set a branch prefix? (leave blank to skip)", "")
if err != nil {
if isInterruptError(err) {
printInterrupt(cfg)
return ErrSilent
}
cfg.Errorf("failed to read prefix: %s", err)
return ErrSilent
}
opts.prefix = strings.TrimSpace(prefixInput)
}
}
// Validate prefix, after it has been determined (from flag or prompt),
// before any branch creation.
if opts.prefix != "" {
if err := git.ValidateRefName(opts.prefix); err != nil {
cfg.Errorf("invalid prefix %q: must be a valid git ref component", opts.prefix)
return ErrInvalidArgs
}
}
if opts.adopt {
// Adopt mode: validate all specified branches exist
if len(opts.branches) == 0 {
cfg.Errorf("--adopt requires at least one branch name")
return ErrInvalidArgs
}
for _, b := range opts.branches {
if !git.BranchExists(b) {
cfg.Errorf("branch %q does not exist", b)
return ErrInvalidArgs
}
if err := sf.ValidateNoDuplicateBranch(b); err != nil {
cfg.Errorf("branch %q already exists in a stack", b)
return ErrInvalidArgs
}
}
branches = opts.branches
} else if len(opts.branches) > 0 {
// Explicit branch names provided — apply prefix and create them
prefixed := make([]string, 0, len(opts.branches))
for _, b := range opts.branches {
if opts.prefix != "" {
b = opts.prefix + "/" + b
}
if err := sf.ValidateNoDuplicateBranch(b); err != nil {
cfg.Errorf("branch %q already exists in a stack", b)
return ErrInvalidArgs
}
if !git.BranchExists(b) {
if err := git.CreateBranch(b, trunk); err != nil {
cfg.Errorf("creating branch %s: %s", b, err)
return ErrSilent
}
}
prefixed = append(prefixed, b)
}
branches = prefixed
} else {
// Interactive mode — prefix was already prompted for above
if !cfg.IsInteractive() {
cfg.Errorf("interactive input required; provide branch names or use --adopt")
return ErrInvalidArgs
}
p := prompter.New(cfg.In, cfg.Out, cfg.Err)
if opts.numbered {
// Auto-generate numbered branch name
branchName := branch.NextNumberedName(opts.prefix, nil)
if err := sf.ValidateNoDuplicateBranch(branchName); err != nil {
cfg.Errorf("branch %q already exists in a stack", branchName)
return ErrInvalidArgs
}
if !git.BranchExists(branchName) {
if err := git.CreateBranch(branchName, trunk); err != nil {
cfg.Errorf("creating branch %s: %s", branchName, err)
return ErrSilent
}
}
branches = []string{branchName}
} else {
if currentBranch != "" && currentBranch != trunk {
// Already on a non-trunk branch — offer to use it
useCurrentBranch, err := p.Confirm(
fmt.Sprintf("Would you like to use %s as the first layer of your stack?", currentBranch),
true,
)
if err != nil {
if isInterruptError(err) {
printInterrupt(cfg)
return ErrSilent
}
cfg.Errorf("failed to confirm branch selection: %s", err)
return ErrSilent
}
if useCurrentBranch {
if err := sf.ValidateNoDuplicateBranch(currentBranch); err != nil {
cfg.Errorf("branch %q already exists in the stack", currentBranch)
return ErrInvalidArgs
}
branches = []string{currentBranch}
}
}
if len(branches) == 0 {
prompt := "What branch would you like to use as the first layer of your stack?"
if opts.prefix != "" {
prompt = fmt.Sprintf("Enter a name for the first branch (will be prefixed with %s/)", opts.prefix)
}
branchName, err := p.Input(prompt, "")
if err != nil {
if isInterruptError(err) {
printInterrupt(cfg)
return ErrSilent
}
cfg.Errorf("failed to read branch name: %s", err)
return ErrSilent
}
branchName = strings.TrimSpace(branchName)
if branchName == "" {
cfg.Errorf("branch name cannot be empty")
return ErrInvalidArgs
}
if opts.prefix != "" {
branchName = opts.prefix + "/" + branchName
}
if err := sf.ValidateNoDuplicateBranch(branchName); err != nil {
cfg.Errorf("branch %q already exists in a stack", branchName)
return ErrInvalidArgs
}
if !git.BranchExists(branchName) {
if err := git.CreateBranch(branchName, trunk); err != nil {
cfg.Errorf("creating branch %s: %s", branchName, err)
return ErrSilent
}
}
branches = []string{branchName}
}
}
}
// Build stack
trunkSHA, _ := git.RevParse(trunk)
branchRefs := make([]stack.BranchRef, len(branches))
for i, b := range branches {
parent := trunk
if i > 0 {
parent = branches[i-1]
}
base, _ := git.MergeBase(b, parent)
branchRefs[i] = stack.BranchRef{Branch: b, Base: base}
}
newStack := stack.Stack{
Prefix: opts.prefix,
Numbered: opts.numbered,
Trunk: stack.BranchRef{
Branch: trunk,
Head: trunkSHA,
},
Branches: branchRefs,
}
sf.AddStack(newStack)
// Discover existing PRs for the new stack's branches.
// For adopt, only record open/draft PRs (ignore closed/merged).
// For non-adopt, use the standard sync which also detects merges.
newStack_ := &sf.Stacks[len(sf.Stacks)-1]
if opts.adopt {
if client, clientErr := cfg.GitHubClient(); clientErr == nil {
for i := range newStack_.Branches {
b := &newStack_.Branches[i]
pr, err := client.FindPRForBranch(b.Branch)
if err != nil || pr == nil {
continue
}
b.PullRequest = &stack.PullRequestRef{
Number: pr.Number,
ID: pr.ID,
URL: pr.URL,
}
}
}
} else {
syncStackPRs(cfg, newStack_)
}
if err := stack.Save(gitDir, sf); err != nil {
return handleSaveError(cfg, err)
}
// Print result
if opts.adopt {
cfg.Printf("Adopting stack with trunk %s and %d branches", trunk, len(branches))
cfg.Printf("Initializing stack: %s", newStack.DisplayChain())
cfg.Printf("You can continue working on %s", branches[len(branches)-1])
} else {
cfg.Successf("Creating stack with trunk %s and branch %s", trunk, branches[len(branches)-1])
// Switch to last branch if not already there
lastBranch := branches[len(branches)-1]
if currentBranch != lastBranch {
if err := git.CheckoutBranch(lastBranch); err != nil {
cfg.Errorf("switching to branch %s: %s", lastBranch, err)
return ErrSilent
}
cfg.Printf("Switched to branch %s", lastBranch)
} else {
cfg.Printf("You can continue working on %s", lastBranch)
}
}
cfg.Printf("To add a new layer to your stack, run `%s`", cfg.ColorCyan("gh stack add"))
cfg.Printf("When you're ready to push to GitHub and open a stack of PRs, run `%s`", cfg.ColorCyan("gh stack submit"))
return nil
}