forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider.go
385 lines (321 loc) · 9.12 KB
/
provider.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
package gits
import (
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/jenkins-x/jx/pkg/auth"
"gopkg.in/AlecAivazis/survey.v1"
)
type OrganisationLister interface {
ListOrganisations() ([]GitOrganisation, error)
}
type GitProvider interface {
OrganisationLister
ListRepositories(org string) ([]*GitRepository, error)
CreateRepository(org string, name string, private bool) (*GitRepository, error)
GetRepository(org string, name string) (*GitRepository, error)
DeleteRepository(org string, name string) error
ForkRepository(originalOrg string, name string, destinationOrg string) (*GitRepository, error)
RenameRepository(org string, name string, newName string) (*GitRepository, error)
ValidateRepositoryName(org string, name string) error
CreatePullRequest(data *GitPullRequestArguments) (*GitPullRequest, error)
UpdatePullRequestStatus(pr *GitPullRequest) error
PullRequestLastCommitStatus(pr *GitPullRequest) (string, error)
ListCommitStatus(org string, repo string, sha string) ([]*GitRepoStatus, error)
MergePullRequest(pr *GitPullRequest, message string) error
CreateWebHook(data *GitWebHookArguments) error
IsGitHub() bool
IsGitea() bool
Kind() string
GetIssue(org string, name string, number int) (*GitIssue, error)
IssueURL(org string, name string, number int, isPull bool) string
SearchIssues(org string, name string, query string) ([]*GitIssue, error)
CreateIssue(owner string, repo string, issue *GitIssue) (*GitIssue, error)
HasIssues() bool
AddPRComment(pr *GitPullRequest, comment string) error
CreateIssueComment(owner string, repo string, number int, comment string) error
UpdateRelease(owner string, repo string, tag string, releaseInfo *GitRelease) error
// returns the path relative to the Jenkins URL to trigger webhooks on this kind of repository
//
// e.g. for GitHub its /github-webhook/
// other examples include:
//
// * gitlab: /gitlab/notify_commit
// https://github.com/elvanja/jenkins-gitlab-hook-plugin#notify-commit-hook
//
// * git plugin
// /git/notifyCommit?url=
// http://kohsuke.org/2011/12/01/polling-must-die-triggering-jenkins-builds-from-a-git-hook/
//
// * gitea
// /gitea-webhook/post
//
// * generic webhook
// /generic-webhook-trigger/invoke?token=abc123
// https://wiki.jenkins.io/display/JENKINS/Generic+Webhook+Trigger+Plugin
JenkinsWebHookPath(gitURL string, secret string) string
Label() string
}
type GitOrganisation struct {
Login string
}
type GitRepository struct {
Name string
AllowMergeCommit bool
HTMLURL string
CloneURL string
SSHURL string
Language string
Fork bool
}
type GitPullRequest struct {
URL string
Owner string
Repo string
Number *int
Mergeable *bool
Merged *bool
State *string
StatusesURL *string
IssueURL *string
DiffURL *string
MergeCommitSHA *string
ClosedAt *time.Time
MergedAt *time.Time
LastCommitSha string
}
type GitIssue struct {
URL string
Owner string
Repo string
Number *int
Key string
Title string
Body string
State *string
Labels []GitLabel
StatusesURL *string
IssueURL *string
ClosedAt *time.Time
IsPullRequest bool
User *GitUser
ClosedBy *GitUser
Assignees []GitUser
}
type GitUser struct {
URL string
Login string
Name string
Email string
AvatarURL string
}
type GitRelease struct {
Name string
TagName string
Body string
URL string
HTMLURL string
}
type GitLabel struct {
URL string
Name string
Color string
}
type GitRepoStatus struct {
ID int64
Context string
URL string
// State is the current state of the repository. Possible values are:
// pending, success, error, or failure.
State string `json:"state,omitempty"`
// TargetURL is the URL of the page representing this status
TargetURL string `json:"target_url,omitempty"`
// Description is a short high level summary of the status.
Description string
}
type GitPullRequestArguments struct {
Owner string
Repo string
Title string
Body string
Head string
Base string
}
type GitWebHookArguments struct {
Owner string
Repo string
URL string
Secret string
}
// IsClosed returns true if the PullRequest has been closed
func (pr *GitPullRequest) IsClosed() bool {
return pr.ClosedAt != nil
}
// Name returns the textual name of the issue
func (i *GitIssue) Name() string {
if i.Key != "" {
return i.Key
}
n := i.Number
if n != nil {
return "#" + strconv.Itoa(*n)
}
return "N/A"
}
func CreateProvider(server *auth.AuthServer, user *auth.UserAuth) (GitProvider, error) {
switch server.Kind {
case "gitea":
return NewGiteaProvider(server, user)
case "bitbucket":
return NewBitbucketProvider(server, user)
default:
return NewGitHubProvider(server, user)
}
}
func ProviderAccessTokenURL(kind string, url string) string {
switch kind {
case "gitea":
return GiteaAccessTokenURL(url)
default:
return GitHubAccessTokenURL(url)
}
}
// PickOrganisation picks an organisations login if there is one available
func PickOrganisation(orgLister OrganisationLister, userName string) (string, error) {
prompt := &survey.Select{
Message: "Which organisation do you want to use?",
Options: getOrganizations(orgLister, userName),
Default: userName,
}
orgName := ""
err := survey.AskOne(prompt, &orgName, nil)
if err != nil {
return "", err
}
if orgName == userName {
return "", nil
}
return orgName, nil
}
func getOrganizations(orgLister OrganisationLister, userName string) []string {
// Always include the username as a pseudo organization
orgNames := []string{userName}
orgs, _ := orgLister.ListOrganisations()
for _, o := range orgs {
if name := o.Login; name != "" {
orgNames = append(orgNames, name)
}
}
sort.Strings(orgNames)
return orgNames
}
func PickRepositories(provider GitProvider, owner string, message string, selectAll bool, filter string) ([]*GitRepository, error) {
answer := []*GitRepository{}
repos, err := provider.ListRepositories(owner)
if err != nil {
return answer, err
}
repoMap := map[string]*GitRepository{}
allRepoNames := []string{}
for _, repo := range repos {
n := repo.Name
if n != "" && (filter == "" || strings.Contains(n, filter)) {
allRepoNames = append(allRepoNames, n)
repoMap[n] = repo
}
}
if len(allRepoNames) == 0 {
return answer, fmt.Errorf("No matching repositories could be found!")
}
sort.Strings(allRepoNames)
prompt := &survey.MultiSelect{
Message: message,
Options: allRepoNames,
}
if selectAll {
prompt.Default = allRepoNames
}
repoNames := []string{}
err = survey.AskOne(prompt, &repoNames, nil)
for _, n := range repoNames {
repo := repoMap[n]
if repo != nil {
answer = append(answer, repo)
}
}
return answer, err
}
// IsGitRepoStatusSuccess returns true if all the statuses are successful
func IsGitRepoStatusSuccess(statuses ...*GitRepoStatus) bool {
for _, status := range statuses {
if !status.IsSuccess() {
return false
}
}
return true
}
// IsGitRepoStatusFailed returns true if any of the statuses have failed
func IsGitRepoStatusFailed(statuses ...*GitRepoStatus) bool {
for _, status := range statuses {
if status.IsFailed() {
return true
}
}
return false
}
func (s *GitRepoStatus) IsSuccess() bool {
return s.State == "success"
}
func (s *GitRepoStatus) IsFailed() bool {
return s.State == "error" || s.State == "failure"
}
func (i *GitRepositoryInfo) PickOrCreateProvider(authConfigSvc auth.AuthConfigService, message string, batchMode bool, gitKind string) (GitProvider, error) {
config := authConfigSvc.Config()
hostUrl := i.HostURLWithoutUser()
server := config.GetOrCreateServer(hostUrl)
userAuth, err := config.PickServerUserAuth(server, message, batchMode)
if err != nil {
return nil, err
}
return i.CreateProviderForUser(server, userAuth, gitKind)
}
func (i *GitRepositoryInfo) CreateProviderForUser(server *auth.AuthServer, user *auth.UserAuth, gitKind string) (GitProvider, error) {
if i.Host == GitHubHost {
return NewGitHubProvider(server, user)
}
if gitKind != "" && server.Kind != gitKind {
server.Kind = gitKind
}
return CreateProvider(server, user)
}
func (i *GitRepositoryInfo) CreateProvider(authConfigSvc auth.AuthConfigService, gitKind string) (GitProvider, error) {
config := authConfigSvc.Config()
hostUrl := i.HostURLWithoutUser()
server := config.GetOrCreateServer(hostUrl)
url := server.URL
if gitKind != "" {
server.Kind = gitKind
}
userAuths := authConfigSvc.Config().FindUserAuths(url)
if len(userAuths) == 0 {
kind := server.Kind
if kind != "" {
userAuth := auth.CreateAuthUserFromEnvironment(strings.ToUpper(kind))
if !userAuth.IsInvalid() {
return CreateProvider(server, &userAuth)
}
}
userAuth := auth.CreateAuthUserFromEnvironment("GIT")
if !userAuth.IsInvalid() {
return CreateProvider(server, &userAuth)
}
}
if len(userAuths) > 0 {
// TODO use default user???
auth := userAuths[0]
return CreateProvider(server, auth)
}
return nil, fmt.Errorf("Could not create Git provider for host %s as no user auths could be found", hostUrl)
}