-
Notifications
You must be signed in to change notification settings - Fork 786
/
import.go
1363 lines (1232 loc) · 38.4 KB
/
import.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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/cenkalti/backoff"
"github.com/jenkins-x/jx/pkg/cloud/amazon"
"github.com/pkg/errors"
"github.com/jenkins-x/golang-jenkins"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/jenkins"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1"
"gopkg.in/AlecAivazis/survey.v1/terminal"
gitcfg "gopkg.in/src-d/go-git.v4/config"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
//_ "github.com/Azure/draft/pkg/linguist"
"time"
"github.com/denormal/go-gitignore"
"github.com/jenkins-x/jx/pkg/prow"
"gopkg.in/yaml.v2"
)
const (
// PlaceHolderPrefix is prefix for placeholders
PlaceHolderPrefix = "REPLACE_ME"
// PlaceHolderAppName placeholder for app name
PlaceHolderAppName = PlaceHolderPrefix + "_APP_NAME"
// PlaceHolderGitProvider placeholder for git provider
PlaceHolderGitProvider = PlaceHolderPrefix + "_GIT_PROVIDER"
// PlaceHolderOrg placeholder for org
PlaceHolderOrg = PlaceHolderPrefix + "_ORG"
// PlaceHolderDockerRegistryOrg placeholder for docker registry
PlaceHolderDockerRegistryOrg = PlaceHolderPrefix + "_DOCKER_REGISTRY_ORG"
// JenkinsfileBackupSuffix the suffix used by Jenkins for backups
JenkinsfileBackupSuffix = ".backup"
minimumMavenDeployVersion = "2.8.2"
masterBranch = "master"
defaultGitIgnoreFile = `
.project
.classpath
.idea
.cache
.DS_Store
*.im?
target
work
`
)
// CallbackFn callback function
type CallbackFn func() error
// ImportOptions options struct for jx import
type ImportOptions struct {
CommonOptions
RepoURL string
Dir string
Organisation string
Repository string
Credentials string
AppName string
GitHub bool
DryRun bool
SelectAll bool
DisableDraft bool
DisableJenkinsfileCheck bool
SelectFilter string
Jenkinsfile string
BranchPattern string
GitRepositoryOptions gits.GitRepositoryOptions
ImportGitCommitMessage string
ListDraftPacks bool
DraftPack string
DockerRegistryOrg string
GitDetails gits.CreateRepoData
DisableDotGitSearch bool
InitialisedGit bool
Jenkins gojenkins.JenkinsClient
GitConfDir string
GitServer *auth.AuthServer
GitUserAuth *auth.UserAuth
GitProvider gits.GitProvider
PostDraftPackCallback CallbackFn
DisableMaven bool
PipelineUserName string
PipelineServer string
}
var (
importLong = templates.LongDesc(`
Imports a local folder or Git repository into Jenkins X.
If you specify no other options or arguments then the current directory is imported.
Or you can use '--dir' to specify a directory to import.
You can specify the git URL as an argument.
For more documentation see: [https://jenkins-x.io/developing/import/](https://jenkins-x.io/developing/import/)
` + SeeAlsoText("jx create project"))
importExample = templates.Examples(`
# Import the current folder
jx import
# Import a different folder
jx import /foo/bar
# Import a Git repository from a URL
jx import --url https://github.com/jenkins-x/spring-boot-web-example.git
# Select a number of repositories from a GitHub organisation
jx import --github --org myname
# Import all repositories from a GitHub organisation selecting ones to not import
jx import --github --org myname --all
# Import all repositories from a GitHub organisation which contain the text foo
jx import --github --org myname --all --filter foo
`)
)
// NewCmdImport the cobra command for jx import
func NewCmdImport(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := &ImportOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
},
}
cmd := &cobra.Command{
Use: "import",
Short: "Imports a local project or Git repository into Jenkins",
Long: importLong,
Example: importExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.RepoURL, "url", "u", "", "The git clone URL to clone into the current directory and then import")
cmd.Flags().BoolVarP(&options.GitHub, "github", "", false, "If you wish to pick the repositories from GitHub to import")
cmd.Flags().BoolVarP(&options.SelectAll, "all", "", false, "If selecting projects to import from a Git provider this defaults to selecting them all")
cmd.Flags().StringVarP(&options.SelectFilter, "filter", "", "", "If selecting projects to import from a Git provider this filters the list of repositories")
options.addImportFlags(cmd, false)
return cmd
}
func (options *ImportOptions) addImportFlags(cmd *cobra.Command, createProject bool) {
notCreateProject := func(text string) string {
if createProject {
return ""
}
return text
}
cmd.Flags().StringVarP(&options.Organisation, "org", "", "", "Specify the Git provider organisation to import the project into (if it is not already in one)")
cmd.Flags().StringVarP(&options.Repository, "name", "", notCreateProject("n"), "Specify the Git repository name to import the project into (if it is not already in one)")
cmd.Flags().StringVarP(&options.Credentials, "credentials", notCreateProject("c"), "", "The Jenkins credentials name used by the job")
cmd.Flags().StringVarP(&options.Jenkinsfile, "jenkinsfile", notCreateProject("j"), "", "The name of the Jenkinsfile to use. If not specified then 'Jenkinsfile' will be used")
cmd.Flags().BoolVarP(&options.DryRun, "dry-run", "", false, "Performs local changes to the repo but skips the import into Jenkins X")
cmd.Flags().BoolVarP(&options.DisableDraft, "no-draft", "", false, "Disable Draft from trying to default a Dockerfile and Helm Chart")
cmd.Flags().BoolVarP(&options.DisableJenkinsfileCheck, "no-jenkinsfile", "", false, "Disable defaulting a Jenkinsfile if its missing")
cmd.Flags().StringVarP(&options.ImportGitCommitMessage, "import-commit-message", "", "", "Specifies the initial commit message used when importing the project")
cmd.Flags().StringVarP(&options.BranchPattern, "branches", "", "", "The branch pattern for branches to trigger CI/CD pipelines on")
cmd.Flags().BoolVarP(&options.ListDraftPacks, "list-packs", "", false, "list available draft packs")
cmd.Flags().StringVarP(&options.DraftPack, "pack", "", "", "The name of the pack to use")
cmd.Flags().StringVarP(&options.DockerRegistryOrg, "docker-registry-org", "", "", "The name of the docker registry organisation to use. If not specified then the Git provider organisation will be used")
cmd.Flags().StringVarP(&options.ExternalJenkinsBaseURL, "external-jenkins-url", "", "", "The jenkins url that an external git provider needs to use")
cmd.Flags().BoolVarP(&options.DisableMaven, "disable-updatebot", "", false, "disable updatebot-maven-plugin from attempting to fix/update the maven pom.xml")
options.addCommonFlags(cmd)
addGitRepoOptionsArguments(cmd, &options.GitRepositoryOptions)
}
// Run executes the command
func (options *ImportOptions) Run() error {
if options.ListDraftPacks {
packs, err := options.allDraftPacks()
if err != nil {
log.Error(err.Error())
return err
}
log.Infoln("Available draft packs:")
for i := 0; i < len(packs); i++ {
log.Infof(packs[i] + "\n")
}
return nil
}
options.Factory.SetBatch(options.BatchMode)
var err error
isProw := false
jxClient, ns, err := options.JXClientAndDevNamespace()
if err != nil {
return err
}
if !options.DryRun {
_, err = options.KubeClient()
if err != nil {
return err
}
isProw, err = options.isProw()
if err != nil {
return err
}
if !isProw {
options.Jenkins, err = options.JenkinsClient()
if err != nil {
return err
}
}
}
err = options.DefaultsFromTeamSettings()
if err != nil {
return err
}
var userAuth *auth.UserAuth
if options.GitProvider == nil {
authConfigSvc, err := options.CreateGitAuthConfigServiceDryRun(options.DryRun)
if err != nil {
return err
}
config := authConfigSvc.Config()
var server *auth.AuthServer
if options.RepoURL != "" {
gitInfo, err := gits.ParseGitURL(options.RepoURL)
if err != nil {
return err
}
serverURL := gitInfo.HostURLWithoutUser()
server = config.GetOrCreateServer(serverURL)
} else {
server, err = config.PickOrCreateServer(gits.GitHubURL, options.GitRepositoryOptions.ServerURL, "Which Git service do you wish to use", options.BatchMode, options.In, options.Out, options.Err)
if err != nil {
return err
}
}
// Get the org in case there is more than one user auth on the server and batchMode is true
org := options.getOrganisationOrCurrentUser()
userAuth, err = config.PickServerUserAuth(server, "Git user name:", options.BatchMode, org, options.In, options.Out, options.Err)
if err != nil {
return err
}
if server.Kind == "" {
server.Kind, err = options.GitServerHostURLKind(server.URL)
if err != nil {
return err
}
}
if userAuth.IsInvalid() {
f := func(username string) error {
options.Git().PrintCreateRepositoryGenerateAccessToken(server, username, options.Out)
return nil
}
err = config.EditUserAuth(server.Label(), userAuth, userAuth.Username, true, options.BatchMode, f, options.In, options.Out, options.Err)
if err != nil {
return err
}
// TODO lets verify the auth works?
if userAuth.IsInvalid() {
return fmt.Errorf("Authentication has failed for user %v. Please check the user's access credentials and try again", userAuth.Username)
}
}
err = authConfigSvc.SaveUserAuth(server.URL, userAuth)
if err != nil {
return fmt.Errorf("Failed to store git auth configuration %s", err)
}
options.GitServer = server
options.GitUserAuth = userAuth
options.GitProvider, err = gits.CreateProvider(server, userAuth, options.Git())
if err != nil {
return err
}
}
if options.GitHub {
return options.ImportProjectsFromGitHub()
}
if options.Dir == "" {
args := options.Args
if len(args) > 0 {
options.Dir = args[0]
} else {
dir, err := os.Getwd()
if err != nil {
return err
}
options.Dir = dir
}
}
checkForJenkinsfile := options.Jenkinsfile == "" && !options.DisableJenkinsfileCheck
shouldClone := checkForJenkinsfile || !options.DisableDraft
if options.RepoURL != "" {
if shouldClone {
// lets make sure there's a .git at the end for GitHub URLs
err = options.CloneRepository()
if err != nil {
return err
}
}
} else {
err = options.DiscoverGit()
if err != nil {
return err
}
if options.RepoURL == "" {
err = options.DiscoverRemoteGitURL()
if err != nil {
return err
}
}
}
if options.AppName == "" {
if options.RepoURL != "" {
info, err := gits.ParseGitURL(options.RepoURL)
if err != nil {
log.Warnf("Failed to parse git URL %s : %s\n", options.RepoURL, err)
} else {
options.AppName = info.Name
}
}
}
if options.AppName == "" {
dir, err := filepath.Abs(options.Dir)
if err != nil {
return err
}
_, options.AppName = filepath.Split(dir)
}
options.AppName = kube.ToValidName(strings.ToLower(options.AppName))
if !options.DisableDraft {
err = options.DraftCreate()
if err != nil {
return err
}
}
err = options.fixDockerIgnoreFile()
if err != nil {
return err
}
err = options.fixMaven()
if err != nil {
return err
}
if options.RepoURL == "" {
if !options.DryRun {
err = options.CreateNewRemoteRepository()
if err != nil {
return err
}
}
} else {
if shouldClone {
err = options.Git().Push(options.Dir)
if err != nil {
return err
}
}
}
if options.DryRun {
log.Infoln("dry-run so skipping import to Jenkins X")
return nil
}
if !isProw {
err = options.checkChartmuseumCredentialExists()
if err != nil {
return err
}
}
err = kube.NewSourceRepositoryService(jxClient, ns).CreateOrUpdateSourceRepository(
options.AppName, options.Organisation, options.GitProvider.ServerURL())
if err != nil {
return errors.Wrapf(err, "creating application resource for %s", util.ColorInfo(options.AppName))
}
return options.doImport()
}
// ImportProjectsFromGitHub import projects from github
func (options *ImportOptions) ImportProjectsFromGitHub() error {
repos, err := gits.PickRepositories(options.GitProvider, options.Organisation, "Which repositories do you want to import", options.SelectAll, options.SelectFilter, options.In, options.Out, options.Err)
if err != nil {
return err
}
log.Infoln("Selected repositories")
for _, r := range repos {
o2 := ImportOptions{
CommonOptions: options.CommonOptions,
Dir: options.Dir,
RepoURL: r.CloneURL,
Organisation: options.Organisation,
Repository: r.Name,
Jenkins: options.Jenkins,
GitProvider: options.GitProvider,
DisableJenkinsfileCheck: options.DisableJenkinsfileCheck,
DisableDraft: options.DisableDraft,
}
log.Infof("Importing repository %s\n", util.ColorInfo(r.Name))
err = o2.Run()
if err != nil {
return err
}
}
return nil
}
// DraftCreate creates a draft
func (options *ImportOptions) DraftCreate() error {
// TODO this is a workaround of this draft issue:
// https://github.com/Azure/draft/issues/476
dir := options.Dir
var err error
jenkinsfile := jenkins.DefaultJenkinsfile
withRename := false
if options.Jenkinsfile != "" {
jenkinsfile = options.Jenkinsfile
withRename = true
}
defaultJenkinsfile := filepath.Join(dir, jenkins.DefaultJenkinsfile)
if !filepath.IsAbs(jenkinsfile) {
jenkinsfile = filepath.Join(dir, jenkinsfile)
}
args := &InvokeDraftPack{
Dir: dir,
CustomDraftPack: options.DraftPack,
Jenkinsfile: jenkinsfile,
DefaultJenkinsfile: defaultJenkinsfile,
WithRename: withRename,
InitialisedGit: options.InitialisedGit,
DisableJenkinsfileCheck: options.DisableJenkinsfileCheck,
}
options.DraftPack, err = options.invokeDraftPack(args)
if err != nil {
return err
}
// lets rename the chart to be the same as our app name
err = options.renameChartToMatchAppName()
if err != nil {
return err
}
if options.PostDraftPackCallback != nil {
err = options.PostDraftPackCallback()
if err != nil {
return err
}
}
gitServerName, err := gits.GetHost(options.GitProvider)
if err != nil {
return err
}
if options.GitUserAuth == nil {
userAuth := options.GitProvider.UserAuth()
options.GitUserAuth = &userAuth
}
if options.Organisation == "" {
gitUsername := options.GitUserAuth.Username
options.Organisation, err = gits.GetOwner(options.BatchMode, options.GitProvider, gitUsername, options.In, options.Out, options.Err)
if err != nil {
return err
}
}
if options.AppName == "" {
dir := options.Dir
_, defaultRepoName := filepath.Split(dir)
options.AppName, err = gits.GetRepoName(options.BatchMode, false, options.GitProvider, defaultRepoName, options.Organisation, options.In, options.Out, options.Err)
if err != nil {
return err
}
}
dockerRegistryOrg := options.getDockerRegistryOrg()
err = options.ReplacePlaceholders(gitServerName, dockerRegistryOrg)
if err != nil {
return err
}
// Create Prow owners file
err = options.CreateProwOwnersFile()
if err != nil {
return err
}
err = options.CreateProwOwnersAliasesFile()
if err != nil {
return err
}
err = options.Git().Add(dir, "*")
if err != nil {
return err
}
err = options.Git().CommitIfChanges(dir, "Draft create")
if err != nil {
return err
}
return nil
}
func (options *ImportOptions) getDockerRegistryOrg() string {
dockerRegistryOrg := options.DockerRegistryOrg
if dockerRegistryOrg == "" {
dockerRegistryOrg = options.getOrganisationOrCurrentUser()
}
return dockerRegistryOrg
}
func (options *ImportOptions) getOrganisationOrCurrentUser() string {
org := options.getOrganisation()
if org == "" {
org = options.getCurrentUser()
}
return org
}
func (options *ImportOptions) getCurrentUser() string {
//walk through every file in the given dir and update the placeholders
var currentUser string
if options.GitServer != nil {
currentUser = options.GitServer.CurrentUser
if currentUser == "" {
if options.GitProvider != nil {
currentUser = options.GitProvider.CurrentUsername()
}
}
}
if currentUser == "" {
log.Warn("No username defined for the current Git server!")
currentUser = options.GitRepositoryOptions.Username
}
return currentUser
}
func (options *ImportOptions) getOrganisation() string {
org := ""
gitInfo, err := gits.ParseGitURL(options.RepoURL)
if err == nil && gitInfo.Organisation != "" {
org = gitInfo.Organisation
} else {
org = options.Organisation
}
return org
}
// CreateNewRemoteRepository creates a new remote repository
func (options *ImportOptions) CreateNewRemoteRepository() error {
authConfigSvc, err := options.CreateGitAuthConfigService()
if err != nil {
return err
}
dir := options.Dir
_, defaultRepoName := filepath.Split(dir)
options.GitRepositoryOptions.Owner = options.getOrganisation()
details := &options.GitDetails
if details.RepoName == "" {
details, err = gits.PickNewGitRepository(options.BatchMode, authConfigSvc, defaultRepoName, &options.GitRepositoryOptions,
options.GitServer, options.GitUserAuth, options.Git(), options.In, options.Out, options.Err)
if err != nil {
return err
}
}
repo, err := details.CreateRepository()
if err != nil {
return err
}
options.GitProvider = details.GitProvider
options.RepoURL = repo.CloneURL
pushGitURL, err := options.Git().CreatePushURL(repo.CloneURL, details.User)
if err != nil {
return err
}
err = options.Git().AddRemote(dir, "origin", pushGitURL)
if err != nil {
return err
}
err = options.Git().PushMaster(dir)
if err != nil {
return err
}
log.Infof("Pushed Git repository to %s\n\n", util.ColorInfo(repo.HTMLURL))
// If the user creating the repo is not the pipeline user, add the pipeline user as a contributor to the repo
if options.PipelineUserName != options.GitUserAuth.Username && options.GitServer.URL == options.PipelineServer {
// Make the invitation
err := options.GitProvider.AddCollaborator(options.PipelineUserName, details.Organisation, details.RepoName)
if err != nil {
return err
}
// If repo is put in an organisation that the pipeline user is not part of an invitation needs to be accepted.
// Create a new provider for the pipeline user
authConfig := authConfigSvc.Config()
if err != nil {
return err
}
pipelineUserAuth := authConfig.FindUserAuth(options.GitServer.URL, options.PipelineUserName)
if pipelineUserAuth == nil {
log.Warnf("Pipeline Git user credentials not found. %s will need to accept the invitation to collaborate\n"+
"on %s if %s is not part of %s.\n\n",
options.PipelineUserName, details.RepoName, options.PipelineUserName, details.Organisation)
} else {
pipelineServerAuth := authConfig.GetServer(authConfig.CurrentServer)
pipelineUserProvider, err := gits.CreateProvider(pipelineServerAuth, pipelineUserAuth, options.Git())
if err != nil {
return err
}
// Get all invitations for the pipeline user
// Wrapped in retry to not immediately fail the quickstart creation if APIs are flaky.
f := func() error {
invites, _, err := pipelineUserProvider.ListInvitations()
if err != nil {
return err
}
for _, x := range invites {
// Accept all invitations for the pipeline user
_, err = pipelineUserProvider.AcceptInvitation(*x.ID)
if err != nil {
return err
}
}
return nil
}
exponentialBackOff := backoff.NewExponentialBackOff()
timeout := 20 * time.Second
exponentialBackOff.MaxElapsedTime = timeout
exponentialBackOff.Reset()
err = backoff.Retry(f, exponentialBackOff)
if err != nil {
return err
}
}
}
return nil
}
// CloneRepository clones a repository
func (options *ImportOptions) CloneRepository() error {
url := options.RepoURL
if url == "" {
return fmt.Errorf("no Git repository URL defined")
}
gitInfo, err := gits.ParseGitURL(url)
if err != nil {
return fmt.Errorf("failed to parse Git URL %s due to: %s", url, err)
}
if gitInfo.Host == gits.GitHubHost && strings.HasPrefix(gitInfo.Scheme, "http") {
if !strings.HasSuffix(url, ".git") {
url += ".git"
}
options.RepoURL = url
}
cloneDir, err := util.CreateUniqueDirectory(options.Dir, gitInfo.Name, util.MaximumNewDirectoryAttempts)
if err != nil {
return errors.Wrapf(err, "failed to create unique directory for '%s'", options.Dir)
}
err = options.Git().Clone(url, cloneDir)
if err != nil {
return errors.Wrapf(err, "failed to clone in directory '%s'", cloneDir)
}
options.Dir = cloneDir
return nil
}
// DiscoverGit checks if there is a git clone or prompts the user to import it
func (options *ImportOptions) DiscoverGit() error {
surveyOpts := survey.WithStdio(options.In, options.Out, options.Err)
if !options.DisableDotGitSearch {
root, gitConf, err := options.Git().FindGitConfigDir(options.Dir)
if err != nil {
return err
}
if root != "" {
if root != options.Dir {
log.Infof("Importing from directory %s as we found a .git folder there\n", root)
}
options.Dir = root
options.GitConfDir = gitConf
return nil
}
}
dir := options.Dir
if dir == "" {
return fmt.Errorf("no directory specified")
}
// lets prompt the user to initialise the Git repository
if !options.BatchMode {
log.Infof("The directory %s is not yet using git\n", util.ColorInfo(dir))
flag := false
prompt := &survey.Confirm{
Message: "Would you like to initialise git now?",
Default: true,
}
err := survey.AskOne(prompt, &flag, nil, surveyOpts)
if err != nil {
return err
}
if !flag {
return fmt.Errorf("please initialise git yourself then try again")
}
}
options.InitialisedGit = true
err := options.Git().Init(dir)
if err != nil {
return err
}
options.GitConfDir = filepath.Join(dir, ".git", "config")
err = options.DefaultGitIgnore()
if err != nil {
return err
}
options.Git().Add(dir, ".gitignore")
err = options.Git().Add(dir, "*")
if err != nil {
return err
}
err = options.Git().Status(dir)
if err != nil {
return err
}
message := options.ImportGitCommitMessage
if message == "" {
if options.BatchMode {
message = "Initial import"
} else {
messagePrompt := &survey.Input{
Message: "Commit message: ",
Default: "Initial import",
}
err = survey.AskOne(messagePrompt, &message, nil, surveyOpts)
if err != nil {
return err
}
}
}
err = options.Git().CommitIfChanges(dir, message)
if err != nil {
return err
}
log.Infof("\nGit repository created\n")
return nil
}
// DefaultGitIgnore creates a default .gitignore
func (options *ImportOptions) DefaultGitIgnore() error {
name := filepath.Join(options.Dir, ".gitignore")
exists, err := util.FileExists(name)
if err != nil {
return err
}
if !exists {
data := []byte(defaultGitIgnoreFile)
err = ioutil.WriteFile(name, data, DefaultWritePermissions)
if err != nil {
return fmt.Errorf("failed to write %s due to %s", name, err)
}
}
return nil
}
// DiscoverRemoteGitURL finds the git url by looking in the directory
// and looking for a .git/config file
func (options *ImportOptions) DiscoverRemoteGitURL() error {
gitConf := options.GitConfDir
if gitConf == "" {
return fmt.Errorf("no GitConfDir defined")
}
cfg := gitcfg.NewConfig()
data, err := ioutil.ReadFile(gitConf)
if err != nil {
return fmt.Errorf("failed to load %s due to %s", gitConf, err)
}
err = cfg.Unmarshal(data)
if err != nil {
return fmt.Errorf("failed to unmarshal %s due to %s", gitConf, err)
}
remotes := cfg.Remotes
if len(remotes) == 0 {
return nil
}
url := options.Git().GetRemoteUrl(cfg, "origin")
if url == "" {
url = options.Git().GetRemoteUrl(cfg, "upstream")
if url == "" {
url, err = options.pickRemoteURL(cfg)
if err != nil {
return err
}
}
}
if url != "" {
options.RepoURL = url
}
return nil
}
func (options *ImportOptions) doImport() error {
gitURL := options.RepoURL
gitProvider := options.GitProvider
if gitProvider == nil {
p, err := options.gitProviderForURL(gitURL, "user name to register webhook")
if err != nil {
return err
}
gitProvider = p
}
authConfigSvc, err := options.CreateGitAuthConfigService()
if err != nil {
return err
}
jenkinsfile := options.Jenkinsfile
if jenkinsfile == "" {
jenkinsfile = jenkins.DefaultJenkinsfile
}
err = options.ensureDockerRepositoryExists()
if err != nil {
return err
}
isProw, err := options.isProw()
if err != nil {
return err
}
if isProw {
// register the webhook
err = options.createWebhookProw(gitURL, gitProvider)
if err != nil {
return err
}
return options.addProwConfig(gitURL)
}
return options.ImportProject(gitURL, options.Dir, jenkinsfile, options.BranchPattern, options.Credentials, false, gitProvider, authConfigSvc, false, options.BatchMode)
}
func (options *ImportOptions) addProwConfig(gitURL string) error {
gitInfo, err := gits.ParseGitURL(gitURL)
if err != nil {
return err
}
repo := gitInfo.Organisation + "/" + gitInfo.Name
client, err := options.KubeClient()
if err != nil {
return err
}
err = prow.AddApplication(client, []string{repo}, options.currentNamespace, options.DraftPack)
if err != nil {
return err
}
startBuildOptions := StartPipelineOptions{
GetOptions: GetOptions{
CommonOptions: CommonOptions{
Factory: options.Factory,
},
},
}
startBuildOptions.Args = []string{fmt.Sprintf("%s/%s/%s", gitInfo.Organisation, gitInfo.Name, masterBranch)}
err = startBuildOptions.Run()
if err != nil {
return fmt.Errorf("failed to start pipeline build")
}
options.logImportedProject(false, gitInfo)
return nil
}
// ensureDockerRepositoryExists for some kinds of container registry we need to pre-initialise its use such as for ECR
func (options *ImportOptions) ensureDockerRepositoryExists() error {
orgName := options.getOrganisationOrCurrentUser()
appName := options.AppName
if orgName == "" {
log.Warnf("Missing organisation name!\n")
return nil
}
if appName == "" {
log.Warnf("Missing application name!\n")
return nil
}
kubeClient, curNs, err := options.KubeClientAndNamespace()
if err != nil {
return err
}
ns, _, err := kube.GetDevNamespace(kubeClient, curNs)
if err != nil {
return err
}
region, _ := kube.ReadRegion(kubeClient, ns)
cm, err := kubeClient.CoreV1().ConfigMaps(ns).Get(kube.ConfigMapJenkinsDockerRegistry, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("Could not find ConfigMap %s in namespace %s: %s", kube.ConfigMapJenkinsDockerRegistry, ns, err)
}
if cm.Data != nil {
dockerRegistry := cm.Data["docker.registry"]
if dockerRegistry != "" {
if strings.HasSuffix(dockerRegistry, ".amazonaws.com") && strings.Index(dockerRegistry, ".ecr.") > 0 {
return amazon.LazyCreateRegistry(kubeClient, ns, region, dockerRegistry, orgName, appName)
}
}
}
return nil
}
// ReplacePlaceholders replaces app name, git server name, git org, and docker registry org placeholders
func (options *ImportOptions) ReplacePlaceholders(gitServerName, dockerRegistryOrg string) error {
options.Organisation = kube.ToValidName(strings.ToLower(options.Organisation))
log.Infof("replacing placeholders in directory %s\n", options.Dir)
log.Infof("app name: %s, git server: %s, org: %s, Docker registry org: %s\n", options.AppName, gitServerName, options.Organisation, dockerRegistryOrg)
ignore, err := gitignore.NewRepository(options.Dir)
if err != nil {
return err
}
replacer := strings.NewReplacer(
PlaceHolderAppName, strings.ToLower(options.AppName),
PlaceHolderGitProvider, strings.ToLower(gitServerName),
PlaceHolderOrg, strings.ToLower(options.Organisation),
PlaceHolderDockerRegistryOrg, strings.ToLower(dockerRegistryOrg))
pathsToRename := []string{} // Renaming must be done post-Walk
if err := filepath.Walk(options.Dir, func(f string, fi os.FileInfo, err error) error {
if skip, err := options.skipPathForReplacement(f, fi, ignore); skip {
return err
}
if strings.Contains(filepath.Base(f), PlaceHolderPrefix) {
// Prepend so children are renamed before their parents
pathsToRename = append([]string{f}, pathsToRename...)
}
if !fi.IsDir() {
if err := replacePlaceholdersInFile(replacer, f); err != nil {
return err
}
}