forked from drone/go-scm
-
Notifications
You must be signed in to change notification settings - Fork 84
/
repo.go
627 lines (557 loc) · 17 KB
/
repo.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
// Copyright 2017 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package stash
import (
"context"
"fmt"
"net/url"
"sort"
"strconv"
"github.com/jenkins-x/go-scm/scm"
)
type repository struct {
Slug string `json:"slug"`
ID int `json:"id"`
Name string `json:"name"`
ScmID string `json:"scmId"`
State string `json:"state"`
StatusMessage string `json:"statusMessage"`
Forkable bool `json:"forkable"`
Project struct {
Key string `json:"key"`
ID int `json:"id"`
Name string `json:"name"`
Public bool `json:"public"`
Type string `json:"type"`
Links struct {
Self []link `json:"self"`
} `json:"links"`
} `json:"project"`
Public bool `json:"public"`
Links struct {
Clone []link `json:"clone"`
Self []link `json:"self"`
} `json:"links"`
}
type repositories struct {
pagination
Values []*repository `json:"values"`
}
type link struct {
Href string `json:"href"`
Name string `json:"name"`
}
type hooks struct {
pagination
Values []*hook `json:"values"`
}
type hook struct {
ID int `json:"id"`
Name string `json:"name"`
CreatedDate int64 `json:"createdDate"`
UpdatedDate int64 `json:"updatedDate"`
Events []string `json:"events"`
URL string `json:"url"`
Active bool `json:"active"`
Config struct {
Secret string `json:"secret"`
} `json:"configuration"`
}
type hookInput struct {
Name string `json:"name"`
Events []string `json:"events"`
URL string `json:"url"`
Active bool `json:"active"`
Config struct {
Secret string `json:"secret"`
} `json:"configuration"`
}
type status struct {
State string `json:"state"`
Key string `json:"key"`
Name string `json:"name"`
URL string `json:"url"`
Desc string `json:"description"`
}
type statuses struct {
pagination
Values []*status `json:"values"`
}
type participants struct {
pagination
Values []*participant `json:"values"`
}
type participant struct {
User user `json:"user"`
Permission string `json:"permission"`
}
type projGroups struct {
pagination
Values []*projGroup
}
type projGroup struct {
Group group `json:"group"`
Permission string `json:"permission"`
}
type group struct {
Name string `json:"name"`
}
type members struct {
pagination
Values []*member `json:"values"`
}
type member struct {
Name string `json:"name"`
Slug string `json:"slug"`
}
type repositoryService struct {
client *wrapper
}
type repoInput struct {
Name string `json:"name"`
ScmID string `json:"scmId"`
Public bool `json:"public"`
}
type addCollaboratorInput struct {
Name string `json:"name"`
Permission string `json:"permission"`
}
func (s *repositoryService) Create(ctx context.Context, input *scm.RepositoryInput) (*scm.Repository, *scm.Response, error) {
in := &repoInput{
Name: input.Name,
ScmID: "git",
Public: !input.Private,
}
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos", input.Namespace)
out := new(repository)
res, err := s.client.do(ctx, "POST", path, in, out)
return convertRepository(out), res, err
}
type forkProjectInput struct {
Key string `json:"key,omitempty"`
}
type forkInput struct {
Slug string `json:"slug,omitempty"`
Project *forkProjectInput `json:"project,omitempty"`
}
func (s *repositoryService) Fork(ctx context.Context, input *scm.RepositoryInput, origRepo string) (*scm.Repository, *scm.Response, error) {
namespace, name := scm.Split(origRepo)
in := new(forkInput)
if input.Name != "" {
in.Slug = input.Name
}
if input.Namespace != "" {
in.Project = &forkProjectInput{Key: input.Namespace}
}
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s", namespace, name)
out := new(repository)
res, err := s.client.do(ctx, "POST", path, in, out)
return convertRepository(out), res, err
}
func (s *repositoryService) FindCombinedStatus(ctx context.Context, repo, ref string) (*scm.CombinedStatus, *scm.Response, error) {
path := fmt.Sprintf("rest/build-status/1.0/commits/%s?orderBy=oldest", url.PathEscape(ref))
out := new(statuses)
res, err := s.client.do(ctx, "GET", path, nil, &out)
if err != nil {
return nil, res, err
}
combinedState := scm.StateUnknown
byContext := make(map[string]*status)
for _, s := range out.Values {
byContext[s.Key] = s
}
keys := make([]string, 0, len(byContext))
for k := range byContext {
keys = append(keys, k)
}
sort.Strings(keys)
var statuses []*scm.Status
for _, k := range keys {
s := byContext[k]
statuses = append(statuses, convertStatus(s))
}
for _, s := range statuses {
// If we've still got a default state, or the state of the current status is worse than the current state, set it.
if combinedState == scm.StateUnknown || combinedState > s.State {
combinedState = s.State
}
}
return &scm.CombinedStatus{
State: combinedState,
Sha: ref,
Statuses: statuses,
}, res, err
}
func (s *repositoryService) FindUserPermission(ctx context.Context, repo, user string) (string, *scm.Response, error) {
namespace, name := scm.Split(repo)
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s/permissions/users?filter=%s", namespace, name, url.QueryEscape(user))
out := new(participants)
res, err := s.client.do(ctx, "GET", path, nil, out)
if err != nil {
return "", res, err
}
for _, p := range out.Values {
if p.User.Name == user {
return apiStringToPermission(p.Permission), res, nil
}
}
return "", res, nil
}
func (s *repositoryService) AddCollaborator(ctx context.Context, repo, user, permission string) (bool, bool, *scm.Response, error) {
existingPerm, res, err := s.FindUserPermission(ctx, repo, user)
if err != nil {
return false, false, res, err
}
if existingPerm == permission {
return false, true, res, nil
}
apiPerm := permissionToAPIString(permission, false)
if apiPerm == "" {
return false, false, nil, fmt.Errorf("unknown permission '%s'", permission)
}
namespace, name := scm.Split(repo)
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s/permissions/users?&name=%s&permission=%s", namespace, name, user, apiPerm)
input := &addCollaboratorInput{
Name: user,
Permission: apiPerm,
}
res, err = s.client.do(ctx, "PUT", path, input, nil)
if err != nil {
return false, false, res, err
}
return true, false, res, nil
}
func (s *repositoryService) IsCollaborator(ctx context.Context, repo, user string) (bool, *scm.Response, error) {
users, resp, err := s.ListCollaborators(ctx, repo, &scm.ListOptions{})
if err != nil {
return false, resp, err
}
for k := range users {
if users[k].Name == user || users[k].Login == user {
return true, resp, err
}
}
return false, resp, err
}
func (s *repositoryService) ListCollaborators(ctx context.Context, repo string, opts *scm.ListOptions) ([]scm.User, *scm.Response, error) {
namespace, name := scm.Split(repo)
opts.Size = 1000
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s/permissions/users?%s", namespace, name, encodeListOptions(opts))
out := new(participants)
res, err := s.client.do(ctx, "GET", path, nil, out)
if !out.pagination.LastPage.Bool {
res.Page.First = 1
res.Page.Next = opts.Page + 1
}
return convertParticipants(out), res, err
}
func (s *repositoryService) ListLabels(context.Context, string, *scm.ListOptions) ([]*scm.Label, *scm.Response, error) {
// TODO implement me!
return nil, nil, nil
}
// Find returns the repository by name.
func (s *repositoryService) Find(ctx context.Context, repo string) (*scm.Repository, *scm.Response, error) {
namespace, name := scm.Split(repo)
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s", namespace, name)
out := new(repository)
res, err := s.client.do(ctx, "GET", path, nil, out)
return convertRepository(out), res, err
}
// FindHook returns a repository hook.
func (s *repositoryService) FindHook(ctx context.Context, repo, id string) (*scm.Hook, *scm.Response, error) {
namespace, name := scm.Split(repo)
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s/webhooks/%s", namespace, name, id)
out := new(hook)
res, err := s.client.do(ctx, "GET", path, nil, out)
return convertHook(out), res, err
}
// FindPerms returns the repository permissions.
func (s *repositoryService) FindPerms(ctx context.Context, repo string) (*scm.Perm, *scm.Response, error) {
// HACK: test if the user has read access to the repository.
_, _, err := s.Find(ctx, repo)
if err != nil {
return &scm.Perm{
Pull: false,
Push: false,
Admin: false,
}, nil, nil
}
// HACK: test if the user has admin access to the repository.
_, _, err = s.ListHooks(ctx, repo, &scm.ListOptions{})
if err == nil {
return &scm.Perm{
Pull: true,
Push: true,
Admin: true,
}, nil, nil
}
// HACK: test if the user has write access to the repository.
_, name := scm.Split(repo)
repos, _, _ := s.listWrite(ctx, repo)
for _, repo := range repos {
if repo.Name == name {
return &scm.Perm{
Pull: true,
Push: true,
Admin: false,
}, nil, nil
}
}
return &scm.Perm{
Pull: true,
Push: false,
Admin: false,
}, nil, nil
}
// List returns the user repository list.
func (s *repositoryService) List(ctx context.Context, opts *scm.ListOptions) ([]*scm.Repository, *scm.Response, error) {
path := fmt.Sprintf("rest/api/1.0/repos?%s", encodeListRoleOptions(opts))
out := new(repositories)
res, err := s.client.do(ctx, "GET", path, nil, &out)
if !out.pagination.LastPage.Bool {
res.Page.First = 1
res.Page.Next = opts.Page + 1
}
return convertRepositoryList(out), res, err
}
func (s *repositoryService) ListOrganisation(ctx context.Context, org string, opts *scm.ListOptions) ([]*scm.Repository, *scm.Response, error) {
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos?%s", org, encodeListRoleOptions(opts))
out := new(repositories)
res, err := s.client.do(ctx, "GET", path, nil, &out)
if !out.pagination.LastPage.Bool {
res.Page.First = 1
res.Page.Next = opts.Page + 1
}
return convertRepositoryList(out), res, err
}
func (s *repositoryService) ListUser(context.Context, string, *scm.ListOptions) ([]*scm.Repository, *scm.Response, error) {
return nil, nil, scm.ErrNotSupported
}
// listWrite returns the user repository list.
func (s *repositoryService) listWrite(ctx context.Context, repo string) ([]*scm.Repository, *scm.Response, error) {
namespace, name := scm.Split(repo)
path := fmt.Sprintf("rest/api/1.0/repos?size=1000&permission=REPO_WRITE&project=%s&name=%s", namespace, name)
out := new(repositories)
res, err := s.client.do(ctx, "GET", path, nil, out)
return convertRepositoryList(out), res, err
}
// ListHooks returns a list or repository hooks.
func (s *repositoryService) ListHooks(ctx context.Context, repo string, opts *scm.ListOptions) ([]*scm.Hook, *scm.Response, error) {
namespace, name := scm.Split(repo)
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s/webhooks?%s", namespace, name, encodeListOptions(opts))
out := new(hooks)
res, err := s.client.do(ctx, "GET", path, nil, out)
if !out.pagination.LastPage.Bool {
res.Page.First = 1
res.Page.Next = opts.Page + 1
}
return convertHookList(out), res, err
}
// ListStatus returns a list of commit statuses.
func (s *repositoryService) ListStatus(ctx context.Context, _, ref string, opts *scm.ListOptions) ([]*scm.Status, *scm.Response, error) {
path := fmt.Sprintf("rest/build-status/1.0/commits/%s?%s", url.PathEscape(ref), encodeListOptions(opts))
out := new(statuses)
res, err := s.client.do(ctx, "GET", path, nil, &out)
if !out.pagination.LastPage.Bool {
res.Page.First = 1
res.Page.Next = opts.Page + 1
}
return convertStatusList(out), res, err
}
// CreateHook creates a new repository webhook.
func (s *repositoryService) CreateHook(ctx context.Context, repo string, input *scm.HookInput) (*scm.Hook, *scm.Response, error) {
namespace, name := scm.Split(repo)
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s/webhooks", namespace, name)
in := new(hookInput)
in.URL = input.Target
in.Active = true
in.Name = input.Name
in.Config.Secret = input.Secret
// nolint
in.Events = append(
input.NativeEvents,
convertHookEvents(input.Events)...,
)
out := new(hook)
res, err := s.client.do(ctx, "POST", path, in, out)
return convertHook(out), res, err
}
func (s *repositoryService) UpdateHook(ctx context.Context, repo string, input *scm.HookInput) (*scm.Hook, *scm.Response, error) {
return nil, nil, scm.ErrNotSupported
}
// CreateStatus creates a new commit status.
// reference: https://developer.atlassian.com/server/bitbucket/how-tos/updating-build-status-for-commits/
func (s *repositoryService) CreateStatus(ctx context.Context, repo, ref string, input *scm.StatusInput) (*scm.Status, *scm.Response, error) {
path := fmt.Sprintf("rest/build-status/1.0/commits/%s", url.PathEscape(ref))
in := status{
State: convertFromState(input.State),
Key: input.Label,
Name: input.Label,
URL: input.Target,
Desc: input.Desc,
}
res, err := s.client.do(ctx, "POST", path, in, nil)
return &scm.Status{
State: input.State,
Label: input.Label,
Desc: input.Desc,
Target: input.Target,
}, res, err
}
// DeleteHook deletes a repository webhook.
func (s *repositoryService) DeleteHook(ctx context.Context, repo, id string) (*scm.Response, error) {
namespace, name := scm.Split(repo)
path := fmt.Sprintf("rest/api/1.0/projects/%s/repos/%s/webhooks/%s", namespace, name, id)
return s.client.do(ctx, "DELETE", path, nil, nil)
}
func (s *repositoryService) Delete(context.Context, string) (*scm.Response, error) {
return nil, scm.ErrNotSupported
}
// helper function to convert from the gogs repository list to
// the common repository structure.
func convertRepositoryList(from *repositories) []*scm.Repository {
to := []*scm.Repository{}
for _, v := range from.Values {
to = append(to, convertRepository(v))
}
return to
}
// helper function to convert from the gogs repository structure
// to the common repository structure.
func convertRepository(from *repository) *scm.Repository {
return &scm.Repository{
ID: strconv.Itoa(from.ID),
Name: from.Slug,
Namespace: from.Project.Key,
FullName: fmt.Sprintf("%s/%s", from.Project.Key, from.Slug),
Link: extractSelfLink(from.Links.Self),
Branch: "master",
Private: !from.Public,
CloneSSH: extractLink(from.Links.Clone, "ssh"),
Clone: anonymizeLink(extractLink(from.Links.Clone, "http")),
}
}
func extractLink(links []link, name string) (href string) {
for _, link := range links {
if link.Name == name {
return link.Href
}
}
return
}
func extractSelfLink(links []link) (href string) {
for _, link := range links {
return link.Href
}
return
}
func anonymizeLink(link string) (href string) {
parsed, err := url.Parse(link)
if err != nil {
return link
}
parsed.User = nil
return parsed.String()
}
func convertHookList(from *hooks) []*scm.Hook {
to := []*scm.Hook{}
for _, v := range from.Values {
to = append(to, convertHook(v))
}
return to
}
func convertHook(from *hook) *scm.Hook {
return &scm.Hook{
ID: strconv.Itoa(from.ID),
Name: from.Name,
Active: from.Active,
Target: from.URL,
Events: from.Events,
}
}
func convertHookEvents(from scm.HookEvents) []string {
var events []string
if from.Push || from.Branch || from.Tag {
events = append(events, "repo:refs_changed")
}
if from.PullRequest {
events = append(events, "pr:declined", "pr:modified", "pr:deleted", "pr:opened", "pr:merged", "pr:from_ref_updated")
}
if from.PullRequestComment {
events = append(events, "pr:comment:added", "pr:comment:deleted", "pr:comment:edited")
}
return events
}
func convertStatusList(from *statuses) []*scm.Status {
to := []*scm.Status{}
for _, v := range from.Values {
to = append(to, convertStatus(v))
}
return to
}
func convertStatus(from *status) *scm.Status {
return &scm.Status{
State: convertState(from.State),
Label: from.Key,
Desc: from.Desc,
Target: from.URL,
}
}
func convertFromState(from scm.State) string {
switch from {
case scm.StatePending, scm.StateRunning:
return "INPROGRESS"
case scm.StateSuccess:
return "SUCCESSFUL"
default:
return "FAILED"
}
}
func convertState(from string) scm.State {
switch from {
case "FAILED":
return scm.StateFailure
case "INPROGRESS":
return scm.StatePending
case "SUCCESSFUL":
return scm.StateSuccess
default:
return scm.StateUnknown
}
}
func convertParticipants(participants *participants) []scm.User {
answer := []scm.User{}
for _, p := range participants.Values {
answer = append(answer, *convertUser(&p.User))
}
return answer
}
func apiStringToPermission(apiString string) string {
switch apiString {
case "ADMIN", "PROJECT_ADMIN", "REPO_ADMIN":
return scm.AdminPermission
case "PROJECT_CREATE", "PROJECT_WRITE", "REPO_WRITE":
return scm.WritePermission
case "PROJECT_READ", "REPO_READ":
return scm.ReadPermission
default:
return scm.NoPermission
}
}
func permissionToAPIString(perm string, isProject bool) string {
prefix := "REPO"
if isProject {
prefix = "PROJECT"
}
switch perm {
case scm.AdminPermission:
return prefix + "_ADMIN"
case scm.WritePermission:
return prefix + "_WRITE"
case scm.ReadPermission:
return prefix + "_READ"
default:
return ""
}
}