-
Notifications
You must be signed in to change notification settings - Fork 1
/
provider.go
349 lines (312 loc) · 8.77 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
package gits
import (
"fmt"
"io"
"net/url"
"sort"
"strings"
"time"
"github.com/jenkins-x/jx/pkg/auth"
"gopkg.in/AlecAivazis/survey.v1"
"gopkg.in/AlecAivazis/survey.v1/terminal"
)
type GitOrganisation struct {
Login string
}
type GitRepository struct {
Name string
AllowMergeCommit bool
HTMLURL string
CloneURL string
SSHURL string
Language string
Fork bool
Stars int
}
type GitPullRequest struct {
URL string
Author *GitUser
Owner string
Repo string
Number *int
Mergeable *bool
Merged *bool
HeadRef *string
State *string
StatusesURL *string
IssueURL *string
DiffURL *string
MergeCommitSHA *string
ClosedAt *time.Time
MergedAt *time.Time
LastCommitSha string
Title string
Body string
}
type GitCommit struct {
SHA string
Message string
Author *GitUser
URL string
Branch string
Committer *GitUser
}
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
CreatedAt *time.Time
UpdatedAt *time.Time
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
DownloadCount int
}
type GitLabel struct {
URL string
Name string
Color string
}
type GitRepoStatus struct {
ID string
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 {
Title string
Body string
Head string
Base string
GitRepositoryInfo *GitRepositoryInfo
}
type GitWebHookArguments struct {
Owner string
Repo *GitRepositoryInfo
URL string
Secret string
}
// IsClosed returns true if the PullRequest has been closed
func (pr *GitPullRequest) IsClosed() bool {
return pr.ClosedAt != nil
}
func CreateProvider(server *auth.AuthServer, user *auth.UserAuth, git Gitter) (GitProvider, error) {
switch server.Kind {
case KindBitBucketCloud:
return NewBitbucketCloudProvider(server, user, git)
case KindBitBucketServer:
return NewBitbucketServerProvider(server, user, git)
case KindGitea:
return NewGiteaProvider(server, user, git)
case KindGitlab:
return NewGitlabProvider(server, user, git)
default:
return NewGitHubProvider(server, user, git)
}
}
// GetHost returns the Git Provider hostname, e.g github.com
func GetHost(gitProvider GitProvider) (string, error) {
if gitProvider == nil {
return "", fmt.Errorf("no Git provider")
}
if gitProvider.ServerURL() == "" {
return "", fmt.Errorf("no Git provider server URL found")
}
url, err := url.Parse(gitProvider.ServerURL())
if err != nil {
return "", fmt.Errorf("error parsing ")
}
return url.Host, nil
}
func ProviderAccessTokenURL(kind string, url string, username string) string {
switch kind {
case KindBitBucketCloud:
// TODO pass in the username
return BitBucketCloudAccessTokenURL(url, username)
case KindBitBucketServer:
return BitBucketServerAccessTokenURL(url)
case KindGitea:
return GiteaAccessTokenURL(url)
case KindGitlab:
return GitlabAccessTokenURL(url)
default:
return GitHubAccessTokenURL(url)
}
}
// PickOrganisation picks an organisations login if there is one available
func PickOrganisation(orgLister OrganisationLister, userName string, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) (string, error) {
prompt := &survey.Select{
Message: "Which organisation do you want to use?",
Options: GetOrganizations(orgLister, userName),
Default: userName,
}
orgName := ""
surveyOpts := survey.WithStdio(in, out, errOut)
err := survey.AskOne(prompt, &orgName, nil, surveyOpts)
if err != nil {
return "", err
}
if orgName == userName {
return "", nil
}
return orgName, nil
}
// GetOrganizations gets the organisation
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, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) ([]*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{}
surveyOpts := survey.WithStdio(in, out, errOut)
err = survey.AskOne(prompt, &repoNames, nil, surveyOpts)
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, git Gitter, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) (GitProvider, error) {
config := authConfigSvc.Config()
hostUrl := i.HostURLWithoutUser()
server := config.GetOrCreateServer(hostUrl)
if server.Kind == "" {
server.Kind = gitKind
}
userAuth, err := config.PickServerUserAuth(server, message, batchMode, "", in, out, errOut)
if err != nil {
return nil, err
}
return i.CreateProviderForUser(server, userAuth, gitKind, git)
}
func (i *GitRepositoryInfo) CreateProviderForUser(server *auth.AuthServer, user *auth.UserAuth, gitKind string, git Gitter) (GitProvider, error) {
if i.Host == GitHubHost {
return NewGitHubProvider(server, user, git)
}
if gitKind != "" && server.Kind != gitKind {
server.Kind = gitKind
}
return CreateProvider(server, user, git)
}
func (i *GitRepositoryInfo) CreateProvider(authConfigSvc auth.AuthConfigService, gitKind string, git Gitter) (GitProvider, error) {
hostUrl := i.HostURLWithoutUser()
return CreateProviderForURL(authConfigSvc, gitKind, hostUrl, git)
}
// CreateProviderForURL creates the Git provider for the given git kind and host URL
func CreateProviderForURL(authConfigSvc auth.AuthConfigService, gitKind string, hostUrl string, git Gitter) (GitProvider, error) {
config := authConfigSvc.Config()
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, git)
}
}
userAuth := auth.CreateAuthUserFromEnvironment("GIT")
if !userAuth.IsInvalid() {
return CreateProvider(server, &userAuth, git)
}
}
if len(userAuths) > 0 {
// TODO use default user???
auth := userAuths[0]
return CreateProvider(server, auth, git)
}
return nil, fmt.Errorf("Could not create Git provider for host %s as no user auths could be found", hostUrl)
}