forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevelop.go
More file actions
370 lines (317 loc) · 11.1 KB
/
develop.go
File metadata and controls
370 lines (317 loc) · 11.1 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
package develop
import (
ctx "context"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmd/issue/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type DevelopOptions struct {
HttpClient func() (*http.Client, error)
GitClient *git.Client
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Remotes func() (context.Remotes, error)
IssueNumber int
Name string
BranchRepo string
BaseBranch string
Checkout bool
List bool
}
func NewCmdDevelop(f *cmdutil.Factory, runF func(*DevelopOptions) error) *cobra.Command {
opts := &DevelopOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
BaseRepo: f.BaseRepo,
Remotes: f.Remotes,
}
cmd := &cobra.Command{
Use: "develop {<number> | <url>}",
Short: "Manage linked branches for an issue",
Long: heredoc.Docf(`
Manage linked branches for an issue.
When using the %[1]s--base%[1]s flag, the new development branch will be created from the specified
remote branch. The new branch will be configured as the base branch for pull requests created using
%[1]sgh pr create%[1]s.
`, "`"),
Example: heredoc.Doc(`
# List branches for issue 123
$ gh issue develop --list 123
# List branches for issue 123 in repo cli/cli
$ gh issue develop --list --repo cli/cli 123
# Create a branch for issue 123 based on the my-feature branch
$ gh issue develop 123 --base my-feature
# Create a branch for issue 123 and check it out
$ gh issue develop 123 --checkout
# Create a branch in repo monalisa/cli for issue 123 in repo cli/cli
$ gh issue develop 123 --repo cli/cli --branch-repo monalisa/cli
`),
Args: cmdutil.ExactArgs(1, "issue number or url is required"),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// This is all a hack to not break the deprecated issue-repo flag.
// It will be removed in the near future and this hack can be removed at the same time.
flags := cmd.Flags()
if flags.Changed("issue-repo") {
if flags.Changed("repo") {
if flags.Changed("branch-repo") {
return cmdutil.FlagErrorf("specify only `--repo` and `--branch-repo`")
}
branchRepo, _ := flags.GetString("repo")
_ = flags.Set("branch-repo", branchRepo)
}
repo, _ := flags.GetString("issue-repo")
_ = flags.Set("repo", repo)
}
if cmd.Parent() != nil {
return cmd.Parent().PersistentPreRunE(cmd, args)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0])
if err != nil {
return err
}
// If the args provided the base repo then use that directly.
if baseRepo, present := baseRepo.Value(); present {
opts.BaseRepo = func() (ghrepo.Interface, error) {
return baseRepo, nil
}
} else {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
}
opts.IssueNumber = issueNumber
if err := cmdutil.MutuallyExclusive("specify only one of `--list` or `--branch-repo`", opts.List, opts.BranchRepo != ""); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive("specify only one of `--list` or `--base`", opts.List, opts.BaseBranch != ""); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive("specify only one of `--list` or `--checkout`", opts.List, opts.Checkout); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive("specify only one of `--list` or `--name`", opts.List, opts.Name != ""); err != nil {
return err
}
if runF != nil {
return runF(opts)
}
return developRun(opts)
},
}
fl := cmd.Flags()
fl.StringVar(&opts.BranchRepo, "branch-repo", "", "Name or URL of the repository where you want to create your new branch")
fl.StringVarP(&opts.BaseBranch, "base", "b", "", "Name of the remote branch you want to make your new branch from")
fl.BoolVarP(&opts.Checkout, "checkout", "c", false, "Checkout the branch after creating it")
fl.BoolVarP(&opts.List, "list", "l", false, "List linked branches for the issue")
fl.StringVarP(&opts.Name, "name", "n", "", "Name of the branch to create")
var issueRepoSelector string
fl.StringVarP(&issueRepoSelector, "issue-repo", "i", "", "Name or URL of the issue's repository")
_ = cmd.Flags().MarkDeprecated("issue-repo", "use `--repo` instead")
return cmd
}
func developRun(opts *DevelopOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
opts.IO.StartProgressIndicatorWithLabel(fmt.Sprintf("Fetching issue #%d", opts.IssueNumber))
defer opts.IO.StopProgressIndicator()
issue, err := shared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, []string{"id", "number"})
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
opts.IO.StartProgressIndicatorWithLabel("Checking linked branch support")
err = api.CheckLinkedBranchFeature(apiClient, baseRepo.RepoHost())
if err != nil {
return err
}
opts.IO.StopProgressIndicator()
if opts.List {
return developRunList(opts, apiClient, baseRepo, issue)
}
return developRunCreate(opts, apiClient, baseRepo, issue)
}
func developRunCreate(opts *DevelopOptions, apiClient *api.Client, issueRepo ghrepo.Interface, issue *api.Issue) error {
branchRepo := issueRepo
if opts.BranchRepo != "" {
var err error
branchRepo, err = ghrepo.FromFullName(opts.BranchRepo)
if err != nil {
return err
}
}
opts.IO.StartProgressIndicatorWithLabel("Preparing linked branch")
defer opts.IO.StopProgressIndicator()
branchName := ""
reusedExisting := false
if opts.Name != "" {
opts.IO.StartProgressIndicatorWithLabel("Checking existing linked branches")
branches, err := api.ListLinkedBranches(apiClient, issueRepo, issue.Number)
if err != nil {
return err
}
branchName = findExistingLinkedBranchName(branches, branchRepo, opts.Name)
reusedExisting = branchName != ""
}
repoID := ""
branchID := ""
baseValidated := false
if opts.BaseBranch != "" {
opts.IO.StartProgressIndicatorWithLabel(fmt.Sprintf("Validating base branch %q", opts.BaseBranch))
foundRepoID, foundBranchID, err := api.FindRepoBranchID(apiClient, branchRepo, opts.BaseBranch)
if err != nil {
return err
}
repoID = foundRepoID
branchID = foundBranchID
baseValidated = true
}
if branchName == "" {
if !baseValidated {
opts.IO.StartProgressIndicatorWithLabel("Resolving base branch")
foundRepoID, foundBranchID, err := api.FindRepoBranchID(apiClient, branchRepo, opts.BaseBranch)
if err != nil {
return err
}
repoID = foundRepoID
branchID = foundBranchID
}
opts.IO.StartProgressIndicatorWithLabel("Creating linked branch")
createdBranchName, err := api.CreateLinkedBranch(apiClient, branchRepo.RepoHost(), repoID, issue.ID, branchID, opts.Name)
if err != nil {
return err
}
branchName = createdBranchName
}
if branchName == "" {
return fmt.Errorf("failed to create linked branch: API returned empty branch name")
}
opts.IO.StopProgressIndicator()
if reusedExisting && opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Using existing linked branch %q\n", branchName)
}
// Remember which branch to target when creating a PR.
if opts.BaseBranch != "" {
if err := opts.GitClient.SetBranchConfig(ctx.Background(), branchName, git.MergeBaseConfig, opts.BaseBranch); err != nil {
return err
}
}
fmt.Fprintf(opts.IO.Out, "%s/%s/tree/%s\n", branchRepo.RepoHost(), ghrepo.FullName(branchRepo), branchName)
return checkoutBranch(opts, branchRepo, branchName)
}
func findExistingLinkedBranchName(branches []api.LinkedBranch, branchRepo ghrepo.Interface, branchName string) string {
for _, branch := range branches {
if branch.BranchName != branchName {
continue
}
linkedRepo, err := linkedBranchRepoFromURL(branch.URL)
if err != nil {
continue
}
if ghrepo.IsSame(linkedRepo, branchRepo) {
return branch.BranchName
}
}
return ""
}
func linkedBranchRepoFromURL(branchURL string) (ghrepo.Interface, error) {
u, err := url.Parse(branchURL)
if err != nil {
return nil, err
}
pathParts := strings.SplitN(strings.Trim(u.Path, "/"), "/", 3)
if len(pathParts) < 2 {
return nil, fmt.Errorf("invalid linked branch URL: %q", branchURL)
}
u.Path = "/" + strings.Join(pathParts[0:2], "/")
return ghrepo.FromURL(u)
}
func developRunList(opts *DevelopOptions, apiClient *api.Client, issueRepo ghrepo.Interface, issue *api.Issue) error {
opts.IO.StartProgressIndicatorWithLabel("Fetching linked branches")
defer opts.IO.StopProgressIndicator()
branches, err := api.ListLinkedBranches(apiClient, issueRepo, issue.Number)
if err != nil {
return err
}
opts.IO.StopProgressIndicator()
if len(branches) == 0 {
return cmdutil.NewNoResultsError(fmt.Sprintf("no linked branches found for %s#%d", ghrepo.FullName(issueRepo), issue.Number))
}
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "\nShowing linked branches for %s#%d\n\n", ghrepo.FullName(issueRepo), issue.Number)
}
printLinkedBranches(opts.IO, branches)
return nil
}
func printLinkedBranches(io *iostreams.IOStreams, branches []api.LinkedBranch) {
cs := io.ColorScheme()
table := tableprinter.New(io, tableprinter.WithHeader("BRANCH", "URL"))
for _, branch := range branches {
table.AddField(branch.BranchName, tableprinter.WithColor(cs.ColorFromString("cyan")))
table.AddField(branch.URL)
table.EndRow()
}
_ = table.Render()
}
func checkoutBranch(opts *DevelopOptions, branchRepo ghrepo.Interface, checkoutBranch string) (err error) {
remotes, err := opts.Remotes()
if err != nil {
// If the user specified the branch to be checked out and no remotes are found
// display an error. Otherwise bail out silently, likely the command was not
// run from inside a git directory.
if opts.Checkout {
return err
} else {
return nil
}
}
baseRemote, err := remotes.FindByRepo(branchRepo.RepoOwner(), branchRepo.RepoName())
if err != nil {
// If the user specified the branch to be checked out and no remote matches the
// base repo, then display an error. Otherwise bail out silently.
if opts.Checkout {
return err
} else {
return nil
}
}
gc := opts.GitClient
if err := gc.Fetch(ctx.Background(), baseRemote.Name, fmt.Sprintf("+refs/heads/%[1]s:refs/remotes/%[2]s/%[1]s", checkoutBranch, baseRemote.Name)); err != nil {
return err
}
if !opts.Checkout {
return nil
}
if gc.HasLocalBranch(ctx.Background(), checkoutBranch) {
if err := gc.CheckoutBranch(ctx.Background(), checkoutBranch); err != nil {
return err
}
if err := gc.Pull(ctx.Background(), baseRemote.Name, checkoutBranch); err != nil {
_, _ = fmt.Fprintf(opts.IO.ErrOut, "%s warning: not possible to fast-forward to: %q\n", opts.IO.ColorScheme().WarningIcon(), checkoutBranch)
}
} else {
if err := gc.CheckoutNewBranch(ctx.Background(), baseRemote.Name, checkoutBranch); err != nil {
return err
}
}
return nil
}