/
gitlabv4.go
251 lines (211 loc) · 6.83 KB
/
gitlabv4.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
/*
Copyright 2017 caicloud authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gitlab
import (
"fmt"
"strings"
log "github.com/golang/glog"
"gopkg.in/xanzy/go-gitlab.v0"
"github.com/caicloud/cyclone/pkg/api"
"github.com/caicloud/cyclone/pkg/scm"
"github.com/caicloud/cyclone/pkg/scm/provider"
)
// GitlabV4 represents the SCM provider of Gitlab with API V4.
type GitlabV4 struct {
scmCfg *api.SCMConfig
client *gitlab.Client
}
func NewGitlabV4(scmCfg *api.SCMConfig) (scm.SCMProvider, error) {
client, err := newGitlabV4Client(scmCfg.Server, scmCfg.Username, scmCfg.Token)
if err != nil {
log.Error("fail to new gitlab client as %v", err)
return nil, err
}
return &GitlabV4{scmCfg, client}, nil
}
// GetToken gets the token by the username and password of SCM config.
func (g *GitlabV4) GetToken() (string, error) {
return getOauthToken(g.scmCfg)
}
// CheckToken checks whether the token has the authority of repo by trying ListRepos with the token.
func (g *GitlabV4) CheckToken() bool {
if _, err := g.listReposInner(false); err != nil {
return false
}
return true
}
// ListRepos lists the repos by the SCM config.
func (g *GitlabV4) ListRepos() ([]api.Repository, error) {
return g.listReposInner(true)
}
// listReposInner lists the projects by the SCM config,
// list all projects while the parameter 'listAll' is true,
// otherwise, list projects by default 'provider.ListPerPageOpt' number.
func (g *GitlabV4) listReposInner(listAll bool) ([]api.Repository, error) {
trueVar := true
opt := &gitlab.ListProjectsOptions{
ListOptions: gitlab.ListOptions{
PerPage: provider.ListPerPageOpt,
},
Membership: &trueVar,
}
// Get all pages of results.
var allProjects []*gitlab.Project
for {
projects, resp, err := g.client.Projects.ListProjects(opt)
if err != nil {
return nil, err
}
allProjects = append(allProjects, projects...)
if resp.NextPage == 0 || !listAll {
break
}
opt.ListOptions.Page = resp.NextPage
}
repos := make([]api.Repository, len(allProjects))
for i, repo := range allProjects {
repos[i].Name = repo.PathWithNamespace
repos[i].URL = repo.HTTPURLToRepo
}
return repos, nil
}
// ListBranches lists the branches for specified repo.
func (g *GitlabV4) ListBranches(repo string) ([]string, error) {
opts := &gitlab.ListBranchesOptions{}
branches, _, err := g.client.Branches.ListBranches(repo, opts)
if err != nil {
log.Errorf("Fail to list branches for %s", repo)
return nil, err
}
branchNames := make([]string, len(branches))
for i, branch := range branches {
branchNames[i] = branch.Name
}
return branchNames, nil
}
// ListTags lists the tags for specified repo.
func (g *GitlabV4) ListTags(repo string) ([]string, error) {
opts := &gitlab.ListTagsOptions{}
tags, _, err := g.client.Tags.ListTags(repo, opts)
if err != nil {
log.Errorf("Fail to list tags for %s", repo)
return nil, err
}
tagNames := make([]string, len(tags))
for i, tag := range tags {
tagNames[i] = tag.Name
}
return tagNames, nil
}
// CreateWebHook creates webhook for specified repo.
func (g *GitlabV4) CreateWebHook(repoURL string, webHook *scm.WebHook) error {
if webHook == nil || len(webHook.Url) == 0 || len(webHook.Events) == 0 {
return fmt.Errorf("The webhook %v is not correct", webHook)
}
enableState, disableState := true, false
// Push event is enable for Gitlab webhook in default, so need to remove this default option.
hook := gitlab.AddProjectHookOptions{
PushEvents: &disableState,
}
for _, e := range webHook.Events {
switch e {
case scm.PullRequestEventType:
hook.MergeRequestsEvents = &enableState
case scm.PullRequestCommentEventType:
hook.NoteEvents = &enableState
case scm.PushEventType:
hook.PushEvents = &enableState
case scm.TagReleaseEventType:
hook.TagPushEvents = &enableState
default:
log.Errorf("The event type %s is not supported, will be ignored", e)
return nil
}
}
hook.URL = &webHook.Url
onwer, name := provider.ParseRepoURL(repoURL)
_, _, err := g.client.Projects.AddProjectHook(onwer+"/"+name, &hook)
log.Error(err)
return err
}
// DeleteWebHook deletes webhook from specified repo.
func (g *GitlabV4) DeleteWebHook(repoURL string, webHookUrl string) error {
owner, name := provider.ParseRepoURL(repoURL)
hooks, _, err := g.client.Projects.ListProjectHooks(owner+"/"+name, nil)
if err != nil {
return err
}
for _, hook := range hooks {
if strings.HasPrefix(hook.URL, webHookUrl) {
_, err = g.client.Projects.DeleteProjectHook(owner+"/"+name, hook.ID)
return nil
}
}
return nil
}
// NewTagFromLatest generate a new tag
func (g *GitlabV4) NewTagFromLatest(tagName, description, commitID, url string) error {
owner, name := provider.ParseRepoURL(url)
tag := &gitlab.CreateTagOptions{
TagName: &tagName,
Ref: &commitID,
Message: &description,
}
_, _, err := g.client.Tags.CreateTag(owner+"/"+name, tag)
log.Error(err)
return err
}
// GetTemplateType get template type of repo
func (g *GitlabV4) GetTemplateType(repo string) (string, error) {
languages, err := getLanguages(g.scmCfg, v4APIVersion, repo)
if err != nil {
log.Error("list language failed:%v", err)
return "", err
}
language := getTopLanguage(languages)
switch language {
case api.JavaRepoType, api.JavaScriptRepoType:
files, err := getContents(g.scmCfg, v4APIVersion, repo)
if err != nil {
log.Error("get contents failed:%v", err)
return language, nil
}
for _, f := range files {
if language == api.JavaRepoType && strings.Contains(f.Name, "pom.xml") {
return api.MavenRepoType, nil
}
if language == api.JavaRepoType && strings.Contains(f.Name, "build.gradle") {
return api.GradleRepoType, nil
}
if language == api.JavaScriptRepoType && strings.Contains(f.Name, "package.json") {
return api.NodeRepoType, nil
}
}
}
return language, nil
}
// CreateStatus generate a new status for repository.
func (g *GitlabV4) CreateStatus(recordStatus api.Status, targetURL, repoURL, commitSha string) error {
state, description := transStatus(recordStatus)
owner, project := provider.ParseRepoURL(repoURL)
context := "continuous-integration/cyclone"
status := &gitlab.SetCommitStatusOptions{
State: gitlab.BuildStateValue(state),
Description: &description,
TargetURL: &targetURL,
Context: &context,
}
_, _, err := g.client.Commits.SetCommitStatus(owner+"/"+project, commitSha, status)
log.Error(err)
return nil
}