forked from tektoncd/pipelines-as-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitlab.go
More file actions
557 lines (493 loc) · 18.6 KB
/
gitlab.go
File metadata and controls
557 lines (493 loc) · 18.6 KB
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
package gitlab
import (
"context"
"crypto/subtle"
"fmt"
"net/http"
"net/url"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1"
"github.com/openshift-pipelines/pipelines-as-code/pkg/changedfiles"
"github.com/openshift-pipelines/pipelines-as-code/pkg/events"
"github.com/openshift-pipelines/pipelines-as-code/pkg/opscomments"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params/info"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params/triggertype"
"github.com/openshift-pipelines/pipelines-as-code/pkg/provider"
providerMetrics "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/metrics"
gitlab "gitlab.com/gitlab-org/api/client-go"
"go.uber.org/zap"
)
const (
apiPublicURL = "https://gitlab.com"
taskStatusTemplate = `
<table>
<tr><th>Status</th><th>Duration</th><th>Name</th></tr>
{{- range $taskrun := .TaskRunList }}
<tr>
<td>{{ formatCondition $taskrun.PipelineRunTaskRunStatus.Status.Conditions }}</td>
<td>{{ formatDuration $taskrun.PipelineRunTaskRunStatus.Status.StartTime $taskrun.PipelineRunTaskRunStatus.Status.CompletionTime }}</td><td>
{{ $taskrun.ConsoleLogURL }}
</td></tr>
{{- end }}
</table>`
noClientErrStr = `no gitlab client has been initialized, exiting... (hint: did you forget setting a secret on your repo?)`
)
var anyMergeRequestEventType = []string{"Merge Request", "MergeRequest"}
var _ provider.Interface = (*Provider)(nil)
type Provider struct {
gitlabClient *gitlab.Client
Logger *zap.SugaredLogger
run *params.Run
pacInfo *info.PacOpts
Token *string
targetProjectID int
sourceProjectID int
userID int
pathWithNamespace string
repoURL string
apiURL string
eventEmitter *events.EventEmitter
repo *v1alpha1.Repository
triggerEvent string
}
func (v *Provider) Client() *gitlab.Client {
providerMetrics.RecordAPIUsage(
v.Logger,
// URL used instead of "gitlab" to differentiate in the case of a CI cluster which
// serves multiple GitLab instances
v.apiURL,
v.triggerEvent,
v.repo,
)
return v.gitlabClient
}
func (v *Provider) SetGitLabClient(client *gitlab.Client) {
v.gitlabClient = client
}
func (v *Provider) SetPacInfo(pacInfo *info.PacOpts) {
v.pacInfo = pacInfo
}
func (v *Provider) CreateComment(_ context.Context, event *info.Event, commit, updateMarker string) error {
if v.gitlabClient == nil {
return fmt.Errorf("no gitlab client has been initialized")
}
if event.PullRequestNumber == 0 {
return fmt.Errorf("create comment only works on merge requests")
}
// List comments of the merge request
if updateMarker != "" {
comments, _, err := v.Client().Notes.ListMergeRequestNotes(event.TargetProjectID, event.PullRequestNumber, &gitlab.ListMergeRequestNotesOptions{
ListOptions: gitlab.ListOptions{
Page: 1,
PerPage: 100,
},
})
if err != nil {
return err
}
re := regexp.MustCompile(updateMarker)
for _, comment := range comments {
if re.MatchString(comment.Body) {
_, _, err := v.Client().Notes.UpdateMergeRequestNote(event.TargetProjectID, event.PullRequestNumber, comment.ID, &gitlab.UpdateMergeRequestNoteOptions{
Body: &commit,
})
return err
}
}
}
_, _, err := v.Client().Notes.CreateMergeRequestNote(event.TargetProjectID, event.PullRequestNumber, &gitlab.CreateMergeRequestNoteOptions{
Body: &commit,
})
return err
}
// CheckPolicyAllowing TODO: Implement ME.
func (v *Provider) CheckPolicyAllowing(_ context.Context, _ *info.Event, _ []string) (bool, string) {
return false, ""
}
func (v *Provider) SetLogger(logger *zap.SugaredLogger) {
v.Logger = logger
}
func (v *Provider) Validate(_ context.Context, _ *params.Run, event *info.Event) error {
token := event.Request.Header.Get("X-Gitlab-Token")
if event.Provider.WebhookSecret == "" && token != "" {
return fmt.Errorf("gitlab failed validation: failed to find webhook secret")
}
if subtle.ConstantTimeCompare([]byte(event.Provider.WebhookSecret), []byte(token)) == 0 {
return fmt.Errorf("gitlab failed validation: event's secret doesn't match with webhook secret")
}
return nil
}
// If I understood properly, you can have "personal" projects and groups
// attached projects. But this doesn't seem to show in the API, so we
// are just doing it the path_with_namespace to get the "org".
//
// Note that "orgs/groups" may have subgroups, so we get the first parts
// as Orgs and the last element as Repo It's just a detail to show for
// UI, we actually don't use this field for access or other logical
// stuff.
func getOrgRepo(pathWithNamespace string) (string, string) {
org := filepath.Dir(pathWithNamespace)
return org, filepath.Base(pathWithNamespace)
}
func (v *Provider) GetConfig() *info.ProviderConfig {
return &info.ProviderConfig{
TaskStatusTMPL: taskStatusTemplate,
APIURL: apiPublicURL,
Name: "gitlab",
}
}
func (v *Provider) SetClient(_ context.Context, run *params.Run, runevent *info.Event, repo *v1alpha1.Repository, eventsEmitter *events.EventEmitter) error {
var err error
if runevent.Provider.Token == "" {
return fmt.Errorf("no git_provider.secret has been set in the repo crd")
}
// Try to detect automatically the API url if url is not coming from public
// gitlab. Unless user has set a spec.provider.url in its repo crd
apiURL := ""
switch {
case runevent.Provider.URL != "":
apiURL = runevent.Provider.URL
case v.repoURL != "" && !strings.HasPrefix(v.repoURL, apiPublicURL):
apiURL = strings.ReplaceAll(v.repoURL, v.pathWithNamespace, "")
case runevent.URL != "":
burl, err := url.Parse(runevent.URL)
if err != nil {
return err
}
apiURL = fmt.Sprintf("%s://%s", burl.Scheme, burl.Host)
default:
// this really should not happen but let's just hope this is it
apiURL = apiPublicURL
}
_, err = url.Parse(apiURL)
if err != nil {
return fmt.Errorf("failed to parse api url %s: %w", apiURL, err)
}
v.apiURL = apiURL
v.gitlabClient, err = gitlab.NewClient(runevent.Provider.Token, gitlab.WithBaseURL(apiURL))
if err != nil {
return err
}
v.Token = &runevent.Provider.Token
run.Clients.Log.Infof("gitlab: initialized for client with token for apiURL=%s, org=%s, repo=%s", apiURL, runevent.Organization, runevent.Repository)
// In a scenario where the source repository is forked and a merge request (MR) is created on the upstream
// repository, runevent.SourceProjectID will not be 0 when SetClient is called from the pac-watcher code.
// This is because, in the controller, SourceProjectID is set in the annotation of the pull request,
// and runevent.SourceProjectID is set before SetClient is called. Therefore, we need to take
// the ID from runevent.SourceProjectID when v.sourceProject is 0 (nil).
if v.sourceProjectID == 0 && runevent.SourceProjectID > 0 {
v.sourceProjectID = runevent.SourceProjectID
}
// if we don't have sourceProjectID (ie: incoming-webhook) then try to set
// it ASAP if we can.
if v.sourceProjectID == 0 && runevent.Organization != "" && runevent.Repository != "" {
projectSlug := path.Join(runevent.Organization, runevent.Repository)
projectinfo, _, err := v.Client().Projects.GetProject(projectSlug, &gitlab.GetProjectOptions{})
if err != nil {
return err
}
// TODO: we really need to move out the runevent.*ProjecTID to v.*ProjectID,
// I just spent half an hour debugging because i didn't realise it was there instead in v.*
v.sourceProjectID = projectinfo.ID
runevent.SourceProjectID = projectinfo.ID
runevent.TargetProjectID = projectinfo.ID
runevent.DefaultBranch = projectinfo.DefaultBranch
}
v.run = run
v.eventEmitter = eventsEmitter
v.repo = repo
v.triggerEvent = runevent.EventType
return nil
}
func (v *Provider) CreateStatus(_ context.Context, event *info.Event, statusOpts provider.StatusOpts,
) error {
var detailsURL string
if v.gitlabClient == nil {
return fmt.Errorf("no gitlab client has been initialized, " +
"exiting... (hint: did you forget setting a secret on your repo?)")
}
switch statusOpts.Conclusion {
case "skipped":
statusOpts.Conclusion = "canceled"
statusOpts.Title = "skipped validating this commit"
case "neutral":
statusOpts.Conclusion = "canceled"
statusOpts.Title = "stopped"
case "failure":
statusOpts.Conclusion = "failed"
statusOpts.Title = "failed"
case "success":
statusOpts.Conclusion = "success"
statusOpts.Title = "successfully validated your commit"
case "completed":
statusOpts.Conclusion = "success"
statusOpts.Title = "completed"
case "pending":
statusOpts.Conclusion = "running"
}
if statusOpts.DetailsURL != "" {
detailsURL = statusOpts.DetailsURL
}
onPr := ""
if statusOpts.OriginalPipelineRunName != "" {
onPr = "/" + statusOpts.OriginalPipelineRunName
}
body := fmt.Sprintf("**%s%s** has %s\n\n%s\n\n<small>Full log available [here](%s)</small>",
v.pacInfo.ApplicationName, onPr, statusOpts.Title, statusOpts.Text, detailsURL)
contextName := provider.GetCheckName(statusOpts, v.pacInfo)
opt := &gitlab.SetCommitStatusOptions{
State: gitlab.BuildStateValue(statusOpts.Conclusion),
Name: gitlab.Ptr(contextName),
TargetURL: gitlab.Ptr(detailsURL),
Description: gitlab.Ptr(statusOpts.Title),
Context: gitlab.Ptr(contextName),
}
// setCommitStatus attempts to set the commit status for a given SHA, handling GitLab's permission model.
// First tries the source project (fork), then falls back to the target project (upstream repo).
// This fallback is necessary because:
// - In fork/MR scenarios, the GitLab token may not have write access to the contributor's fork
// - This ensures commit status can be displayed somewhere useful regardless
// of permission differences
// Returns nil if status is set on either project, logs error if both attempts fail.
_, _, err := v.Client().Commits.SetCommitStatus(event.SourceProjectID, event.SHA, opt)
if err == nil {
v.Logger.Debugf("created commit status on source project ID %d", event.SourceProjectID)
return nil
}
if _, _, err2 := v.Client().Commits.SetCommitStatus(event.TargetProjectID, event.SHA, opt); err2 == nil {
v.Logger.Debugf("created commit status on target project ID %d", event.TargetProjectID)
return nil
}
v.Logger.Debugf(
"Failed to create commit status: source project ID %d, target project ID %d. "+
"If you want Gitlab Pipeline Status update, ensure your GitLab token has access "+
"to the source repository. Error: %v",
event.SourceProjectID, event.TargetProjectID, err)
eventType := triggertype.IsPullRequestType(event.EventType)
// When a GitOps command is sent on a pushed commit, it mistakenly treats it as a pull_request
// and attempts to create a note, but notes are not intended for pushed commits.
if event.TriggerTarget == triggertype.PullRequest && opscomments.IsAnyOpsEventType(event.EventType) {
eventType = triggertype.PullRequest
}
var commentStrategy string
if v.repo != nil && v.repo.Spec.Settings != nil && v.repo.Spec.Settings.Gitlab != nil {
commentStrategy = v.repo.Spec.Settings.Gitlab.CommentStrategy
}
switch commentStrategy {
case "disable_all":
v.Logger.Warn("Comments related to PipelineRuns status have been disabled for GitLab merge requests")
return nil
default:
if eventType == triggertype.PullRequest || provider.Valid(event.EventType, anyMergeRequestEventType) {
mopt := &gitlab.CreateMergeRequestNoteOptions{Body: gitlab.Ptr(body)}
_, _, err := v.Client().Notes.CreateMergeRequestNote(event.TargetProjectID, event.PullRequestNumber, mopt)
return err
}
}
return nil
}
func (v *Provider) GetTektonDir(_ context.Context, event *info.Event, path, provenance string) (string, error) {
if v.gitlabClient == nil {
return "", fmt.Errorf("no gitlab client has been initialized, " +
"exiting... (hint: did you forget setting a secret on your repo?)")
}
// default set provenance from head
revision := event.HeadBranch
if provenance == "default_branch" {
revision = event.DefaultBranch
v.Logger.Infof("Using PipelineRun definition from default_branch: %s", event.DefaultBranch)
} else {
trigger := event.TriggerTarget.String()
if event.TriggerTarget == triggertype.PullRequest {
trigger = "merge request"
}
v.Logger.Infof("Using PipelineRun definition from source %s on commit SHA: %s", trigger, event.SHA)
}
opt := &gitlab.ListTreeOptions{
Path: gitlab.Ptr(path),
Ref: gitlab.Ptr(revision),
Recursive: gitlab.Ptr(true),
ListOptions: gitlab.ListOptions{
OrderBy: "id",
Pagination: "keyset",
PerPage: 20,
Sort: "asc",
},
}
options := []gitlab.RequestOptionFunc{}
nodes := []*gitlab.TreeNode{}
for {
objects, resp, err := v.Client().Repositories.ListTree(v.sourceProjectID, opt, options...)
if err != nil {
return "", fmt.Errorf("failed to list %s dir: %w", path, err)
}
if resp != nil && resp.StatusCode == http.StatusNotFound {
return "", nil
}
nodes = append(nodes, objects...)
// Exit the loop when we've seen all pages.
if resp.NextLink == "" {
break
}
// Otherwise, set param to query the next page
options = []gitlab.RequestOptionFunc{
gitlab.WithKeysetPaginationParameters(resp.NextLink),
}
}
return v.concatAllYamlFiles(nodes, revision)
}
// concatAllYamlFiles concat all yaml files from a directory as one big multi document yaml string.
func (v *Provider) concatAllYamlFiles(objects []*gitlab.TreeNode, revision string) (string, error) {
var allTemplates string
for _, value := range objects {
if strings.HasSuffix(value.Name, ".yaml") ||
strings.HasSuffix(value.Name, ".yml") {
data, _, err := v.getObject(value.Path, revision, v.sourceProjectID)
if err != nil {
return "", err
}
if err := provider.ValidateYaml(data, value.Path); err != nil {
return "", err
}
if allTemplates != "" && !strings.HasPrefix(string(data), "---") {
allTemplates += "---"
}
allTemplates += "\n" + string(data) + "\n"
}
}
return allTemplates, nil
}
func (v *Provider) getObject(fname, branch string, pid int) ([]byte, *gitlab.Response, error) {
opt := &gitlab.GetRawFileOptions{
Ref: gitlab.Ptr(branch),
}
file, resp, err := v.Client().RepositoryFiles.GetRawFile(pid, fname, opt)
if err != nil {
return []byte{}, resp, fmt.Errorf("failed to get filename from api %s dir: %w", fname, err)
}
if resp != nil && resp.StatusCode == http.StatusNotFound {
return []byte{}, resp, nil
}
return file, resp, nil
}
func (v *Provider) GetFileInsideRepo(_ context.Context, runevent *info.Event, path, _ string) (string, error) {
getobj, _, err := v.getObject(path, runevent.HeadBranch, v.sourceProjectID)
if err != nil {
return "", err
}
return string(getobj), nil
}
func (v *Provider) GetCommitInfo(_ context.Context, runevent *info.Event) error {
if v.gitlabClient == nil {
return fmt.Errorf("%s", noClientErrStr)
}
// if we don't have a SHA (ie: incoming-webhook) then get it from the branch
// and populate in the runevent.
if runevent.SHA == "" && runevent.HeadBranch != "" {
branchinfo, _, err := v.Client().Commits.GetCommit(v.sourceProjectID, runevent.HeadBranch, &gitlab.GetCommitOptions{})
if err != nil {
return err
}
runevent.SHA = branchinfo.ID
runevent.SHATitle = branchinfo.Title
runevent.SHAURL = branchinfo.WebURL
}
return nil
}
func (v *Provider) GetFiles(_ context.Context, runevent *info.Event) (changedfiles.ChangedFiles, error) {
if v.gitlabClient == nil {
return changedfiles.ChangedFiles{}, fmt.Errorf("no gitlab client has been initialized, " +
"exiting... (hint: did you forget setting a secret on your repo?)")
}
if runevent.TriggerTarget == triggertype.PullRequest {
opt := &gitlab.ListMergeRequestDiffsOptions{
ListOptions: gitlab.ListOptions{
OrderBy: "id",
Pagination: "keyset",
PerPage: 20,
Sort: "asc",
},
}
options := []gitlab.RequestOptionFunc{}
changedFiles := changedfiles.ChangedFiles{}
for {
mrchanges, resp, err := v.Client().MergeRequests.ListMergeRequestDiffs(v.targetProjectID, runevent.PullRequestNumber, opt, options...)
if err != nil {
return changedfiles.ChangedFiles{}, err
}
for _, change := range mrchanges {
changedFiles.All = append(changedFiles.All, change.NewPath)
if change.NewFile {
changedFiles.Added = append(changedFiles.Added, change.NewPath)
}
if change.DeletedFile {
changedFiles.Deleted = append(changedFiles.Deleted, change.NewPath)
}
if !change.RenamedFile && !change.DeletedFile && !change.NewFile {
changedFiles.Modified = append(changedFiles.Modified, change.NewPath)
}
if change.RenamedFile {
changedFiles.Renamed = append(changedFiles.Renamed, change.NewPath)
}
}
// Exit the loop when we've seen all pages.
if resp.NextLink == "" {
break
}
// Otherwise, set param to query the next page
options = []gitlab.RequestOptionFunc{
gitlab.WithKeysetPaginationParameters(resp.NextLink),
}
}
return changedFiles, nil
}
if runevent.TriggerTarget == "push" {
pushChanges, _, err := v.Client().Commits.GetCommitDiff(v.sourceProjectID, runevent.SHA, &gitlab.GetCommitDiffOptions{})
if err != nil {
return changedfiles.ChangedFiles{}, err
}
changedFiles := changedfiles.ChangedFiles{}
for _, change := range pushChanges {
changedFiles.All = append(changedFiles.All, change.NewPath)
if change.NewFile {
changedFiles.Added = append(changedFiles.Added, change.NewPath)
}
if change.DeletedFile {
changedFiles.Deleted = append(changedFiles.Deleted, change.NewPath)
}
if !change.RenamedFile && !change.DeletedFile && !change.NewFile {
changedFiles.Modified = append(changedFiles.Modified, change.NewPath)
}
if change.RenamedFile {
changedFiles.Renamed = append(changedFiles.Renamed, change.NewPath)
}
}
return changedFiles, nil
}
return changedfiles.ChangedFiles{}, nil
}
func (v *Provider) CreateToken(_ context.Context, _ []string, _ *info.Event) (string, error) {
return "", nil
}
// isHeadCommitOfBranch validates that branch exists and the SHA is HEAD commit of the branch.
func (v *Provider) isHeadCommitOfBranch(runevent *info.Event, branchName string) error {
if v.gitlabClient == nil {
return fmt.Errorf("no gitlab client has been initialized, " +
"exiting... (hint: did you forget setting a secret on your repo?)")
}
branch, _, err := v.Client().Branches.GetBranch(v.sourceProjectID, branchName)
if err != nil {
return err
}
if branch.Commit.ID == runevent.SHA {
return nil
}
return fmt.Errorf("provided SHA %s is not the HEAD commit of the branch %s", runevent.SHA, branchName)
}
func (v *Provider) GetTemplate(commentType provider.CommentType) string {
return provider.GetHTMLTemplate(commentType)
}