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

jfrog / froggit-go / 16776401171

06 Aug 2025 12:05PM UTC coverage: 84.143% (-0.5%) from 84.627%
16776401171

push

github

web-flow
improved `CreateBranch` and `CommitAndPushFiles` performance  (#163)

34 of 69 new or added lines in 1 file covered. (49.28%)

1 existing line in 1 file now uncovered.

4521 of 5373 relevant lines covered (84.14%)

6.35 hits per line

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

85.4
/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/v62/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) {
145✔
65
        ghClient, err := buildGithubClient(vcsInfo, logger)
145✔
66
        if err != nil {
145✔
67
                return nil, err
×
68
        }
×
69
        return &GitHubClient{
145✔
70
                        vcsInfo:  vcsInfo,
145✔
71
                        logger:   logger,
145✔
72
                        ghClient: ghClient,
145✔
73
                        rateLimitRetryExecutor: GitHubRateLimitRetryExecutor{RetryExecutor: vcsutils.RetryExecutor{
145✔
74
                                Logger:                   logger,
145✔
75
                                MaxRetries:               maxRetries,
145✔
76
                                RetriesIntervalMilliSecs: retriesIntervalMilliSecs},
145✔
77
                        }},
145✔
78
                nil
145✔
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) {
145✔
93
        httpClient := &http.Client{}
145✔
94
        if vcsInfo.Token != "" {
206✔
95
                httpClient = oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(&oauth2.Token{AccessToken: vcsInfo.Token}))
61✔
96
        }
61✔
97
        ghClient := github.NewClient(httpClient)
145✔
98
        if vcsInfo.APIEndpoint != "" {
256✔
99
                baseURL, err := url.Parse(strings.TrimSuffix(vcsInfo.APIEndpoint, "/") + "/")
111✔
100
                if err != nil {
111✔
101
                        return nil, err
×
102
                }
×
103
                logger.Info("Using API endpoint:", baseURL)
111✔
104
                ghClient.BaseURL = baseURL
111✔
105
        }
106
        return ghClient, nil
145✔
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
        body, ghResponse, err := client.ghClient.Repositories.DownloadContents(ctx, owner, repository, path, &github.RepositoryContentGetOptions{Ref: branch})
3✔
1028
        defer func() {
6✔
1029
                if body != nil {
4✔
1030
                        err = errors.Join(err, body.Close())
1✔
1031
                }
1✔
1032
        }()
1033

1034
        if ghResponse == nil || ghResponse.Response == nil {
4✔
1035
                return
1✔
1036
        }
1✔
1037

1038
        statusCode = ghResponse.StatusCode
2✔
1039
        if err != nil && statusCode != http.StatusOK {
2✔
1040
                err = fmt.Errorf("expected %d status code while received %d status code with error:\n%s", http.StatusOK, ghResponse.StatusCode, err)
×
1041
                return
×
1042
        }
×
1043

1044
        if body != nil {
3✔
1045
                content, err = io.ReadAll(body)
1✔
1046
        }
1✔
1047
        return
2✔
1048
}
1049

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1231
        return matchedTeams, nil
1✔
1232
}
1233

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1409
        return treeEntries, nil
1✔
1410
}
1411

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1610
        return compressedScan, err
1✔
1611
}
1612

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1785
                ghSnapshot.Manifests[manifestName] = ghManifest
2✔
1786
        }
1787
        return ghSnapshot, nil
2✔
1788
}
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