forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
step_split_monorepo.go
331 lines (301 loc) · 9 KB
/
step_split_monorepo.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
package cmd
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
)
const (
optionOrganisation = "organisation"
defaultKubernetesDir = "kubernetes"
)
var (
stepSplitMonorepoOptions = []string{optionMinJxVersion}
stepSplitMonorepoLong = templates.LongDesc(`
Mirrors the code from a monorepo into separate microservice style git repositories so its easier to do finer grained releases.
If you have lots of apps in folders in a monorepo then this comamnd can run on that repo to mirror changes into a number of microsevice based repositories which can each then get auto-imported into Jenkins X
`)
stepSplitMonorepoExample = templates.Examples(`
# Split the current folder up into separate git repositories
jx step split monorepo -o mygithuborg
`)
)
// StepSplitMonorepoOptions contains the command line flags
type StepSplitMonorepoOptions struct {
StepOptions
Glob string
Organisation string
Dir string
OutputDir string
KubernetesDir string
NoGit bool
}
// NewCmdStepSplitMonorepo Creates a new Command object
func NewCmdStepSplitMonorepo(f Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := &StepSplitMonorepoOptions{
StepOptions: StepOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "split monorepo",
Short: "Mirrors the code from a monorepo into separate microservice style git repositories so its easier to do finer grained releases",
Long: stepSplitMonorepoLong,
Example: stepSplitMonorepoExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.Glob, "glob", "g", "*", "The glob pattern to find folders to mirror to separate repositories")
cmd.Flags().StringVarP(&options.Organisation, optionOrganisation, "o", "", "The github organisation to split the repositories into")
cmd.Flags().StringVarP(&options.Dir, "source-dir", "s", "", "The source directory to look inside for the folders to move into separate git repositories")
cmd.Flags().StringVarP(&options.OutputDir, optionOutputDir, "d", "generated", "The output directory where new projects are created")
cmd.Flags().StringVarP(&options.KubernetesDir, "kubernetes-folder", "", defaultKubernetesDir, "The folder containing all the kubernetes YAML for each app")
cmd.Flags().BoolVarP(&options.NoGit, "no-git", "", false, "If enabled then don't try to clone/create the separate repositories in github")
return cmd
}
// Run implements this command
func (o *StepSplitMonorepoOptions) Run() error {
organisation := o.Organisation
if organisation == "" {
return util.MissingOption(optionOrganisation)
}
outputDir := o.OutputDir
if outputDir == "" {
return util.MissingOption(optionOutputDir)
}
var err error
dir := o.Dir
if dir == "" {
dir, err = os.Getwd()
if err != nil {
return err
}
}
glob := o.Glob
fullGlob := filepath.Join(dir, glob)
o.Debugf("Searching in monorepo at: %s\n", fullGlob)
matches, err := filepath.Glob(fullGlob)
if err != nil {
return err
}
kubeDir := o.KubernetesDir
if kubeDir == "" {
kubeDir = defaultKubernetesDir
}
var gitProvider gits.GitProvider
if !o.NoGit {
gitProvider, err = o.createGitProviderForURL(gits.KindGitHub, gits.GitHubURL)
if err != nil {
return err
}
}
for _, path := range matches {
_, name := filepath.Split(path)
if !strings.HasPrefix(name, ".") && name != kubeDir {
fi, err := os.Stat(path)
if err != nil {
return err
}
switch mode := fi.Mode(); {
case mode.IsDir():
o.Debugf("Found match: %s\n", path)
outPath := filepath.Join(outputDir, name)
var gitUrl string
var repo *gits.GitRepository
createRepo := true
if !o.NoGit {
// lets clone the project if it exists
repo, err = gitProvider.GetRepository(organisation, name)
if repo != nil && err == nil {
err = os.MkdirAll(outPath, DefaultWritePermissions)
if err != nil {
return err
}
createRepo = false
userAuth := gitProvider.UserAuth()
gitUrl, err = o.Git().CreatePushURL(repo.CloneURL, &userAuth)
if err != nil {
return err
}
log.Infof("Cloning %s into directory %s\n", util.ColorInfo(repo.CloneURL), util.ColorInfo(outPath))
err = o.Git().CloneOrPull(gitUrl, outPath)
if err != nil {
return err
}
}
}
err = util.CopyDirOverwrite(path, outPath)
if err != nil {
return err
}
// lets copy the .gitignore
localGitIgnore := filepath.Join(outPath, ".gitignore")
exists, err := util.FileExists(localGitIgnore)
if err != nil {
return err
}
if !exists {
rootGitIgnore := filepath.Join(dir, ".gitignore")
exists, err = util.FileExists(rootGitIgnore)
if err != nil {
return err
}
if exists {
err = util.CopyFile(rootGitIgnore, localGitIgnore)
if err != nil {
return err
}
}
}
if !o.NoGit {
if createRepo {
repo, err = gitProvider.CreateRepository(organisation, name, false)
if err != nil {
return err
}
log.Infof("Created git repository to %s\n\n", util.ColorInfo(repo.HTMLURL))
userAuth := gitProvider.UserAuth()
gitUrl, err = o.Git().CreatePushURL(repo.CloneURL, &userAuth)
err := o.Git().Init(outPath)
if err != nil {
return err
}
err = o.Git().AddRemote(outPath, "origin", gitUrl)
if err != nil {
return err
}
}
// ignore errors as probably already added
o.Git().Add(outPath, ".gitignore")
o.Git().Add(outPath, "src", "charts", "*")
message := "generated by: jx step split monorepo"
err = o.Git().CommitIfChanges(outPath, message)
if err != nil {
return err
}
err = o.Git().PushMaster(outPath)
if err != nil {
return err
}
log.Infof("Pushed git repository to %s\n\n", util.ColorInfo(repo.HTMLURL))
}
}
}
}
if kubeDir != "" {
// now lets copy any kubernetes YAML into helm charts in the apps
matches, err = filepath.Glob(filepath.Join(dir, kubeDir, "*"))
if err != nil {
return err
}
for _, path := range matches {
_, name := filepath.Split(path)
if strings.HasSuffix(name, ".yaml") {
appName := strings.TrimSuffix(name, ".yaml")
outPath := filepath.Join(outputDir, appName)
exists, err := util.FileExists(outPath)
if err != nil {
return err
}
if !exists && strings.HasSuffix(appName, "-deployment") {
// lets try strip "-deployment" from the file name
appName = strings.TrimSuffix(appName, "-deployment")
outPath = filepath.Join(outputDir, appName)
exists, err = util.FileExists(outPath)
if err != nil {
return err
}
}
if exists {
chartDir := filepath.Join(outPath, "charts", appName)
templatesDir := filepath.Join(chartDir, "templates")
err = os.MkdirAll(templatesDir, DefaultWritePermissions)
if err != nil {
return err
}
valuesYaml := `replicaCount: 1`
chartYaml := `apiVersion: v1
description: A Helm chart for Kubernetes
icon: https://raw.githubusercontent.com/jenkins-x/jenkins-x-platform/master/images/java.png
name: ` + appName + `
version: 0.0.1-SNAPSHOT
`
helmIgnore := `# Patterns to ignore when building packages.
# This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line.
.DS_Store
# Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*~
# Various IDEs
.project
.idea/
*.tmproj`
err = generateFileIfMissing(filepath.Join(chartDir, "values.yaml"), valuesYaml)
if err != nil {
return err
}
err = generateFileIfMissing(filepath.Join(chartDir, "Chart.yaml"), chartYaml)
if err != nil {
return err
}
err = generateFileIfMissing(filepath.Join(chartDir, ".helmignore"), helmIgnore)
if err != nil {
return err
}
yaml, err := ioutil.ReadFile(path)
if err != nil {
return err
}
err = generateFileIfMissing(filepath.Join(templatesDir, "deployment.yaml"), string(yaml))
if err != nil {
return err
}
}
}
}
}
return nil
}
func (o *CommonOptions) createGitProviderForURL(gitKind string, gitUrl string) (gits.GitProvider, error) {
authConfigSvc, err := o.CreateGitAuthConfigService()
if err != nil {
return nil, err
}
return gits.CreateProviderForURL(authConfigSvc, gitKind, gitUrl, o.Git())
}
// generateFileIfMissing generates the given file from the source code if the file does not already exist
func generateFileIfMissing(path string, text string) error {
exists, err := util.FileExists(path)
if err != nil {
return err
}
if !exists {
return ioutil.WriteFile(path, []byte(text), DefaultWritePermissions)
}
return nil
}