/
gitlab.go
518 lines (463 loc) · 13.2 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
package client
import (
"crypto/tls"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/caarlos0/log"
"github.com/goreleaser/goreleaser/internal/artifact"
"github.com/goreleaser/goreleaser/internal/tmpl"
"github.com/goreleaser/goreleaser/pkg/config"
"github.com/goreleaser/goreleaser/pkg/context"
"github.com/xanzy/go-gitlab"
)
const DefaultGitLabDownloadURL = "https://gitlab.com"
type gitlabClient struct {
client *gitlab.Client
}
// NewGitLab returns a gitlab client implementation.
func NewGitLab(ctx *context.Context, token string) (Client, error) {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{
// nolint: gosec
InsecureSkipVerify: ctx.Config.GitLabURLs.SkipTLSVerify,
},
}
options := []gitlab.ClientOptionFunc{
gitlab.WithHTTPClient(&http.Client{
Transport: transport,
}),
}
if ctx.Config.GitLabURLs.API != "" {
apiURL, err := tmpl.New(ctx).Apply(ctx.Config.GitLabURLs.API)
if err != nil {
return nil, fmt.Errorf("templating GitLab API URL: %w", err)
}
options = append(options, gitlab.WithBaseURL(apiURL))
}
var client *gitlab.Client
var err error
if checkUseJobToken(*ctx, token) {
client, err = gitlab.NewJobClient(token, options...)
} else {
client, err = gitlab.NewClient(token, options...)
}
if err != nil {
return &gitlabClient{}, err
}
return &gitlabClient{client: client}, nil
}
func (c *gitlabClient) Changelog(ctx *context.Context, repo Repo, prev, current string) (string, error) {
cmpOpts := &gitlab.CompareOptions{
From: &prev,
To: ¤t,
}
result, _, err := c.client.Repositories.Compare(repo.String(), cmpOpts)
var log []string
if err != nil {
return "", err
}
for _, commit := range result.Commits {
log = append(log, fmt.Sprintf(
"%s: %s (%s <%s>)",
commit.ShortID,
strings.Split(commit.Message, "\n")[0],
commit.AuthorName,
commit.AuthorEmail,
))
}
return strings.Join(log, "\n"), nil
}
// GetDefaultBranch get the default branch
func (c *gitlabClient) GetDefaultBranch(ctx *context.Context, repo Repo) (string, error) {
projectID := repo.String()
p, res, err := c.client.Projects.GetProject(projectID, nil)
if err != nil {
log.WithFields(log.Fields{
"projectID": projectID,
"statusCode": res.StatusCode,
"err": err.Error(),
}).Warn("error checking for default branch")
return "", err
}
return p.DefaultBranch, nil
}
// CloseMilestone closes a given milestone.
func (c *gitlabClient) CloseMilestone(ctx *context.Context, repo Repo, title string) error {
milestone, err := c.getMilestoneByTitle(repo, title)
if err != nil {
return err
}
if milestone == nil {
return ErrNoMilestoneFound{Title: title}
}
closeStateEvent := "close"
opts := &gitlab.UpdateMilestoneOptions{
Description: &milestone.Description,
DueDate: milestone.DueDate,
StartDate: milestone.StartDate,
StateEvent: &closeStateEvent,
Title: &milestone.Title,
}
_, _, err = c.client.Milestones.UpdateMilestone(
repo.String(),
milestone.ID,
opts,
)
return err
}
// CreateFile gets a file in the repository at a given path
// and updates if it exists or creates it for later pipes in the pipeline.
func (c *gitlabClient) CreateFile(
ctx *context.Context,
commitAuthor config.CommitAuthor,
repo Repo,
content []byte, // the content of the formula.rb
path, // the path to the formula.rb
message string, // the commit msg
) error {
fileName := path
projectID := repo.String()
// Use the project default branch if we can get it...otherwise, just use
// 'master'
var branch, ref string
var err error
// Use the branch if given one
if repo.Branch != "" {
branch = repo.Branch
} else {
// Try to get the default branch from the Git provider
branch, err = c.GetDefaultBranch(ctx, repo)
if err != nil {
// Fall back to 'master' 😭
log.WithFields(log.Fields{
"fileName": fileName,
"projectID": repo.String(),
"requestedBranch": branch,
"err": err.Error(),
}).Warn("error checking for default branch, using master")
ref = "master"
branch = "master"
}
}
ref = branch
opts := &gitlab.GetFileOptions{Ref: &ref}
castedContent := string(content)
log.WithFields(log.Fields{
"owner": repo.Owner,
"name": repo.Name,
"ref": ref,
"branch": branch,
}).Debug("projectID at brew")
_, res, err := c.client.RepositoryFiles.GetFile(repo.String(), fileName, opts)
if err != nil && (res == nil || res.StatusCode != 404) {
log.WithFields(log.Fields{
"fileName": fileName,
"ref": ref,
"projectID": projectID,
"statusCode": res.StatusCode,
"err": err.Error(),
}).Error("error getting file for brew formula")
return err
}
log.WithFields(log.Fields{
"fileName": fileName,
"branch": branch,
"projectID": projectID,
}).Debug("found already existing brew formula file")
if res.StatusCode == 404 {
log.WithFields(log.Fields{
"fileName": fileName,
"ref": ref,
"projectID": projectID,
}).Debug("creating brew formula")
createOpts := &gitlab.CreateFileOptions{
AuthorName: &commitAuthor.Name,
AuthorEmail: &commitAuthor.Email,
Content: &castedContent,
Branch: &branch,
CommitMessage: &message,
}
fileInfo, res, err := c.client.RepositoryFiles.CreateFile(projectID, fileName, createOpts)
if err != nil {
log.WithFields(log.Fields{
"fileName": fileName,
"branch": branch,
"projectID": projectID,
"statusCode": res.StatusCode,
"err": err.Error(),
}).Error("error creating brew formula file")
return err
}
log.WithFields(log.Fields{
"fileName": fileName,
"branch": branch,
"projectID": projectID,
"filePath": fileInfo.FilePath,
}).Debug("created brew formula file")
return nil
}
log.WithFields(log.Fields{
"fileName": fileName,
"ref": ref,
"projectID": projectID,
}).Debug("updating brew formula")
updateOpts := &gitlab.UpdateFileOptions{
AuthorName: &commitAuthor.Name,
AuthorEmail: &commitAuthor.Email,
Content: &castedContent,
Branch: &branch,
CommitMessage: &message,
}
updateFileInfo, res, err := c.client.RepositoryFiles.UpdateFile(projectID, fileName, updateOpts)
if err != nil {
log.WithFields(log.Fields{
"fileName": fileName,
"branch": branch,
"projectID": projectID,
"statusCode": res.StatusCode,
"err": err.Error(),
}).Error("error updating brew formula file")
return err
}
log.WithFields(log.Fields{
"fileName": fileName,
"branch": branch,
"projectID": projectID,
"filePath": updateFileInfo.FilePath,
"statusCode": res.StatusCode,
}).Debug("updated brew formula file")
return nil
}
// CreateRelease creates a new release or updates it by keeping
// the release notes if it exists.
func (c *gitlabClient) CreateRelease(ctx *context.Context, body string) (releaseID string, err error) {
title, err := tmpl.New(ctx).Apply(ctx.Config.Release.NameTemplate)
if err != nil {
return "", err
}
gitlabName, err := tmpl.New(ctx).Apply(ctx.Config.Release.GitLab.Name)
if err != nil {
return "", err
}
projectID := gitlabName
if ctx.Config.Release.GitLab.Owner != "" {
projectID = ctx.Config.Release.GitLab.Owner + "/" + projectID
}
log.WithFields(log.Fields{
"owner": ctx.Config.Release.GitLab.Owner,
"name": gitlabName,
"projectID": projectID,
}).Debug("projectID")
name := title
tagName := ctx.Git.CurrentTag
release, resp, err := c.client.Releases.GetRelease(projectID, tagName)
if err != nil && (resp == nil || (resp.StatusCode != 403 && resp.StatusCode != 404)) {
return "", err
}
if resp.StatusCode == 403 || resp.StatusCode == 404 {
log.WithFields(log.Fields{
"err": err.Error(),
}).Debug("get release")
description := body
ref := ctx.Git.Commit
gitURL := ctx.Git.URL
log.WithFields(log.Fields{
"name": name,
"description": description,
"ref": ref,
"url": gitURL,
}).Debug("creating release")
release, _, err = c.client.Releases.CreateRelease(projectID, &gitlab.CreateReleaseOptions{
Name: &name,
Description: &description,
Ref: &ref,
TagName: &tagName,
})
if err != nil {
log.WithFields(log.Fields{
"err": err.Error(),
}).Debug("error create release")
return "", err
}
log.WithField("name", release.Name).Info("release created")
} else {
desc := body
if release != nil {
desc = getReleaseNotes(release.Description, body, ctx.Config.Release.ReleaseNotesMode)
}
release, _, err = c.client.Releases.UpdateRelease(projectID, tagName, &gitlab.UpdateReleaseOptions{
Name: &name,
Description: &desc,
})
if err != nil {
log.WithFields(log.Fields{
"err": err.Error(),
}).Debug("error update release")
return "", err
}
log.WithField("name", release.Name).Info("release updated")
}
return tagName, err // gitlab references a tag in a repo by its name
}
func (c *gitlabClient) ReleaseURLTemplate(ctx *context.Context) (string, error) {
var urlTemplate string
gitlabName, err := tmpl.New(ctx).Apply(ctx.Config.Release.GitLab.Name)
if err != nil {
return "", err
}
downloadURL, err := tmpl.New(ctx).Apply(ctx.Config.GitLabURLs.Download)
if err != nil {
return "", err
}
if ctx.Config.Release.GitLab.Owner != "" {
urlTemplate = fmt.Sprintf(
"%s/%s/%s/-/releases/{{ .Tag }}/downloads/{{ .ArtifactName }}",
downloadURL,
ctx.Config.Release.GitLab.Owner,
gitlabName,
)
} else {
urlTemplate = fmt.Sprintf(
"%s/%s/-/releases/{{ .Tag }}/downloads/{{ .ArtifactName }}",
downloadURL,
gitlabName,
)
}
return urlTemplate, nil
}
// Upload uploads a file into a release repository.
func (c *gitlabClient) Upload(
ctx *context.Context,
releaseID string,
artifact *artifact.Artifact,
file *os.File,
) error {
// create new template and apply name field
gitlabName, err := tmpl.New(ctx).Apply(ctx.Config.Release.GitLab.Name)
if err != nil {
return err
}
projectID := gitlabName
// check if owner is empty
if ctx.Config.Release.GitLab.Owner != "" {
projectID = ctx.Config.Release.GitLab.Owner + "/" + projectID
}
var baseLinkURL string
var linkURL string
if ctx.Config.GitLabURLs.UsePackageRegistry {
log.WithField("file", file.Name()).Debug("uploading file as generic package")
if _, _, err := c.client.GenericPackages.PublishPackageFile(
projectID,
ctx.Config.ProjectName,
ctx.Version,
artifact.Name,
file,
nil,
); err != nil {
return err
}
baseLinkURL, err = c.client.GenericPackages.FormatPackageURL(
projectID,
ctx.Config.ProjectName,
ctx.Version,
artifact.Name,
)
if err != nil {
return err
}
linkURL = c.client.BaseURL().String() + baseLinkURL
} else {
log.WithField("file", file.Name()).Debug("uploading file as attachment")
projectFile, _, err := c.client.Projects.UploadFile(
projectID,
file,
filepath.Base(file.Name()),
nil,
)
if err != nil {
return err
}
baseLinkURL = projectFile.URL
gitlabBaseURL, err := tmpl.New(ctx).Apply(ctx.Config.GitLabURLs.Download)
if err != nil {
return fmt.Errorf("templating GitLab Download URL: %w", err)
}
// search for project details based on projectID
projectDetails, _, err := c.client.Projects.GetProject(projectID, nil)
if err != nil {
return err
}
linkURL = gitlabBaseURL + "/" + projectDetails.PathWithNamespace + baseLinkURL
}
log.WithFields(log.Fields{
"file": file.Name(),
"url": baseLinkURL,
}).Debug("uploaded file")
name := artifact.Name
filename := "/" + name
releaseLink, _, err := c.client.ReleaseLinks.CreateReleaseLink(
projectID,
releaseID,
&gitlab.CreateReleaseLinkOptions{
Name: &name,
URL: &linkURL,
FilePath: &filename,
})
if err != nil {
return RetriableError{err}
}
log.WithFields(log.Fields{
"id": releaseLink.ID,
"url": releaseLink.DirectAssetURL,
}).Debug("created release link")
// for checksums.txt the field is nil, so we initialize it
if artifact.Extra == nil {
artifact.Extra = make(map[string]interface{})
}
return nil
}
// getMilestoneByTitle returns a milestone by title.
func (c *gitlabClient) getMilestoneByTitle(repo Repo, title string) (*gitlab.Milestone, error) {
opts := &gitlab.ListMilestonesOptions{
Title: &title,
}
for {
milestones, resp, err := c.client.Milestones.ListMilestones(repo.String(), opts)
if err != nil {
return nil, err
}
for _, milestone := range milestones {
if milestone != nil && milestone.Title == title {
return milestone, nil
}
}
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
return nil, nil
}
// checkUseJobToken examines the context and given token, and determines if We should use NewJobClient vs NewClient
func checkUseJobToken(ctx context.Context, token string) bool {
// The CI_JOB_TOKEN env var is set automatically in all GitLab runners.
// If this comes back as empty, we aren't in a functional GitLab runner
ciToken := os.Getenv("CI_JOB_TOKEN")
if ciToken == "" {
return false
}
// We only want to use the JobToken client if we have specified
// UseJobToken. Older versions of GitLab don't work with this, so we
// want to be specific
if ctx.Config.GitLabURLs.UseJobToken {
// We may be creating a new client with a non-CI_JOB_TOKEN, for
// things like Homebrew publishing. We can't use the
// CI_JOB_TOKEN there
return token == ciToken
}
return false
}