-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
create.go
907 lines (794 loc) · 25.8 KB
/
create.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
package create
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cenkalti/backoff/v4"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"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"
)
type errWithExitCode interface {
ExitCode() int
}
type iprompter interface {
Input(string, string) (string, error)
Select(string, string, []string) (int, error)
Confirm(string, bool) (bool, error)
}
type CreateOptions struct {
HttpClient func() (*http.Client, error)
GitClient *git.Client
Config func() (config.Config, error)
IO *iostreams.IOStreams
Prompter iprompter
BackOff backoff.BackOff
Name string
Description string
Homepage string
Team string
Template string
Public bool
Private bool
Internal bool
Visibility string
Push bool
Clone bool
Source string
Remote string
GitIgnoreTemplate string
LicenseTemplate string
DisableIssues bool
DisableWiki bool
Interactive bool
IncludeAllBranches bool
AddReadme bool
}
func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command {
opts := &CreateOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Config: f.Config,
Prompter: f.Prompter,
}
var enableIssues bool
var enableWiki bool
cmd := &cobra.Command{
Use: "create [<name>]",
Short: "Create a new repository",
Long: heredoc.Docf(`
Create a new GitHub repository.
To create a repository interactively, use %[1]sgh repo create%[1]s with no arguments.
To create a remote repository non-interactively, supply the repository name and one of %[1]s--public%[1]s, %[1]s--private%[1]s, or %[1]s--internal%[1]s.
Pass %[1]s--clone%[1]s to clone the new repository locally.
To create a remote repository from an existing local repository, specify the source directory with %[1]s--source%[1]s.
By default, the remote repository name will be the name of the source directory.
Pass %[1]s--push%[1]s to push any local commits to the new repository.
`, "`"),
Example: heredoc.Doc(`
# create a repository interactively
gh repo create
# create a new remote repository and clone it locally
gh repo create my-project --public --clone
# create a remote repository from the current directory
gh repo create my-project --private --source=. --remote=upstream
`),
Args: cobra.MaximumNArgs(1),
Aliases: []string{"new"},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
opts.Name = args[0]
}
if len(args) == 0 && cmd.Flags().NFlag() == 0 {
if !opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("at least one argument required in non-interactive mode")
}
opts.Interactive = true
} else {
// exactly one visibility flag required
if !opts.Public && !opts.Private && !opts.Internal {
return cmdutil.FlagErrorf("`--public`, `--private`, or `--internal` required when not running interactively")
}
err := cmdutil.MutuallyExclusive(
"expected exactly one of `--public`, `--private`, or `--internal`",
opts.Public, opts.Private, opts.Internal)
if err != nil {
return err
}
if opts.Public {
opts.Visibility = "PUBLIC"
} else if opts.Private {
opts.Visibility = "PRIVATE"
} else {
opts.Visibility = "INTERNAL"
}
}
if opts.Source == "" {
if opts.Remote != "" {
return cmdutil.FlagErrorf("the `--remote` option can only be used with `--source`")
}
if opts.Push {
return cmdutil.FlagErrorf("the `--push` option can only be used with `--source`")
}
if opts.Name == "" && !opts.Interactive {
return cmdutil.FlagErrorf("name argument required to create new remote repository")
}
} else if opts.Clone || opts.GitIgnoreTemplate != "" || opts.LicenseTemplate != "" || opts.Template != "" {
return cmdutil.FlagErrorf("the `--source` option is not supported with `--clone`, `--template`, `--license`, or `--gitignore`")
}
if opts.Template != "" && (opts.GitIgnoreTemplate != "" || opts.LicenseTemplate != "") {
return cmdutil.FlagErrorf(".gitignore and license templates are not added when template is provided")
}
if opts.Template != "" && opts.AddReadme {
return cmdutil.FlagErrorf("the `--add-readme` option is not supported with `--template`")
}
if cmd.Flags().Changed("enable-issues") {
opts.DisableIssues = !enableIssues
}
if cmd.Flags().Changed("enable-wiki") {
opts.DisableWiki = !enableWiki
}
if opts.Template != "" && opts.Team != "" {
return cmdutil.FlagErrorf("the `--template` option is not supported with `--team`")
}
if opts.Template == "" && opts.IncludeAllBranches {
return cmdutil.FlagErrorf("the `--include-all-branches` option is only supported when using `--template`")
}
if runF != nil {
return runF(opts)
}
return createRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Description, "description", "d", "", "Description of the repository")
cmd.Flags().StringVarP(&opts.Homepage, "homepage", "h", "", "Repository home page `URL`")
cmd.Flags().StringVarP(&opts.Team, "team", "t", "", "The `name` of the organization team to be granted access")
cmd.Flags().StringVarP(&opts.Template, "template", "p", "", "Make the new repository based on a template `repository`")
cmd.Flags().BoolVar(&opts.Public, "public", false, "Make the new repository public")
cmd.Flags().BoolVar(&opts.Private, "private", false, "Make the new repository private")
cmd.Flags().BoolVar(&opts.Internal, "internal", false, "Make the new repository internal")
cmd.Flags().StringVarP(&opts.GitIgnoreTemplate, "gitignore", "g", "", "Specify a gitignore template for the repository")
cmd.Flags().StringVarP(&opts.LicenseTemplate, "license", "l", "", "Specify an Open Source License for the repository")
cmd.Flags().StringVarP(&opts.Source, "source", "s", "", "Specify path to local repository to use as source")
cmd.Flags().StringVarP(&opts.Remote, "remote", "r", "", "Specify remote name for the new repository")
cmd.Flags().BoolVar(&opts.Push, "push", false, "Push local commits to the new repository")
cmd.Flags().BoolVarP(&opts.Clone, "clone", "c", false, "Clone the new repository to the current directory")
cmd.Flags().BoolVar(&opts.DisableIssues, "disable-issues", false, "Disable issues in the new repository")
cmd.Flags().BoolVar(&opts.DisableWiki, "disable-wiki", false, "Disable wiki in the new repository")
cmd.Flags().BoolVar(&opts.IncludeAllBranches, "include-all-branches", false, "Include all branches from template repository")
cmd.Flags().BoolVar(&opts.AddReadme, "add-readme", false, "Add a README file to the new repository")
// deprecated flags
cmd.Flags().BoolP("confirm", "y", false, "Skip the confirmation prompt")
cmd.Flags().BoolVar(&enableIssues, "enable-issues", true, "Enable issues in the new repository")
cmd.Flags().BoolVar(&enableWiki, "enable-wiki", true, "Enable wiki in the new repository")
_ = cmd.Flags().MarkDeprecated("confirm", "Pass any argument to skip confirmation prompt")
_ = cmd.Flags().MarkDeprecated("enable-issues", "Disable issues with `--disable-issues`")
_ = cmd.Flags().MarkDeprecated("enable-wiki", "Disable wiki with `--disable-wiki`")
_ = cmd.RegisterFlagCompletionFunc("gitignore", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
httpClient, err := opts.HttpClient()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
cfg, err := opts.Config()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
hostname, _ := cfg.Authentication().DefaultHost()
results, err := listGitIgnoreTemplates(httpClient, hostname)
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return results, cobra.ShellCompDirectiveNoFileComp
})
_ = cmd.RegisterFlagCompletionFunc("license", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
httpClient, err := opts.HttpClient()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
cfg, err := opts.Config()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
hostname, _ := cfg.Authentication().DefaultHost()
licenses, err := listLicenseTemplates(httpClient, hostname)
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var results []string
for _, license := range licenses {
results = append(results, fmt.Sprintf("%s\t%s", license.Key, license.Name))
}
return results, cobra.ShellCompDirectiveNoFileComp
})
return cmd
}
func createRun(opts *CreateOptions) error {
if opts.Interactive {
answer, err := opts.Prompter.Select("What would you like to do?", "", []string{
"Create a new repository on GitHub from scratch",
"Create a new repository on GitHub from a template repository",
"Push an existing local repository to GitHub",
})
if err != nil {
return err
}
switch answer {
case 0:
return createFromScratch(opts)
case 1:
return createFromTemplate(opts)
case 2:
return createFromLocal(opts)
}
}
if opts.Source == "" {
return createFromScratch(opts)
}
return createFromLocal(opts)
}
// create new repo on remote host
func createFromScratch(opts *CreateOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
var repoToCreate ghrepo.Interface
cfg, err := opts.Config()
if err != nil {
return err
}
host, _ := cfg.Authentication().DefaultHost()
if opts.Interactive {
opts.Name, opts.Description, opts.Visibility, err = interactiveRepoInfo(httpClient, host, opts.Prompter, "")
if err != nil {
return err
}
opts.AddReadme, err = opts.Prompter.Confirm("Would you like to add a README file?", false)
if err != nil {
return err
}
opts.GitIgnoreTemplate, err = interactiveGitIgnore(httpClient, host, opts.Prompter)
if err != nil {
return err
}
opts.LicenseTemplate, err = interactiveLicense(httpClient, host, opts.Prompter)
if err != nil {
return err
}
targetRepo := shared.NormalizeRepoName(opts.Name)
if idx := strings.IndexRune(opts.Name, '/'); idx > 0 {
targetRepo = opts.Name[0:idx+1] + shared.NormalizeRepoName(opts.Name[idx+1:])
}
confirmed, err := opts.Prompter.Confirm(fmt.Sprintf(`This will create "%s" as a %s repository on GitHub. Continue?`, targetRepo, strings.ToLower(opts.Visibility)), true)
if err != nil {
return err
} else if !confirmed {
return cmdutil.CancelError
}
}
if strings.Contains(opts.Name, "/") {
var err error
repoToCreate, err = ghrepo.FromFullName(opts.Name)
if err != nil {
return fmt.Errorf("argument error: %w", err)
}
} else {
repoToCreate = ghrepo.NewWithHost("", opts.Name, host)
}
input := repoCreateInput{
Name: repoToCreate.RepoName(),
Visibility: opts.Visibility,
OwnerLogin: repoToCreate.RepoOwner(),
TeamSlug: opts.Team,
Description: opts.Description,
HomepageURL: opts.Homepage,
HasIssuesEnabled: !opts.DisableIssues,
HasWikiEnabled: !opts.DisableWiki,
GitIgnoreTemplate: opts.GitIgnoreTemplate,
LicenseTemplate: opts.LicenseTemplate,
IncludeAllBranches: opts.IncludeAllBranches,
InitReadme: opts.AddReadme,
}
var templateRepoMainBranch string
if opts.Template != "" {
var templateRepo ghrepo.Interface
apiClient := api.NewClientFromHTTP(httpClient)
templateRepoName := opts.Template
if !strings.Contains(templateRepoName, "/") {
currentUser, err := api.CurrentLoginName(apiClient, host)
if err != nil {
return err
}
templateRepoName = currentUser + "/" + templateRepoName
}
templateRepo, err = ghrepo.FromFullName(templateRepoName)
if err != nil {
return fmt.Errorf("argument error: %w", err)
}
repo, err := api.GitHubRepo(apiClient, templateRepo)
if err != nil {
return err
}
input.TemplateRepositoryID = repo.ID
templateRepoMainBranch = repo.DefaultBranchRef.Name
}
repo, err := repoCreate(httpClient, repoToCreate.RepoHost(), input)
if err != nil {
return err
}
cs := opts.IO.ColorScheme()
isTTY := opts.IO.IsStdoutTTY()
if isTTY {
fmt.Fprintf(opts.IO.Out,
"%s Created repository %s on GitHub\n",
cs.SuccessIconWithColor(cs.Green),
ghrepo.FullName(repo))
} else {
fmt.Fprintln(opts.IO.Out, repo.URL)
}
if opts.Interactive {
var err error
opts.Clone, err = opts.Prompter.Confirm("Clone the new repository locally?", true)
if err != nil {
return err
}
}
if opts.Clone {
protocol := cfg.GitProtocol(repo.RepoHost())
remoteURL := ghrepo.FormatRemoteURL(repo, protocol)
if !opts.AddReadme && opts.LicenseTemplate == "" && opts.GitIgnoreTemplate == "" && opts.Template == "" {
// cloning empty repository or template
if err := localInit(opts.GitClient, remoteURL, repo.RepoName()); err != nil {
return err
}
} else if err := cloneWithRetry(opts, remoteURL, templateRepoMainBranch); err != nil {
return err
}
}
return nil
}
// create new repo on remote host from template repo
func createFromTemplate(opts *CreateOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
cfg, err := opts.Config()
if err != nil {
return err
}
host, _ := cfg.Authentication().DefaultHost()
opts.Name, opts.Description, opts.Visibility, err = interactiveRepoInfo(httpClient, host, opts.Prompter, "")
if err != nil {
return err
}
if !strings.Contains(opts.Name, "/") {
username, _, err := userAndOrgs(httpClient, host)
if err != nil {
return err
}
opts.Name = fmt.Sprintf("%s/%s", username, opts.Name)
}
repoToCreate, err := ghrepo.FromFullName(opts.Name)
if err != nil {
return fmt.Errorf("argument error: %w", err)
}
templateRepo, err := interactiveRepoTemplate(httpClient, host, repoToCreate.RepoOwner(), opts.Prompter)
if err != nil {
return err
}
input := repoCreateInput{
Name: repoToCreate.RepoName(),
Visibility: opts.Visibility,
OwnerLogin: repoToCreate.RepoOwner(),
TeamSlug: opts.Team,
Description: opts.Description,
HomepageURL: opts.Homepage,
HasIssuesEnabled: !opts.DisableIssues,
HasWikiEnabled: !opts.DisableWiki,
GitIgnoreTemplate: opts.GitIgnoreTemplate,
LicenseTemplate: opts.LicenseTemplate,
IncludeAllBranches: opts.IncludeAllBranches,
InitReadme: opts.AddReadme,
TemplateRepositoryID: templateRepo.ID,
}
templateRepoMainBranch := templateRepo.DefaultBranchRef.Name
targetRepo := shared.NormalizeRepoName(opts.Name)
if idx := strings.IndexRune(opts.Name, '/'); idx > 0 {
targetRepo = opts.Name[0:idx+1] + shared.NormalizeRepoName(opts.Name[idx+1:])
}
confirmed, err := opts.Prompter.Confirm(fmt.Sprintf(`This will create "%s" as a %s repository on GitHub. Continue?`, targetRepo, strings.ToLower(opts.Visibility)), true)
if err != nil {
return err
} else if !confirmed {
return cmdutil.CancelError
}
repo, err := repoCreate(httpClient, repoToCreate.RepoHost(), input)
if err != nil {
return err
}
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.Out,
"%s Created repository %s on GitHub\n",
cs.SuccessIconWithColor(cs.Green),
ghrepo.FullName(repo))
opts.Clone, err = opts.Prompter.Confirm("Clone the new repository locally?", true)
if err != nil {
return err
}
if opts.Clone {
protocol := cfg.GitProtocol(repo.RepoHost())
remoteURL := ghrepo.FormatRemoteURL(repo, protocol)
if err := cloneWithRetry(opts, remoteURL, templateRepoMainBranch); err != nil {
return err
}
}
return nil
}
// create repo on remote host from existing local repo
func createFromLocal(opts *CreateOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
cs := opts.IO.ColorScheme()
isTTY := opts.IO.IsStdoutTTY()
stdout := opts.IO.Out
cfg, err := opts.Config()
if err != nil {
return err
}
host, _ := cfg.Authentication().DefaultHost()
if opts.Interactive {
var err error
opts.Source, err = opts.Prompter.Input("Path to local repository", ".")
if err != nil {
return err
}
}
repoPath := opts.Source
opts.GitClient.RepoDir = repoPath
var baseRemote string
if opts.Remote == "" {
baseRemote = "origin"
} else {
baseRemote = opts.Remote
}
absPath, err := filepath.Abs(repoPath)
if err != nil {
return err
}
isRepo, err := isLocalRepo(opts.GitClient)
if err != nil {
return err
}
if !isRepo {
if repoPath == "." {
return fmt.Errorf("current directory is not a git repository. Run `git init` to initialize it")
}
return fmt.Errorf("%s is not a git repository. Run `git -C \"%s\" init` to initialize it", absPath, repoPath)
}
committed, err := hasCommits(opts.GitClient)
if err != nil {
return err
}
if opts.Push {
// fail immediately if trying to push with no commits
if !committed {
return fmt.Errorf("`--push` enabled but no commits found in %s", absPath)
}
}
if opts.Interactive {
opts.Name, opts.Description, opts.Visibility, err = interactiveRepoInfo(httpClient, host, opts.Prompter, filepath.Base(absPath))
if err != nil {
return err
}
}
var repoToCreate ghrepo.Interface
// repo name will be currdir name or specified
if opts.Name == "" {
repoToCreate = ghrepo.NewWithHost("", filepath.Base(absPath), host)
} else if strings.Contains(opts.Name, "/") {
var err error
repoToCreate, err = ghrepo.FromFullName(opts.Name)
if err != nil {
return fmt.Errorf("argument error: %w", err)
}
} else {
repoToCreate = ghrepo.NewWithHost("", opts.Name, host)
}
input := repoCreateInput{
Name: repoToCreate.RepoName(),
Visibility: opts.Visibility,
OwnerLogin: repoToCreate.RepoOwner(),
TeamSlug: opts.Team,
Description: opts.Description,
HomepageURL: opts.Homepage,
HasIssuesEnabled: !opts.DisableIssues,
HasWikiEnabled: !opts.DisableWiki,
GitIgnoreTemplate: opts.GitIgnoreTemplate,
LicenseTemplate: opts.LicenseTemplate,
}
repo, err := repoCreate(httpClient, repoToCreate.RepoHost(), input)
if err != nil {
return err
}
if isTTY {
fmt.Fprintf(stdout,
"%s Created repository %s on GitHub\n",
cs.SuccessIconWithColor(cs.Green),
ghrepo.FullName(repo))
} else {
fmt.Fprintln(stdout, repo.URL)
}
protocol := cfg.GitProtocol(repo.RepoHost())
remoteURL := ghrepo.FormatRemoteURL(repo, protocol)
if opts.Interactive {
addRemote, err := opts.Prompter.Confirm("Add a remote?", true)
if err != nil {
return err
}
if !addRemote {
return nil
}
baseRemote, err = opts.Prompter.Input("What should the new remote be called?", "origin")
if err != nil {
return err
}
}
if err := sourceInit(opts.GitClient, opts.IO, remoteURL, baseRemote); err != nil {
return err
}
// don't prompt for push if there are no commits
if opts.Interactive && committed {
var err error
opts.Push, err = opts.Prompter.Confirm(fmt.Sprintf("Would you like to push commits from the current branch to %q?", baseRemote), true)
if err != nil {
return err
}
}
if opts.Push {
err := opts.GitClient.Push(context.Background(), baseRemote, "HEAD")
if err != nil {
return err
}
if isTTY {
fmt.Fprintf(stdout, "%s Pushed commits to %s\n", cs.SuccessIcon(), remoteURL)
}
}
return nil
}
func cloneWithRetry(opts *CreateOptions, remoteURL, branch string) error {
// Allow injecting alternative BackOff in tests.
if opts.BackOff == nil {
opts.BackOff = backoff.NewConstantBackOff(3 * time.Second)
}
var args []string
if branch != "" {
args = append(args, "--branch", branch)
}
ctx := context.Background()
return backoff.Retry(func() error {
stderr := &bytes.Buffer{}
_, err := opts.GitClient.Clone(ctx, remoteURL, args, git.WithStderr(stderr))
var execError errWithExitCode
if errors.As(err, &execError) && execError.ExitCode() == 128 {
return err
} else {
_, _ = io.Copy(opts.IO.ErrOut, stderr)
}
return backoff.Permanent(err)
}, backoff.WithContext(backoff.WithMaxRetries(opts.BackOff, 3), ctx))
}
func sourceInit(gitClient *git.Client, io *iostreams.IOStreams, remoteURL, baseRemote string) error {
cs := io.ColorScheme()
remoteAdd, err := gitClient.Command(context.Background(), "remote", "add", baseRemote, remoteURL)
if err != nil {
return err
}
_, err = remoteAdd.Output()
if err != nil {
return fmt.Errorf("%s Unable to add remote %q", cs.FailureIcon(), baseRemote)
}
if io.IsStdoutTTY() {
fmt.Fprintf(io.Out, "%s Added remote %s\n", cs.SuccessIcon(), remoteURL)
}
return nil
}
// check if local repository has committed changes
func hasCommits(gitClient *git.Client) (bool, error) {
hasCommitsCmd, err := gitClient.Command(context.Background(), "rev-parse", "HEAD")
if err != nil {
return false, err
}
_, err = hasCommitsCmd.Output()
if err == nil {
return true, nil
}
var execError *exec.ExitError
if errors.As(err, &execError) {
exitCode := int(execError.ExitCode())
if exitCode == 128 {
return false, nil
}
return false, err
}
return false, nil
}
// check if path is the top level directory of a git repo
func isLocalRepo(gitClient *git.Client) (bool, error) {
projectDir, projectDirErr := gitClient.GitDir(context.Background())
if projectDirErr != nil {
var execError *exec.ExitError
if errors.As(projectDirErr, &execError) {
if exitCode := int(execError.ExitCode()); exitCode == 128 {
return false, nil
}
return false, projectDirErr
}
}
if projectDir != ".git" {
return false, nil
}
return true, nil
}
// clone the checkout branch to specified path
func localInit(gitClient *git.Client, remoteURL, path string) error {
ctx := context.Background()
gitInit, err := gitClient.Command(ctx, "init", path)
if err != nil {
return err
}
_, err = gitInit.Output()
if err != nil {
return err
}
// Copy the client so we do not modify the original client's RepoDir.
gc := gitClient.Copy()
gc.RepoDir = path
gitRemoteAdd, err := gc.Command(ctx, "remote", "add", "origin", remoteURL)
if err != nil {
return err
}
_, err = gitRemoteAdd.Output()
if err != nil {
return err
}
return nil
}
func interactiveRepoTemplate(client *http.Client, hostname, owner string, prompter iprompter) (*api.Repository, error) {
templateRepos, err := listTemplateRepositories(client, hostname, owner)
if err != nil {
return nil, err
}
if len(templateRepos) == 0 {
return nil, fmt.Errorf("%s has no template repositories", owner)
}
var templates []string
for _, repo := range templateRepos {
templates = append(templates, repo.Name)
}
selected, err := prompter.Select("Choose a template repository", "", templates)
if err != nil {
return nil, err
}
return &templateRepos[selected], nil
}
func interactiveGitIgnore(client *http.Client, hostname string, prompter iprompter) (string, error) {
confirmed, err := prompter.Confirm("Would you like to add a .gitignore?", false)
if err != nil {
return "", err
} else if !confirmed {
return "", nil
}
templates, err := listGitIgnoreTemplates(client, hostname)
if err != nil {
return "", err
}
selected, err := prompter.Select("Choose a .gitignore template", "", templates)
if err != nil {
return "", err
}
return templates[selected], nil
}
func interactiveLicense(client *http.Client, hostname string, prompter iprompter) (string, error) {
confirmed, err := prompter.Confirm("Would you like to add a license?", false)
if err != nil {
return "", err
} else if !confirmed {
return "", nil
}
licenses, err := listLicenseTemplates(client, hostname)
if err != nil {
return "", err
}
licenseNames := make([]string, 0, len(licenses))
for _, license := range licenses {
licenseNames = append(licenseNames, license.Name)
}
selected, err := prompter.Select("Choose a license", "", licenseNames)
if err != nil {
return "", err
}
return licenses[selected].Key, nil
}
// name, description, and visibility
func interactiveRepoInfo(client *http.Client, hostname string, prompter iprompter, defaultName string) (string, string, string, error) {
name, owner, err := interactiveRepoNameAndOwner(client, hostname, prompter, defaultName)
if err != nil {
return "", "", "", err
}
if owner != "" {
name = fmt.Sprintf("%s/%s", owner, name)
}
description, err := prompter.Input("Description", "")
if err != nil {
return "", "", "", err
}
visibilityOptions := []string{"Public", "Private", "Internal"}
selected, err := prompter.Select("Visibility", "Public", visibilityOptions)
if err != nil {
return "", "", "", err
}
return name, description, strings.ToUpper(visibilityOptions[selected]), nil
}
func interactiveRepoNameAndOwner(client *http.Client, hostname string, prompter iprompter, defaultName string) (string, string, error) {
name, err := prompter.Input("Repository name", defaultName)
if err != nil {
return "", "", err
}
name, owner, err := splitNameAndOwner(name)
if err != nil {
return "", "", err
}
if owner != "" {
// User supplied an explicit owner prefix.
return name, owner, nil
}
username, orgs, err := userAndOrgs(client, hostname)
if err != nil {
return "", "", err
}
if len(orgs) == 0 {
// User doesn't belong to any orgs.
// Leave the owner blank to indicate a personal repo.
return name, "", nil
}
owners := append(orgs, username)
sort.Strings(owners)
selected, err := prompter.Select("Repository owner", username, owners)
if err != nil {
return "", "", err
}
owner = owners[selected]
if owner == username {
// Leave the owner blank to indicate a personal repo.
return name, "", nil
}
return name, owner, nil
}
func splitNameAndOwner(name string) (string, string, error) {
if !strings.Contains(name, "/") {
return name, "", nil
}
repo, err := ghrepo.FromFullName(name)
if err != nil {
return "", "", fmt.Errorf("argument error: %w", err)
}
return repo.RepoName(), repo.RepoOwner(), nil
}