-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathrepo.go
662 lines (544 loc) · 20 KB
/
repo.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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
// SPDX-License-Identifier: Apache-2.0
package github
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/sirupsen/logrus"
api "github.com/go-vela/server/api/types"
"github.com/go-vela/types/constants"
"github.com/go-vela/types/library"
"github.com/google/go-github/v61/github"
)
// ConfigBackoff is a wrapper for Config that will retry five times if the function
// fails to retrieve the yaml/yml file.
func (c *client) ConfigBackoff(ctx context.Context, u *library.User, r *api.Repo, ref string) (data []byte, err error) {
// number of times to retry
retryLimit := 5
for i := 0; i < retryLimit; i++ {
logrus.Debugf("Fetching config file - Attempt %d", i+1)
// attempt to fetch the config
data, err = c.Config(ctx, u, r, ref)
// return err if the last attempt returns error
if err != nil && i == retryLimit-1 {
return
}
// if data is valid break the retry loop
if data != nil {
break
}
// sleep in between retries
sleep := time.Duration(i+1) * time.Second
time.Sleep(sleep)
}
return
}
// Config gets the pipeline configuration from the GitHub repo.
func (c *client) Config(ctx context.Context, u *library.User, r *api.Repo, ref string) ([]byte, error) {
c.Logger.WithFields(logrus.Fields{
"org": r.GetOrg(),
"repo": r.GetName(),
"user": u.GetName(),
}).Tracef("capturing configuration file for %s/commit/%s", r.GetFullName(), ref)
// create GitHub OAuth client with user's token
client := c.newClientToken(*u.Token)
// default pipeline file names
files := []string{".vela.yml", ".vela.yaml"}
// starlark support - prefer .star/.py, use default as fallback
if strings.EqualFold(r.GetPipelineType(), constants.PipelineTypeStarlark) {
files = append([]string{".vela.star", ".vela.py"}, files...)
}
// set the reference for the options to capture the pipeline configuration
opts := &github.RepositoryContentGetOptions{
Ref: ref,
}
for _, file := range files {
// send API call to capture the .vela.yml pipeline configuration
data, _, resp, err := client.Repositories.GetContents(ctx, r.GetOrg(), r.GetName(), file, opts)
if err != nil {
if resp.StatusCode != http.StatusNotFound {
return nil, err
}
}
// data is not nil if .vela.yml exists
if data != nil {
strData, err := data.GetContent()
if err != nil {
return nil, err
}
return []byte(strData), nil
}
}
return nil, fmt.Errorf("no valid pipeline configuration file (%s) found", strings.Join(files, ","))
}
// Disable deactivates a repo by deleting the webhook.
func (c *client) Disable(ctx context.Context, u *library.User, org, name string) error {
c.Logger.WithFields(logrus.Fields{
"org": org,
"repo": name,
"user": u.GetName(),
}).Tracef("deleting repository webhooks for %s/%s", org, name)
// create GitHub OAuth client with user's token
client := c.newClientToken(*u.Token)
// send API call to capture the hooks for the repo
hooks, _, err := client.Repositories.ListHooks(ctx, org, name, nil)
if err != nil {
return err
}
// accounting for situations in which multiple hooks have been
// associated with this vela instance, which causes some
// disable, repair, enable operations to act in undesirable ways
var ids []int64
// iterate through each element in the hooks
for _, hook := range hooks {
// skip if the hook has no ID
if hook.GetID() == 0 {
continue
}
// capture hook ID if the hook url matches
if strings.EqualFold(hook.GetConfig().GetURL(), fmt.Sprintf("%s/webhook", c.config.ServerWebhookAddress)) {
ids = append(ids, hook.GetID())
}
}
// skip if we have no hook IDs
if len(ids) == 0 {
c.Logger.WithFields(logrus.Fields{
"org": org,
"repo": name,
"user": u.GetName(),
}).Warnf("no repository webhooks matching %s/webhook found for %s/%s", c.config.ServerWebhookAddress, org, name)
return nil
}
// go through all found hook IDs and delete them
for _, id := range ids {
// send API call to delete the webhook
_, err = client.Repositories.DeleteHook(ctx, org, name, id)
}
return err
}
// Enable activates a repo by creating the webhook.
func (c *client) Enable(ctx context.Context, u *library.User, r *api.Repo, h *library.Hook) (*library.Hook, string, error) {
c.Logger.WithFields(logrus.Fields{
"org": r.GetOrg(),
"repo": r.GetName(),
"user": u.GetName(),
}).Tracef("creating repository webhook for %s/%s", r.GetOrg(), r.GetName())
// create GitHub OAuth client with user's token
client := c.newClientToken(*u.Token)
// always listen to repository events in case of repo name change
events := []string{eventRepository}
// subscribe to comment event if any comment action is allowed
if r.GetAllowEvents().GetComment().GetCreated() ||
r.GetAllowEvents().GetComment().GetEdited() {
events = append(events, eventIssueComment)
}
// subscribe to deployment event if allowed
if r.GetAllowEvents().GetDeployment().GetCreated() {
events = append(events, eventDeployment)
}
// subscribe to pull_request event if any PR action is allowed
if r.GetAllowEvents().GetPullRequest().GetOpened() ||
r.GetAllowEvents().GetPullRequest().GetEdited() ||
r.GetAllowEvents().GetPullRequest().GetSynchronize() {
events = append(events, eventPullRequest)
}
// subscribe to push event if branch push or tag is allowed
if r.GetAllowEvents().GetPush().GetBranch() ||
r.GetAllowEvents().GetPush().GetTag() {
events = append(events, eventPush)
}
// create the hook object to make the API call
hook := &github.Hook{
Events: events,
Config: &github.HookConfig{
URL: github.String(fmt.Sprintf("%s/webhook", c.config.ServerWebhookAddress)),
ContentType: github.String("form"),
Secret: github.String(r.GetHash()),
},
Active: github.Bool(true),
}
// send API call to create the webhook
hookInfo, resp, err := client.Repositories.CreateHook(ctx, r.GetOrg(), r.GetName(), hook)
// create the first hook for the repo and record its ID from GitHub
webhook := new(library.Hook)
webhook.SetWebhookID(hookInfo.GetID())
webhook.SetSourceID(r.GetName() + "-" + eventInitialize)
webhook.SetCreated(hookInfo.GetCreatedAt().Unix())
webhook.SetEvent(eventInitialize)
webhook.SetNumber(h.GetNumber() + 1)
webhook.SetStatus(constants.StatusSuccess)
switch resp.StatusCode {
case http.StatusUnprocessableEntity:
return nil, "", fmt.Errorf("repo already enabled")
case http.StatusNotFound:
return nil, "", fmt.Errorf("repo not found")
}
// create the URL for the repo
url := fmt.Sprintf("%s/%s/%s", c.config.Address, r.GetOrg(), r.GetName())
return webhook, url, err
}
// Update edits a repo webhook.
func (c *client) Update(ctx context.Context, u *library.User, r *api.Repo, hookID int64) (bool, error) {
c.Logger.WithFields(logrus.Fields{
"org": r.GetOrg(),
"repo": r.GetName(),
"user": u.GetName(),
}).Tracef("updating repository webhook for %s/%s", r.GetOrg(), r.GetName())
// create GitHub OAuth client with user's token
client := c.newClientToken(*u.Token)
// always listen to repository events in case of repo name change
events := []string{eventRepository}
// subscribe to comment event if any comment action is allowed
if r.GetAllowEvents().GetComment().GetCreated() ||
r.GetAllowEvents().GetComment().GetEdited() {
events = append(events, eventIssueComment)
}
// subscribe to deployment event if allowed
if r.GetAllowEvents().GetDeployment().GetCreated() {
events = append(events, eventDeployment)
}
// subscribe to pull_request event if any PR action is allowed
if r.GetAllowEvents().GetPullRequest().GetOpened() ||
r.GetAllowEvents().GetPullRequest().GetEdited() ||
r.GetAllowEvents().GetPullRequest().GetSynchronize() {
events = append(events, eventPullRequest)
}
// subscribe to push event if branch push or tag is allowed
if r.GetAllowEvents().GetPush().GetBranch() ||
r.GetAllowEvents().GetPush().GetTag() {
events = append(events, eventPush)
}
// create the hook object to make the API call
hook := &github.Hook{
Events: events,
Config: &github.HookConfig{
URL: github.String(fmt.Sprintf("%s/webhook", c.config.ServerWebhookAddress)),
ContentType: github.String("form"),
Secret: github.String(r.GetHash()),
},
Active: github.Bool(true),
}
// send API call to update the webhook
_, resp, err := client.Repositories.EditHook(ctx, r.GetOrg(), r.GetName(), hookID, hook)
// track if webhook exists in GitHub; a missing webhook
// indicates the webhook has been manually deleted from GitHub
return resp.StatusCode != http.StatusNotFound, err
}
// Status sends the commit status for the given SHA from the GitHub repo.
func (c *client) Status(ctx context.Context, u *library.User, b *library.Build, org, name string) error {
c.Logger.WithFields(logrus.Fields{
"build": b.GetNumber(),
"org": org,
"repo": name,
"user": u.GetName(),
}).Tracef("setting commit status for %s/%s/%d @ %s", org, name, b.GetNumber(), b.GetCommit())
// only report opened, synchronize, and reopened action types for pull_request events
if strings.EqualFold(b.GetEvent(), constants.EventPull) && !strings.EqualFold(b.GetEventAction(), constants.ActionOpened) &&
!strings.EqualFold(b.GetEventAction(), constants.ActionSynchronize) && !strings.EqualFold(b.GetEventAction(), constants.ActionReopened) {
return nil
}
// create GitHub OAuth client with user's token
client := c.newClientToken(*u.Token)
context := fmt.Sprintf("%s/%s", c.config.StatusContext, b.GetEvent())
url := fmt.Sprintf("%s/%s/%s/%d", c.config.WebUIAddress, org, name, b.GetNumber())
var (
state string
description string
)
// set the state and description for the status context
// depending on what the status of the build is
switch b.GetStatus() {
case constants.StatusRunning, constants.StatusPending:
//nolint:goconst // ignore making constant
state = "pending"
description = fmt.Sprintf("the build is %s", b.GetStatus())
case constants.StatusPendingApproval:
state = "pending"
description = "build needs approval from repo admin to run"
case constants.StatusSuccess:
//nolint:goconst // ignore making constant
state = "success"
description = "the build was successful"
case constants.StatusFailure:
//nolint:goconst // ignore making constant
state = "failure"
description = "the build has failed"
case constants.StatusCanceled:
state = "failure"
description = "the build was canceled"
case constants.StatusKilled:
state = "failure"
description = "the build was killed"
case constants.StatusSkipped:
state = "success"
description = "build was skipped as no steps/stages found"
default:
state = "error"
description = "there was an error"
}
// check if the build event is deployment
if strings.EqualFold(b.GetEvent(), constants.EventDeploy) {
// parse out deployment number from build source URL
//
// pattern: <org>/<repo>/deployments/<deployment_id>
var parts []string
if strings.Contains(b.GetSource(), "/deployments/") {
parts = strings.Split(b.GetSource(), "/deployments/")
}
// capture number by converting from string
number, err := strconv.Atoi(parts[1])
if err != nil {
// capture number by scanning from string
_, err := fmt.Sscanf(b.GetSource(), "%s/%d", nil, &number)
if err != nil {
return err
}
}
// create the status object to make the API call
status := &github.DeploymentStatusRequest{
Description: github.String(description),
Environment: github.String(b.GetDeploy()),
State: github.String(state),
}
// provide "Details" link in GitHub UI if server was configured with it
if len(c.config.WebUIAddress) > 0 {
status.LogURL = github.String(url)
}
_, _, err = client.Repositories.CreateDeploymentStatus(ctx, org, name, int64(number), status)
return err
}
// create the status object to make the API call
status := &github.RepoStatus{
Context: github.String(context),
Description: github.String(description),
State: github.String(state),
}
// provide "Details" link in GitHub UI if server was configured with it
if len(c.config.WebUIAddress) > 0 && b.GetStatus() != constants.StatusSkipped {
status.TargetURL = github.String(url)
}
// send API call to create the status context for the commit
_, _, err := client.Repositories.CreateStatus(ctx, org, name, b.GetCommit(), status)
return err
}
// StepStatus sends the commit status for the given SHA to the GitHub repo with the step as the context.
func (c *client) StepStatus(ctx context.Context, u *library.User, b *library.Build, s *library.Step, org, name string) error {
c.Logger.WithFields(logrus.Fields{
"build": b.GetNumber(),
"org": org,
"repo": name,
"user": u.GetName(),
}).Tracef("setting commit status for %s/%s/%d @ %s", org, name, b.GetNumber(), b.GetCommit())
// no commit statuses on deployments
if strings.EqualFold(b.GetEvent(), constants.EventDeploy) {
return nil
}
// create GitHub OAuth client with user's token
client := c.newClientToken(*u.Token)
context := fmt.Sprintf("%s/%s/%s", c.config.StatusContext, b.GetEvent(), s.GetReportAs())
url := fmt.Sprintf("%s/%s/%s/%d#step:%d", c.config.WebUIAddress, org, name, b.GetNumber(), s.GetNumber())
var (
state string
description string
)
// set the state and description for the status context
// depending on what the status of the step is
switch s.GetStatus() {
case constants.StatusRunning, constants.StatusPending, constants.StatusPendingApproval:
state = "pending"
description = fmt.Sprintf("the step is %s", s.GetStatus())
case constants.StatusSuccess:
state = "success"
description = "the step was successful"
case constants.StatusFailure:
state = "failure"
description = "the step has failed"
case constants.StatusCanceled:
state = "failure"
description = "the step was canceled"
case constants.StatusKilled:
state = "failure"
description = "the step was killed"
case constants.StatusSkipped:
state = "failure"
description = "step was skipped or never ran"
default:
state = "error"
description = "there was an error"
}
// create the status object to make the API call
status := &github.RepoStatus{
Context: github.String(context),
Description: github.String(description),
State: github.String(state),
}
// provide "Details" link in GitHub UI if server was configured with it
if len(c.config.WebUIAddress) > 0 && b.GetStatus() != constants.StatusSkipped {
status.TargetURL = github.String(url)
}
// send API call to create the status context for the commit
_, _, err := client.Repositories.CreateStatus(ctx, org, name, b.GetCommit(), status)
return err
}
// GetRepo gets repo information from Github.
func (c *client) GetRepo(ctx context.Context, u *library.User, r *api.Repo) (*api.Repo, int, error) {
c.Logger.WithFields(logrus.Fields{
"org": r.GetOrg(),
"repo": r.GetName(),
"user": u.GetName(),
}).Tracef("retrieving repository information for %s", r.GetFullName())
// create GitHub OAuth client with user's token
client := c.newClientToken(u.GetToken())
// send an API call to get the repo info
repo, resp, err := client.Repositories.Get(ctx, r.GetOrg(), r.GetName())
if err != nil {
return nil, resp.StatusCode, err
}
return toLibraryRepo(*repo), resp.StatusCode, nil
}
// GetOrgAndRepoName returns the name of the org and the repository in the SCM.
func (c *client) GetOrgAndRepoName(ctx context.Context, u *library.User, o string, r string) (string, string, error) {
c.Logger.WithFields(logrus.Fields{
"org": o,
"repo": r,
"user": u.GetName(),
}).Tracef("retrieving repository information for %s/%s", o, r)
// create GitHub OAuth client with user's token
client := c.newClientToken(u.GetToken())
// send an API call to get the repo info
repo, _, err := client.Repositories.Get(ctx, o, r)
if err != nil {
return "", "", err
}
return repo.GetOwner().GetLogin(), repo.GetName(), nil
}
// ListUserRepos returns a list of all repos the user has access to.
func (c *client) ListUserRepos(ctx context.Context, u *library.User) ([]*api.Repo, error) {
c.Logger.WithFields(logrus.Fields{
"user": u.GetName(),
}).Tracef("listing source repositories for %s", u.GetName())
// create GitHub OAuth client with user's token
client := c.newClientToken(u.GetToken())
r := []*github.Repository{}
f := []*api.Repo{}
// set the max per page for the options to capture the list of repos
opts := &github.RepositoryListOptions{
ListOptions: github.ListOptions{PerPage: 100}, // 100 is max
}
// loop to capture *ALL* the repos
for {
// send API call to capture the user's repos
repos, resp, err := client.Repositories.List(ctx, "", opts)
if err != nil {
return nil, fmt.Errorf("unable to list user repos: %w", err)
}
r = append(r, repos...)
// break the loop if there is no more results to page through
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
// iterate through each repo for the user
for _, repo := range r {
// skip if the repo is void
// fixes an issue with GitHub replication being out of sync
if repo == nil {
continue
}
// skip if the repo is archived or disabled
if repo.GetArchived() || repo.GetDisabled() {
continue
}
f = append(f, toLibraryRepo(*repo))
}
return f, nil
}
// toLibraryRepo does a partial conversion of a github repo to a library repo.
func toLibraryRepo(gr github.Repository) *api.Repo {
// setting the visbility to match the SCM visbility
var visibility string
if *gr.Private {
visibility = constants.VisibilityPrivate
} else {
visibility = constants.VisibilityPublic
}
return &api.Repo{
Org: gr.GetOwner().Login,
Name: gr.Name,
FullName: gr.FullName,
Link: gr.HTMLURL,
Clone: gr.CloneURL,
Branch: gr.DefaultBranch,
Topics: &gr.Topics,
Private: gr.Private,
Visibility: &visibility,
}
}
// GetPullRequest defines a function that retrieves
// a pull request for a repo.
func (c *client) GetPullRequest(ctx context.Context, u *library.User, r *api.Repo, number int) (string, string, string, string, error) {
c.Logger.WithFields(logrus.Fields{
"org": r.GetOrg(),
"repo": r.GetName(),
"user": u.GetName(),
}).Tracef("retrieving pull request %d for repo %s", number, r.GetFullName())
// create GitHub OAuth client with user's token
client := c.newClientToken(u.GetToken())
pull, _, err := client.PullRequests.Get(ctx, r.GetOrg(), r.GetName(), number)
if err != nil {
return "", "", "", "", err
}
commit := pull.GetHead().GetSHA()
branch := pull.GetBase().GetRef()
baseref := pull.GetBase().GetRef()
headref := pull.GetHead().GetRef()
return commit, branch, baseref, headref, nil
}
// GetHTMLURL retrieves the html_url from repository contents from the GitHub repo.
func (c *client) GetHTMLURL(ctx context.Context, u *library.User, org, repo, name, ref string) (string, error) {
c.Logger.WithFields(logrus.Fields{
"org": org,
"repo": repo,
"user": u.GetName(),
}).Tracef("capturing html_url for %s/%s/%s@%s", org, repo, name, ref)
// create GitHub OAuth client with user's token
client := c.newClientToken(*u.Token)
// set the reference for the options to capture the repository contents
opts := &github.RepositoryContentGetOptions{
Ref: ref,
}
// send API call to capture the repository contents for org/repo/name at the ref provided
data, _, _, err := client.Repositories.GetContents(ctx, org, repo, name, opts)
if err != nil {
return "", err
}
// data is not nil if the file exists
if data != nil {
URL := data.GetHTMLURL()
if err != nil {
return "", err
}
return URL, nil
}
return "", fmt.Errorf("no valid repository contents found")
}
// GetBranch defines a function that retrieves a branch for a repo.
func (c *client) GetBranch(ctx context.Context, u *library.User, r *api.Repo, branch string) (string, string, error) {
c.Logger.WithFields(logrus.Fields{
"org": r.GetOrg(),
"repo": r.GetName(),
"user": u.GetName(),
}).Tracef("retrieving branch %s for repo %s", branch, r.GetFullName())
// create GitHub OAuth client with user's token
client := c.newClientToken(u.GetToken())
maxRedirects := 3
data, _, err := client.Repositories.GetBranch(ctx, r.GetOrg(), r.GetName(), branch, maxRedirects)
if err != nil {
return "", "", err
}
return data.GetName(), data.GetCommit().GetSHA(), nil
}