-
Notifications
You must be signed in to change notification settings - Fork 30
/
import.go
1552 lines (1406 loc) · 48.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 importcmd
import (
"context"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/denormal/go-gitignore"
"github.com/jenkins-x-plugins/jx-project/pkg/cmd/common"
"github.com/jenkins-x-plugins/jx-project/pkg/config"
"github.com/jenkins-x-plugins/jx-project/pkg/constants"
"github.com/jenkins-x-plugins/jx-project/pkg/maven"
"github.com/jenkins-x-plugins/jx-project/pkg/prow"
"github.com/jenkins-x/go-scm/scm"
v1 "github.com/jenkins-x/jx-api/v4/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx-api/v4/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx-helpers/v3/pkg/boot"
"github.com/jenkins-x/jx-helpers/v3/pkg/cmdrunner"
"github.com/jenkins-x/jx-helpers/v3/pkg/cobras/helper"
"github.com/jenkins-x/jx-helpers/v3/pkg/cobras/templates"
"github.com/jenkins-x/jx-helpers/v3/pkg/files"
"github.com/jenkins-x/jx-helpers/v3/pkg/gitclient"
"github.com/jenkins-x/jx-helpers/v3/pkg/gitclient/cli"
"github.com/jenkins-x/jx-helpers/v3/pkg/gitclient/gitdiscovery"
"github.com/jenkins-x/jx-helpers/v3/pkg/gitclient/giturl"
"github.com/jenkins-x/jx-helpers/v3/pkg/input"
"github.com/jenkins-x/jx-helpers/v3/pkg/input/inputfactory"
"github.com/jenkins-x/jx-helpers/v3/pkg/kube"
"github.com/jenkins-x/jx-helpers/v3/pkg/kube/jxclient"
"github.com/jenkins-x/jx-helpers/v3/pkg/kube/jxenv"
"github.com/jenkins-x/jx-helpers/v3/pkg/kube/naming"
"github.com/jenkins-x/jx-helpers/v3/pkg/options"
"github.com/jenkins-x/jx-helpers/v3/pkg/scmhelpers"
"github.com/jenkins-x/jx-helpers/v3/pkg/termcolor"
"github.com/jenkins-x/jx-logging/v3/pkg/log"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/yaml"
)
// CallbackFn callback function
type CallbackFn func() error
// ImportOptions options struct for jx-project import
type ImportOptions struct {
options.BaseOptions
Args []string
RepoURL string
GitProviderURL string
DiscoveredGitURL string
Dir string
Organisation string
Repository string
// Credentials string
AppName string
SelectFilter string
Jenkinsfile string
// BranchPattern string
ImportGitCommitMessage string
Pack string
DockerRegistryOrg string
DeployKind string
SchedulerName string
GitConfDir string
PipelineUserName string
PipelineServer string
// ImportMode string
ServiceAccount string
Namespace string
OperatorNamespace string
BootSecretName string
PipelineCatalogDir string
DisableMaven bool
UseDefaultGit bool
GithubAppInstalled bool
GitHub bool
DryRun bool
SelectAll bool
DisableBuildPack bool
DisableWebhooks bool
DisableDotGitSearch bool
DisableStartPipeline bool
InitialisedGit bool
WaitForSourceRepositoryPullRequest bool
NoDevPullRequest bool
IgnoreExistingRepository bool
IgnoreCollaborator bool
IgnoreJenkinsXFile bool
PullRequestPollPeriod time.Duration
PullRequestPollTimeout time.Duration
DeployOptions v1.DeployOptions
GitRepositoryOptions scm.RepositoryInput
KubeClient kubernetes.Interface
JXClient versioned.Interface
Input input.Interface
ScmFactory scmhelpers.Factory
Gitter gitclient.Interface
CommandRunner cmdrunner.CommandRunner
DevEnv *v1.Environment
BootScmClient *scm.Client
OnCompleteCallback func() error
PostDraftPackCallback CallbackFn
gitInfo *giturl.GitRepository
Destination ImportDestination
reporter ImportReporter
PackFilter func(*Pack)
// env customization
EnvName string
EnvStrategy string
NestedRepo bool
/*
TODO jenkins support
Jenkins gojenkins.JenkinsClient
jenkinsClientFactory *jenkinsutil.ClientFactory
*/
}
const (
updateBotMavenPluginVersion = "RELEASE"
jenkinsfileName = "Jenkinsfile"
)
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/docs/using-jx/creating/import/](https://jenkins-x.io/docs/using-jx/creating/import/)
`)
importExample = templates.Examples(`
# Import the current folder
%s import
# Import a different folder
%s import /foo/bar
# Import a Git repository from a URL
%s import --url https://github.com/jenkins-x/spring-boot-web-example.git
# Select a number of repositories from a GitHub organisation
%s import --github --org myname
# Import all repositories from a GitHub organisation selecting ones to not import
%s import --github --org myname --all
# Import all repositories from a GitHub organisation which contain the text foo
%s import --github --org myname --all --filter foo
`)
deployKinds = []string{constants.DeployKindKnative, constants.DeployKindDefault}
)
// NewCmdImport the cobra command for jx-project import
func NewCmdImport() *cobra.Command {
cmd, _ := NewCmdImportAndOptions()
return cmd
}
// NewCmdImportAndOptions creates the cobra command for jx-project import and the options
func NewCmdImportAndOptions() (*cobra.Command, *ImportOptions) {
options := &ImportOptions{}
cmd := &cobra.Command{
Use: "import",
Short: "Imports a local project or Git repository into Jenkins",
Long: importLong,
Example: fmt.Sprintf(importExample, common.BinaryName, common.BinaryName, common.BinaryName, common.BinaryName, common.BinaryName, common.BinaryName),
Run: func(cmd *cobra.Command, args []string) {
err := options.Run()
helper.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")
options.AddImportFlags(cmd, false)
return cmd, options
}
func (o *ImportOptions) AddImportFlags(cmd *cobra.Command, createProject bool) {
notCreateProject := func(text string) string {
if createProject {
return ""
}
return text
}
cmd.Flags().StringVarP(&o.GitProviderURL, "git-provider-url", "", "", "Deprecated: please use --git-server")
cmd.Flags().StringVarP(&o.Organisation, "org", "", "", "Specify the Git provider organisation to import the project into (if it is not already in one)")
cmd.Flags().StringVarP(&o.Dir, "dir", "", ".", "Specify the directory to import")
cmd.Flags().StringVarP(&o.PipelineCatalogDir, "pipeline-catalog-dir", "", "", "The pipeline catalog directory you want to use instead of the buildPackGitURL in the dev Environment Team settings. Generally only used for testing pipelines")
cmd.Flags().StringVarP(&o.Repository, "name", notCreateProject("n"), "", "Specify the Git repository name to import the project into (if it is not already in one)")
cmd.Flags().BoolVarP(&o.DryRun, "dry-run", "", false, "Performs local changes to the repo but skips the import into Jenkins X")
cmd.Flags().BoolVarP(&o.DisableBuildPack, "no-pack", "", false, "Disable trying to default a Dockerfile and Helm Chart from the pipeline catalog pack")
cmd.Flags().StringVarP(&o.ImportGitCommitMessage, "import-commit-message", "", "", "Specifies the initial commit message used when importing the project")
cmd.Flags().StringVarP(&o.Pack, "pack", "", "", "The name of the pipeline catalog pack to use. If none is specified it will be chosen based on matching the source code languages")
cmd.Flags().StringVarP(&o.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(&o.OperatorNamespace, "operator-namespace", "", boot.GitOperatorNamespace, "The namespace where the git operator is installed")
cmd.Flags().StringVarP(&o.BootSecretName, "boot-secret-name", "", boot.SecretName, "The name of the boot secret")
cmd.Flags().BoolVarP(&o.UseDefaultGit, "use-default-git", "", false, "use default git account")
cmd.Flags().StringVarP(&o.DeployKind, "deploy-kind", "", "", fmt.Sprintf("The kind of deployment to use for the project. Should be one of %s", strings.Join(deployKinds, ", ")))
cmd.Flags().BoolVarP(&o.DeployOptions.Canary, constants.OptionCanary, "", false, "should we use canary rollouts (progressive delivery) by default for this application. e.g. using a Canary deployment via flagger. Requires the installation of flagger and istio/gloo in your cluster")
cmd.Flags().BoolVarP(&o.DeployOptions.HPA, constants.OptionHPA, "", false, "should we enable the Horizontal Pod Autoscaler for this application.")
cmd.Flags().BoolVarP(&o.Destination.JenkinsX.Enabled, "jx", "", false, "if you want to default to importing this project into Jenkins X instead of a Jenkins server if you have a mixed Jenkins X and Jenkins cluster")
cmd.Flags().StringVarP(&o.Destination.JenkinsfileRunner.Image, "jenkinsfilerunner", "", "", "if you want to import into Jenkins X with Jenkinsfilerunner this argument lets you specify the container image to use")
cmd.Flags().StringVar(&o.ServiceAccount, "service-account", "tekton-bot", "The Kubernetes ServiceAccount to use to run the initial pipeline")
cmd.Flags().BoolVarP(&o.WaitForSourceRepositoryPullRequest, "wait-for-pr", "", true, "waits for the Pull Request generated on the cluster environment git repository to merge")
cmd.Flags().BoolVarP(&o.NoDevPullRequest, "no-dev-pr", "", false, "disables generating a Pull Request on the cluster git repository")
cmd.Flags().BoolVarP(&o.DisableStartPipeline, "no-start", "", false, "disables starting a release pipeline when importing/creating a new project")
cmd.Flags().BoolVarP(&o.IgnoreCollaborator, "no-collaborator", "", false, "disables checking if the bot user is a collaborator. Only used if you have an issue with your git provider and this functionality in go-scm")
cmd.Flags().DurationVarP(&o.PullRequestPollPeriod, "pr-poll-period", "", time.Second*20, "the time between polls of the Pull Request on the cluster environment git repository")
cmd.Flags().DurationVarP(&o.PullRequestPollTimeout, "pr-poll-timeout", "", time.Minute*20, "the maximum amount of time we wait for the Pull Request on the cluster environment git repository")
cmd.Flags().StringVar(&o.EnvName, "env-name", "", "The name of the environment to create (only used for env projects)")
// FIXME parse enum and through what specified do not fit in enum
cmd.Flags().StringVar(&o.EnvStrategy, "env-strategy", "Never", "The promotion strategy of the environment to create (only used for env projects)")
cmd.Flags().BoolVarP(&o.NestedRepo, "nested-repo", "", false, "Specify if using nested repositories (in gitlab)")
o.BaseOptions.AddBaseFlags(cmd)
o.ScmFactory.AddFlags(cmd)
cmd.Flags().StringVarP(&o.Destination.Jenkins.Server, "jenkins", "", "", "The name of the Jenkins server to import the project into")
}
// Validate validates the command line options
func (o *ImportOptions) Validate() error {
err := o.BaseOptions.Validate()
if err != nil {
return errors.Wrapf(err, "failed to validate base options")
}
if o.Input == nil {
o.Input = inputfactory.NewInput(&o.BaseOptions)
}
o.KubeClient, o.Namespace, err = kube.LazyCreateKubeClientAndNamespace(o.KubeClient, o.Namespace)
if err != nil {
return errors.Wrapf(err, "failed to create the kube client")
}
o.JXClient, err = jxclient.LazyCreateJXClient(o.JXClient)
if err != nil {
return errors.Wrapf(err, "failed to create the jx client")
}
if o.CommandRunner == nil {
o.CommandRunner = cmdrunner.QuietCommandRunner
}
if o.DevEnv == nil {
o.DevEnv, err = jxenv.GetDevEnvironment(o.JXClient, o.Namespace)
if err != nil {
return errors.Wrapf(err, "failed to find the dev Environment")
}
}
if o.DevEnv == nil {
extraMessage := ""
if o.Namespace != "jx" {
extraMessage = " Please run 'jx ns jx' to switch to the development namespace and retry this command"
}
return errors.Errorf("could not find the dev Environment in the namespace %s.%s", o.Namespace, extraMessage)
}
if o.ScmFactory.GitServerURL == "" && o.GitProviderURL != "" {
o.ScmFactory.GitServerURL = o.GitProviderURL
}
if o.ScmFactory.GitServerURL == "" && o.gitInfo != nil {
o.ScmFactory.GitServerURL = o.gitInfo.HostURL()
}
if o.ScmFactory.GitServerURL == "" {
o.ScmFactory.GitServerURL, err = o.defaultGitServerURLFromDevEnv()
if err != nil {
return errors.Wrapf(err, "failed to default the git server URL from the dev Environment")
}
}
if o.ScmFactory.GitServerURL == "" {
return options.MissingOption("git-server")
}
if o.ScmFactory.GitKind == "" {
o.ScmFactory.GitKind = giturl.SaasGitKind(o.ScmFactory.GitServerURL)
if o.ScmFactory.GitKind == "" {
log.Logger().Infof("no --git-kind supplied for server %s so assuming kind is github", o.ScmFactory.GitServerURL)
o.ScmFactory.GitKind = "github"
}
}
if o.ScmFactory.ScmClient == nil {
if !o.BatchMode && o.ScmFactory.Input == nil {
o.ScmFactory.Input = o.Input
}
o.ScmFactory.ScmClient, err = o.ScmFactory.Create()
if err != nil {
return errors.Wrapf(err, "failed to create ScmClient")
}
}
if o.Dir == "" {
dir, err := os.Getwd()
if err != nil {
return err
}
o.Dir = dir
}
return nil
}
// Run executes the command
func (o *ImportOptions) Run() error {
err := o.Validate()
if err != nil {
return errors.Wrapf(err, "failed to validate options")
}
o.DiscoveredGitURL = o.RepoURL
if o.RepoURL == "" {
err = o.DiscoverGit()
if err != nil {
return err
}
o.DiscoveredGitURL, err = gitdiscovery.FindGitURLFromDir(o.Dir, true)
if err != nil {
return errors.Wrapf(err, "failed to discover the git URL")
}
}
if o.DiscoveredGitURL != "" {
o.gitInfo, err = giturl.ParseGitURL(o.DiscoveredGitURL)
if err != nil {
return err
}
}
err = o.DefaultsFromTeamSettings()
if err != nil {
return err
}
/* TODO
if o.GitHub {
return o.ImportProjectsFromGitHub()
}
*/
checkForJenkinsfile := o.Jenkinsfile == ""
shouldClone := checkForJenkinsfile || !o.DisableBuildPack
if o.RepoURL != "" {
if shouldClone {
o.RepoURL, err = o.ScmFactory.CreateAuthenticatedURL(o.RepoURL)
if err != nil {
return err
}
err = o.CloneRepository()
if err != nil {
return err
}
}
}
if o.AppName == "" && o.gitInfo != nil {
o.Organisation = o.gitInfo.Organisation
o.AppName = o.gitInfo.Name
}
if o.AppName == "" {
dir, err := filepath.Abs(o.Dir)
if err != nil {
return err
}
_, o.AppName = filepath.Split(dir)
}
if o.Repository == "" && o.NestedRepo {
o.Repository = o.AppName
}
o.AppName = naming.ToValidName(strings.ToLower(o.AppName))
jenkinsfile, err := o.HasJenkinsfile()
if err != nil {
return err
}
devEnvCloneDir, err := o.CloneDevEnvironment()
if err != nil {
return errors.Wrapf(err, "failed to clone dev env git repository")
}
if jenkinsfile != "" {
// lets pick the import destination for the jenkinsfile
o.Destination, err = o.PickImportDestination(devEnvCloneDir, jenkinsfile)
if err != nil {
return err
}
if o.Destination.Jenkins.Server != "" {
// lets not run the Jenkins X build packs
o.DisableBuildPack = true
} else if o.Destination.JenkinsfileRunner.Enabled {
o.DisableBuildPack = false
o.Pack = "jenkinsfilerunner"
}
}
// lets disable the build pack if we have a jenkins-x.yml or a .lighthouse/*/triggers.yaml file
jxProjectFile := filepath.Join(o.Dir, config.ProjectConfigFileName)
jxProjectFileExists, err := files.FileExists(jxProjectFile)
if err != nil {
return errors.Wrapf(err, "failed to check if dir contains a %s file", jxProjectFile)
}
if jxProjectFileExists && !o.IgnoreJenkinsXFile {
converted, err := o.convertOldPipeline()
if err != nil {
return errors.Wrapf(err, "failed to convert old pipeline")
}
o.DisableBuildPack = true
if !converted {
// we may need to add a custom build pack to handle the old jenkins-x.yml build packs
projectConfig, projectConfigFile, err := config.LoadProjectConfig(o.Dir)
if err != nil {
return errors.Wrapf(err, "failed to load project oconfig file from %s", o.Dir)
}
if projectConfig.BuildPackGitURef == "" || strings.HasPrefix(projectConfig.BuildPackGitURef, "https://github.com/jenkins-x/jx3-pipeline-catalog") {
projectConfig.BuildPackGitURef = "https://github.com/jenkins-x/jxr-packs-kubernetes"
err = projectConfig.SaveConfig(projectConfigFile)
if err != nil {
return errors.Wrapf(err, "failed to save config file %s", projectConfigFile)
}
}
}
}
if !o.DisableBuildPack {
g := filepath.Join(o.Dir, ".lighthouse", "*", "triggers.yaml")
matches, err := filepath.Glob(g)
if err != nil {
return errors.Wrapf(err, "failed to evaluate glob %s", g)
}
if len(matches) > 0 {
o.DisableBuildPack = true
}
}
if !o.DisableBuildPack {
err = o.EvaluateBuildPack(devEnvCloneDir, jenkinsfile)
if err != nil {
return err
}
}
o.OnCompleteCallback = func() error {
if !o.DisableBuildPack {
log.Logger().Infof("committing the pipeline catalog changes...")
_, err = gitclient.AddAndCommitFiles(o.Git(), o.Dir, "chore: Jenkins X build pack")
if err != nil {
return err
}
}
err = o.fixDockerIgnoreFile()
if err != nil {
return err
}
err = o.fixMaven()
if err != nil {
return err
}
if shouldClone {
err = gitclient.Push(o.Git(), o.Dir, "origin", false, "HEAD")
if err != nil {
return err
}
}
return nil
}
newRepository := false
if o.DiscoveredGitURL == "" {
if !o.DryRun {
err = o.CreateNewRemoteRepository()
if err != nil {
if !o.DisableBuildPack {
log.Logger().Warn("Remote repository creation failed. In order to retry consider adding '--no-pack' option.")
}
return err
}
newRepository = true
}
}
if o.DryRun {
shouldClone = false
err = o.OnCompleteCallback()
if err != nil {
return errors.Wrapf(err, "failed to fix dockerfile and maven")
}
log.Logger().Info("dry-run so skipping actual import to Jenkins X")
return nil
}
if !o.IgnoreCollaborator {
err = o.AddAndAcceptCollaborator(newRepository)
if err != nil {
return errors.Wrapf(err, "failed to add and accept collaborator")
}
}
gitURL := ""
if o.DiscoveredGitURL != "" {
gitInfo, err := giturl.ParseGitURL(o.DiscoveredGitURL)
if err != nil {
return err
}
gitURL = gitInfo.URLWithoutUser()
}
if gitURL == "" {
return errors.Errorf("no git URL could be found")
}
/* TODO github app support
if !o.GithubAppInstalled {
githubAppMode, err := o.IsGitHubAppMode()
if err != nil {
return err
}
if githubAppMode {
githubApp := &github.GithubApp{
Factory: o.GetFactory(),
}
installed, err := githubApp.Install(o.Organisation, o.Repository, o.GetIOFileHandles(), false)
if err != nil {
return err
}
o.GithubAppInstalled = installed
}
}
*/
return o.doImport()
}
// ImportProjectsFromGitHub import projects from github
/** TODO
func (o *ImportOptions) ImportProjectsFromGitHub() error {
repos, err := gits.PickRepositories(o.ScmClient, o.Organisation, "Which repositories do you want to import", o.SelectAll, o.SelectFilter, o.GetIOFileHandles())
if err != nil {
return err
}
log.Logger().Info("Selected repositories")
for _, r := range repos {
o2 := ImportOptions{
CommonOptions: o.CommonOptions,
Dir: o.Dir,
RepoURL: r.CloneURL,
Organisation: o.Organisation,
Repository: r.Name,
//Jenkins: o.Jenkins,
ScmClient: o.ScmClient,
DisableBuildPack: o.DisableBuildPack,
}
log.Logger().Infof("Importing repository %s", termcolor.ColorInfo(r.Name))
err = o2.Run()
if err != nil {
return err
}
}
return nil
}
*/
// GetReporter returns the reporter interface
func (o *ImportOptions) GetReporter() ImportReporter {
if o.reporter == nil {
o.reporter = &LogImportReporter{}
}
return o.reporter
}
// SetReporter overrides the reporter interface
func (o *ImportOptions) SetReporter(reporter ImportReporter) {
o.reporter = reporter
}
// CreateNewRemoteRepository creates a new remote repository
func (o *ImportOptions) CreateNewRemoteRepository() error {
dir := o.Dir
_, defaultRepoName := filepath.Split(dir)
var err error
o.GitRepositoryOptions.Namespace = o.GetOrganisation()
details := &o.GitRepositoryOptions
if o.Organisation == "" {
o.Organisation, err = o.PickOwner("")
if err != nil {
return errors.Wrapf(err, "failed to pick owner")
}
}
if details.Name == "" {
details.Name, err = o.PickRepoName(o.Organisation, defaultRepoName, false)
if err != nil {
return errors.Wrapf(err, "failed to pick repository name")
}
}
ctx := context.Background()
createRepo := o.GitRepositoryOptions
// need to clear the owner if its a user
if o.getCurrentUser() == createRepo.Namespace {
createRepo.Namespace = ""
}
repo, _, err := o.ScmFactory.ScmClient.Repositories.Create(ctx, &createRepo)
if err != nil {
return errors.Wrapf(err, "failed to create git repository %s/%s", o.GitRepositoryOptions.Namespace, o.GitRepositoryOptions.Name)
}
if err != nil {
return err
}
// mostly to default a value in test cases if its missing
if repo.Clone == "" {
repo.Clone = repo.Link
}
// lets allow a BDD test to switch the git host to push to
// e.g. if using kind and gitea and running tests inside k8s without public access to the gitea server
gitPushHost := os.Getenv("JX_GIT_PUSH_HOST")
if repo.Clone != "" && gitPushHost != "" {
u, err := url.Parse(repo.Clone)
if err != nil {
return errors.Wrapf(err, "failed to parse repository clone URL %s", repo.Clone)
}
u.Host = gitPushHost
repo.Clone = u.String()
log.Logger().Infof("switching to the git clone URL %s", info(repo.Clone))
}
o.DiscoveredGitURL = repo.Clone
pushGitURL, err := o.ScmFactory.CreateAuthenticatedURL(repo.Clone)
if err != nil {
return err
}
err = gitclient.AddRemote(o.Git(), dir, "origin", pushGitURL)
if err != nil {
return err
}
// lets use a retry loop to push in case the repository is not yet setup quite yet
f := func() error {
return gitclient.Push(o.Git(), dir, "origin", false, "HEAD")
}
bo := backoff.NewExponentialBackOff()
bo.InitialInterval = 3 * time.Second
bo.MaxElapsedTime = time.Minute
bo.Reset()
err = backoff.Retry(f, bo)
if err != nil {
return err
}
repoURL := repo.Link
o.GetReporter().PushedGitRepository(repoURL)
return nil
}
// CloneRepository clones a repository
func (o *ImportOptions) CloneRepository() error {
url := o.RepoURL
if url == "" {
return fmt.Errorf("no Git repository URL defined")
}
gitInfo, err := giturl.ParseGitURL(url)
if err != nil {
return fmt.Errorf("failed to parse Git URL %s due to: %s", url, err)
}
if gitInfo.Host == giturl.GitHubHost && strings.HasPrefix(gitInfo.Scheme, "http") {
if !strings.HasSuffix(url, ".git") {
url += ".git"
}
o.RepoURL = url
}
cloneDir, err := files.CreateUniqueDirectory(o.Dir, gitInfo.Name, files.MaximumNewDirectoryAttempts)
if err != nil {
return errors.Wrapf(err, "failed to create unique directory for '%s'", o.Dir)
}
cloneDir, err = gitclient.CloneToDir(o.Git(), url, cloneDir)
if err != nil {
return errors.Wrapf(err, "failed to clone in directory '%s'", cloneDir)
}
o.Dir = cloneDir
return nil
}
// DiscoverGit checks if there is a git clone or prompts the user to import it
func (o *ImportOptions) DiscoverGit() error {
if !o.DisableDotGitSearch {
root, gitConf, err := gitclient.FindGitConfigDir(o.Dir)
if err != nil {
return err
}
if root != "" {
if root != o.Dir {
o.GetReporter().Trace("Importing from directory %s as we found a .git folder there", root)
}
o.Dir = root
o.GitConfDir = gitConf
return nil
}
}
dir := o.Dir
if dir == "" {
return fmt.Errorf("no directory specified")
}
// lets prompt the user to initialise the Git repository
if !o.BatchMode {
o.GetReporter().Trace("The directory %s is not yet using git", termcolor.ColorInfo(dir))
flag, err := o.Input.Confirm("Would you like to initialise git now?", true, "We need to initialise git in the directory to continue")
if err != nil {
return errors.Wrapf(err, "failed to confirm git initialise")
}
if !flag {
return fmt.Errorf("please initialise git yourself then try again")
}
}
o.InitialisedGit = true
err := gitclient.Init(o.Git(), dir)
if err != nil {
return err
}
o.GitConfDir = filepath.Join(dir, ".git", "config")
err = o.DefaultGitIgnore()
if err != nil {
return err
}
err = gitclient.Add(o.Git(), dir, ".gitignore")
if err != nil {
log.Logger().Debug("failed to add .gitignore")
}
err = gitclient.Add(o.Git(), dir, "*")
if err != nil {
return err
}
_, err = gitclient.Status(o.Git(), dir)
if err != nil {
return err
}
message := o.ImportGitCommitMessage
if message == "" {
if o.BatchMode {
message = "chore: initial import"
} else {
message, err = o.Input.PickValue("Commit message: ", "chore: initial import", true, "Please enter the initial git commit message")
if err != nil {
return errors.Wrapf(err, "failed to confirm commit message")
}
}
}
err = gitclient.CommitIfChanges(o.Git(), dir, message)
if err != nil {
return err
}
o.GetReporter().GitRepositoryCreated()
return nil
}
// DefaultGitIgnore creates a default .gitignore
func (o *ImportOptions) DefaultGitIgnore() error {
name := filepath.Join(o.Dir, ".gitignore")
exists, err := files.FileExists(name)
if err != nil {
return err
}
if !exists {
data := []byte(constants.DefaultGitIgnoreFile)
err = ioutil.WriteFile(name, data, files.DefaultFileWritePermissions)
if err != nil {
return fmt.Errorf("failed to write %s due to %s", name, err)
}
}
return nil
}
func (o *ImportOptions) doImport() error {
gitURL := o.DiscoveredGitURL
dockerfileLocation := ""
if o.Dir != "" {
dockerfileLocation = filepath.Join(o.Dir, "Dockerfile")
} else {
dockerfileLocation = "Dockerfile"
}
dockerfileExists, err := files.FileExists(dockerfileLocation)
if err != nil {
return err
}
if dockerfileExists {
err = o.ensureDockerRepositoryExists()
if err != nil {
return err
}
}
// TODO should we prompt the user for the git kind if we can't detect / find it?
gitKind := o.ScmFactory.GitKind
remoteCluster, err := o.addSourceConfigPullRequest(gitURL, gitKind)
if err != nil {
return errors.Wrapf(err, "failed to create Pull Request on the cluster git repository")
}
if o.DisableStartPipeline {
return nil
}
repoName := o.GitRepositoryOptions.Name
if repoName == "" {
repoName = o.AppName
}
repoFullName := scm.Join(o.Organisation, repoName)
if !o.Destination.Jenkins.Enabled && !remoteCluster {
c := &cmdrunner.Command{
Name: "jx",
Args: []string{"pipeline", "wait", "--owner", o.Organisation, "--repo", repoName},
Out: os.Stdout,
Err: os.Stderr,
}
_, err = o.CommandRunner(c)
if err != nil {
return errors.Wrapf(err, "failed to wait for the pipeline to be setup %s", repoFullName)
}
}
// lets git push the build pack changes now to trigger a release
//
// TODO we could make this an optional Pull request etc?
if o.OnCompleteCallback != nil {
err = o.OnCompleteCallback()
if err != nil {
return errors.Wrapf(err, "failed to push git changes")
}
}
if o.Destination.Jenkins.Enabled {
return nil
}
log.Logger().Info("")
log.Logger().Infof("Pipeline should start soon for: %s", info(repoFullName))
log.Logger().Info("")
log.Logger().Infof("Watch pipeline activity via: %s", info(fmt.Sprintf("jx get activity -f %s -w", repoFullName)))
log.Logger().Infof("Browse the pipeline log via: %s", info(fmt.Sprintf("jx get build logs %s", repoFullName)))
log.Logger().Infof("You can list the pipelines via: %s", info("jx get pipelines"))
log.Logger().Infof("When the pipeline is complete: %s", info("jx get applications"))
log.Logger().Info("")
log.Logger().Infof("For more help on available commands see: %s", info("https://jenkins-x.io/developing/browsing/"))
log.Logger().Info("")
return nil
}
// ensureDockerRepositoryExists for some kinds of container registry we need to pre-initialise its use such as for ECR
func (o *ImportOptions) ensureDockerRepositoryExists() error {
orgName := o.getOrganisationOrCurrentUser()
appName := o.AppName
if orgName == "" {
log.Logger().Warnf("Missing organisation name!")
return nil
}
if appName == "" {
log.Logger().Warnf("Missing application name!")
return nil
}
/* TODO
kubeClient, curNs, err := o.KubeClientAndNamespace()
if err != nil {
return err
}
ns, _, err := jxenv.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, o.getDockerRegistryOrg(), appName)
}
}
}
*/
return nil
}
// ReplacePlaceholders replaces app name, git server name, git org, and docker registry org placeholders
func (o *ImportOptions) ReplacePlaceholders(gitServerName, dockerRegistryOrg string) error {
safeOrganisationName := naming.ToValidName(strings.ToLower(o.Organisation))
o.GetReporter().Trace("replacing placeholders in directory %s", o.Dir)
o.GetReporter().Trace("app name: %s, git server: %s, org: %s, Docker registry org: %s", o.AppName, gitServerName, o.Organisation, dockerRegistryOrg)
ignore, err := gitignore.NewRepository(o.Dir)
if err != nil {
return err
}
replacer := strings.NewReplacer(
constants.PlaceHolderAppName, strings.ToLower(o.AppName),
constants.PlaceHolderGitProvider, strings.ToLower(gitServerName),
constants.PlaceHolderOrg, safeOrganisationName,
constants.PlaceHolderDockerRegistryOrg, strings.ToLower(dockerRegistryOrg))
pathsToRename := []string{} // Renaming must be done post-Walk
if err := filepath.Walk(o.Dir, func(f string, fi os.FileInfo, err error) error {
if skip, err := o.skipPathForReplacement(f, fi, ignore); skip {
return err
}
if strings.Contains(filepath.Base(f), constants.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
}
}
return nil
}); err != nil {
return fmt.Errorf("error replacing placeholders %v", err)
}
for _, path := range pathsToRename {
if err := replacePlaceholdersInPathBase(replacer, path); err != nil {
return err
}
}
return nil
}
func (o *ImportOptions) skipPathForReplacement(path string, fi os.FileInfo, ignore gitignore.GitIgnore) (bool, error) {
relPath, _ := filepath.Rel(o.Dir, path)
match := ignore.Relative(relPath, fi.IsDir())
matchIgnore := match != nil && match.Ignore() // Defaults to including if match == nil
if fi.IsDir() {
if matchIgnore || fi.Name() == ".git" {
o.GetReporter().Trace("skipping directory %q", path)
return true, filepath.SkipDir
}
} else if matchIgnore {
o.GetReporter().Trace("skipping ignored file %q", path)
return true, nil
}
// Don't process nor follow symlinks
if (fi.Mode() & os.ModeSymlink) == os.ModeSymlink {
o.GetReporter().Trace("skipping symlink file %q", path)
return true, nil
}
return false, nil
}
func replacePlaceholdersInFile(replacer *strings.Replacer, file string) error {
input, err := ioutil.ReadFile(file)
if err != nil {
log.Logger().Errorf("failed to read file %s: %v", file, err)
return err
}
lines := string(input)
if strings.Contains(lines, constants.PlaceHolderPrefix) { // Avoid unnecessarily rewriting files
output := replacer.Replace(lines)