-
Notifications
You must be signed in to change notification settings - Fork 787
/
gitlab.go
987 lines (850 loc) · 25.3 KB
/
gitlab.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
package gits
import (
"context"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
errors2 "github.com/pkg/errors"
"github.com/google/go-github/github"
"github.com/jenkins-x/jx/v2/pkg/auth"
"github.com/jenkins-x/jx/v2/pkg/log"
"github.com/jenkins-x/jx/v2/pkg/util"
"github.com/xanzy/go-gitlab"
)
type GitlabProvider struct {
Username string
Client *gitlab.Client
Context context.Context
Server auth.AuthServer
User auth.UserAuth
Git Gitter
}
func NewGitlabProvider(server *auth.AuthServer, user *auth.UserAuth, git Gitter) (GitProvider, error) {
u := server.URL
c := gitlab.NewClient(nil, user.ApiToken)
if !IsGitLabServerURL(u) {
if err := c.SetBaseURL(u); err != nil {
return nil, err
}
}
return WithGitlabClient(server, user, c, git)
}
func IsGitLabServerURL(u string) bool {
u = strings.TrimSuffix(u, "/")
return u == "" || u == "https://gitlab.com" || u == "http://gitlab.com"
}
// Used by unit tests to inject a mocked client
func WithGitlabClient(server *auth.AuthServer, user *auth.UserAuth, client *gitlab.Client, git Gitter) (GitProvider, error) {
provider := &GitlabProvider{
Server: *server,
User: *user,
Username: user.Username,
Client: client,
Git: git,
}
return provider, nil
}
func (g *GitlabProvider) ListRepositories(org string) ([]*GitRepository, error) {
result, _, err := getRepositories(g.Client, g.Username, org, "")
if err != nil {
return nil, err
}
var repos []*GitRepository
for _, p := range result {
repos = append(repos, fromGitlabProject(p))
}
return repos, nil
}
func (g *GitlabProvider) ListReleases(org string, name string) ([]*GitRelease, error) {
answer := []*GitRelease{}
// TODO
return answer, nil
}
// GetRelease returns the release info for the org, repo name and tag
func (g *GitlabProvider) GetRelease(org string, name string, tag string) (*GitRelease, error) {
return nil, nil
}
func getRepositories(g *gitlab.Client, username string, org string, searchFilter string) ([]*gitlab.Project, *gitlab.Response, error) {
// TODO: handle the case of more than "pageSize" results, similarly to ListOpenPullRequests().
gitlabSearchFilter := gitlab.String(searchFilter)
listOpts := gitlab.ListOptions{PerPage: pageSize}
listProjectOpts := &gitlab.ListProjectsOptions{
Owned: gitlab.Bool(true),
Search: gitlabSearchFilter,
ListOptions: listOpts,
}
if org != "" {
projects, resp, err := g.Groups.ListGroupProjects(org, &gitlab.ListGroupProjectsOptions{Search: gitlabSearchFilter, ListOptions: listOpts})
if err != nil {
return g.Projects.ListUserProjects(org, listProjectOpts)
}
return projects, resp, err
}
return g.Projects.ListUserProjects(username, listProjectOpts)
}
func GetOwnerNamespaceID(g *gitlab.Client, owner string) (int, error) {
n := &gitlab.ListNamespacesOptions{
Search: &owner,
}
namespaces, _, err := g.Namespaces.ListNamespaces(n)
if err != nil {
return -1, err
}
for _, v := range namespaces {
if v.FullPath == owner {
return v.ID, nil
}
}
return -1, fmt.Errorf("no namespace found for owner %s", owner)
}
func fromGitlabProject(p *gitlab.Project) *GitRepository {
org := ""
if p.Namespace != nil {
org = p.Namespace.Path
}
return &GitRepository{
Organisation: org,
Project: org,
Name: p.Name,
HTMLURL: p.WebURL,
SSHURL: p.SSHURLToRepo,
CloneURL: p.HTTPURLToRepo,
Fork: p.ForkedFromProject != nil,
}
}
func (g *GitlabProvider) CreateRepository(org string, name string, private bool) (*GitRepository, error) {
visibility := gitlab.PublicVisibility
if private {
visibility = gitlab.PrivateVisibility
}
namespaceID, err := GetOwnerNamespaceID(g.Client, owner(org, g.Username))
if err != nil {
return nil, err
}
p := &gitlab.CreateProjectOptions{
Name: &name,
Visibility: &visibility,
NamespaceID: &namespaceID,
}
project, _, err := g.Client.Projects.CreateProject(p)
if err != nil {
return nil, err
}
return fromGitlabProject(project), nil
}
func owner(org, username string) string {
if org == "" {
return username
}
return org
}
func (g *GitlabProvider) GetRepository(org, name string) (*GitRepository, error) {
pid, err := g.projectId(org, g.Username, name)
if err != nil {
return nil, err
}
project, response, err := g.Client.Projects.GetProject(pid, nil, nil)
if err != nil {
return nil, fmt.Errorf("request: %s failed due to: %s", response.Request.URL, err)
}
return fromGitlabProject(project), nil
}
func (g *GitlabProvider) ListOrganisations() ([]GitOrganisation, error) {
groups, _, err := g.Client.Groups.ListGroups(nil)
if err != nil {
return nil, err
}
var organizations []GitOrganisation
for _, v := range groups {
organizations = append(organizations, GitOrganisation{v.Path})
}
return organizations, nil
}
func (g *GitlabProvider) projectId(org, username, name string) (string, error) {
repos, _, err := getRepositories(g.Client, username, org, name)
if err != nil {
return "", err
}
for _, repo := range repos {
if repo.Name == name {
return strconv.Itoa(repo.ID), nil
}
}
return "", fmt.Errorf("no repository found with name %s", name)
}
func (g *GitlabProvider) DeleteRepository(org, name string) error {
pid, err := g.projectId(org, g.Username, name)
if err != nil {
return err
}
_, err = g.Client.Projects.DeleteProject(pid)
if err != nil {
return fmt.Errorf("failed to delete repository %s due to: %s", pid, err)
}
return err
}
func (g *GitlabProvider) ForkRepository(originalOrg, name, destinationOrg string) (*GitRepository, error) {
pid, err := g.projectId(originalOrg, g.Username, name)
if err != nil {
return nil, err
}
project, _, err := g.Client.Projects.ForkProject(pid, nil, nil)
if err != nil {
return nil, err
}
return fromGitlabProject(project), nil
}
func (g *GitlabProvider) RenameRepository(org, name, newName string) (*GitRepository, error) {
pid, err := g.projectId(org, g.Username, name)
if err != nil {
return nil, err
}
options := &gitlab.EditProjectOptions{
Name: &newName,
}
project, _, err := g.Client.Projects.EditProject(pid, options)
if err != nil {
return nil, err
}
return fromGitlabProject(project), nil
}
func (g *GitlabProvider) ValidateRepositoryName(org, name string) error {
pid, err := g.projectId(org, g.Username, name)
if err == nil {
return fmt.Errorf("repository %s already exists", pid)
}
return nil
}
func (g *GitlabProvider) CreatePullRequest(data *GitPullRequestArguments) (*GitPullRequest, error) {
owner := data.GitRepository.Organisation
repo := data.GitRepository.Name
title := data.Title
body := data.Body
head := data.Head
base := data.Base
o := &gitlab.CreateMergeRequestOptions{
Title: &title,
Description: &body,
SourceBranch: &head,
TargetBranch: &base,
}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return nil, err
}
mr, _, err := g.Client.MergeRequests.CreateMergeRequest(pid, o)
if err != nil {
return nil, err
}
return fromMergeRequest(mr, owner, repo), nil
}
// UpdatePullRequest updates pull request with number using data
func (g *GitlabProvider) UpdatePullRequest(data *GitPullRequestArguments, number int) (*GitPullRequest, error) {
owner := data.GitRepository.Organisation
repo := data.GitRepository.Name
title := data.Title
body := data.Body
base := data.Base
o := &gitlab.UpdateMergeRequestOptions{
Title: &title,
Description: &body,
}
if base != "" {
o.TargetBranch = &base
}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return nil, err
}
mr, resp, err := g.Client.MergeRequests.UpdateMergeRequest(pid, number, o)
if err != nil {
if resp != nil && resp.Body != nil {
data, err2 := ioutil.ReadAll(resp.Body)
if err2 == nil && len(data) > 0 {
return nil, errors2.Wrapf(err, "response: %s", string(data))
}
}
return nil, err
}
return &GitPullRequest{
URL: mr.WebURL,
Owner: owner,
Repo: repo,
Number: &mr.IID,
}, nil
}
func fromMergeRequest(mr *gitlab.MergeRequest, owner, repo string) *GitPullRequest {
merged := false
if mr.MergedAt != nil {
merged = true
}
var assignees []*GitUser
if mr.Assignee != nil {
assignees = append(assignees, convertUser(mr.Assignee))
}
for _, a := range mr.Assignees {
assignees = append(assignees, convertUser(a))
}
return &GitPullRequest{
Author: convertUser(mr.Author),
Assignees: assignees,
URL: mr.WebURL,
Owner: owner,
Repo: repo,
Number: &mr.IID,
State: &mr.State,
Labels: convertPullRequestLabels(mr.Labels),
Title: mr.Title,
Body: mr.Description,
MergeCommitSHA: &mr.MergeCommitSHA,
Merged: &merged,
LastCommitSha: mr.SHA,
MergedAt: mr.MergedAt,
ClosedAt: mr.ClosedAt,
}
}
func (g *GitlabProvider) UpdatePullRequestStatus(pr *GitPullRequest) error {
owner := pr.Owner
repo := pr.Repo
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return err
}
mr, _, err := g.Client.MergeRequests.GetMergeRequest(pid, *pr.Number, nil, nil)
if err != nil {
return err
}
*pr = *fromMergeRequest(mr, owner, repo)
return nil
}
// GetPullRequest gets a PR
func (g *GitlabProvider) GetPullRequest(owner string, repo *GitRepository, number int) (*GitPullRequest, error) {
pr := &GitPullRequest{
Owner: owner,
Repo: repo.Name,
Number: &number,
}
err := g.UpdatePullRequestStatus(pr)
return pr, err
}
// ListOpenPullRequests lists the open pull requests
func (g *GitlabProvider) ListOpenPullRequests(owner string, repo string) ([]*GitPullRequest, error) {
gitlabOpen := "opened"
opt := &gitlab.ListProjectMergeRequestsOptions{
State: &gitlabOpen,
ListOptions: gitlab.ListOptions{
Page: 0,
PerPage: pageSize,
},
}
answer := []*GitPullRequest{}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return nil, err
}
for {
prs, _, err := g.Client.MergeRequests.ListProjectMergeRequests(pid, opt)
if err != nil {
return answer, err
}
for _, pr := range prs {
answer = append(answer, fromMergeRequest(pr, owner, repo))
}
if len(prs) < pageSize || len(prs) == 0 {
break
}
opt.Page++
}
return answer, nil
}
// GetPullRequestCommits gets the PR commits
func (g *GitlabProvider) GetPullRequestCommits(owner string, repository *GitRepository, number int) ([]*GitCommit, error) {
repo := repository.Name
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return nil, err
}
commits, _, err := g.Client.MergeRequests.GetMergeRequestCommits(pid, number, nil)
if err != nil {
return nil, err
}
answer := []*GitCommit{}
for _, commit := range commits {
if commit == nil {
continue
}
summary := &GitCommit{
Message: commit.Message,
SHA: commit.ID,
Author: &GitUser{
Email: commit.AuthorEmail,
},
}
answer = append(answer, summary)
}
return answer, nil
}
func (g *GitlabProvider) PullRequestLastCommitStatus(pr *GitPullRequest) (string, error) {
owner := pr.Owner
repo := pr.Repo
ref := pr.LastCommitSha
if ref == "" {
return "", fmt.Errorf("missing String for LastCommitSha %#v", pr)
}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return "", err
}
c, _, err := g.Client.Commits.GetCommitStatuses(pid, ref, nil)
if err != nil {
return "", err
}
for _, result := range c {
if result.Status != "" {
return result.Status, nil
}
}
return "", fmt.Errorf("could not find a status for repository %s with ref %s", pid, ref)
}
func (g *GitlabProvider) ListCommitStatus(org string, repo string, sha string) ([]*GitRepoStatus, error) {
pid, err := g.projectId(org, g.Username, repo)
if err != nil {
return nil, err
}
c, _, err := g.Client.Commits.GetCommitStatuses(pid, sha, nil)
if err != nil {
return nil, err
}
var statuses []*GitRepoStatus
for _, result := range c {
statuses = append(statuses, fromCommitStatus(result))
}
return statuses, nil
}
// UpdateCommitStatus updates the commit status
func (g *GitlabProvider) UpdateCommitStatus(owner string, repo string, sha string, status *GitRepoStatus) (*GitRepoStatus, error) {
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return nil, err
}
glState := gitlab.BuildStateValue(status.State)
if status.State == "failure" {
glState = gitlab.Failed
}
statusOptions := &gitlab.SetCommitStatusOptions{
State: glState,
Name: &status.Context,
Context: &status.Context,
Description: &status.Description,
TargetURL: &status.TargetURL,
}
c, _, err := g.Client.Commits.SetCommitStatus(pid, sha, statusOptions, nil)
if err != nil {
return nil, err
}
return &GitRepoStatus{
ID: strconv.Itoa(c.ID),
Description: c.Description,
State: c.Status,
Context: c.Name,
URL: c.TargetURL,
TargetURL: c.TargetURL,
}, err
}
func fromCommitStatus(status *gitlab.CommitStatus) *GitRepoStatus {
jxState := status.Status
if status.Status == "failed" {
jxState = "failure"
}
return &GitRepoStatus{
ID: strconv.Itoa(status.ID),
URL: status.TargetURL,
TargetURL: status.TargetURL,
State: jxState,
Description: status.Description,
Context: status.Name,
}
}
func (g *GitlabProvider) MergePullRequest(pr *GitPullRequest, message string) error {
pid, err := g.projectId(pr.Owner, g.Username, pr.Repo)
if err != nil {
return err
}
opt := &gitlab.AcceptMergeRequestOptions{MergeCommitMessage: &message}
_, _, err = g.Client.MergeRequests.AcceptMergeRequest(pid, *pr.Number, opt)
return err
}
func (g *GitlabProvider) CreateWebHook(data *GitWebHookArguments) error {
pid, err := g.projectId(data.Owner, g.Username, data.Repo.Name)
if err != nil {
return nil
}
flag := true
owner := owner(data.Owner, g.Username)
webhookURL := util.UrlJoin(data.URL, owner, data.Repo.Name)
opt := &gitlab.AddProjectHookOptions{
URL: &webhookURL,
Token: &data.Secret,
PushEvents: &flag,
MergeRequestsEvents: &flag,
IssuesEvents: &flag,
NoteEvents: &flag,
}
_, _, err = g.Client.Projects.AddProjectHook(pid, opt)
return err
}
// ListWebHooks lists the webhooks
func (g *GitlabProvider) ListWebHooks(owner string, repo string) ([]*GitWebHookArguments, error) {
answer := []*GitWebHookArguments{}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return answer, err
}
opt := &gitlab.ListProjectHooksOptions{}
hooks, _, err := g.Client.Projects.ListProjectHooks(pid, opt, nil)
for _, hook := range hooks {
answer = append(answer, gitLabToGitHook(owner, repo, hook))
}
return answer, err
}
func gitLabToGitHook(owner string, repo string, hook *gitlab.ProjectHook) *GitWebHookArguments {
return &GitWebHookArguments{
ID: int64(hook.ID),
Owner: owner,
Repo: &GitRepository{
Organisation: owner,
Name: repo,
},
URL: hook.URL,
}
}
func (g *GitlabProvider) UpdateWebHook(data *GitWebHookArguments) error {
pid, err := g.projectId(data.Owner, g.Username, data.Repo.Name)
if err != nil {
return nil
}
flag := true
owner := owner(data.Owner, g.Username)
webhookURL := util.UrlJoin(data.URL, owner, data.Repo.Name)
opt := &gitlab.EditProjectHookOptions{
URL: &webhookURL,
Token: &data.Secret,
PushEvents: &flag,
MergeRequestsEvents: &flag,
IssuesEvents: &flag,
NoteEvents: &flag,
}
_, _, err = g.Client.Projects.EditProjectHook(pid, int(data.ID), opt)
return err
}
func (g *GitlabProvider) SearchIssues(org, repo, query string) ([]*GitIssue, error) {
opt := &gitlab.ListProjectIssuesOptions{Search: &query}
return g.searchIssuesWithOptions(org, repo, opt)
}
func (g *GitlabProvider) SearchIssuesClosedSince(org string, repo string, t time.Time) ([]*GitIssue, error) {
closed := "closed"
opt := &gitlab.ListProjectIssuesOptions{State: &closed}
issues, err := g.searchIssuesWithOptions(org, repo, opt)
if err != nil {
return issues, err
}
return FilterIssuesClosedSince(issues, t), nil
}
func (g *GitlabProvider) searchIssuesWithOptions(org string, repo string, opt *gitlab.ListProjectIssuesOptions) ([]*GitIssue, error) {
pid, err := g.projectId(org, g.Username, repo)
if err != nil {
return nil, err
}
issues, _, err := g.Client.Issues.ListProjectIssues(pid, opt)
if err != nil {
return nil, err
}
return fromGitlabIssues(issues, owner(org, g.Username), repo), nil
}
func (g *GitlabProvider) GetIssue(org, repo string, number int) (*GitIssue, error) {
owner := owner(org, g.Username)
pid, err := g.projectId(org, g.Username, repo)
if err != nil {
return nil, err
}
issue, _, err := g.Client.Issues.GetIssue(pid, number)
if err != nil {
return nil, err
}
return fromGitlabIssue(issue, owner, repo), nil
}
func (g *GitlabProvider) CreateIssue(owner string, repo string, issue *GitIssue) (*GitIssue, error) {
labels := []string{}
for _, label := range issue.Labels {
name := label.Name
if name != "" {
labels = append(labels, name)
}
}
gitlabLabels := gitlab.Labels(labels)
opt := &gitlab.CreateIssueOptions{
Title: &issue.Title,
Description: &issue.Body,
Labels: &gitlabLabels,
}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return nil, err
}
gitlabIssue, _, err := g.Client.Issues.CreateIssue(pid, opt)
if err != nil {
return nil, err
}
return fromGitlabIssue(gitlabIssue, owner, repo), nil
}
func fromGitlabIssues(issues []*gitlab.Issue, owner, repo string) []*GitIssue {
var result []*GitIssue
for _, v := range issues {
result = append(result, fromGitlabIssue(v, owner, repo))
}
return result
}
func fromGitlabIssue(issue *gitlab.Issue, owner, repo string) *GitIssue {
var labels []GitLabel
for _, v := range issue.Labels {
labels = append(labels, GitLabel{Name: v})
}
return &GitIssue{
Number: &issue.IID,
URL: issue.WebURL,
Owner: owner,
Repo: repo,
Title: issue.Title,
Body: issue.Description,
Labels: labels,
CreatedAt: issue.CreatedAt,
UpdatedAt: issue.UpdatedAt,
ClosedAt: issue.ClosedAt,
}
}
func (g *GitlabProvider) AddPRComment(pr *GitPullRequest, comment string) error {
owner := pr.Owner
repo := pr.Repo
opt := &gitlab.CreateMergeRequestNoteOptions{Body: &comment}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return nil
}
_, _, err = g.Client.Notes.CreateMergeRequestNote(pid, *pr.Number, opt)
return err
}
func (g *GitlabProvider) CreateIssueComment(owner string, repo string, number int, comment string) error {
opt := &gitlab.CreateIssueNoteOptions{Body: &comment}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return err
}
_, _, err = g.Client.Notes.CreateIssueNote(pid, number, opt)
return err
}
func (g *GitlabProvider) HasIssues() bool {
return true
}
func (g *GitlabProvider) IsGitHub() bool {
return false
}
func (g *GitlabProvider) IsGitea() bool {
return false
}
func (g *GitlabProvider) IsBitbucketCloud() bool {
return false
}
func (g *GitlabProvider) IsBitbucketServer() bool {
return false
}
func (g *GitlabProvider) IsGerrit() bool {
return false
}
func (g *GitlabProvider) Kind() string {
return "gitlab"
}
func (g *GitlabProvider) JenkinsWebHookPath(gitURL string, secret string) string {
return "/project"
}
func (g *GitlabProvider) Label() string {
return g.Server.Label()
}
func (g *GitlabProvider) ServerURL() string {
return g.Server.URL
}
func (g *GitlabProvider) BranchArchiveURL(org string, name string, branch string) string {
return util.UrlJoin(g.ServerURL(), org, name, "-/archive", branch, name+"-"+branch+".zip")
}
func (g *GitlabProvider) CurrentUsername() string {
return g.Username
}
func (g *GitlabProvider) UserAuth() auth.UserAuth {
return g.User
}
func (g *GitlabProvider) getUserID(username string) (*int, error) {
users, _, err := g.Client.Users.ListUsers(&gitlab.ListUsersOptions{Username: &username})
if err != nil {
return nil, err
}
if len(users) == 0 {
return nil, nil
}
user := users[0]
return &user.ID, nil
}
func (g *GitlabProvider) UserInfo(username string) *GitUser {
users, _, err := g.Client.Users.ListUsers(&gitlab.ListUsersOptions{Username: &username})
if err != nil || len(users) == 0 {
return nil
}
user := users[0]
return &GitUser{
Login: username,
URL: user.WebsiteURL,
AvatarURL: user.AvatarURL,
Name: user.Name,
Email: user.Email,
}
}
func (g *GitlabProvider) UpdateRelease(owner string, repo string, tag string, releaseInfo *GitRelease) error {
return nil
}
// UpdateReleaseStatus is not supported for this git provider
func (g *GitlabProvider) UpdateReleaseStatus(owner string, repo string, tag string, releaseInfo *GitRelease) error {
return nil
}
// IssueURL returns the URL of the issue
func (g *GitlabProvider) IssueURL(org string, name string, number int, isPull bool) string {
return ""
}
// AddCollaborator adds a collaborator
func (g *GitlabProvider) AddCollaborator(user string, organisation string, repo string) error {
pid, err := g.projectId(organisation, g.Username, repo)
if err != nil {
return err
}
userId, err := g.getUserID(user)
if err != nil {
return err
}
accessLevel := gitlab.DeveloperPermissions
opts := &gitlab.AddProjectMemberOptions{
UserID: userId,
AccessLevel: &accessLevel,
}
_, _, err = g.Client.ProjectMembers.AddProjectMember(pid, opts)
return err
}
// ListInvitations lists pending invites
func (g *GitlabProvider) ListInvitations() ([]*github.RepositoryInvitation, *github.Response, error) {
log.Logger().Infof("Automatically adding the pipeline user as a collaborator is currently not implemented for gitlab.")
return []*github.RepositoryInvitation{}, &github.Response{}, nil
}
// AcceptInvitation accepts an invitation
func (g *GitlabProvider) AcceptInvitation(ID int64) (*github.Response, error) {
log.Logger().Infof("Automatically adding the pipeline user as a collaborator is currently not implemented for gitlab.")
return &github.Response{}, nil
}
// GetContent returns the content of a file
func (g *GitlabProvider) GetContent(org string, name string, path string, ref string) (*GitFileContent, error) {
return nil, fmt.Errorf("Getting content not supported on gitlab")
}
// ShouldForkForPullReques treturns true if we should create a personal fork of this repository
// before creating a pull request
func (g *GitlabProvider) ShouldForkForPullRequest(originalOwner string, repoName string, username string) bool {
// return originalOwner != username
// TODO assuming forking doesn't work yet?
return false
}
// GitlabAccessTokenURL returns the URL to click on to generate a personal access token for the Git provider
func GitlabAccessTokenURL(url string) string {
return util.UrlJoin(url, "/profile/personal_access_tokens")
}
// ListCommits lists the commits for the specified repo and owner
func (g *GitlabProvider) ListCommits(owner, repo string, opt *ListCommitsArguments) ([]*GitCommit, error) {
return nil, fmt.Errorf("Listing commits not supported on gitlab")
}
// AddLabelsToIssue adds labels to issues or pullrequests
func (g *GitlabProvider) AddLabelsToIssue(owner, repo string, number int, labels []string) error {
pr, err := g.GetPullRequest(owner, &GitRepository{Name: repo}, number)
if err != nil {
return err
}
labelMap := make(map[string]struct{})
for _, l := range pr.Labels {
if l.Name != nil {
labelMap[*l.Name] = struct{}{}
}
}
for _, l := range labels {
labelMap[l] = struct{}{}
}
glLabels := gitlab.Labels{}
for l := range labelMap {
glLabels = append(glLabels, l)
}
o := &gitlab.UpdateMergeRequestOptions{
Labels: &glLabels,
}
pid, err := g.projectId(owner, g.Username, repo)
if err != nil {
return err
}
_, resp, err := g.Client.MergeRequests.UpdateMergeRequest(pid, number, o)
if err != nil {
if resp != nil && resp.Body != nil {
data, err2 := ioutil.ReadAll(resp.Body)
if err2 == nil && len(data) > 0 {
return errors2.Wrapf(err, "response: %s", string(data))
}
}
return err
}
return nil
}
// GetLatestRelease fetches the latest release from the git provider for org and name
func (g *GitlabProvider) GetLatestRelease(org string, name string) (*GitRelease, error) {
// TODO
return nil, nil
}
// UploadReleaseAsset will upload an asset to org/repo to a release with id, giving it a name, it will return the release asset from the git provider
func (g *GitlabProvider) UploadReleaseAsset(org string, repo string, id int64, name string, asset *os.File) (*GitReleaseAsset, error) {
return nil, nil
}
// GetBranch returns the branch information for an owner/repo, including the commit at the tip
func (g *GitlabProvider) GetBranch(owner string, repo string, branch string) (*GitBranch, error) {
return nil, nil
}
// GetProjects returns all the git projects in owner/repo
func (g *GitlabProvider) GetProjects(owner string, repo string) ([]GitProject, error) {
return nil, nil
}
//ConfigureFeatures sets specific features as enabled or disabled for owner/repo
func (g *GitlabProvider) ConfigureFeatures(owner string, repo string, issues *bool, projects *bool, wikis *bool) (*GitRepository, error) {
return nil, nil
}
// IsWikiEnabled returns true if a wiki is enabled for owner/repo
func (g *GitlabProvider) IsWikiEnabled(owner string, repo string) (bool, error) {
return false, nil
}
func convertPullRequestLabels(from gitlab.Labels) []*Label {
var labels []*Label
for _, label := range from {
l := label
labels = append(labels, &Label{
Name: &l,
})
}
return labels
}
func convertUser(from *gitlab.BasicUser) *GitUser {
return &GitUser{
URL: from.WebURL,
Login: from.Username,
Name: from.Name,
AvatarURL: from.AvatarURL,
}
}