forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_codeship.go
318 lines (267 loc) · 8.58 KB
/
create_codeship.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
package cmd
import (
"io"
"fmt"
"context"
"errors"
"github.com/codeship/codeship-go"
"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/jenkins-x/jx/pkg/version"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1"
"io/ioutil"
"path"
"strings"
)
type CreateCodeshipFlags struct {
OrganisationName string
CodeshipUsername string
CodeshipPassword string
CodeshipOrganisation string
GitUser string
GitEmail string
GKEServiceAccount string
}
// CreateCodeshipOptions the options for the create spring command
type CreateCodeshipOptions struct {
CreateOptions
Flags CreateCodeshipFlags
GitRepositoryOptions gits.GitRepositoryOptions
}
var (
createCodeshipExample = templates.Examples(`
jx create codeship
# to specify the clusters via flags
jx create codeship -o org
`)
)
// NewCmdCreateCodeship creates a command object for the "create" command
func NewCmdCreateCodeship(f Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := &CreateCodeshipOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "codeship",
Short: "Creates a build on CodeShip to create/update JX clusters",
Example: createCodeshipExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
options.addCommonFlags(cmd)
options.addFlags(cmd)
return cmd
}
func (options *CreateCodeshipOptions) addFlags(cmd *cobra.Command) {
// global flags
cmd.Flags().StringVarP(&options.Flags.OrganisationName, "organisation-name", "o", "", "The organisation name that will be used as the Git repo containing cluster details, the repo will be organisation-<org name>")
cmd.Flags().StringVarP(&options.Flags.CodeshipUsername, "codeship-username", "", "", "The username to login to Codeship with, this will not be stored anywhere")
cmd.Flags().StringVarP(&options.Flags.CodeshipPassword, "codeship-password", "", "", "The password to login to Codeship with, this will not be stored anywhere")
cmd.Flags().StringVarP(&options.Flags.CodeshipOrganisation, "codeship-organisation", "", "", "The Codeship organisation to use, this will not be stored anywhere")
cmd.Flags().StringVarP(&options.Flags.GitUser, "git-user", "", "Codeship", "The name to use for any git commits")
cmd.Flags().StringVarP(&options.Flags.GitEmail, "git-email", "", "codeship@jenkins-x.io", "The email to use for any git commits")
cmd.Flags().StringVarP(&options.Flags.GKEServiceAccount, "gke-service-account", "", "", "The GKE service account to use")
}
func (o *CreateCodeshipOptions) validate() error {
if o.Flags.OrganisationName == "" {
return errors.New("No organisation has been set")
}
// TODO we should only do this if a GKE cluster has been specified
if o.Flags.GKEServiceAccount == "" {
return errors.New("No gke service account has been set")
}
return nil
}
// Run implements this command
func (o *CreateCodeshipOptions) Run() error {
err := o.validate()
if err != nil {
return err
}
if o.Flags.CodeshipUsername == "" {
prompt := &survey.Input{
Message: "Username for Codeship",
Help: "This will not be stored anywhere",
}
err := survey.AskOne(prompt, &o.Flags.CodeshipUsername, nil)
if err != nil {
return err
}
}
if o.Flags.CodeshipPassword == "" {
prompt := &survey.Password{
Message: "Password for Codeship",
Help: "This will not be stored anywhere",
}
err := survey.AskOne(prompt, &o.Flags.CodeshipPassword, nil)
if err != nil {
return err
}
}
if o.Flags.CodeshipOrganisation == "" {
prompt := &survey.Input{
Message: "Codeship organisation",
Help: "This will not be stored anywhere",
}
err := survey.AskOne(prompt, &o.Flags.CodeshipOrganisation, nil)
if err != nil {
return err
}
}
organisationDir, err := util.OrganisationsDir()
if err != nil {
return err
}
authConfigSvc, err := o.CreateGitAuthConfigService()
if err != nil {
return err
}
defaultRepoName := fmt.Sprintf("organisation-%s", o.Flags.OrganisationName)
details, err := gits.PickNewOrExistingGitRepository(o.Stdout(), o.BatchMode, authConfigSvc,
defaultRepoName, &o.GitRepositoryOptions, nil, nil, o.Git(), true)
if err != nil {
return err
}
org := details.Organisation
repoName := details.RepoName
owner := org
if owner == "" {
owner = details.User.Username
}
provider := details.GitProvider
repo, err := provider.GetRepository(owner, repoName)
var dir string
if err == nil {
fmt.Fprintf(o.Stdout(), "git repository %s/%s already exists\n", util.ColorInfo(owner), util.ColorInfo(repoName))
// if the repo already exists then lets just modify it if required
dir, err = util.CreateUniqueDirectory(organisationDir, details.RepoName, util.MaximumNewDirectoryAttempts)
if err != nil {
return err
}
pushGitURL, err := o.Git().CreatePushURL(repo.CloneURL, details.User)
if err != nil {
return err
}
err = o.Git().Clone(pushGitURL, dir)
if err != nil {
return err
}
}
clusterDir := path.Join(dir , "clusters")
clusters, err := findClusters(clusterDir)
if err != nil {
return err
}
auth := codeship.NewBasicAuth(o.Flags.CodeshipUsername, o.Flags.CodeshipPassword)
client, err := codeship.New(auth)
if err != nil {
return err
}
ctx := context.Background()
csOrg, err := client.Organization(ctx, o.Flags.CodeshipOrganisation)
if err != nil {
return err
}
_, uuid, err := ProjectExists(ctx, csOrg, o.Flags.CodeshipOrganisation, repoName)
b, err := ioutil.ReadFile(o.Flags.GKEServiceAccount)
if err != nil {
return err
}
serviceAccount := string(b)
if uuid == "" {
createProjectRequest := codeship.ProjectCreateRequest{
Type: codeship.ProjectTypeBasic,
RepositoryURL: fmt.Sprintf("git@github.com:%s/%s", owner, repoName),
SetupCommands: []string{"./build.sh"},
EnvironmentVariables: []codeship.EnvironmentVariable{
{Name: "GKE_SA_JSON", Value: serviceAccount},
{Name: "ORG", Value: o.Flags.OrganisationName},
{Name: "GIT_USERNAME", Value: details.User.Username},
{Name: "GIT_API_TOKEN", Value: details.User.ApiToken},
{Name: "JX_VERSION", Value: jxVersion()},
{Name: "GIT_USER", Value: o.Flags.GitUser},
{Name: "GIT_EMAIL", Value: o.Flags.GitEmail},
{Name: "BUILD_NUMBER", Value: "1"},
{Name: "ENVIRONMENTS", Value: strings.Join(clusters, ",")},
},
}
project, _, err := csOrg.CreateProject(ctx, createProjectRequest)
if err != nil {
return err
}
uuid = project.UUID
log.Infof("Created Project %s\n", util.ColorInfo(project.Name))
} else {
updateProjectRequest := codeship.ProjectUpdateRequest{
Type: codeship.ProjectTypeBasic,
SetupCommands: []string{"./build.sh"},
EnvironmentVariables: []codeship.EnvironmentVariable{
{Name: "GKE_SA_JSON", Value: serviceAccount},
{Name: "ORG", Value: o.Flags.OrganisationName},
{Name: "GIT_USERNAME", Value: details.User.Username},
{Name: "GIT_API_TOKEN", Value: details.User.ApiToken},
{Name: "JX_VERSION", Value: jxVersion()},
{Name: "GIT_USER", Value: o.Flags.GitUser},
{Name: "GIT_EMAIL", Value: o.Flags.GitEmail},
{Name: "BUILD_NUMBER", Value: "1"},
{Name: "ENVIRONMENTS", Value: strings.Join(clusters, ",")},
},
}
project, _, err := csOrg.UpdateProject(ctx, uuid, updateProjectRequest)
if err != nil {
return err
}
log.Infof("Updated Project %s\n", util.ColorInfo(project.Name))
}
log.Infof("Triggering build for %s\n", util.ColorInfo(uuid))
_, _, err = csOrg.CreateBuild(ctx, uuid, "heads/master", "")
if err != nil {
return err
}
return nil
}
func ProjectExists(ctx context.Context, org *codeship.Organization, codeshipOrg string, codeshipRepo string) (bool, string, error) {
projects, _, err := org.ListProjects(ctx)
if err != nil {
return false, "", err
}
projectName := fmt.Sprintf("%s/%s", codeshipOrg, codeshipRepo)
for _, p := range projects.Projects {
if p.Name == projectName {
log.Infof("Project %s already exists\n", util.ColorInfo(p.Name))
return true, p.UUID, nil
}
}
return false, "", nil
}
func jxVersion() string {
if version.Version == "1.0.1" {
return "1.3.99"
}
return version.Version
}
func findClusters(path string) ([]string,error){
var clusters = []string{}
files, err := ioutil.ReadDir(path)
if err != nil {
return clusters, err
}
for _, f := range files {
if f.IsDir() {
clusters = append(clusters, fmt.Sprintf("%s=gke" , f.Name()))
}
}
return clusters, nil
}