• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

jfrog / froggit-go / 17042625601

18 Aug 2025 01:52PM UTC coverage: 84.164% (+0.02%) from 84.143%
17042625601

push

github

web-flow
Upgrade dependencies - github-go version to v74 (#164)

23 of 27 new or added lines in 1 file covered. (85.19%)

1 existing line in 1 file now uncovered.

4523 of 5374 relevant lines covered (84.16%)

6.36 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.49
/vcsclient/github.go
1
package vcsclient
2

3
import (
4
        "context"
5
        "crypto/rand"
6
        base64Utils "encoding/base64"
7
        "errors"
8
        "fmt"
9
        "io"
10
        "net/http"
11
        "net/url"
12
        "path/filepath"
13
        "sort"
14
        "strconv"
15
        "strings"
16
        "time"
17

18
        "github.com/google/go-github/v74/github"
19
        "github.com/grokify/mogo/encoding/base64"
20
        "github.com/jfrog/froggit-go/vcsutils"
21
        "github.com/jfrog/gofrog/datastructures"
22
        "github.com/mitchellh/mapstructure"
23
        "golang.org/x/crypto/nacl/box"
24
        "golang.org/x/exp/slices"
25
        "golang.org/x/oauth2"
26
)
27

28
const (
29
        maxRetries               = 5
30
        retriesIntervalMilliSecs = 60000
31
        // https://github.com/orgs/community/discussions/27190
32
        githubPrContentSizeLimit = 65536
33
        // The maximum number of reviewers that can be added to a GitHub environment
34
        ghMaxEnvReviewers = 6
35
        regularFileCode   = "100644"
36
)
37

38
var rateLimitRetryStatuses = []int{http.StatusForbidden, http.StatusTooManyRequests}
39

40
type GitHubRateLimitExecutionHandler func() (*github.Response, error)
41

42
type GitHubRateLimitRetryExecutor struct {
43
        vcsutils.RetryExecutor
44
        GitHubRateLimitExecutionHandler
45
}
46

47
func (ghe *GitHubRateLimitRetryExecutor) Execute() error {
113✔
48
        ghe.ExecutionHandler = func() (bool, error) {
226✔
49
                ghResponse, err := ghe.GitHubRateLimitExecutionHandler()
113✔
50
                return shouldRetryIfRateLimitExceeded(ghResponse, err), err
113✔
51
        }
113✔
52
        return ghe.RetryExecutor.Execute()
113✔
53
}
54

55
// GitHubClient API version 3
56
type GitHubClient struct {
57
        vcsInfo                VcsInfo
58
        rateLimitRetryExecutor GitHubRateLimitRetryExecutor
59
        logger                 vcsutils.Log
60
        ghClient               *github.Client
61
}
62

63
// NewGitHubClient create a new GitHubClient
64
func NewGitHubClient(vcsInfo VcsInfo, logger vcsutils.Log) (*GitHubClient, error) {
146✔
65
        ghClient, err := buildGithubClient(vcsInfo, logger)
146✔
66
        if err != nil {
146✔
67
                return nil, err
×
68
        }
×
69
        return &GitHubClient{
146✔
70
                        vcsInfo:  vcsInfo,
146✔
71
                        logger:   logger,
146✔
72
                        ghClient: ghClient,
146✔
73
                        rateLimitRetryExecutor: GitHubRateLimitRetryExecutor{RetryExecutor: vcsutils.RetryExecutor{
146✔
74
                                Logger:                   logger,
146✔
75
                                MaxRetries:               maxRetries,
146✔
76
                                RetriesIntervalMilliSecs: retriesIntervalMilliSecs},
146✔
77
                        }},
146✔
78
                nil
146✔
79
}
80

81
func (client *GitHubClient) runWithRateLimitRetries(handler func() (*github.Response, error)) error {
113✔
82
        client.rateLimitRetryExecutor.GitHubRateLimitExecutionHandler = handler
113✔
83
        return client.rateLimitRetryExecutor.Execute()
113✔
84
}
113✔
85

86
// TestConnection on GitHub
87
func (client *GitHubClient) TestConnection(ctx context.Context) error {
4✔
88
        _, _, err := client.ghClient.Meta.Zen(ctx)
4✔
89
        return err
4✔
90
}
4✔
91

92
func buildGithubClient(vcsInfo VcsInfo, logger vcsutils.Log) (*github.Client, error) {
146✔
93
        httpClient := &http.Client{}
146✔
94
        if vcsInfo.Token != "" {
208✔
95
                httpClient = oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(&oauth2.Token{AccessToken: vcsInfo.Token}))
62✔
96
        }
62✔
97
        ghClient := github.NewClient(httpClient)
146✔
98
        if vcsInfo.APIEndpoint != "" {
258✔
99
                baseURL, err := url.Parse(strings.TrimSuffix(vcsInfo.APIEndpoint, "/") + "/")
112✔
100
                if err != nil {
112✔
101
                        return nil, err
×
102
                }
×
103
                logger.Info("Using API endpoint:", baseURL)
112✔
104
                ghClient.BaseURL = baseURL
112✔
105
        }
106
        return ghClient, nil
146✔
107
}
108

109
// AddSshKeyToRepository on GitHub
110
func (client *GitHubClient) AddSshKeyToRepository(ctx context.Context, owner, repository, keyName, publicKey string, permission Permission) error {
8✔
111
        err := validateParametersNotBlank(map[string]string{
8✔
112
                "owner":      owner,
8✔
113
                "repository": repository,
8✔
114
                "key name":   keyName,
8✔
115
                "public key": publicKey,
8✔
116
        })
8✔
117
        if err != nil {
13✔
118
                return err
5✔
119
        }
5✔
120

121
        readOnly := permission != ReadWrite
3✔
122
        key := github.Key{
3✔
123
                Key:      &publicKey,
3✔
124
                Title:    &keyName,
3✔
125
                ReadOnly: &readOnly,
3✔
126
        }
3✔
127

3✔
128
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
129
                _, ghResponse, err := client.ghClient.Repositories.CreateKey(ctx, owner, repository, &key)
3✔
130
                return ghResponse, err
3✔
131
        })
3✔
132
}
133

134
// ListRepositories on GitHub
135
func (client *GitHubClient) ListRepositories(ctx context.Context) (results map[string][]string, err error) {
5✔
136
        results = make(map[string][]string)
5✔
137
        for nextPage := 1; ; nextPage++ {
11✔
138
                var repositoriesInPage []*github.Repository
6✔
139
                var ghResponse *github.Response
6✔
140
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
12✔
141
                        repositoriesInPage, ghResponse, err = client.executeListRepositoriesInPage(ctx, nextPage)
6✔
142
                        return ghResponse, err
6✔
143
                })
6✔
144
                if err != nil {
8✔
145
                        return
2✔
146
                }
2✔
147

148
                for _, repo := range repositoriesInPage {
37✔
149
                        results[*repo.Owner.Login] = append(results[*repo.Owner.Login], *repo.Name)
33✔
150
                }
33✔
151
                if nextPage+1 > ghResponse.LastPage {
7✔
152
                        break
3✔
153
                }
154
        }
155
        return
3✔
156
}
157

158
func (client *GitHubClient) executeListRepositoriesInPage(ctx context.Context, page int) ([]*github.Repository, *github.Response, error) {
6✔
159
        options := &github.RepositoryListByAuthenticatedUserOptions{ListOptions: github.ListOptions{Page: page}}
6✔
160
        return client.ghClient.Repositories.ListByAuthenticatedUser(ctx, options)
6✔
161
}
6✔
162

163
// ListBranches on GitHub
164
func (client *GitHubClient) ListBranches(ctx context.Context, owner, repository string) (branchList []string, err error) {
2✔
165
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
166
                var ghResponse *github.Response
2✔
167
                branchList, ghResponse, err = client.executeListBranch(ctx, owner, repository)
2✔
168
                return ghResponse, err
2✔
169
        })
2✔
170
        return
2✔
171
}
172

173
func (client *GitHubClient) executeListBranch(ctx context.Context, owner, repository string) ([]string, *github.Response, error) {
2✔
174
        branches, ghResponse, err := client.ghClient.Repositories.ListBranches(ctx, owner, repository, nil)
2✔
175
        if err != nil {
3✔
176
                return []string{}, ghResponse, err
1✔
177
        }
1✔
178

179
        branchList := make([]string, 0, len(branches))
1✔
180
        for _, branch := range branches {
3✔
181
                branchList = append(branchList, *branch.Name)
2✔
182
        }
2✔
183
        return branchList, ghResponse, nil
1✔
184
}
185

186
// CreateWebhook on GitHub
187
func (client *GitHubClient) CreateWebhook(ctx context.Context, owner, repository, _, payloadURL string,
188
        webhookEvents ...vcsutils.WebhookEvent) (string, string, error) {
2✔
189
        token := vcsutils.CreateToken()
2✔
190
        hook := createGitHubHook(token, payloadURL, webhookEvents...)
2✔
191
        var ghResponseHook *github.Hook
2✔
192
        var err error
2✔
193
        if err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
194
                var ghResponse *github.Response
2✔
195
                ghResponseHook, ghResponse, err = client.ghClient.Repositories.CreateHook(ctx, owner, repository, hook)
2✔
196
                return ghResponse, err
2✔
197
        }); err != nil {
3✔
198
                return "", "", err
1✔
199
        }
1✔
200

201
        return strconv.FormatInt(*ghResponseHook.ID, 10), token, nil
1✔
202
}
203

204
// UpdateWebhook on GitHub
205
func (client *GitHubClient) UpdateWebhook(ctx context.Context, owner, repository, _, payloadURL, token,
206
        webhookID string, webhookEvents ...vcsutils.WebhookEvent) error {
2✔
207
        webhookIDInt64, err := strconv.ParseInt(webhookID, 10, 64)
2✔
208
        if err != nil {
2✔
209
                return err
×
210
        }
×
211

212
        hook := createGitHubHook(token, payloadURL, webhookEvents...)
2✔
213
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
214
                var ghResponse *github.Response
2✔
215
                _, ghResponse, err = client.ghClient.Repositories.EditHook(ctx, owner, repository, webhookIDInt64, hook)
2✔
216
                return ghResponse, err
2✔
217
        })
2✔
218
}
219

220
// DeleteWebhook on GitHub
221
func (client *GitHubClient) DeleteWebhook(ctx context.Context, owner, repository, webhookID string) error {
2✔
222
        webhookIDInt64, err := strconv.ParseInt(webhookID, 10, 64)
2✔
223
        if err != nil {
3✔
224
                return err
1✔
225
        }
1✔
226

227
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
228
                return client.ghClient.Repositories.DeleteHook(ctx, owner, repository, webhookIDInt64)
1✔
229
        })
1✔
230
}
231

232
// SetCommitStatus on GitHub
233
func (client *GitHubClient) SetCommitStatus(ctx context.Context, commitStatus CommitStatus, owner, repository, ref,
234
        title, description, detailsURL string) error {
2✔
235
        state := getGitHubCommitState(commitStatus)
2✔
236
        status := &github.RepoStatus{
2✔
237
                Context:     &title,
2✔
238
                TargetURL:   &detailsURL,
2✔
239
                State:       &state,
2✔
240
                Description: &description,
2✔
241
        }
2✔
242

2✔
243
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
244
                _, ghResponse, err := client.ghClient.Repositories.CreateStatus(ctx, owner, repository, ref, status)
2✔
245
                return ghResponse, err
2✔
246
        })
2✔
247
}
248

249
// GetCommitStatuses on GitHub
250
func (client *GitHubClient) GetCommitStatuses(ctx context.Context, owner, repository, ref string) (statusInfoList []CommitStatusInfo, err error) {
6✔
251
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
12✔
252
                var ghResponse *github.Response
6✔
253
                statusInfoList, ghResponse, err = client.executeGetCommitStatuses(ctx, owner, repository, ref)
6✔
254
                return ghResponse, err
6✔
255
        })
6✔
256
        return
6✔
257
}
258

259
func (client *GitHubClient) executeGetCommitStatuses(ctx context.Context, owner, repository, ref string) (statusInfoList []CommitStatusInfo, ghResponse *github.Response, err error) {
6✔
260
        statuses, ghResponse, err := client.ghClient.Repositories.GetCombinedStatus(ctx, owner, repository, ref, nil)
6✔
261
        if err != nil {
10✔
262
                return
4✔
263
        }
4✔
264

265
        for _, singleStatus := range statuses.Statuses {
6✔
266
                statusInfoList = append(statusInfoList, CommitStatusInfo{
4✔
267
                        State:         commitStatusAsStringToStatus(*singleStatus.State),
4✔
268
                        Description:   singleStatus.GetDescription(),
4✔
269
                        DetailsUrl:    singleStatus.GetTargetURL(),
4✔
270
                        Creator:       singleStatus.GetCreator().GetName(),
4✔
271
                        LastUpdatedAt: singleStatus.GetUpdatedAt().Time,
4✔
272
                        CreatedAt:     singleStatus.GetCreatedAt().Time,
4✔
273
                })
4✔
274
        }
4✔
275
        return
2✔
276
}
277

278
// DownloadRepository on GitHub
279
func (client *GitHubClient) DownloadRepository(ctx context.Context, owner, repository, branch, localPath string) (err error) {
2✔
280
        // Get the archive download link from GitHub
2✔
281
        var baseURL *url.URL
2✔
282
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
283
                var ghResponse *github.Response
2✔
284
                baseURL, ghResponse, err = client.executeGetArchiveLink(ctx, owner, repository, branch)
2✔
285
                return ghResponse, err
2✔
286
        })
2✔
287
        if err != nil {
3✔
288
                return
1✔
289
        }
1✔
290

291
        // Download the archive
292
        httpResponse, err := executeDownloadArchiveFromLink(baseURL.String())
1✔
293
        if err != nil {
1✔
294
                return
×
295
        }
×
296
        defer func() { err = errors.Join(err, httpResponse.Body.Close()) }()
2✔
297
        client.logger.Info(repository, vcsutils.SuccessfulRepoDownload)
1✔
298

1✔
299
        // Untar the archive
1✔
300
        if err = vcsutils.Untar(localPath, httpResponse.Body, true); err != nil {
1✔
301
                return
×
302
        }
×
303
        client.logger.Info(vcsutils.SuccessfulRepoExtraction)
1✔
304

1✔
305
        repositoryInfo, err := client.GetRepositoryInfo(ctx, owner, repository)
1✔
306
        if err != nil {
1✔
307
                return
×
308
        }
×
309
        // Create a .git folder in the archive with the remote repository HTTP clone url
310
        err = vcsutils.CreateDotGitFolderWithRemote(localPath, vcsutils.RemoteName, repositoryInfo.CloneInfo.HTTP)
1✔
311
        return
1✔
312
}
313

314
func (client *GitHubClient) executeGetArchiveLink(ctx context.Context, owner, repository, branch string) (baseURL *url.URL, ghResponse *github.Response, err error) {
2✔
315
        client.logger.Debug("Getting GitHub archive link to download")
2✔
316
        return client.ghClient.Repositories.GetArchiveLink(ctx, owner, repository, github.Tarball,
2✔
317
                &github.RepositoryContentGetOptions{Ref: branch}, 5)
2✔
318
}
2✔
319

320
func executeDownloadArchiveFromLink(baseURL string) (*http.Response, error) {
1✔
321
        httpClient := &http.Client{}
1✔
322
        req, err := http.NewRequest(http.MethodGet, baseURL, nil)
1✔
323
        if err != nil {
1✔
324
                return nil, err
×
325
        }
×
326
        httpResponse, err := httpClient.Do(req)
1✔
327
        if err != nil {
1✔
328
                return httpResponse, err
×
329
        }
×
330
        return httpResponse, vcsutils.CheckResponseStatusWithBody(httpResponse, http.StatusOK)
1✔
331
}
332

333
func (client *GitHubClient) GetPullRequestCommentSizeLimit() int {
×
334
        return githubPrContentSizeLimit
×
335
}
×
336

337
func (client *GitHubClient) GetPullRequestDetailsSizeLimit() int {
×
338
        return githubPrContentSizeLimit
×
339
}
×
340

341
// CreatePullRequest on GitHub
342
func (client *GitHubClient) CreatePullRequest(ctx context.Context, owner, repository, sourceBranch, targetBranch, title, description string) error {
2✔
343
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
344
                _, githubResponse, err := client.executeCreatePullRequest(ctx, owner, repository, sourceBranch, targetBranch, title, description)
2✔
345
                return githubResponse, err
2✔
346
        })
2✔
347
}
348

349
func (client *GitHubClient) CreatePullRequestDetailed(ctx context.Context, owner, repository, sourceBranch, targetBranch, title, description string) (CreatedPullRequestInfo, error) {
2✔
350
        var prInfo CreatedPullRequestInfo
2✔
351

2✔
352
        err := client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
353
                pr, ghResponse, err := client.executeCreatePullRequest(ctx, owner, repository, sourceBranch, targetBranch, title, description)
2✔
354
                if err != nil {
3✔
355
                        return ghResponse, err
1✔
356
                }
1✔
357
                prInfo = mapToPullRequestInfo(pr)
1✔
358
                return ghResponse, nil
1✔
359
        })
360

361
        return prInfo, err
2✔
362
}
363

364
func (client *GitHubClient) executeCreatePullRequest(ctx context.Context, owner, repository, sourceBranch, targetBranch, title, description string) (*github.PullRequest, *github.Response, error) {
4✔
365
        head := owner + ":" + sourceBranch
4✔
366
        client.logger.Debug(vcsutils.CreatingPullRequest, title)
4✔
367

4✔
368
        pr, ghResponse, err := client.ghClient.PullRequests.Create(ctx, owner, repository, &github.NewPullRequest{
4✔
369
                Title: &title,
4✔
370
                Body:  &description,
4✔
371
                Head:  &head,
4✔
372
                Base:  &targetBranch,
4✔
373
        })
4✔
374
        return pr, ghResponse, err
4✔
375
}
4✔
376

377
func mapToPullRequestInfo(pr *github.PullRequest) CreatedPullRequestInfo {
1✔
378
        return CreatedPullRequestInfo{
1✔
379
                Number:      pr.GetNumber(),
1✔
380
                URL:         pr.GetHTMLURL(),
1✔
381
                StatusesUrl: pr.GetStatusesURL(),
1✔
382
        }
1✔
383
}
1✔
384

385
// UpdatePullRequest on GitHub
386
func (client *GitHubClient) UpdatePullRequest(ctx context.Context, owner, repository, title, body, targetBranchName string, id int, state vcsutils.PullRequestState) error {
3✔
387
        client.logger.Debug(vcsutils.UpdatingPullRequest, id)
3✔
388
        var baseRef *github.PullRequestBranch
3✔
389
        if targetBranchName != "" {
5✔
390
                baseRef = &github.PullRequestBranch{Ref: &targetBranchName}
2✔
391
        }
2✔
392
        pullRequest := &github.PullRequest{
3✔
393
                Body:  &body,
3✔
394
                Title: &title,
3✔
395
                State: vcsutils.MapPullRequestState(&state),
3✔
396
                Base:  baseRef,
3✔
397
        }
3✔
398

3✔
399
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
400
                _, ghResponse, err := client.ghClient.PullRequests.Edit(ctx, owner, repository, id, pullRequest)
3✔
401
                return ghResponse, err
3✔
402
        })
3✔
403
}
404

405
// ListOpenPullRequestsWithBody on GitHub
406
func (client *GitHubClient) ListOpenPullRequestsWithBody(ctx context.Context, owner, repository string) ([]PullRequestInfo, error) {
1✔
407
        return client.getOpenPullRequests(ctx, owner, repository, true)
1✔
408
}
1✔
409

410
// ListOpenPullRequests on GitHub
411
func (client *GitHubClient) ListOpenPullRequests(ctx context.Context, owner, repository string) ([]PullRequestInfo, error) {
1✔
412
        return client.getOpenPullRequests(ctx, owner, repository, false)
1✔
413
}
1✔
414

415
func (client *GitHubClient) getOpenPullRequests(ctx context.Context, owner, repository string, withBody bool) ([]PullRequestInfo, error) {
2✔
416
        var pullRequests []*github.PullRequest
2✔
417
        client.logger.Debug(vcsutils.FetchingOpenPullRequests, repository)
2✔
418
        err := client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
419
                var ghResponse *github.Response
2✔
420
                var err error
2✔
421
                pullRequests, ghResponse, err = client.ghClient.PullRequests.List(ctx, owner, repository, &github.PullRequestListOptions{State: "open"})
2✔
422
                return ghResponse, err
2✔
423
        })
2✔
424
        if err != nil {
2✔
425
                return []PullRequestInfo{}, err
×
426
        }
×
427

428
        return mapGitHubPullRequestToPullRequestInfoList(pullRequests, withBody)
2✔
429
}
430

431
func (client *GitHubClient) GetPullRequestByID(ctx context.Context, owner, repository string, pullRequestId int) (PullRequestInfo, error) {
4✔
432
        var pullRequest *github.PullRequest
4✔
433
        var ghResponse *github.Response
4✔
434
        var err error
4✔
435
        client.logger.Debug(vcsutils.FetchingPullRequestById, repository)
4✔
436
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
8✔
437
                pullRequest, ghResponse, err = client.ghClient.PullRequests.Get(ctx, owner, repository, pullRequestId)
4✔
438
                return ghResponse, err
4✔
439
        })
4✔
440
        if err != nil {
7✔
441
                return PullRequestInfo{}, err
3✔
442
        }
3✔
443

444
        if err = vcsutils.CheckResponseStatusWithBody(ghResponse.Response, http.StatusOK); err != nil {
1✔
445
                return PullRequestInfo{}, err
×
446
        }
×
447

448
        return mapGitHubPullRequestToPullRequestInfo(pullRequest, false)
1✔
449
}
450

451
func mapGitHubPullRequestToPullRequestInfo(ghPullRequest *github.PullRequest, withBody bool) (PullRequestInfo, error) {
4✔
452
        var sourceBranch, targetBranch string
4✔
453
        var err1, err2 error
4✔
454
        if ghPullRequest != nil && ghPullRequest.Head != nil && ghPullRequest.Base != nil {
8✔
455
                sourceBranch, err1 = extractBranchFromLabel(vcsutils.DefaultIfNotNil(ghPullRequest.Head.Label))
4✔
456
                targetBranch, err2 = extractBranchFromLabel(vcsutils.DefaultIfNotNil(ghPullRequest.Base.Label))
4✔
457
                err := errors.Join(err1, err2)
4✔
458
                if err != nil {
4✔
459
                        return PullRequestInfo{}, err
×
460
                }
×
461
        }
462

463
        var sourceRepoName, sourceRepoOwner string
4✔
464
        if ghPullRequest.Head.Repo == nil {
4✔
465
                return PullRequestInfo{}, errors.New("the source repository information is missing when fetching the pull request details")
×
466
        }
×
467
        if ghPullRequest.Head.Repo.Owner == nil {
4✔
468
                return PullRequestInfo{}, errors.New("the source repository owner name is missing when fetching the pull request details")
×
469
        }
×
470
        sourceRepoName = vcsutils.DefaultIfNotNil(ghPullRequest.Head.Repo.Name)
4✔
471
        sourceRepoOwner = vcsutils.DefaultIfNotNil(ghPullRequest.Head.Repo.Owner.Login)
4✔
472

4✔
473
        var targetRepoName, targetRepoOwner string
4✔
474
        if ghPullRequest.Base.Repo == nil {
4✔
475
                return PullRequestInfo{}, errors.New("the target repository information is missing when fetching the pull request details")
×
476
        }
×
477
        if ghPullRequest.Base.Repo.Owner == nil {
4✔
478
                return PullRequestInfo{}, errors.New("the target repository owner name is missing when fetching the pull request details")
×
479
        }
×
480
        targetRepoName = vcsutils.DefaultIfNotNil(ghPullRequest.Base.Repo.Name)
4✔
481
        targetRepoOwner = vcsutils.DefaultIfNotNil(ghPullRequest.Base.Repo.Owner.Login)
4✔
482

4✔
483
        var body string
4✔
484
        if withBody {
5✔
485
                body = vcsutils.DefaultIfNotNil(ghPullRequest.Body)
1✔
486
        }
1✔
487

488
        return PullRequestInfo{
4✔
489
                ID:     int64(vcsutils.DefaultIfNotNil(ghPullRequest.Number)),
4✔
490
                Title:  vcsutils.DefaultIfNotNil(ghPullRequest.Title),
4✔
491
                URL:    vcsutils.DefaultIfNotNil(ghPullRequest.HTMLURL),
4✔
492
                Body:   body,
4✔
493
                Author: vcsutils.DefaultIfNotNil(ghPullRequest.User.Login),
4✔
494
                Source: BranchInfo{
4✔
495
                        Name:       sourceBranch,
4✔
496
                        Repository: sourceRepoName,
4✔
497
                        Owner:      sourceRepoOwner,
4✔
498
                },
4✔
499
                Target: BranchInfo{
4✔
500
                        Name:       targetBranch,
4✔
501
                        Repository: targetRepoName,
4✔
502
                        Owner:      targetRepoOwner,
4✔
503
                },
4✔
504
                Status: vcsutils.DefaultIfNotNil(ghPullRequest.State),
4✔
505
        }, nil
4✔
506
}
507

508
// Extracts branch name from the following expected label format repo:branch
509
func extractBranchFromLabel(label string) (string, error) {
8✔
510
        split := strings.Split(label, ":")
8✔
511
        if len(split) <= 1 {
8✔
512
                return "", fmt.Errorf("bad label format %s", label)
×
513
        }
×
514
        return split[1], nil
8✔
515
}
516

517
// AddPullRequestComment on GitHub
518
func (client *GitHubClient) AddPullRequestComment(ctx context.Context, owner, repository, content string, pullRequestID int) error {
6✔
519
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "content": content})
6✔
520
        if err != nil {
10✔
521
                return err
4✔
522
        }
4✔
523

524
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
525
                var ghResponse *github.Response
2✔
526
                // We use the Issues API to add a regular comment. The PullRequests API adds a code review comment.
2✔
527
                _, ghResponse, err = client.ghClient.Issues.CreateComment(ctx, owner, repository, pullRequestID, &github.IssueComment{Body: &content})
2✔
528
                return ghResponse, err
2✔
529
        })
2✔
530
}
531

532
// AddPullRequestReviewComments on GitHub
533
func (client *GitHubClient) AddPullRequestReviewComments(ctx context.Context, owner, repository string, pullRequestID int, comments ...PullRequestComment) error {
2✔
534
        prID := strconv.Itoa(pullRequestID)
2✔
535
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "pullRequestID": prID})
2✔
536
        if err != nil {
2✔
537
                return err
×
538
        }
×
539
        if len(comments) == 0 {
2✔
540
                return errors.New(vcsutils.ErrNoCommentsProvided)
×
541
        }
×
542

543
        var commits []*github.RepositoryCommit
2✔
544
        var ghResponse *github.Response
2✔
545
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
546
                commits, ghResponse, err = client.ghClient.PullRequests.ListCommits(ctx, owner, repository, pullRequestID, nil)
2✔
547
                return ghResponse, err
2✔
548
        })
2✔
549
        if err != nil {
3✔
550
                return err
1✔
551
        }
1✔
552
        if len(commits) == 0 {
1✔
553
                return errors.New("could not fetch the commits list for pull request " + prID)
×
554
        }
×
555

556
        latestCommitSHA := commits[len(commits)-1].GetSHA()
1✔
557

1✔
558
        for _, comment := range comments {
3✔
559
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
560
                        ghResponse, err = client.executeCreatePullRequestReviewComment(ctx, owner, repository, latestCommitSHA, pullRequestID, comment)
2✔
561
                        return ghResponse, err
2✔
562
                })
2✔
563
                if err != nil {
2✔
564
                        return err
×
565
                }
×
566
        }
567
        return nil
1✔
568
}
569

570
func (client *GitHubClient) executeCreatePullRequestReviewComment(ctx context.Context, owner, repository, latestCommitSHA string, pullRequestID int, comment PullRequestComment) (*github.Response, error) {
2✔
571
        filePath := filepath.Clean(comment.NewFilePath)
2✔
572
        startLine := &comment.NewStartLine
2✔
573
        // GitHub API won't accept 'start_line' if it equals the end line
2✔
574
        if *startLine == comment.NewEndLine {
2✔
575
                startLine = nil
×
576
        }
×
577
        _, ghResponse, err := client.ghClient.PullRequests.CreateComment(ctx, owner, repository, pullRequestID, &github.PullRequestComment{
2✔
578
                CommitID:  &latestCommitSHA,
2✔
579
                Body:      &comment.Content,
2✔
580
                StartLine: startLine,
2✔
581
                Line:      &comment.NewEndLine,
2✔
582
                Path:      &filePath,
2✔
583
        })
2✔
584
        if err != nil {
2✔
585
                err = fmt.Errorf("could not create a code review comment for <%s/%s> in pull request %d. error received: %w",
×
586
                        owner, repository, pullRequestID, err)
×
587
        }
×
588
        return ghResponse, err
2✔
589
}
590

591
// ListPullRequestReviewComments on GitHub
592
func (client *GitHubClient) ListPullRequestReviewComments(ctx context.Context, owner, repository string, pullRequestID int) ([]CommentInfo, error) {
2✔
593
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
2✔
594
        if err != nil {
2✔
595
                return nil, err
×
596
        }
×
597

598
        commentsInfoList := []CommentInfo{}
2✔
599
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
600
                var ghResponse *github.Response
2✔
601
                commentsInfoList, ghResponse, err = client.executeListPullRequestReviewComments(ctx, owner, repository, pullRequestID)
2✔
602
                return ghResponse, err
2✔
603
        })
2✔
604
        return commentsInfoList, err
2✔
605
}
606

607
// ListPullRequestReviews on GitHub
608
func (client *GitHubClient) ListPullRequestReviews(ctx context.Context, owner, repository string, pullRequestID int) ([]PullRequestReviewDetails, error) {
2✔
609
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
2✔
610
        if err != nil {
2✔
611
                return nil, err
×
612
        }
×
613

614
        var reviews []*github.PullRequestReview
2✔
615
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
616
                var ghResponse *github.Response
2✔
617
                reviews, ghResponse, err = client.ghClient.PullRequests.ListReviews(ctx, owner, repository, pullRequestID, nil)
2✔
618
                return ghResponse, err
2✔
619
        })
2✔
620
        if err != nil {
3✔
621
                return nil, err
1✔
622
        }
1✔
623

624
        var reviewInfos []PullRequestReviewDetails
1✔
625
        for _, review := range reviews {
2✔
626
                reviewInfos = append(reviewInfos, PullRequestReviewDetails{
1✔
627
                        ID:          review.GetID(),
1✔
628
                        Reviewer:    review.GetUser().GetLogin(),
1✔
629
                        Body:        review.GetBody(),
1✔
630
                        State:       review.GetState(),
1✔
631
                        SubmittedAt: review.GetSubmittedAt().String(),
1✔
632
                        CommitID:    review.GetCommitID(),
1✔
633
                })
1✔
634
        }
1✔
635

636
        return reviewInfos, nil
1✔
637
}
638

639
func (client *GitHubClient) executeListPullRequestReviewComments(ctx context.Context, owner, repository string, pullRequestID int) ([]CommentInfo, *github.Response, error) {
2✔
640
        commentsList, ghResponse, err := client.ghClient.PullRequests.ListComments(ctx, owner, repository, pullRequestID, nil)
2✔
641
        if err != nil {
3✔
642
                return []CommentInfo{}, ghResponse, err
1✔
643
        }
1✔
644
        commentsInfoList := []CommentInfo{}
1✔
645
        for _, comment := range commentsList {
2✔
646
                commentsInfoList = append(commentsInfoList, CommentInfo{
1✔
647
                        ID:      comment.GetID(),
1✔
648
                        Content: comment.GetBody(),
1✔
649
                        Created: comment.GetCreatedAt().Time,
1✔
650
                })
1✔
651
        }
1✔
652
        return commentsInfoList, ghResponse, nil
1✔
653
}
654

655
// ListPullRequestComments on GitHub
656
func (client *GitHubClient) ListPullRequestComments(ctx context.Context, owner, repository string, pullRequestID int) ([]CommentInfo, error) {
4✔
657
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
4✔
658
        if err != nil {
4✔
659
                return []CommentInfo{}, err
×
660
        }
×
661

662
        var commentsList []*github.IssueComment
4✔
663
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
8✔
664
                var ghResponse *github.Response
4✔
665
                commentsList, ghResponse, err = client.ghClient.Issues.ListComments(ctx, owner, repository, pullRequestID, &github.IssueListCommentsOptions{})
4✔
666
                return ghResponse, err
4✔
667
        })
4✔
668

669
        if err != nil {
7✔
670
                return []CommentInfo{}, err
3✔
671
        }
3✔
672

673
        return mapGitHubIssuesCommentToCommentInfoList(commentsList)
1✔
674
}
675

676
// DeletePullRequestReviewComments on GitHub
677
func (client *GitHubClient) DeletePullRequestReviewComments(ctx context.Context, owner, repository string, _ int, comments ...CommentInfo) error {
2✔
678
        for _, comment := range comments {
5✔
679
                commentID := comment.ID
3✔
680
                err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "commentID": strconv.FormatInt(commentID, 10)})
3✔
681
                if err != nil {
3✔
682
                        return err
×
683
                }
×
684

685
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
686
                        return client.executeDeletePullRequestReviewComment(ctx, owner, repository, commentID)
3✔
687
                })
3✔
688
                if err != nil {
4✔
689
                        return err
1✔
690
                }
1✔
691

692
        }
693
        return nil
1✔
694
}
695

696
func (client *GitHubClient) executeDeletePullRequestReviewComment(ctx context.Context, owner, repository string, commentID int64) (*github.Response, error) {
3✔
697
        ghResponse, err := client.ghClient.PullRequests.DeleteComment(ctx, owner, repository, commentID)
3✔
698
        if err != nil {
4✔
699
                err = fmt.Errorf("could not delete pull request review comment: %w", err)
1✔
700
        }
1✔
701
        return ghResponse, err
3✔
702
}
703

704
// DeletePullRequestComment on GitHub
705
func (client *GitHubClient) DeletePullRequestComment(ctx context.Context, owner, repository string, _, commentID int) error {
2✔
706
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
2✔
707
        if err != nil {
2✔
708
                return err
×
709
        }
×
710
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
711
                return client.executeDeletePullRequestComment(ctx, owner, repository, commentID)
2✔
712
        })
2✔
713
}
714

715
func (client *GitHubClient) executeDeletePullRequestComment(ctx context.Context, owner, repository string, commentID int) (*github.Response, error) {
2✔
716
        ghResponse, err := client.ghClient.Issues.DeleteComment(ctx, owner, repository, int64(commentID))
2✔
717
        if err != nil {
3✔
718
                return ghResponse, err
1✔
719
        }
1✔
720

721
        var statusCode int
1✔
722
        if ghResponse.Response != nil {
2✔
723
                statusCode = ghResponse.Response.StatusCode
1✔
724
        }
1✔
725
        if statusCode != http.StatusNoContent && statusCode != http.StatusOK {
1✔
726
                return ghResponse, fmt.Errorf("expected %d status code while received %d status code", http.StatusNoContent, ghResponse.Response.StatusCode)
×
727
        }
×
728

729
        return ghResponse, nil
1✔
730
}
731

732
// GetLatestCommit on GitHub
733
func (client *GitHubClient) GetLatestCommit(ctx context.Context, owner, repository, branch string) (CommitInfo, error) {
10✔
734
        commits, err := client.GetCommits(ctx, owner, repository, branch)
10✔
735
        if err != nil {
18✔
736
                return CommitInfo{}, err
8✔
737
        }
8✔
738
        latestCommit := CommitInfo{}
2✔
739
        if len(commits) > 0 {
4✔
740
                latestCommit = commits[0]
2✔
741
        }
2✔
742
        return latestCommit, nil
2✔
743
}
744

745
// GetCommits on GitHub
746
func (client *GitHubClient) GetCommits(ctx context.Context, owner, repository, branch string) ([]CommitInfo, error) {
12✔
747
        err := validateParametersNotBlank(map[string]string{
12✔
748
                "owner":      owner,
12✔
749
                "repository": repository,
12✔
750
                "branch":     branch,
12✔
751
        })
12✔
752
        if err != nil {
16✔
753
                return nil, err
4✔
754
        }
4✔
755

756
        var commitsInfo []CommitInfo
8✔
757
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
16✔
758
                var ghResponse *github.Response
8✔
759
                listOptions := &github.CommitsListOptions{
8✔
760
                        SHA: branch,
8✔
761
                        ListOptions: github.ListOptions{
8✔
762
                                Page:    1,
8✔
763
                                PerPage: vcsutils.NumberOfCommitsToFetch,
8✔
764
                        },
8✔
765
                }
8✔
766
                commitsInfo, ghResponse, err = client.executeGetCommits(ctx, owner, repository, listOptions)
8✔
767
                return ghResponse, err
8✔
768
        })
8✔
769
        return commitsInfo, err
8✔
770
}
771

772
// GetCommitsWithQueryOptions on GitHub
773
func (client *GitHubClient) GetCommitsWithQueryOptions(ctx context.Context, owner, repository string, listOptions GitCommitsQueryOptions) ([]CommitInfo, error) {
2✔
774
        err := validateParametersNotBlank(map[string]string{
2✔
775
                "owner":      owner,
2✔
776
                "repository": repository,
2✔
777
        })
2✔
778
        if err != nil {
2✔
779
                return nil, err
×
780
        }
×
781
        var commitsInfo []CommitInfo
2✔
782
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
783
                var ghResponse *github.Response
2✔
784
                commitsInfo, ghResponse, err = client.executeGetCommits(ctx, owner, repository, convertToGitHubCommitsListOptions(listOptions))
2✔
785
                return ghResponse, err
2✔
786
        })
2✔
787
        return commitsInfo, err
2✔
788
}
789

790
func convertToGitHubCommitsListOptions(listOptions GitCommitsQueryOptions) *github.CommitsListOptions {
2✔
791
        return &github.CommitsListOptions{
2✔
792
                Since: listOptions.Since,
2✔
793
                Until: time.Now(),
2✔
794
                ListOptions: github.ListOptions{
2✔
795
                        Page:    listOptions.Page,
2✔
796
                        PerPage: listOptions.PerPage,
2✔
797
                },
2✔
798
        }
2✔
799
}
2✔
800

801
func (client *GitHubClient) executeGetCommits(ctx context.Context, owner, repository string, listOptions *github.CommitsListOptions) ([]CommitInfo, *github.Response, error) {
10✔
802
        commits, ghResponse, err := client.ghClient.Repositories.ListCommits(ctx, owner, repository, listOptions)
10✔
803
        if err != nil {
16✔
804
                return nil, ghResponse, err
6✔
805
        }
6✔
806

807
        var commitsInfo []CommitInfo
4✔
808
        for _, commit := range commits {
11✔
809
                commitInfo := mapGitHubCommitToCommitInfo(commit)
7✔
810
                commitsInfo = append(commitsInfo, commitInfo)
7✔
811
        }
7✔
812
        return commitsInfo, ghResponse, nil
4✔
813
}
814

815
// GetRepositoryInfo on GitHub
816
func (client *GitHubClient) GetRepositoryInfo(ctx context.Context, owner, repository string) (RepositoryInfo, error) {
6✔
817
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
6✔
818
        if err != nil {
9✔
819
                return RepositoryInfo{}, err
3✔
820
        }
3✔
821

822
        var repo *github.Repository
3✔
823
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
824
                var ghResponse *github.Response
3✔
825
                repo, ghResponse, err = client.ghClient.Repositories.Get(ctx, owner, repository)
3✔
826
                return ghResponse, err
3✔
827
        })
3✔
828
        if err != nil {
4✔
829
                return RepositoryInfo{}, err
1✔
830
        }
1✔
831

832
        return RepositoryInfo{RepositoryVisibility: getGitHubRepositoryVisibility(repo), CloneInfo: CloneInfo{HTTP: repo.GetCloneURL(), SSH: repo.GetSSHURL()}}, nil
2✔
833
}
834

835
// GetCommitBySha on GitHub
836
func (client *GitHubClient) GetCommitBySha(ctx context.Context, owner, repository, sha string) (CommitInfo, error) {
7✔
837
        err := validateParametersNotBlank(map[string]string{
7✔
838
                "owner":      owner,
7✔
839
                "repository": repository,
7✔
840
                "sha":        sha,
7✔
841
        })
7✔
842
        if err != nil {
11✔
843
                return CommitInfo{}, err
4✔
844
        }
4✔
845

846
        var commit *github.RepositoryCommit
3✔
847
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
848
                var ghResponse *github.Response
3✔
849
                commit, ghResponse, err = client.ghClient.Repositories.GetCommit(ctx, owner, repository, sha, nil)
3✔
850
                return ghResponse, err
3✔
851
        })
3✔
852
        if err != nil {
5✔
853
                return CommitInfo{}, err
2✔
854
        }
2✔
855

856
        return mapGitHubCommitToCommitInfo(commit), nil
1✔
857
}
858

859
// CreateLabel on GitHub
860
func (client *GitHubClient) CreateLabel(ctx context.Context, owner, repository string, labelInfo LabelInfo) error {
6✔
861
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "LabelInfo.name": labelInfo.Name})
6✔
862
        if err != nil {
10✔
863
                return err
4✔
864
        }
4✔
865

866
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
867
                var ghResponse *github.Response
2✔
868
                _, ghResponse, err = client.ghClient.Issues.CreateLabel(ctx, owner, repository, &github.Label{
2✔
869
                        Name:        &labelInfo.Name,
2✔
870
                        Description: &labelInfo.Description,
2✔
871
                        Color:       &labelInfo.Color,
2✔
872
                })
2✔
873
                return ghResponse, err
2✔
874
        })
2✔
875
}
876

877
// GetLabel on GitHub
878
func (client *GitHubClient) GetLabel(ctx context.Context, owner, repository, name string) (*LabelInfo, error) {
7✔
879
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "name": name})
7✔
880
        if err != nil {
11✔
881
                return nil, err
4✔
882
        }
4✔
883

884
        var labelInfo *LabelInfo
3✔
885
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
886
                var ghResponse *github.Response
3✔
887
                labelInfo, ghResponse, err = client.executeGetLabel(ctx, owner, repository, name)
3✔
888
                return ghResponse, err
3✔
889
        })
3✔
890
        return labelInfo, err
3✔
891
}
892

893
func (client *GitHubClient) executeGetLabel(ctx context.Context, owner, repository, name string) (*LabelInfo, *github.Response, error) {
3✔
894
        label, ghResponse, err := client.ghClient.Issues.GetLabel(ctx, owner, repository, name)
3✔
895
        if err != nil {
5✔
896
                if ghResponse != nil && ghResponse.Response != nil && ghResponse.Response.StatusCode == http.StatusNotFound {
3✔
897
                        return nil, ghResponse, nil
1✔
898
                }
1✔
899
                return nil, ghResponse, err
1✔
900
        }
901

902
        labelInfo := &LabelInfo{
1✔
903
                Name:        *label.Name,
1✔
904
                Description: *label.Description,
1✔
905
                Color:       *label.Color,
1✔
906
        }
1✔
907
        return labelInfo, ghResponse, nil
1✔
908
}
909

910
// ListPullRequestLabels on GitHub
911
func (client *GitHubClient) ListPullRequestLabels(ctx context.Context, owner, repository string, pullRequestID int) ([]string, error) {
5✔
912
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
5✔
913
        if err != nil {
8✔
914
                return nil, err
3✔
915
        }
3✔
916

917
        results := []string{}
2✔
918
        for nextPage := 0; ; nextPage++ {
4✔
919
                options := &github.ListOptions{Page: nextPage}
2✔
920
                var labels []*github.Label
2✔
921
                var ghResponse *github.Response
2✔
922
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
923
                        labels, ghResponse, err = client.ghClient.Issues.ListLabelsByIssue(ctx, owner, repository, pullRequestID, options)
2✔
924
                        return ghResponse, err
2✔
925
                })
2✔
926
                if err != nil {
3✔
927
                        return nil, err
1✔
928
                }
1✔
929
                for _, label := range labels {
2✔
930
                        results = append(results, *label.Name)
1✔
931
                }
1✔
932
                if nextPage+1 >= ghResponse.LastPage {
2✔
933
                        break
1✔
934
                }
935
        }
936
        return results, nil
1✔
937
}
938

939
func (client *GitHubClient) ListPullRequestsAssociatedWithCommit(ctx context.Context, owner, repository string, commitSHA string) ([]PullRequestInfo, error) {
2✔
940
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
2✔
941
        if err != nil {
2✔
942
                return nil, err
×
943
        }
×
944

945
        var pulls []*github.PullRequest
2✔
946
        if err = client.runWithRateLimitRetries(func() (ghResponse *github.Response, err error) {
4✔
947
                pulls, ghResponse, err = client.ghClient.PullRequests.ListPullRequestsWithCommit(ctx, owner, repository, commitSHA, nil)
2✔
948
                return ghResponse, err
2✔
949
        }); err != nil {
3✔
950
                return nil, err
1✔
951
        }
1✔
952
        return mapGitHubPullRequestToPullRequestInfoList(pulls, false)
1✔
953
}
954

955
// UnlabelPullRequest on GitHub
956
func (client *GitHubClient) UnlabelPullRequest(ctx context.Context, owner, repository, name string, pullRequestID int) error {
5✔
957
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
5✔
958
        if err != nil {
8✔
959
                return err
3✔
960
        }
3✔
961

962
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
963
                return client.ghClient.Issues.RemoveLabelForIssue(ctx, owner, repository, pullRequestID, name)
2✔
964
        })
2✔
965
}
966

967
// UploadCodeScanning to GitHub Security tab
968
func (client *GitHubClient) UploadCodeScanning(ctx context.Context, owner, repository, branch, sarifContent string) (id string, err error) {
2✔
969
        commit, err := client.GetLatestCommit(ctx, owner, repository, branch)
2✔
970
        if err != nil {
3✔
971
                return
1✔
972
        }
1✔
973

974
        commitSHA := commit.Hash
1✔
975
        branch = vcsutils.AddBranchPrefix(branch)
1✔
976
        client.logger.Debug(vcsutils.UploadingCodeScanning, repository, "/", branch)
1✔
977

1✔
978
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
979
                var ghResponse *github.Response
1✔
980
                id, ghResponse, err = client.executeUploadCodeScanning(ctx, owner, repository, branch, commitSHA, sarifContent)
1✔
981
                return ghResponse, err
1✔
982
        })
1✔
983
        return
1✔
984
}
985

986
func (client *GitHubClient) executeUploadCodeScanning(ctx context.Context, owner, repository, branch, commitSHA, sarifContent string) (id string, ghResponse *github.Response, err error) {
1✔
987
        encodedSarif, err := encodeScanningResult(sarifContent)
1✔
988
        if err != nil {
1✔
989
                return
×
990
        }
×
991

992
        sarifID, ghResponse, err := client.ghClient.CodeScanning.UploadSarif(ctx, owner, repository, &github.SarifAnalysis{
1✔
993
                CommitSHA: &commitSHA,
1✔
994
                Ref:       &branch,
1✔
995
                Sarif:     &encodedSarif,
1✔
996
        })
1✔
997

1✔
998
        // According to go-github API - successful ghResponse will return 202 status code
1✔
999
        // The body of the ghResponse will appear in the error, and the Sarif struct will be empty.
1✔
1000
        if err != nil && ghResponse.Response.StatusCode != http.StatusAccepted {
1✔
1001
                return
×
1002
        }
×
1003

1004
        id = extractIdFronSarifIDIfExists(sarifID)
1✔
1005
        return
1✔
1006
}
1007

1008
func extractIdFronSarifIDIfExists(sarifID *github.SarifID) string {
1✔
1009
        if sarifID != nil && *sarifID.ID != "" {
1✔
1010
                return *sarifID.ID
×
1011
        }
×
1012
        return ""
1✔
1013
}
1014

1015
// DownloadFileFromRepo on GitHub
1016
func (client *GitHubClient) DownloadFileFromRepo(ctx context.Context, owner, repository, branch, path string) (content []byte, statusCode int, err error) {
3✔
1017
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
1018
                var ghResponse *github.Response
3✔
1019
                content, statusCode, ghResponse, err = client.executeDownloadFileFromRepo(ctx, owner, repository, branch, path)
3✔
1020
                return ghResponse, err
3✔
1021
        })
3✔
1022

1023
        return
3✔
1024
}
1025

1026
func (client *GitHubClient) executeDownloadFileFromRepo(ctx context.Context, owner, repository, branch, path string) (content []byte, statusCode int, ghResponse *github.Response, err error) {
3✔
1027
        fileContent, _, ghResponse, err := client.ghClient.Repositories.GetContents(ctx, owner, repository, path, &github.RepositoryContentGetOptions{Ref: branch})
3✔
1028
        if ghResponse == nil || ghResponse.Response == nil {
4✔
1029
                return
1✔
1030
        }
1✔
1031

1032
        statusCode = ghResponse.StatusCode
2✔
1033
        if err != nil {
3✔
1034
                if statusCode != http.StatusOK {
2✔
1035
                        err = fmt.Errorf("expected %d status code while received %d status code with error:\n%s", http.StatusOK, ghResponse.StatusCode, err)
1✔
1036
                }
1✔
1037
                return
1✔
1038
        }
1039

1040
        if fileContent != nil {
2✔
1041
                var contentStr string
1✔
1042
                contentStr, err = fileContent.GetContent()
1✔
1043
                if err != nil {
1✔
NEW
1044
                        return
×
NEW
1045
                }
×
1046
                content = []byte(contentStr)
1✔
1047
        }
1048
        return
1✔
1049
}
1050

1051
// GetRepositoryEnvironmentInfo on GitHub
1052
func (client *GitHubClient) GetRepositoryEnvironmentInfo(ctx context.Context, owner, repository, name string) (RepositoryEnvironmentInfo, error) {
2✔
1053
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "name": name})
2✔
1054
        if err != nil {
2✔
1055
                return RepositoryEnvironmentInfo{}, err
×
1056
        }
×
1057

1058
        var repositoryEnvInfo *RepositoryEnvironmentInfo
2✔
1059
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1060
                var ghResponse *github.Response
2✔
1061
                repositoryEnvInfo, ghResponse, err = client.executeGetRepositoryEnvironmentInfo(ctx, owner, repository, name)
2✔
1062
                return ghResponse, err
2✔
1063
        })
2✔
1064
        return *repositoryEnvInfo, err
2✔
1065
}
1066

1067
func (client *GitHubClient) CreateBranch(ctx context.Context, owner, repository, sourceBranch, newBranch string) error {
2✔
1068
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "sourceBranch": sourceBranch, "newBranch": newBranch})
2✔
1069
        if err != nil {
2✔
1070
                return err
×
1071
        }
×
1072

1073
        var sourceBranchRef *github.Reference
2✔
1074
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1075
                sourceBranch = vcsutils.AddBranchPrefix(sourceBranch)
2✔
1076
                sourceBranchRef, _, err = client.ghClient.Git.GetRef(ctx, owner, repository, sourceBranch)
2✔
1077
                if err != nil {
3✔
1078
                        return nil, err
1✔
1079
                }
1✔
1080
                return nil, nil
1✔
1081
        })
1082
        if err != nil {
3✔
1083
                return err
1✔
1084
        }
1✔
1085

1086
        if sourceBranchRef == nil {
1✔
1087
                return fmt.Errorf("failed to get reference for source branch %s", sourceBranch)
×
1088
        }
×
1089
        if sourceBranchRef.Object == nil {
1✔
1090
                return fmt.Errorf("source branch %s reference object is nil", sourceBranch)
×
1091
        }
×
1092

1093
        latestCommitSHA := sourceBranchRef.Object.SHA
1✔
1094
        newBranch = vcsutils.AddBranchPrefix(newBranch)
1✔
1095
        ref := &github.Reference{
1✔
1096
                Ref:    github.Ptr("refs/heads/" + newBranch),
1✔
1097
                Object: &github.GitObject{SHA: latestCommitSHA},
1✔
1098
        }
1✔
1099

1✔
1100
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
1101
                _, _, err = client.ghClient.Git.CreateRef(ctx, owner, repository, ref)
1✔
1102
                if err != nil {
1✔
1103
                        return nil, err
×
1104
                }
×
1105
                return nil, nil
1✔
1106
        })
1107
}
1108

1109
func (client *GitHubClient) AddOrganizationSecret(ctx context.Context, owner, secretName, secretValue string) error {
2✔
1110
        err := validateParametersNotBlank(map[string]string{"secretName": secretName, "owner": owner, "secretValue": secretValue})
2✔
1111
        if err != nil {
2✔
1112
                return err
×
1113
        }
×
1114

1115
        publicKey, _, err := client.ghClient.Actions.GetOrgPublicKey(ctx, owner)
2✔
1116
        if err != nil {
3✔
1117
                return err
1✔
1118
        }
1✔
1119

1120
        encryptedValue, err := encryptSecret(publicKey, secretValue)
1✔
1121
        if err != nil {
1✔
1122
                return err
×
1123
        }
×
1124

1125
        secret := &github.EncryptedSecret{
1✔
1126
                Name:           secretName,
1✔
1127
                KeyID:          publicKey.GetKeyID(),
1✔
1128
                EncryptedValue: encryptedValue,
1✔
1129
                Visibility:     "all",
1✔
1130
        }
1✔
1131

1✔
1132
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
1133
                _, err = client.ghClient.Actions.CreateOrUpdateOrgSecret(ctx, owner, secret)
1✔
1134
                return nil, err
1✔
1135
        })
1✔
1136
        return err
1✔
1137
}
1138

1139
func (client *GitHubClient) CreateOrgVariable(ctx context.Context, owner, variableName, variableValue string) error {
2✔
1140
        err := validateParametersNotBlank(map[string]string{"owner": owner, "variableName": variableName, "variableValue": variableValue})
2✔
1141
        if err != nil {
2✔
1142
                return err
×
1143
        }
×
1144

1145
        variable := &github.ActionsVariable{
2✔
1146
                Name:       variableName,
2✔
1147
                Value:      variableValue,
2✔
1148
                Visibility: github.Ptr("all"),
2✔
1149
        }
2✔
1150

2✔
1151
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1152
                _, err = client.ghClient.Actions.CreateOrgVariable(ctx, owner, variable)
2✔
1153
                return nil, err
2✔
1154
        })
2✔
1155
        return err
2✔
1156
}
1157

1158
func (client *GitHubClient) AllowWorkflows(ctx context.Context, owner string) error {
2✔
1159
        err := validateParametersNotBlank(map[string]string{"owner": owner})
2✔
1160
        if err != nil {
2✔
1161
                return err
×
1162
        }
×
1163

1164
        requestBody := &github.ActionsPermissions{
2✔
1165
                AllowedActions:      github.Ptr("all"),
2✔
1166
                EnabledRepositories: github.Ptr("all"),
2✔
1167
        }
2✔
1168

2✔
1169
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1170
                _, _, err = client.ghClient.Actions.EditActionsPermissions(ctx, owner, *requestBody)
2✔
1171
                return nil, err
2✔
1172
        })
2✔
1173
        return err
2✔
1174
}
1175

1176
func (client *GitHubClient) GetRepoCollaborators(ctx context.Context, owner, repo, affiliation, permission string) ([]string, error) {
2✔
1177
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repo": repo, "affiliation": affiliation, "permission": permission})
2✔
1178
        if err != nil {
2✔
1179
                return nil, err
×
1180
        }
×
1181

1182
        var collaborators []*github.User
2✔
1183
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1184
                var ghResponse *github.Response
2✔
1185
                var err error
2✔
1186
                collaborators, ghResponse, err = client.ghClient.Repositories.ListCollaborators(ctx, owner, repo, &github.ListCollaboratorsOptions{
2✔
1187
                        Affiliation: affiliation,
2✔
1188
                        Permission:  permission,
2✔
1189
                })
2✔
1190
                return ghResponse, err
2✔
1191
        })
2✔
1192
        if err != nil {
3✔
1193
                return nil, err
1✔
1194
        }
1✔
1195

1196
        var names []string
1✔
1197
        for _, collab := range collaborators {
2✔
1198
                names = append(names, collab.GetLogin())
1✔
1199
        }
1✔
1200
        return names, nil
1✔
1201
}
1202

1203
func (client *GitHubClient) GetRepoTeamsByPermissions(ctx context.Context, owner, repo string, permissions []string) ([]int64, error) {
2✔
1204
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repo": repo, "permissions": strings.Join(permissions, ",")})
2✔
1205
        if err != nil {
2✔
1206
                return nil, err
×
1207
        }
×
1208

1209
        var allTeams []*github.Team
2✔
1210
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1211
                var resp *github.Response
2✔
1212
                var err error
2✔
1213
                allTeams, resp, err = client.ghClient.Repositories.ListTeams(ctx, owner, repo, nil)
2✔
1214
                return resp, err
2✔
1215
        })
2✔
1216
        if err != nil {
3✔
1217
                return nil, err
1✔
1218
        }
1✔
1219

1220
        permMap := make(map[string]bool)
1✔
1221
        for _, p := range permissions {
2✔
1222
                permMap[strings.ToLower(p)] = true
1✔
1223
        }
1✔
1224

1225
        var matchedTeams []int64
1✔
1226
        for _, team := range allTeams {
2✔
1227
                if permMap[strings.ToLower(team.GetPermission())] {
2✔
1228
                        matchedTeams = append(matchedTeams, team.GetID())
1✔
1229
                }
1✔
1230
        }
1231

1232
        return matchedTeams, nil
1✔
1233
}
1234

1235
func (client *GitHubClient) CreateOrUpdateEnvironment(ctx context.Context, owner, repo, envName string, teams []int64, users []string) error {
2✔
1236
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repo": repo, "envName": envName})
2✔
1237
        if err != nil {
2✔
1238
                return err
×
1239
        }
×
1240

1241
        var envReviewers []*github.EnvReviewers
2✔
1242
        for _, team := range teams {
4✔
1243
                envReviewers = append(envReviewers, &github.EnvReviewers{
2✔
1244
                        Type: github.Ptr("Team"),
2✔
1245
                        ID:   &team,
2✔
1246
                })
2✔
1247
        }
2✔
1248

1249
        if len(envReviewers) >= ghMaxEnvReviewers {
2✔
1250
                envReviewers = envReviewers[:ghMaxEnvReviewers]
×
1251
                _, _, err := client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
×
1252
                        Reviewers: envReviewers,
×
1253
                })
×
1254
                return err
×
1255
        }
×
1256

1257
        for _, userName := range users {
2✔
1258
                user, _, err := client.ghClient.Users.Get(ctx, userName)
×
1259

×
1260
                if err != nil {
×
1261
                        return err
×
1262
                }
×
1263
                userId := user.GetID()
×
1264
                envReviewers = append(envReviewers, &github.EnvReviewers{
×
NEW
1265
                        Type: github.Ptr("User"),
×
NEW
1266
                        ID:   github.Ptr(userId),
×
UNCOV
1267
                })
×
1268
        }
1269

1270
        if len(envReviewers) >= ghMaxEnvReviewers {
2✔
1271
                envReviewers = envReviewers[:ghMaxEnvReviewers]
×
1272
                _, _, err := client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
×
1273
                        Reviewers: envReviewers,
×
1274
                })
×
1275
                return err
×
1276
        }
×
1277

1278
        _, _, err = client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
2✔
1279
                Reviewers: envReviewers,
2✔
1280
        })
2✔
1281
        return err
2✔
1282
}
1283

1284
func (client *GitHubClient) CommitAndPushFiles(
1285
        ctx context.Context,
1286
        owner, repo, sourceBranch, commitMessage, authorName, authorEmail string,
1287
        files []FileToCommit,
1288
) error {
2✔
1289
        if len(files) == 0 {
2✔
1290
                return errors.New("no files provided to commit")
×
1291
        }
×
1292

1293
        if len(files) == 1 {
2✔
1294
                client.logger.Debug("Using Contents API for single file commit")
×
1295
                return client.commitSingleFile(ctx, owner, repo, sourceBranch, files[0], commitMessage, authorName, authorEmail)
×
1296
        }
×
1297

1298
        client.logger.Debug("Using Git API for ", len(files), " file commit")
2✔
1299
        return client.commitMultipleFiles(ctx, owner, repo, sourceBranch, files, commitMessage, authorName, authorEmail)
2✔
1300
}
1301

1302
func (client *GitHubClient) commitSingleFile(
1303
        ctx context.Context,
1304
        owner, repo, branch string,
1305
        file FileToCommit,
1306
        commitMessage, authorName, authorEmail string,
1307
) error {
×
1308
        encodedContent := base64Utils.StdEncoding.EncodeToString([]byte(file.Content))
×
1309

×
1310
        fileOptions := &github.RepositoryContentFileOptions{
×
1311
                Message: &commitMessage,
×
1312
                Content: []byte(encodedContent),
×
1313
                Branch:  &branch,
×
1314
                Author: &github.CommitAuthor{
×
1315
                        Name:  &authorName,
×
1316
                        Email: &authorEmail,
×
1317
                },
×
1318
                Committer: &github.CommitAuthor{
×
1319
                        Name:  &authorName,
×
1320
                        Email: &authorEmail,
×
1321
                },
×
1322
        }
×
1323

×
1324
        err := client.runWithRateLimitRetries(func() (*github.Response, error) {
×
1325
                _, ghResponse, err := client.ghClient.Repositories.CreateFile(ctx, owner, repo, file.Path, fileOptions)
×
1326
                return ghResponse, err
×
1327
        })
×
1328

1329
        if err != nil {
×
1330
                return fmt.Errorf("failed to commit single file %s: %w", file.Path, err)
×
1331
        }
×
1332
        return nil
×
1333
}
1334

1335
func (client *GitHubClient) commitMultipleFiles(
1336
        ctx context.Context,
1337
        owner, repo, sourceBranch string,
1338
        files []FileToCommit,
1339
        commitMessage, authorName, authorEmail string,
1340
) error {
2✔
1341
        ref, _, err := client.ghClient.Git.GetRef(ctx, owner, repo, "refs/heads/"+sourceBranch)
2✔
1342
        if err != nil {
3✔
1343
                return fmt.Errorf("failed to get branch ref: %w", err)
1✔
1344
        }
1✔
1345

1346
        parentCommit, _, err := client.ghClient.Git.GetCommit(ctx, owner, repo, *ref.Object.SHA)
1✔
1347
        if err != nil {
1✔
1348
                return fmt.Errorf("failed to get parent commit: %w", err)
×
1349
        }
×
1350

1351
        treeEntries, err := client.createBlobs(ctx, owner, repo, files)
1✔
1352
        if err != nil {
1✔
1353
                return err
×
1354
        }
×
1355

1356
        tree, _, err := client.ghClient.Git.CreateTree(ctx, owner, repo, *parentCommit.Tree.SHA, treeEntries)
1✔
1357
        if err != nil {
1✔
1358
                return fmt.Errorf("failed to create tree: %w", err)
×
1359
        }
×
1360

1361
        commit := &github.Commit{
1✔
1362
                Message: github.Ptr(commitMessage),
1✔
1363
                Tree:    tree,
1✔
1364
                Parents: []*github.Commit{{SHA: parentCommit.SHA}},
1✔
1365
                Author: &github.CommitAuthor{
1✔
1366
                        Name:  github.Ptr(authorName),
1✔
1367
                        Email: github.Ptr(authorEmail),
1✔
1368
                        Date:  &github.Timestamp{Time: time.Now()},
1✔
1369
                },
1✔
1370
        }
1✔
1371

1✔
1372
        newCommit, _, err := client.ghClient.Git.CreateCommit(ctx, owner, repo, commit, nil)
1✔
1373
        if err != nil {
1✔
1374
                return fmt.Errorf("failed to create commit: %w", err)
×
1375
        }
×
1376

1377
        ref.Object.SHA = newCommit.SHA
1✔
1378
        _, _, err = client.ghClient.Git.UpdateRef(ctx, owner, repo, ref, false)
1✔
1379
        if err != nil {
1✔
1380
                return fmt.Errorf("failed to update branch ref: %w", err)
×
1381
        }
×
1382
        return nil
1✔
1383
}
1384

1385
func (client *GitHubClient) createBlobs(ctx context.Context, owner, repo string, files []FileToCommit) ([]*github.TreeEntry, error) {
1✔
1386
        var treeEntries []*github.TreeEntry
1✔
1387
        for _, file := range files {
3✔
1388
                var blob *github.Blob
2✔
1389
                err := client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1390
                        var ghResponse *github.Response
2✔
1391
                        var err error
2✔
1392
                        blob, ghResponse, err = client.ghClient.Git.CreateBlob(ctx, owner, repo, &github.Blob{
2✔
1393
                                Content:  github.Ptr(file.Content),
2✔
1394
                                Encoding: github.Ptr("utf-8"),
2✔
1395
                        })
2✔
1396
                        return ghResponse, err
2✔
1397
                })
2✔
1398
                if err != nil {
2✔
1399
                        return nil, fmt.Errorf("failed to create blob for %s: %w", file.Path, err)
×
1400
                }
×
1401

1402
                treeEntries = append(treeEntries, &github.TreeEntry{
2✔
1403
                        Path: github.Ptr(file.Path),
2✔
1404
                        Mode: github.Ptr(regularFileCode),
2✔
1405
                        Type: github.Ptr("blob"),
2✔
1406
                        SHA:  blob.SHA,
2✔
1407
                })
2✔
1408
        }
1409

1410
        return treeEntries, nil
1✔
1411
}
1412

1413
func (client *GitHubClient) MergePullRequest(ctx context.Context, owner, repo string, prNumber int, commitMessage string) error {
2✔
1414
        err := client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1415
                _, resp, err := client.ghClient.PullRequests.Merge(ctx, owner, repo, prNumber, commitMessage, nil)
2✔
1416
                return resp, err
2✔
1417
        })
2✔
1418
        return err
2✔
1419
}
1420

1421
func (client *GitHubClient) executeGetRepositoryEnvironmentInfo(ctx context.Context, owner, repository, name string) (*RepositoryEnvironmentInfo, *github.Response, error) {
2✔
1422
        environment, ghResponse, err := client.ghClient.Repositories.GetEnvironment(ctx, owner, repository, name)
2✔
1423
        if err != nil {
3✔
1424
                return &RepositoryEnvironmentInfo{}, ghResponse, err
1✔
1425
        }
1✔
1426

1427
        if err = vcsutils.CheckResponseStatusWithBody(ghResponse.Response, http.StatusOK); err != nil {
1✔
1428
                return &RepositoryEnvironmentInfo{}, ghResponse, err
×
1429
        }
×
1430

1431
        reviewers, err := extractGitHubEnvironmentReviewers(environment)
1✔
1432
        if err != nil {
1✔
1433
                return &RepositoryEnvironmentInfo{}, ghResponse, err
×
1434
        }
×
1435

1436
        return &RepositoryEnvironmentInfo{
1✔
1437
                        Name:      environment.GetName(),
1✔
1438
                        Url:       environment.GetURL(),
1✔
1439
                        Reviewers: reviewers,
1✔
1440
                },
1✔
1441
                ghResponse,
1✔
1442
                nil
1✔
1443
}
1444

1445
func (client *GitHubClient) GetModifiedFiles(ctx context.Context, owner, repository, refBefore, refAfter string) ([]string, error) {
6✔
1446
        err := validateParametersNotBlank(map[string]string{
6✔
1447
                "owner":      owner,
6✔
1448
                "repository": repository,
6✔
1449
                "refBefore":  refBefore,
6✔
1450
                "refAfter":   refAfter,
6✔
1451
        })
6✔
1452
        if err != nil {
10✔
1453
                return nil, err
4✔
1454
        }
4✔
1455

1456
        var fileNamesList []string
2✔
1457
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1458
                var ghResponse *github.Response
2✔
1459
                fileNamesList, ghResponse, err = client.executeGetModifiedFiles(ctx, owner, repository, refBefore, refAfter)
2✔
1460
                return ghResponse, err
2✔
1461
        })
2✔
1462
        return fileNamesList, err
2✔
1463
}
1464

1465
func (client *GitHubClient) executeGetModifiedFiles(ctx context.Context, owner, repository, refBefore, refAfter string) ([]string, *github.Response, error) {
2✔
1466
        // According to the https://docs.github.com/en/rest/commits/commits?apiVersion=2022-11-28#compare-two-commits
2✔
1467
        // the list of changed files is always returned with the first page fully,
2✔
1468
        // so we don't need to iterate over other pages to get additional info about the files.
2✔
1469
        // And we also do not need info about the change that is why we can limit only to a single entity.
2✔
1470
        listOptions := &github.ListOptions{PerPage: 1}
2✔
1471

2✔
1472
        comparison, ghResponse, err := client.ghClient.Repositories.CompareCommits(ctx, owner, repository, refBefore, refAfter, listOptions)
2✔
1473
        if err != nil {
3✔
1474
                return nil, ghResponse, err
1✔
1475
        }
1✔
1476

1477
        if err = vcsutils.CheckResponseStatusWithBody(ghResponse.Response, http.StatusOK); err != nil {
1✔
1478
                return nil, ghResponse, err
×
1479
        }
×
1480

1481
        fileNamesSet := datastructures.MakeSet[string]()
1✔
1482
        for _, file := range comparison.Files {
18✔
1483
                fileNamesSet.Add(vcsutils.DefaultIfNotNil(file.Filename))
17✔
1484
                fileNamesSet.Add(vcsutils.DefaultIfNotNil(file.PreviousFilename))
17✔
1485
        }
17✔
1486

1487
        _ = fileNamesSet.Remove("") // Make sure there are no blank filepath.
1✔
1488
        fileNamesList := fileNamesSet.ToSlice()
1✔
1489
        sort.Strings(fileNamesList)
1✔
1490

1✔
1491
        return fileNamesList, ghResponse, nil
1✔
1492
}
1493

1494
// Extract code reviewers from environment
1495
func extractGitHubEnvironmentReviewers(environment *github.Environment) ([]string, error) {
2✔
1496
        var reviewers []string
2✔
1497
        protectionRules := environment.ProtectionRules
2✔
1498
        if protectionRules == nil {
2✔
1499
                return reviewers, nil
×
1500
        }
×
1501
        reviewerStruct := repositoryEnvironmentReviewer{}
2✔
1502
        for _, rule := range protectionRules {
4✔
1503
                for _, reviewer := range rule.Reviewers {
5✔
1504
                        if err := mapstructure.Decode(reviewer.Reviewer, &reviewerStruct); err != nil {
3✔
1505
                                return []string{}, err
×
1506
                        }
×
1507
                        reviewers = append(reviewers, reviewerStruct.Login)
3✔
1508
                }
1509
        }
1510
        return reviewers, nil
2✔
1511
}
1512

1513
func createGitHubHook(token, payloadURL string, webhookEvents ...vcsutils.WebhookEvent) *github.Hook {
4✔
1514
        contentType := "json"
4✔
1515
        return &github.Hook{
4✔
1516
                Events: getGitHubWebhookEvents(webhookEvents...),
4✔
1517
                Config: &github.HookConfig{
4✔
1518
                        ContentType: &contentType,
4✔
1519
                        URL:         &payloadURL,
4✔
1520
                        Secret:      &token,
4✔
1521
                },
4✔
1522
        }
4✔
1523
}
4✔
1524

1525
// Get varargs of webhook events and return a slice of GitHub webhook events
1526
func getGitHubWebhookEvents(webhookEvents ...vcsutils.WebhookEvent) []string {
4✔
1527
        events := datastructures.MakeSet[string]()
4✔
1528
        for _, event := range webhookEvents {
16✔
1529
                switch event {
12✔
1530
                case vcsutils.PrOpened, vcsutils.PrEdited, vcsutils.PrMerged, vcsutils.PrRejected:
8✔
1531
                        events.Add("pull_request")
8✔
1532
                case vcsutils.Push, vcsutils.TagPushed, vcsutils.TagRemoved:
4✔
1533
                        events.Add("push")
4✔
1534
                }
1535
        }
1536
        return events.ToSlice()
4✔
1537
}
1538

1539
func getGitHubRepositoryVisibility(repo *github.Repository) RepositoryVisibility {
5✔
1540
        switch *repo.Visibility {
5✔
1541
        case "public":
3✔
1542
                return Public
3✔
1543
        case "internal":
1✔
1544
                return Internal
1✔
1545
        default:
1✔
1546
                return Private
1✔
1547
        }
1548
}
1549

1550
func getGitHubCommitState(commitState CommitStatus) string {
7✔
1551
        switch commitState {
7✔
1552
        case Pass:
1✔
1553
                return "success"
1✔
1554
        case Fail:
1✔
1555
                return "failure"
1✔
1556
        case Error:
3✔
1557
                return "error"
3✔
1558
        case InProgress:
1✔
1559
                return "pending"
1✔
1560
        }
1561
        return ""
1✔
1562
}
1563

1564
func mapGitHubCommitToCommitInfo(commit *github.RepositoryCommit) CommitInfo {
8✔
1565
        parents := make([]string, len(commit.Parents))
8✔
1566
        for i, c := range commit.Parents {
15✔
1567
                parents[i] = c.GetSHA()
7✔
1568
        }
7✔
1569
        details := commit.GetCommit()
8✔
1570
        return CommitInfo{
8✔
1571
                Hash:          commit.GetSHA(),
8✔
1572
                AuthorName:    details.GetAuthor().GetName(),
8✔
1573
                CommitterName: details.GetCommitter().GetName(),
8✔
1574
                Url:           commit.GetURL(),
8✔
1575
                Timestamp:     details.GetCommitter().GetDate().UTC().Unix(),
8✔
1576
                Message:       details.GetMessage(),
8✔
1577
                ParentHashes:  parents,
8✔
1578
                AuthorEmail:   details.GetAuthor().GetEmail(),
8✔
1579
        }
8✔
1580
}
1581

1582
func mapGitHubIssuesCommentToCommentInfoList(commentsList []*github.IssueComment) (res []CommentInfo, err error) {
1✔
1583
        for _, comment := range commentsList {
3✔
1584
                res = append(res, CommentInfo{
2✔
1585
                        ID:      comment.GetID(),
2✔
1586
                        Content: comment.GetBody(),
2✔
1587
                        Created: comment.GetCreatedAt().Time,
2✔
1588
                })
2✔
1589
        }
2✔
1590
        return
1✔
1591
}
1592

1593
func mapGitHubPullRequestToPullRequestInfoList(pullRequestList []*github.PullRequest, withBody bool) (res []PullRequestInfo, err error) {
3✔
1594
        var mappedPullRequest PullRequestInfo
3✔
1595
        for _, pullRequest := range pullRequestList {
6✔
1596
                mappedPullRequest, err = mapGitHubPullRequestToPullRequestInfo(pullRequest, withBody)
3✔
1597
                if err != nil {
3✔
1598
                        return
×
1599
                }
×
1600
                res = append(res, mappedPullRequest)
3✔
1601
        }
1602
        return
3✔
1603
}
1604

1605
func encodeScanningResult(data string) (string, error) {
1✔
1606
        compressedScan, err := base64.EncodeGzip([]byte(data), 6)
1✔
1607
        if err != nil {
1✔
1608
                return "", err
×
1609
        }
×
1610

1611
        return compressedScan, err
1✔
1612
}
1613

1614
type repositoryEnvironmentReviewer struct {
1615
        Login string `mapstructure:"login"`
1616
}
1617

1618
func shouldRetryIfRateLimitExceeded(ghResponse *github.Response, requestError error) bool {
117✔
1619
        if ghResponse == nil || ghResponse.Response == nil {
168✔
1620
                return false
51✔
1621
        }
51✔
1622

1623
        if !slices.Contains(rateLimitRetryStatuses, ghResponse.StatusCode) {
130✔
1624
                return false
64✔
1625
        }
64✔
1626

1627
        // In case of encountering a rate limit abuse, it's advisable to observe a considerate delay before attempting a retry.
1628
        // This prevents immediate retries within the current sequence, allowing a respectful interval before reattempting the request.
1629
        if requestError != nil && isRateLimitAbuseError(requestError) {
3✔
1630
                return false
1✔
1631
        }
1✔
1632

1633
        body, err := io.ReadAll(ghResponse.Body)
1✔
1634
        if err != nil {
1✔
1635
                return false
×
1636
        }
×
1637
        return strings.Contains(string(body), "rate limit")
1✔
1638
}
1639

1640
func isRateLimitAbuseError(requestError error) bool {
4✔
1641
        var abuseRateLimitError *github.AbuseRateLimitError
4✔
1642
        var rateLimitError *github.RateLimitError
4✔
1643
        return errors.As(requestError, &abuseRateLimitError) || errors.As(requestError, &rateLimitError)
4✔
1644
}
4✔
1645

1646
func encryptSecret(publicKey *github.PublicKey, secretValue string) (string, error) {
1✔
1647
        publicKeyBytes, err := base64Utils.StdEncoding.DecodeString(publicKey.GetKey())
1✔
1648
        if err != nil {
1✔
1649
                return "", err
×
1650
        }
×
1651

1652
        var publicKeyDecoded [32]byte
1✔
1653
        copy(publicKeyDecoded[:], publicKeyBytes)
1✔
1654

1✔
1655
        encrypted, err := box.SealAnonymous(nil, []byte(secretValue), &publicKeyDecoded, rand.Reader)
1✔
1656
        if err != nil {
1✔
1657
                return "", err
×
1658
        }
×
1659

1660
        encryptedBase64 := base64Utils.StdEncoding.EncodeToString(encrypted)
1✔
1661
        return encryptedBase64, nil
1✔
1662
}
1663

1664
func (client *GitHubClient) ListAppRepositories(ctx context.Context) ([]AppRepositoryInfo, error) {
2✔
1665
        var results []AppRepositoryInfo
2✔
1666

2✔
1667
        var allRepositories []*github.Repository
2✔
1668
        for nextPage := 1; ; nextPage++ {
4✔
1669
                var repositoriesInPage *github.ListRepositories
2✔
1670
                var ghResponse *github.Response
2✔
1671
                var err error
2✔
1672
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1673
                        repositoriesInPage, ghResponse, err = client.ghClient.Apps.ListRepos(ctx, &github.ListOptions{Page: nextPage})
2✔
1674
                        return ghResponse, err
2✔
1675
                })
2✔
1676
                if err != nil {
3✔
1677
                        return nil, err
1✔
1678
                }
1✔
1679
                allRepositories = append(allRepositories, repositoriesInPage.Repositories...)
1✔
1680
                if nextPage+1 > ghResponse.LastPage {
2✔
1681
                        break
1✔
1682
                }
1683
        }
1684

1685
        for _, repo := range allRepositories {
2✔
1686
                if repo == nil || repo.Owner == nil || repo.Owner.Login == nil || repo.Name == nil {
1✔
1687
                        continue
×
1688
                }
1689
                repoInfo := AppRepositoryInfo{
1✔
1690
                        ID:            repo.GetID(),
1✔
1691
                        Name:          vcsutils.DefaultIfNotNil(repo.Name),
1✔
1692
                        FullName:      vcsutils.DefaultIfNotNil(repo.FullName),
1✔
1693
                        Owner:         vcsutils.DefaultIfNotNil(repo.Owner.Login),
1✔
1694
                        Private:       repo.GetPrivate(),
1✔
1695
                        Description:   vcsutils.DefaultIfNotNil(repo.Description),
1✔
1696
                        URL:           vcsutils.DefaultIfNotNil(repo.HTMLURL),
1✔
1697
                        CloneURL:      vcsutils.DefaultIfNotNil(repo.CloneURL),
1✔
1698
                        SSHURL:        vcsutils.DefaultIfNotNil(repo.SSHURL),
1✔
1699
                        DefaultBranch: vcsutils.DefaultIfNotNil(repo.DefaultBranch),
1✔
1700
                }
1✔
1701
                results = append(results, repoInfo)
1✔
1702
        }
1703

1704
        return results, nil
1✔
1705
}
1706
func (client *GitHubClient) UploadSnapshotToDependencyGraph(ctx context.Context, owner, repo string, snapshot *SbomSnapshot) error {
2✔
1707
        if snapshot == nil {
2✔
1708
                return fmt.Errorf("provided snapshot is nil")
×
1709
        }
×
1710

1711
        ghSnapshot, err := convertToGitHubSnapshot(snapshot)
2✔
1712
        if err != nil {
2✔
1713
                return fmt.Errorf("failed to convert snapshot to GitHub format: %w", err)
×
1714
        }
×
1715

1716
        var ghResponse *github.Response
2✔
1717
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1718
                _, ghResponse, err = client.ghClient.DependencyGraph.CreateSnapshot(ctx, owner, repo, ghSnapshot)
2✔
1719
                return ghResponse, err
2✔
1720
        })
2✔
1721

1722
        if err != nil {
3✔
1723
                return fmt.Errorf("failed to upload snapshot to dependency graph: %w", err)
1✔
1724
        }
1✔
1725

1726
        if ghResponse == nil || ghResponse.Response == nil || ghResponse.Response.StatusCode != http.StatusCreated {
1✔
1727
                return fmt.Errorf("dependency submission call finished with unexpected status code: %d", ghResponse.Response.StatusCode)
×
1728
        }
×
1729

1730
        client.logger.Info(vcsutils.SuccessfulSnapshotUpload, ghResponse.StatusCode)
1✔
1731
        return nil
1✔
1732
}
1733

1734
func convertToGitHubSnapshot(snapshot *SbomSnapshot) (*github.DependencyGraphSnapshot, error) {
2✔
1735
        ghSnapshot := &github.DependencyGraphSnapshot{
2✔
1736
                Version: snapshot.Version,
2✔
1737
                Sha:     &snapshot.Sha,
2✔
1738
                Ref:     &snapshot.Ref,
2✔
1739
                Scanned: &github.Timestamp{Time: snapshot.Scanned}, // Use current time if not provided
2✔
1740
        }
2✔
1741

2✔
1742
        if snapshot.Job == nil {
2✔
1743
                return nil, fmt.Errorf("job information is required in the snapshot")
×
1744
        }
×
1745
        ghSnapshot.Job = &github.DependencyGraphSnapshotJob{
2✔
1746
                Correlator: &snapshot.Job.Correlator,
2✔
1747
                ID:         &snapshot.Job.ID,
2✔
1748
        }
2✔
1749

2✔
1750
        if snapshot.Detector == nil {
2✔
1751
                return nil, fmt.Errorf("detector information is required in the snapshot")
×
1752
        }
×
1753
        ghSnapshot.Detector = &github.DependencyGraphSnapshotDetector{
2✔
1754
                Name:    &snapshot.Detector.Name,
2✔
1755
                Version: &snapshot.Detector.Version,
2✔
1756
                URL:     &snapshot.Detector.Url,
2✔
1757
        }
2✔
1758

2✔
1759
        if len(snapshot.Manifests) == 0 {
2✔
1760
                return nil, fmt.Errorf("at least one manifest is required in the snapshot")
×
1761
        }
×
1762
        ghSnapshot.Manifests = make(map[string]*github.DependencyGraphSnapshotManifest)
2✔
1763
        for manifestName, manifest := range snapshot.Manifests {
4✔
1764
                ghManifest := &github.DependencyGraphSnapshotManifest{
2✔
1765
                        Name: &manifest.Name,
2✔
1766
                }
2✔
1767

2✔
1768
                if manifest.File == nil {
2✔
1769
                        return nil, fmt.Errorf("manifest '%s' is missing file information", manifestName)
×
1770
                }
×
1771
                ghManifest.File = &github.DependencyGraphSnapshotManifestFile{SourceLocation: &manifest.File.SourceLocation}
2✔
1772

2✔
1773
                if len(manifest.Resolved) == 0 {
2✔
1774
                        return nil, fmt.Errorf("manifest '%s' must have at least one resolved dependency", manifestName)
×
1775
                }
×
1776
                ghManifest.Resolved = make(map[string]*github.DependencyGraphSnapshotResolvedDependency)
2✔
1777
                for depName, dep := range manifest.Resolved {
8✔
1778
                        ghDep := &github.DependencyGraphSnapshotResolvedDependency{
6✔
1779
                                PackageURL:   &dep.PackageURL,
6✔
1780
                                Dependencies: dep.Dependencies,
6✔
1781
                                Relationship: &dep.Relationship,
6✔
1782
                        }
6✔
1783
                        ghManifest.Resolved[depName] = ghDep
6✔
1784
                }
6✔
1785

1786
                ghSnapshot.Manifests[manifestName] = ghManifest
2✔
1787
        }
1788
        return ghSnapshot, nil
2✔
1789
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc