-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitlab.go
395 lines (329 loc) · 8.69 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
package resource
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
gitlab "gitlab.com/gitlab-org/api/client-go"
"golang.org/x/oauth2"
)
var (
NotFound = errors.New("object not found")
)
//go:generate counterfeiter . GitLab
type GitLab interface {
ListTags() ([]*gitlab.Tag, error)
ListTagsUntil(tag_name string) ([]*gitlab.Tag, error)
ListReleases() ([]*gitlab.Release, error)
GetRelease(tag_name string) (*gitlab.Release, error)
GetTag(tag_name string) (*gitlab.Tag, error)
CreateTag(tag_name string, ref string) (*gitlab.Tag, error)
CreateRelease(name string, tag string, description *string) (*gitlab.Release, error)
UpdateRelease(name string, tag string, description *string) (*gitlab.Release, error)
UploadProjectFile(file string) (*gitlab.ProjectFile, error)
DownloadProjectFile(url, file string) error
GetReleaseLinks(tag string) ([]*gitlab.ReleaseLink, error)
CreateReleaseLink(tag string, name string, url string) (*gitlab.ReleaseLink, error)
DeleteReleaseLink(tag string, links *gitlab.ReleaseLink) error
}
const (
defaultBaseURL = "https://gitlab.com/"
)
type GitlabClient struct {
client *gitlab.Client
accessToken string
repository string
}
func NewGitLabClient(source Source) (*GitlabClient, error) {
var httpClient = &http.Client{}
var ctx = context.TODO()
if source.Insecure {
httpClient.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// nolint:ineffassign,staticcheck
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
}
httpClientOpt := gitlab.WithHTTPClient(httpClient)
baseURLOpt := gitlab.WithBaseURL(defaultBaseURL)
if source.GitLabAPIURL != "" {
var err error
baseUrl, err := url.Parse(source.GitLabAPIURL)
if err != nil {
return nil, err
}
baseURLOpt = gitlab.WithBaseURL(baseUrl.String())
}
client, err := gitlab.NewClient(source.AccessToken, httpClientOpt, baseURLOpt)
if err != nil {
return nil, err
}
return &GitlabClient{
client: client,
repository: source.Repository,
accessToken: source.AccessToken,
}, nil
}
func (g *GitlabClient) ListTags() ([]*gitlab.Tag, error) {
var allTags []*gitlab.Tag
opt := &gitlab.ListTagsOptions{
ListOptions: gitlab.ListOptions{
PerPage: 100,
Page: 1,
},
OrderBy: gitlab.Ptr("updated"),
Sort: gitlab.Ptr("desc"),
}
for {
tags, res, err := g.client.Tags.ListTags(g.repository, opt)
if err != nil {
return []*gitlab.Tag{}, err
}
allTags = append(allTags, tags...)
if opt.Page >= res.TotalPages {
break
}
opt.Page = res.NextPage
}
return allTags, nil
}
func (g *GitlabClient) ListReleases() ([]*gitlab.Release, error) {
var allReleases []*gitlab.Release
opt := &gitlab.ListReleasesOptions{
ListOptions: gitlab.ListOptions{
PerPage: 100,
Page: 1,
},
}
for {
releases, res, err := g.client.Releases.ListReleases(g.repository, opt)
if err != nil {
return []*gitlab.Release{}, err
}
allReleases = append(allReleases, releases...)
if opt.Page >= res.TotalPages {
break
}
opt.Page = res.NextPage
}
return allReleases, nil
}
func (g *GitlabClient) ListTagsUntil(tag_name string) ([]*gitlab.Tag, error) {
var allTags []*gitlab.Tag
pageSize := 100
opt := &gitlab.ListTagsOptions{
ListOptions: gitlab.ListOptions{
PerPage: pageSize,
Page: 1,
},
OrderBy: gitlab.Ptr("updated"),
Sort: gitlab.Ptr("desc"),
}
var foundTag *gitlab.Tag
for {
tags, res, err := g.client.Tags.ListTags(g.repository, opt)
if err != nil {
return []*gitlab.Tag{}, err
}
skipToNextPage := false
for i, tag := range tags {
// Some tags might have the same date - if they all have the same date, take
// all of them
if foundTag != nil {
if foundTag.Commit.CommittedDate.Equal(*tag.Commit.CommittedDate) {
allTags = append(allTags, tag)
if i == (pageSize - 1) {
skipToNextPage = true
break
} else {
continue
}
} else {
break
}
}
if tag.Name == tag_name {
allTags = append(allTags, tags[:i+1]...)
foundTag = tag
continue
}
}
if skipToNextPage {
if opt.Page >= res.TotalPages {
break
}
opt.Page = res.NextPage
continue
}
if foundTag != nil {
break
}
allTags = append(allTags, tags...)
if opt.Page >= res.TotalPages {
break
}
opt.Page = res.NextPage
}
return allTags, nil
}
func (g *GitlabClient) GetTag(tag_name string) (*gitlab.Tag, error) {
tag, resp, err := g.client.Tags.GetTag(g.repository, tag_name)
if err != nil {
if resp != nil && resp.StatusCode == http.StatusNotFound {
return nil, NotFound
}
return nil, err
}
defer resp.Body.Close()
return tag, nil
}
func (g *GitlabClient) GetRelease(tag_name string) (*gitlab.Release, error) {
release, resp, err := g.client.Releases.GetRelease(g.repository, tag_name)
if err != nil {
if resp == nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusForbidden:
return nil, NotFound
case http.StatusNotFound:
return nil, NotFound
default:
return nil, err
}
}
return release, nil
}
func (g *GitlabClient) CreateTag(tag_name string, ref string) (*gitlab.Tag, error) {
opt := &gitlab.CreateTagOptions{
TagName: gitlab.Ptr(tag_name),
Ref: gitlab.Ptr(ref),
Message: gitlab.Ptr(tag_name),
}
tag, _, err := g.client.Tags.CreateTag(g.repository, opt)
if err != nil {
return &gitlab.Tag{}, err
}
return tag, nil
}
func (g *GitlabClient) CreateRelease(name string, tag string, description *string) (*gitlab.Release, error) {
opt := &gitlab.CreateReleaseOptions{
Name: gitlab.Ptr(name),
TagName: gitlab.Ptr(tag),
Description: description,
}
release, res, err := g.client.Releases.CreateRelease(g.repository, opt)
if err != nil {
return &gitlab.Release{}, err
}
// https://docs.gitlab.com/ce/api/tags.html#create-a-new-release
// returns 409 if release already exists
if res.StatusCode == http.StatusConflict {
return nil, errors.New("release already exists")
}
return release, nil
}
func (g *GitlabClient) GetReleaseLinks(tag string) ([]*gitlab.ReleaseLink, error) {
links := []*gitlab.ReleaseLink{}
opt := &gitlab.ListReleaseLinksOptions{
PerPage: 100,
Page: 1,
}
for {
items, resp, err := g.client.ReleaseLinks.ListReleaseLinks(g.repository, tag, opt)
if err != nil {
return nil, err
}
links = append(links, items...)
if opt.Page >= resp.TotalPages {
break
}
opt.Page = resp.NextPage
}
return links, nil
}
func (g *GitlabClient) DeleteReleaseLink(tag string, link *gitlab.ReleaseLink) error {
_, _, err := g.client.ReleaseLinks.DeleteReleaseLink(g.repository, tag, link.ID)
if err != nil {
return err
}
return nil
}
func (g *GitlabClient) CreateReleaseLink(tag string, name string, url string) (*gitlab.ReleaseLink, error) {
opt := &gitlab.CreateReleaseLinkOptions{
Name: gitlab.Ptr(name),
URL: gitlab.Ptr(url),
}
link, _, err := g.client.ReleaseLinks.CreateReleaseLink(g.repository, tag, opt)
if err != nil {
return nil, err
}
return link, nil
}
func (g *GitlabClient) UpdateRelease(name string, tag string, description *string) (*gitlab.Release, error) {
opt := &gitlab.UpdateReleaseOptions{
Name: gitlab.Ptr(name),
Description: description,
}
release, _, err := g.client.Releases.UpdateRelease(g.repository, tag, opt)
if err != nil {
return &gitlab.Release{}, err
}
return release, nil
}
func (g *GitlabClient) UploadProjectFile(filepath string) (*gitlab.ProjectFile, error) {
reader, err := os.Open(filepath)
if err != nil {
return &gitlab.ProjectFile{}, err
}
filename := path.Base(filepath)
projectFile, _, err := g.client.Projects.UploadFile(g.repository, reader, filename)
if err != nil {
return &gitlab.ProjectFile{}, err
}
return projectFile, nil
}
func (g *GitlabClient) DownloadProjectFile(fileURL, destPath string) error {
out, err := os.Create(destPath)
if err != nil {
return err
}
defer out.Close()
// e.g. (baseURL) + (group/project) + (/uploads/hash/filename)
filePathRef, err := url.Parse(fileURL)
if err != nil {
return err
}
// https://gitlab.com/gitlab-org/gitlab-ce/issues/51447
nonApiUrl := strings.Replace(filePathRef.String(), "/api/v4", "", 1)
filePathRef, err = url.Parse(nonApiUrl)
if err != nil {
return err
}
client := &http.Client{}
req, err := http.NewRequest("GET", filePathRef.String(), nil)
if err != nil {
return err
}
req.Header.Add("Private-Token", g.accessToken)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download file `%s`: HTTP status %d", filepath.Base(destPath), resp.StatusCode)
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}