-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
fork.go
386 lines (334 loc) · 11.2 KB
/
fork.go
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
package fork
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cenkalti/backoff/v4"
"github.com/cli/cli/v2/api"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/repo/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const defaultRemoteName = "origin"
type iprompter interface {
Confirm(string, bool) (bool, error)
}
type ForkOptions struct {
HttpClient func() (*http.Client, error)
GitClient *git.Client
Config func() (gh.Config, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Remotes func() (ghContext.Remotes, error)
Since func(time.Time) time.Duration
BackOff backoff.BackOff
Prompter iprompter
GitArgs []string
Repository string
Clone bool
Remote bool
PromptClone bool
PromptRemote bool
RemoteName string
Organization string
ForkName string
Rename bool
DefaultBranchOnly bool
}
type errWithExitCode interface {
ExitCode() int
}
// TODO warn about useless flags (--remote, --remote-name) when running from outside a repository
// TODO output over STDOUT not STDERR
// TODO remote-name has no effect on its own; error that or change behavior
func NewCmdFork(f *cmdutil.Factory, runF func(*ForkOptions) error) *cobra.Command {
opts := &ForkOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Config: f.Config,
BaseRepo: f.BaseRepo,
Remotes: f.Remotes,
Prompter: f.Prompter,
Since: time.Since,
}
cmd := &cobra.Command{
Use: "fork [<repository>] [-- <gitflags>...]",
Args: func(cmd *cobra.Command, args []string) error {
if cmd.ArgsLenAtDash() == 0 && len(args[1:]) > 0 {
return cmdutil.FlagErrorf("repository argument required when passing git clone flags")
}
return nil
},
Short: "Create a fork of a repository",
Long: heredoc.Docf(`
Create a fork of a repository.
With no argument, creates a fork of the current repository. Otherwise, forks
the specified repository.
By default, the new fork is set to be your %[1]sorigin%[1]s remote and any existing
origin remote is renamed to %[1]supstream%[1]s. To alter this behavior, you can set
a name for the new fork's remote with %[1]s--remote-name%[1]s.
The %[1]supstream%[1]s remote will be set as the default remote repository.
Additional %[1]sgit clone%[1]s flags can be passed after %[1]s--%[1]s.
`, "`"),
RunE: func(cmd *cobra.Command, args []string) error {
promptOk := opts.IO.CanPrompt()
if len(args) > 0 {
opts.Repository = args[0]
opts.GitArgs = args[1:]
}
if cmd.Flags().Changed("org") && opts.Organization == "" {
return cmdutil.FlagErrorf("--org cannot be blank")
}
if opts.RemoteName == "" {
return cmdutil.FlagErrorf("--remote-name cannot be blank")
} else if !cmd.Flags().Changed("remote-name") {
opts.Rename = true // Any existing 'origin' will be renamed to upstream
}
if promptOk {
// We can prompt for these if they were not specified.
opts.PromptClone = !cmd.Flags().Changed("clone")
opts.PromptRemote = !cmd.Flags().Changed("remote")
}
if runF != nil {
return runF(opts)
}
return forkRun(opts)
},
}
cmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
if err == pflag.ErrHelp {
return err
}
return cmdutil.FlagErrorf("%w\nSeparate git clone flags with `--`.", err)
})
cmd.Flags().BoolVar(&opts.Clone, "clone", false, "Clone the fork")
cmd.Flags().BoolVar(&opts.Remote, "remote", false, "Add a git remote for the fork")
cmd.Flags().StringVar(&opts.RemoteName, "remote-name", defaultRemoteName, "Specify the name for the new remote")
cmd.Flags().StringVar(&opts.Organization, "org", "", "Create the fork in an organization")
cmd.Flags().StringVar(&opts.ForkName, "fork-name", "", "Rename the forked repository")
cmd.Flags().BoolVar(&opts.DefaultBranchOnly, "default-branch-only", false, "Only include the default branch in the fork")
return cmd
}
func forkRun(opts *ForkOptions) error {
var repoToFork ghrepo.Interface
var err error
inParent := false // whether or not we're forking the repo we're currently "in"
if opts.Repository == "" {
baseRepo, err := opts.BaseRepo()
if err != nil {
return fmt.Errorf("unable to determine base repository: %w", err)
}
inParent = true
repoToFork = baseRepo
} else {
repoArg := opts.Repository
if isURL(repoArg) {
parsedURL, err := url.Parse(repoArg)
if err != nil {
return fmt.Errorf("did not understand argument: %w", err)
}
repoToFork, err = ghrepo.FromURL(parsedURL)
if err != nil {
return fmt.Errorf("did not understand argument: %w", err)
}
} else if strings.HasPrefix(repoArg, "git@") {
parsedURL, err := git.ParseURL(repoArg)
if err != nil {
return fmt.Errorf("did not understand argument: %w", err)
}
repoToFork, err = ghrepo.FromURL(parsedURL)
if err != nil {
return fmt.Errorf("did not understand argument: %w", err)
}
} else {
repoToFork, err = ghrepo.FromFullName(repoArg)
if err != nil {
return fmt.Errorf("argument error: %w", err)
}
}
}
connectedToTerminal := opts.IO.IsStdoutTTY() && opts.IO.IsStderrTTY() && opts.IO.IsStdinTTY()
cs := opts.IO.ColorScheme()
stderr := opts.IO.ErrOut
httpClient, err := opts.HttpClient()
if err != nil {
return fmt.Errorf("unable to create client: %w", err)
}
apiClient := api.NewClientFromHTTP(httpClient)
opts.IO.StartProgressIndicator()
forkedRepo, err := api.ForkRepo(apiClient, repoToFork, opts.Organization, opts.ForkName, opts.DefaultBranchOnly)
opts.IO.StopProgressIndicator()
if err != nil {
return fmt.Errorf("failed to fork: %w", err)
}
// This is weird. There is not an efficient way to determine via the GitHub API whether or not a
// given user has forked a given repo. We noticed, also, that the create fork API endpoint just
// returns the fork repo data even if it already exists -- with no change in status code or
// anything. We thus check the created time to see if the repo is brand new or not; if it's not,
// we assume the fork already existed and report an error.
createdAgo := opts.Since(forkedRepo.CreatedAt)
if createdAgo > time.Minute {
if connectedToTerminal {
fmt.Fprintf(stderr, "%s %s %s\n",
cs.Yellow("!"),
cs.Bold(ghrepo.FullName(forkedRepo)),
"already exists")
} else {
fmt.Fprintf(stderr, "%s already exists\n", ghrepo.FullName(forkedRepo))
}
} else {
if connectedToTerminal {
fmt.Fprintf(stderr, "%s Created fork %s\n", cs.SuccessIconWithColor(cs.Green), cs.Bold(ghrepo.FullName(forkedRepo)))
}
}
// Rename the new repo if necessary
if opts.ForkName != "" && !strings.EqualFold(forkedRepo.RepoName(), shared.NormalizeRepoName(opts.ForkName)) {
forkedRepo, err = api.RenameRepo(apiClient, forkedRepo, opts.ForkName)
if err != nil {
return fmt.Errorf("could not rename fork: %w", err)
}
if connectedToTerminal {
fmt.Fprintf(stderr, "%s Renamed fork to %s\n", cs.SuccessIconWithColor(cs.Green), cs.Bold(ghrepo.FullName(forkedRepo)))
}
}
if (inParent && (!opts.Remote && !opts.PromptRemote)) || (!inParent && (!opts.Clone && !opts.PromptClone)) {
return nil
}
cfg, err := opts.Config()
if err != nil {
return err
}
protocolConfig := cfg.GitProtocol(repoToFork.RepoHost())
protocolIsConfiguredByUser := protocolConfig.Source == gh.ConfigUserProvided
protocol := protocolConfig.Value
gitClient := opts.GitClient
ctx := context.Background()
if inParent {
remotes, err := opts.Remotes()
if err != nil {
return err
}
if !protocolIsConfiguredByUser {
if remote, err := remotes.FindByRepo(repoToFork.RepoOwner(), repoToFork.RepoName()); err == nil {
scheme := ""
if remote.FetchURL != nil {
scheme = remote.FetchURL.Scheme
}
if remote.PushURL != nil {
scheme = remote.PushURL.Scheme
}
if scheme != "" {
protocol = scheme
} else {
protocol = "https"
}
}
}
if remote, err := remotes.FindByRepo(forkedRepo.RepoOwner(), forkedRepo.RepoName()); err == nil {
if connectedToTerminal {
fmt.Fprintf(stderr, "%s Using existing remote %s\n", cs.SuccessIcon(), cs.Bold(remote.Name))
}
return nil
}
remoteDesired := opts.Remote
if opts.PromptRemote {
remoteDesired, err = opts.Prompter.Confirm("Would you like to add a remote for the fork?", false)
if err != nil {
return err
}
}
if remoteDesired {
remoteName := opts.RemoteName
remotes, err := opts.Remotes()
if err != nil {
return err
}
if _, err := remotes.FindByName(remoteName); err == nil {
if opts.Rename {
renameTarget := "upstream"
renameCmd, err := gitClient.Command(ctx, "remote", "rename", remoteName, renameTarget)
if err != nil {
return err
}
_, err = renameCmd.Output()
if err != nil {
return err
}
} else {
return fmt.Errorf("a git remote named '%s' already exists", remoteName)
}
}
forkedRepoCloneURL := ghrepo.FormatRemoteURL(forkedRepo, protocol)
_, err = gitClient.AddRemote(ctx, remoteName, forkedRepoCloneURL, []string{})
if err != nil {
return fmt.Errorf("failed to add remote: %w", err)
}
if connectedToTerminal {
fmt.Fprintf(stderr, "%s Added remote %s\n", cs.SuccessIcon(), cs.Bold(remoteName))
}
}
} else {
cloneDesired := opts.Clone
if opts.PromptClone {
cloneDesired, err = opts.Prompter.Confirm("Would you like to clone the fork?", false)
if err != nil {
return err
}
}
if cloneDesired {
// Allow injecting alternative BackOff in tests.
if opts.BackOff == nil {
bo := backoff.NewConstantBackOff(2 * time.Second)
opts.BackOff = bo
}
cloneDir, err := backoff.RetryWithData(func() (string, error) {
forkedRepoURL := ghrepo.FormatRemoteURL(forkedRepo, protocol)
dir, err := gitClient.Clone(ctx, forkedRepoURL, opts.GitArgs)
if err == nil {
return dir, err
}
var execError errWithExitCode
if errors.As(err, &execError) && execError.ExitCode() == 128 {
return "", err
}
return "", backoff.Permanent(err)
}, backoff.WithContext(backoff.WithMaxRetries(opts.BackOff, 3), ctx))
if err != nil {
return fmt.Errorf("failed to clone fork: %w", err)
}
gc := gitClient.Copy()
gc.RepoDir = cloneDir
upstreamURL := ghrepo.FormatRemoteURL(repoToFork, protocol)
upstreamRemote := "upstream"
if _, err := gc.AddRemote(ctx, upstreamRemote, upstreamURL, []string{}); err != nil {
return err
}
if err := gc.SetRemoteResolution(ctx, upstreamRemote, "base"); err != nil {
return err
}
if err := gc.Fetch(ctx, upstreamRemote, ""); err != nil {
return err
}
if connectedToTerminal {
fmt.Fprintf(stderr, "%s Cloned fork\n", cs.SuccessIcon())
fmt.Fprintf(stderr, "%s Repository %s set as the default repository. To learn more about the default repository, run: gh repo set-default --help\n", cs.WarningIcon(), cs.Bold(ghrepo.FullName(repoToFork)))
}
}
}
return nil
}
func isURL(s string) bool {
return strings.HasPrefix(s, "http:/") || strings.HasPrefix(s, "https:/")
}