File: develop.go

package info (click to toggle)
gh 2.46.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,548 kB
  • sloc: sh: 227; makefile: 117
file content (260 lines) | stat: -rw-r--r-- 8,164 bytes parent folder | download | duplicates (2)
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
package develop

import (
	ctx "context"
	"fmt"
	"net/http"

	"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)

	IssueSelector string
	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",
		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 checkout 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 {
			// support `-R, --repo` override
			opts.BaseRepo = f.BaseRepo
			opts.IssueSelector = args[0]
			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 base 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
	}

	opts.IO.StartProgressIndicator()
	issue, issueRepo, err := shared.IssueFromArgWithFields(httpClient, opts.BaseRepo, opts.IssueSelector, []string{"id", "number"})
	opts.IO.StopProgressIndicator()
	if err != nil {
		return err
	}

	apiClient := api.NewClientFromHTTP(httpClient)

	opts.IO.StartProgressIndicator()
	err = api.CheckLinkedBranchFeature(apiClient, issueRepo.RepoHost())
	opts.IO.StopProgressIndicator()
	if err != nil {
		return err
	}

	if opts.List {
		return developRunList(opts, apiClient, issueRepo, issue)
	}
	return developRunCreate(opts, apiClient, issueRepo, issue)
}

func developRunCreate(opts *DevelopOptions, apiClient *api.Client, issueRepo ghrepo.Interface, issue *api.Issue) error {
	branchRepo := issueRepo
	var repoID string
	if opts.BranchRepo != "" {
		var err error
		branchRepo, err = ghrepo.FromFullName(opts.BranchRepo)
		if err != nil {
			return err
		}
	}

	opts.IO.StartProgressIndicator()
	repoID, branchID, err := api.FindRepoBranchID(apiClient, branchRepo, opts.BaseBranch)
	opts.IO.StopProgressIndicator()
	if err != nil {
		return err
	}

	opts.IO.StartProgressIndicator()
	branchName, err := api.CreateLinkedBranch(apiClient, branchRepo.RepoHost(), repoID, issue.ID, branchID, opts.Name)
	opts.IO.StopProgressIndicator()
	if 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 developRunList(opts *DevelopOptions, apiClient *api.Client, issueRepo ghrepo.Interface, issue *api.Issue) error {
	opts.IO.StartProgressIndicator()
	branches, err := api.ListLinkedBranches(apiClient, issueRepo, issue.Number)
	opts.IO.StopProgressIndicator()
	if err != nil {
		return err
	}

	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
}