-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
gitlab.go
96 lines (79 loc) · 2.38 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
package pull_request
import (
"context"
"fmt"
"net/http"
"os"
"github.com/argoproj/argo-cd/v2/applicationset/utils"
"github.com/hashicorp/go-retryablehttp"
gitlab "github.com/xanzy/go-gitlab"
)
type GitLabService struct {
client *gitlab.Client
project string
labels []string
pullRequestState string
}
var _ PullRequestService = (*GitLabService)(nil)
func NewGitLabService(ctx context.Context, token, url, project string, labels []string, pullRequestState string, scmRootCAPath string, insecure bool) (PullRequestService, error) {
var clientOptionFns []gitlab.ClientOptionFunc
// Set a custom Gitlab base URL if one is provided
if url != "" {
clientOptionFns = append(clientOptionFns, gitlab.WithBaseURL(url))
}
if token == "" {
token = os.Getenv("GITLAB_TOKEN")
}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = utils.GetTlsConfig(scmRootCAPath, insecure)
retryClient := retryablehttp.NewClient()
retryClient.HTTPClient.Transport = tr
clientOptionFns = append(clientOptionFns, gitlab.WithHTTPClient(retryClient.HTTPClient))
client, err := gitlab.NewClient(token, clientOptionFns...)
if err != nil {
return nil, fmt.Errorf("error creating Gitlab client: %v", err)
}
return &GitLabService{
client: client,
project: project,
labels: labels,
pullRequestState: pullRequestState,
}, nil
}
func (g *GitLabService) List(ctx context.Context) ([]*PullRequest, error) {
// Filter the merge requests on labels, if they are specified.
var labels *gitlab.Labels
if len(g.labels) > 0 {
labels = (*gitlab.Labels)(&g.labels)
}
opts := &gitlab.ListProjectMergeRequestsOptions{
ListOptions: gitlab.ListOptions{
PerPage: 100,
},
Labels: labels,
}
if g.pullRequestState != "" {
opts.State = &g.pullRequestState
}
pullRequests := []*PullRequest{}
for {
mrs, resp, err := g.client.MergeRequests.ListProjectMergeRequests(g.project, opts)
if err != nil {
return nil, fmt.Errorf("error listing merge requests for project '%s': %v", g.project, err)
}
for _, mr := range mrs {
pullRequests = append(pullRequests, &PullRequest{
Number: mr.IID,
Branch: mr.SourceBranch,
TargetBranch: mr.TargetBranch,
HeadSHA: mr.SHA,
Labels: mr.Labels,
})
}
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
return pullRequests, nil
}