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

jfrog / froggit-go / 15294156338

28 May 2025 07:27AM UTC coverage: 85.319% (-2.4%) from 87.758%
15294156338

push

github

web-flow
Added support for all needed functions of global installation of Frogbot (#153)

174 of 324 new or added lines in 5 files covered. (53.7%)

207 existing lines in 6 files now uncovered.

4376 of 5129 relevant lines covered (85.32%)

6.49 hits per line

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

87.03
/vcsclient/github.go
1
package vcsclient
2

3
import (
4
        "context"
5
        "crypto/rand"
6
        base64Utils "encoding/base64"
7
        "encoding/json"
8
        "errors"
9
        "fmt"
10
        "github.com/google/go-github/v56/github"
11
        "github.com/grokify/mogo/encoding/base64"
12
        "github.com/jfrog/froggit-go/vcsutils"
13
        "github.com/jfrog/gofrog/datastructures"
14
        "github.com/mitchellh/mapstructure"
15
        "golang.org/x/crypto/nacl/box"
16
        "golang.org/x/exp/slices"
17
        "golang.org/x/oauth2"
18
        "io"
19
        "net/http"
20
        "net/url"
21
        "path/filepath"
22
        "sort"
23
        "strconv"
24
        "strings"
25
        "time"
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 {
103✔
48
        ghe.ExecutionHandler = func() (bool, error) {
206✔
49
                ghResponse, err := ghe.GitHubRateLimitExecutionHandler()
103✔
50
                return shouldRetryIfRateLimitExceeded(ghResponse, err), err
103✔
51
        }
103✔
52
        return ghe.RetryExecutor.Execute()
103✔
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) {
137✔
65
        ghClient, err := buildGithubClient(vcsInfo, logger)
137✔
66
        if err != nil {
137✔
67
                return nil, err
×
68
        }
×
69
        return &GitHubClient{
137✔
70
                        vcsInfo:  vcsInfo,
137✔
71
                        logger:   logger,
137✔
72
                        ghClient: ghClient,
137✔
73
                        rateLimitRetryExecutor: GitHubRateLimitRetryExecutor{RetryExecutor: vcsutils.RetryExecutor{
137✔
74
                                Logger:                   logger,
137✔
75
                                MaxRetries:               maxRetries,
137✔
76
                                RetriesIntervalMilliSecs: retriesIntervalMilliSecs},
137✔
77
                        }},
137✔
78
                nil
137✔
79
}
80

81
func (client *GitHubClient) runWithRateLimitRetries(handler func() (*github.Response, error)) error {
103✔
82
        client.rateLimitRetryExecutor.GitHubRateLimitExecutionHandler = handler
103✔
83
        return client.rateLimitRetryExecutor.Execute()
103✔
84
}
103✔
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) {
137✔
93
        httpClient := &http.Client{}
137✔
94
        if vcsInfo.Token != "" {
194✔
95
                httpClient = oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(&oauth2.Token{AccessToken: vcsInfo.Token}))
57✔
96
        }
57✔
97
        ghClient := github.NewClient(httpClient)
137✔
98
        if vcsInfo.APIEndpoint != "" {
240✔
99
                baseURL, err := url.Parse(strings.TrimSuffix(vcsInfo.APIEndpoint, "/") + "/")
103✔
100
                if err != nil {
103✔
101
                        return nil, err
×
102
                }
×
103
                logger.Info("Using API endpoint:", baseURL)
103✔
104
                ghClient.BaseURL = baseURL
103✔
105
        }
106
        return ghClient, nil
137✔
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.RepositoryListOptions{ListOptions: github.ListOptions{Page: page}}
6✔
160
        return client.ghClient.Repositories.List(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
                return client.executeCreatePullRequest(ctx, owner, repository, sourceBranch, targetBranch, title, description)
2✔
345
        })
2✔
346
}
347

348
func (client *GitHubClient) executeCreatePullRequest(ctx context.Context, owner, repository, sourceBranch, targetBranch, title, description string) (*github.Response, error) {
2✔
349
        head := owner + ":" + sourceBranch
2✔
350
        client.logger.Debug(vcsutils.CreatingPullRequest, title)
2✔
351

2✔
352
        _, ghResponse, err := client.ghClient.PullRequests.Create(ctx, owner, repository, &github.NewPullRequest{
2✔
353
                Title: &title,
2✔
354
                Body:  &description,
2✔
355
                Head:  &head,
2✔
356
                Base:  &targetBranch,
2✔
357
        })
2✔
358
        return ghResponse, err
2✔
359
}
2✔
360

361
// UpdatePullRequest on GitHub
362
func (client *GitHubClient) UpdatePullRequest(ctx context.Context, owner, repository, title, body, targetBranchName string, id int, state vcsutils.PullRequestState) error {
3✔
363
        client.logger.Debug(vcsutils.UpdatingPullRequest, id)
3✔
364
        var baseRef *github.PullRequestBranch
3✔
365
        if targetBranchName != "" {
5✔
366
                baseRef = &github.PullRequestBranch{Ref: &targetBranchName}
2✔
367
        }
2✔
368
        pullRequest := &github.PullRequest{
3✔
369
                Body:  &body,
3✔
370
                Title: &title,
3✔
371
                State: vcsutils.MapPullRequestState(&state),
3✔
372
                Base:  baseRef,
3✔
373
        }
3✔
374

3✔
375
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
376
                _, ghResponse, err := client.ghClient.PullRequests.Edit(ctx, owner, repository, id, pullRequest)
3✔
377
                return ghResponse, err
3✔
378
        })
3✔
379
}
380

381
// ListOpenPullRequestsWithBody on GitHub
382
func (client *GitHubClient) ListOpenPullRequestsWithBody(ctx context.Context, owner, repository string) ([]PullRequestInfo, error) {
1✔
383
        return client.getOpenPullRequests(ctx, owner, repository, true)
1✔
384
}
1✔
385

386
// ListOpenPullRequests on GitHub
387
func (client *GitHubClient) ListOpenPullRequests(ctx context.Context, owner, repository string) ([]PullRequestInfo, error) {
1✔
388
        return client.getOpenPullRequests(ctx, owner, repository, false)
1✔
389
}
1✔
390

391
func (client *GitHubClient) getOpenPullRequests(ctx context.Context, owner, repository string, withBody bool) ([]PullRequestInfo, error) {
2✔
392
        var pullRequests []*github.PullRequest
2✔
393
        client.logger.Debug(vcsutils.FetchingOpenPullRequests, repository)
2✔
394
        err := client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
395
                var ghResponse *github.Response
2✔
396
                var err error
2✔
397
                pullRequests, ghResponse, err = client.ghClient.PullRequests.List(ctx, owner, repository, &github.PullRequestListOptions{State: "open"})
2✔
398
                return ghResponse, err
2✔
399
        })
2✔
400
        if err != nil {
2✔
401
                return []PullRequestInfo{}, err
×
402
        }
×
403

404
        return mapGitHubPullRequestToPullRequestInfoList(pullRequests, withBody)
2✔
405
}
406

407
func (client *GitHubClient) GetPullRequestByID(ctx context.Context, owner, repository string, pullRequestId int) (PullRequestInfo, error) {
4✔
408
        var pullRequest *github.PullRequest
4✔
409
        var ghResponse *github.Response
4✔
410
        var err error
4✔
411
        client.logger.Debug(vcsutils.FetchingPullRequestById, repository)
4✔
412
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
8✔
413
                pullRequest, ghResponse, err = client.ghClient.PullRequests.Get(ctx, owner, repository, pullRequestId)
4✔
414
                return ghResponse, err
4✔
415
        })
4✔
416
        if err != nil {
7✔
417
                return PullRequestInfo{}, err
3✔
418
        }
3✔
419

420
        if err = vcsutils.CheckResponseStatusWithBody(ghResponse.Response, http.StatusOK); err != nil {
1✔
421
                return PullRequestInfo{}, err
×
422
        }
×
423

424
        return mapGitHubPullRequestToPullRequestInfo(pullRequest, false)
1✔
425
}
426

427
func mapGitHubPullRequestToPullRequestInfo(ghPullRequest *github.PullRequest, withBody bool) (PullRequestInfo, error) {
4✔
428
        var sourceBranch, targetBranch string
4✔
429
        var err1, err2 error
4✔
430
        if ghPullRequest != nil && ghPullRequest.Head != nil && ghPullRequest.Base != nil {
8✔
431
                sourceBranch, err1 = extractBranchFromLabel(vcsutils.DefaultIfNotNil(ghPullRequest.Head.Label))
4✔
432
                targetBranch, err2 = extractBranchFromLabel(vcsutils.DefaultIfNotNil(ghPullRequest.Base.Label))
4✔
433
                err := errors.Join(err1, err2)
4✔
434
                if err != nil {
4✔
UNCOV
435
                        return PullRequestInfo{}, err
×
UNCOV
436
                }
×
437
        }
438

439
        var sourceRepoName, sourceRepoOwner string
4✔
440
        if ghPullRequest.Head.Repo == nil {
4✔
441
                return PullRequestInfo{}, errors.New("the source repository information is missing when fetching the pull request details")
×
442
        }
×
443
        if ghPullRequest.Head.Repo.Owner == nil {
4✔
444
                return PullRequestInfo{}, errors.New("the source repository owner name is missing when fetching the pull request details")
×
445
        }
×
446
        sourceRepoName = vcsutils.DefaultIfNotNil(ghPullRequest.Head.Repo.Name)
4✔
447
        sourceRepoOwner = vcsutils.DefaultIfNotNil(ghPullRequest.Head.Repo.Owner.Login)
4✔
448

4✔
449
        var targetRepoName, targetRepoOwner string
4✔
450
        if ghPullRequest.Base.Repo == nil {
4✔
451
                return PullRequestInfo{}, errors.New("the target repository information is missing when fetching the pull request details")
×
452
        }
×
453
        if ghPullRequest.Base.Repo.Owner == nil {
4✔
454
                return PullRequestInfo{}, errors.New("the target repository owner name is missing when fetching the pull request details")
×
455
        }
×
456
        targetRepoName = vcsutils.DefaultIfNotNil(ghPullRequest.Base.Repo.Name)
4✔
457
        targetRepoOwner = vcsutils.DefaultIfNotNil(ghPullRequest.Base.Repo.Owner.Login)
4✔
458

4✔
459
        var body string
4✔
460
        if withBody {
5✔
461
                body = vcsutils.DefaultIfNotNil(ghPullRequest.Body)
1✔
462
        }
1✔
463

464
        return PullRequestInfo{
4✔
465
                ID:     int64(vcsutils.DefaultIfNotNil(ghPullRequest.Number)),
4✔
466
                Title:  vcsutils.DefaultIfNotNil(ghPullRequest.Title),
4✔
467
                URL:    vcsutils.DefaultIfNotNil(ghPullRequest.HTMLURL),
4✔
468
                Body:   body,
4✔
469
                Author: vcsutils.DefaultIfNotNil(ghPullRequest.User.Login),
4✔
470
                Source: BranchInfo{
4✔
471
                        Name:       sourceBranch,
4✔
472
                        Repository: sourceRepoName,
4✔
473
                        Owner:      sourceRepoOwner,
4✔
474
                },
4✔
475
                Target: BranchInfo{
4✔
476
                        Name:       targetBranch,
4✔
477
                        Repository: targetRepoName,
4✔
478
                        Owner:      targetRepoOwner,
4✔
479
                },
4✔
480
        }, nil
4✔
481
}
482

483
// Extracts branch name from the following expected label format repo:branch
484
func extractBranchFromLabel(label string) (string, error) {
8✔
485
        split := strings.Split(label, ":")
8✔
486
        if len(split) <= 1 {
8✔
UNCOV
487
                return "", fmt.Errorf("bad label format %s", label)
×
UNCOV
488
        }
×
489
        return split[1], nil
8✔
490
}
491

492
// AddPullRequestComment on GitHub
493
func (client *GitHubClient) AddPullRequestComment(ctx context.Context, owner, repository, content string, pullRequestID int) error {
6✔
494
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "content": content})
6✔
495
        if err != nil {
10✔
496
                return err
4✔
497
        }
4✔
498

499
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
500
                var ghResponse *github.Response
2✔
501
                // We use the Issues API to add a regular comment. The PullRequests API adds a code review comment.
2✔
502
                _, ghResponse, err = client.ghClient.Issues.CreateComment(ctx, owner, repository, pullRequestID, &github.IssueComment{Body: &content})
2✔
503
                return ghResponse, err
2✔
504
        })
2✔
505
}
506

507
// AddPullRequestReviewComments on GitHub
508
func (client *GitHubClient) AddPullRequestReviewComments(ctx context.Context, owner, repository string, pullRequestID int, comments ...PullRequestComment) error {
2✔
509
        prID := strconv.Itoa(pullRequestID)
2✔
510
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "pullRequestID": prID})
2✔
511
        if err != nil {
2✔
512
                return err
×
UNCOV
513
        }
×
514
        if len(comments) == 0 {
2✔
515
                return errors.New(vcsutils.ErrNoCommentsProvided)
×
UNCOV
516
        }
×
517

518
        var commits []*github.RepositoryCommit
2✔
519
        var ghResponse *github.Response
2✔
520
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
521
                commits, ghResponse, err = client.ghClient.PullRequests.ListCommits(ctx, owner, repository, pullRequestID, nil)
2✔
522
                return ghResponse, err
2✔
523
        })
2✔
524
        if err != nil {
3✔
525
                return err
1✔
526
        }
1✔
527
        if len(commits) == 0 {
1✔
528
                return errors.New("could not fetch the commits list for pull request " + prID)
×
UNCOV
529
        }
×
530

531
        latestCommitSHA := commits[len(commits)-1].GetSHA()
1✔
532

1✔
533
        for _, comment := range comments {
3✔
534
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
535
                        ghResponse, err = client.executeCreatePullRequestReviewComment(ctx, owner, repository, latestCommitSHA, pullRequestID, comment)
2✔
536
                        return ghResponse, err
2✔
537
                })
2✔
538
                if err != nil {
2✔
539
                        return err
×
UNCOV
540
                }
×
541
        }
542
        return nil
1✔
543
}
544

545
func (client *GitHubClient) executeCreatePullRequestReviewComment(ctx context.Context, owner, repository, latestCommitSHA string, pullRequestID int, comment PullRequestComment) (*github.Response, error) {
2✔
546
        filePath := filepath.Clean(comment.NewFilePath)
2✔
547
        startLine := &comment.NewStartLine
2✔
548
        // GitHub API won't accept 'start_line' if it equals the end line
2✔
549
        if *startLine == comment.NewEndLine {
2✔
550
                startLine = nil
×
UNCOV
551
        }
×
552
        _, ghResponse, err := client.ghClient.PullRequests.CreateComment(ctx, owner, repository, pullRequestID, &github.PullRequestComment{
2✔
553
                CommitID:  &latestCommitSHA,
2✔
554
                Body:      &comment.Content,
2✔
555
                StartLine: startLine,
2✔
556
                Line:      &comment.NewEndLine,
2✔
557
                Path:      &filePath,
2✔
558
        })
2✔
559
        if err != nil {
2✔
560
                err = fmt.Errorf("could not create a code review comment for <%s/%s> in pull request %d. error received: %w",
×
561
                        owner, repository, pullRequestID, err)
×
UNCOV
562
        }
×
563
        return ghResponse, err
2✔
564
}
565

566
// ListPullRequestReviewComments on GitHub
567
func (client *GitHubClient) ListPullRequestReviewComments(ctx context.Context, owner, repository string, pullRequestID int) ([]CommentInfo, error) {
2✔
568
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
2✔
569
        if err != nil {
2✔
570
                return nil, err
×
UNCOV
571
        }
×
572

573
        commentsInfoList := []CommentInfo{}
2✔
574
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
575
                var ghResponse *github.Response
2✔
576
                commentsInfoList, ghResponse, err = client.executeListPullRequestReviewComments(ctx, owner, repository, pullRequestID)
2✔
577
                return ghResponse, err
2✔
578
        })
2✔
579
        return commentsInfoList, err
2✔
580
}
581

582
// ListPullRequestReviews on GitHub
583
func (client *GitHubClient) ListPullRequestReviews(ctx context.Context, owner, repository string, pullRequestID int) ([]PullRequestReviewDetails, error) {
2✔
584
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
2✔
585
        if err != nil {
2✔
UNCOV
586
                return nil, err
×
UNCOV
587
        }
×
588

589
        var reviews []*github.PullRequestReview
2✔
590
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
591
                var ghResponse *github.Response
2✔
592
                reviews, ghResponse, err = client.ghClient.PullRequests.ListReviews(ctx, owner, repository, pullRequestID, nil)
2✔
593
                return ghResponse, err
2✔
594
        })
2✔
595
        if err != nil {
3✔
596
                return nil, err
1✔
597
        }
1✔
598

599
        var reviewInfos []PullRequestReviewDetails
1✔
600
        for _, review := range reviews {
2✔
601
                reviewInfos = append(reviewInfos, PullRequestReviewDetails{
1✔
602
                        ID:          review.GetID(),
1✔
603
                        Reviewer:    review.GetUser().GetLogin(),
1✔
604
                        Body:        review.GetBody(),
1✔
605
                        State:       review.GetState(),
1✔
606
                        SubmittedAt: review.GetSubmittedAt().String(),
1✔
607
                        CommitID:    review.GetCommitID(),
1✔
608
                })
1✔
609
        }
1✔
610

611
        return reviewInfos, nil
1✔
612
}
613

614
func (client *GitHubClient) executeListPullRequestReviewComments(ctx context.Context, owner, repository string, pullRequestID int) ([]CommentInfo, *github.Response, error) {
2✔
615
        commentsList, ghResponse, err := client.ghClient.PullRequests.ListComments(ctx, owner, repository, pullRequestID, nil)
2✔
616
        if err != nil {
3✔
617
                return []CommentInfo{}, ghResponse, err
1✔
618
        }
1✔
619
        commentsInfoList := []CommentInfo{}
1✔
620
        for _, comment := range commentsList {
2✔
621
                commentsInfoList = append(commentsInfoList, CommentInfo{
1✔
622
                        ID:      comment.GetID(),
1✔
623
                        Content: comment.GetBody(),
1✔
624
                        Created: comment.GetCreatedAt().Time,
1✔
625
                })
1✔
626
        }
1✔
627
        return commentsInfoList, ghResponse, nil
1✔
628
}
629

630
// ListPullRequestComments on GitHub
631
func (client *GitHubClient) ListPullRequestComments(ctx context.Context, owner, repository string, pullRequestID int) ([]CommentInfo, error) {
4✔
632
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
4✔
633
        if err != nil {
4✔
UNCOV
634
                return []CommentInfo{}, err
×
UNCOV
635
        }
×
636

637
        var commentsList []*github.IssueComment
4✔
638
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
8✔
639
                var ghResponse *github.Response
4✔
640
                commentsList, ghResponse, err = client.ghClient.Issues.ListComments(ctx, owner, repository, pullRequestID, &github.IssueListCommentsOptions{})
4✔
641
                return ghResponse, err
4✔
642
        })
4✔
643

644
        if err != nil {
7✔
645
                return []CommentInfo{}, err
3✔
646
        }
3✔
647

648
        return mapGitHubIssuesCommentToCommentInfoList(commentsList)
1✔
649
}
650

651
// DeletePullRequestReviewComments on GitHub
652
func (client *GitHubClient) DeletePullRequestReviewComments(ctx context.Context, owner, repository string, _ int, comments ...CommentInfo) error {
2✔
653
        for _, comment := range comments {
5✔
654
                commentID := comment.ID
3✔
655
                err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "commentID": strconv.FormatInt(commentID, 10)})
3✔
656
                if err != nil {
3✔
UNCOV
657
                        return err
×
UNCOV
658
                }
×
659

660
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
661
                        return client.executeDeletePullRequestReviewComment(ctx, owner, repository, commentID)
3✔
662
                })
3✔
663
                if err != nil {
4✔
664
                        return err
1✔
665
                }
1✔
666

667
        }
668
        return nil
1✔
669
}
670

671
func (client *GitHubClient) executeDeletePullRequestReviewComment(ctx context.Context, owner, repository string, commentID int64) (*github.Response, error) {
3✔
672
        ghResponse, err := client.ghClient.PullRequests.DeleteComment(ctx, owner, repository, commentID)
3✔
673
        if err != nil {
4✔
674
                err = fmt.Errorf("could not delete pull request review comment: %w", err)
1✔
675
        }
1✔
676
        return ghResponse, err
3✔
677
}
678

679
// DeletePullRequestComment on GitHub
680
func (client *GitHubClient) DeletePullRequestComment(ctx context.Context, owner, repository string, _, commentID int) error {
2✔
681
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
2✔
682
        if err != nil {
2✔
UNCOV
683
                return err
×
UNCOV
684
        }
×
685
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
686
                return client.executeDeletePullRequestComment(ctx, owner, repository, commentID)
2✔
687
        })
2✔
688
}
689

690
func (client *GitHubClient) executeDeletePullRequestComment(ctx context.Context, owner, repository string, commentID int) (*github.Response, error) {
2✔
691
        ghResponse, err := client.ghClient.Issues.DeleteComment(ctx, owner, repository, int64(commentID))
2✔
692
        if err != nil {
3✔
693
                return ghResponse, err
1✔
694
        }
1✔
695

696
        var statusCode int
1✔
697
        if ghResponse.Response != nil {
2✔
698
                statusCode = ghResponse.Response.StatusCode
1✔
699
        }
1✔
700
        if statusCode != http.StatusNoContent && statusCode != http.StatusOK {
1✔
UNCOV
701
                return ghResponse, fmt.Errorf("expected %d status code while received %d status code", http.StatusNoContent, ghResponse.Response.StatusCode)
×
UNCOV
702
        }
×
703

704
        return ghResponse, nil
1✔
705
}
706

707
// GetLatestCommit on GitHub
708
func (client *GitHubClient) GetLatestCommit(ctx context.Context, owner, repository, branch string) (CommitInfo, error) {
10✔
709
        commits, err := client.GetCommits(ctx, owner, repository, branch)
10✔
710
        if err != nil {
18✔
711
                return CommitInfo{}, err
8✔
712
        }
8✔
713
        latestCommit := CommitInfo{}
2✔
714
        if len(commits) > 0 {
4✔
715
                latestCommit = commits[0]
2✔
716
        }
2✔
717
        return latestCommit, nil
2✔
718
}
719

720
// GetCommits on GitHub
721
func (client *GitHubClient) GetCommits(ctx context.Context, owner, repository, branch string) ([]CommitInfo, error) {
12✔
722
        err := validateParametersNotBlank(map[string]string{
12✔
723
                "owner":      owner,
12✔
724
                "repository": repository,
12✔
725
                "branch":     branch,
12✔
726
        })
12✔
727
        if err != nil {
16✔
728
                return nil, err
4✔
729
        }
4✔
730

731
        var commitsInfo []CommitInfo
8✔
732
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
16✔
733
                var ghResponse *github.Response
8✔
734
                listOptions := &github.CommitsListOptions{
8✔
735
                        SHA: branch,
8✔
736
                        ListOptions: github.ListOptions{
8✔
737
                                Page:    1,
8✔
738
                                PerPage: vcsutils.NumberOfCommitsToFetch,
8✔
739
                        },
8✔
740
                }
8✔
741
                commitsInfo, ghResponse, err = client.executeGetCommits(ctx, owner, repository, listOptions)
8✔
742
                return ghResponse, err
8✔
743
        })
8✔
744
        return commitsInfo, err
8✔
745
}
746

747
// GetCommitsWithQueryOptions on GitHub
748
func (client *GitHubClient) GetCommitsWithQueryOptions(ctx context.Context, owner, repository string, listOptions GitCommitsQueryOptions) ([]CommitInfo, error) {
2✔
749
        err := validateParametersNotBlank(map[string]string{
2✔
750
                "owner":      owner,
2✔
751
                "repository": repository,
2✔
752
        })
2✔
753
        if err != nil {
2✔
UNCOV
754
                return nil, err
×
UNCOV
755
        }
×
756
        var commitsInfo []CommitInfo
2✔
757
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
758
                var ghResponse *github.Response
2✔
759
                commitsInfo, ghResponse, err = client.executeGetCommits(ctx, owner, repository, convertToGitHubCommitsListOptions(listOptions))
2✔
760
                return ghResponse, err
2✔
761
        })
2✔
762
        return commitsInfo, err
2✔
763
}
764

765
func convertToGitHubCommitsListOptions(listOptions GitCommitsQueryOptions) *github.CommitsListOptions {
2✔
766
        return &github.CommitsListOptions{
2✔
767
                Since: listOptions.Since,
2✔
768
                Until: time.Now(),
2✔
769
                ListOptions: github.ListOptions{
2✔
770
                        Page:    listOptions.Page,
2✔
771
                        PerPage: listOptions.PerPage,
2✔
772
                },
2✔
773
        }
2✔
774
}
2✔
775

776
func (client *GitHubClient) executeGetCommits(ctx context.Context, owner, repository string, listOptions *github.CommitsListOptions) ([]CommitInfo, *github.Response, error) {
10✔
777
        commits, ghResponse, err := client.ghClient.Repositories.ListCommits(ctx, owner, repository, listOptions)
10✔
778
        if err != nil {
16✔
779
                return nil, ghResponse, err
6✔
780
        }
6✔
781

782
        var commitsInfo []CommitInfo
4✔
783
        for _, commit := range commits {
11✔
784
                commitInfo := mapGitHubCommitToCommitInfo(commit)
7✔
785
                commitsInfo = append(commitsInfo, commitInfo)
7✔
786
        }
7✔
787
        return commitsInfo, ghResponse, nil
4✔
788
}
789

790
// GetRepositoryInfo on GitHub
791
func (client *GitHubClient) GetRepositoryInfo(ctx context.Context, owner, repository string) (RepositoryInfo, error) {
6✔
792
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
6✔
793
        if err != nil {
9✔
794
                return RepositoryInfo{}, err
3✔
795
        }
3✔
796

797
        var repo *github.Repository
3✔
798
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
799
                var ghResponse *github.Response
3✔
800
                repo, ghResponse, err = client.ghClient.Repositories.Get(ctx, owner, repository)
3✔
801
                return ghResponse, err
3✔
802
        })
3✔
803
        if err != nil {
4✔
804
                return RepositoryInfo{}, err
1✔
805
        }
1✔
806

807
        return RepositoryInfo{RepositoryVisibility: getGitHubRepositoryVisibility(repo), CloneInfo: CloneInfo{HTTP: repo.GetCloneURL(), SSH: repo.GetSSHURL()}}, nil
2✔
808
}
809

810
// GetCommitBySha on GitHub
811
func (client *GitHubClient) GetCommitBySha(ctx context.Context, owner, repository, sha string) (CommitInfo, error) {
7✔
812
        err := validateParametersNotBlank(map[string]string{
7✔
813
                "owner":      owner,
7✔
814
                "repository": repository,
7✔
815
                "sha":        sha,
7✔
816
        })
7✔
817
        if err != nil {
11✔
818
                return CommitInfo{}, err
4✔
819
        }
4✔
820

821
        var commit *github.RepositoryCommit
3✔
822
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
823
                var ghResponse *github.Response
3✔
824
                commit, ghResponse, err = client.ghClient.Repositories.GetCommit(ctx, owner, repository, sha, nil)
3✔
825
                return ghResponse, err
3✔
826
        })
3✔
827
        if err != nil {
5✔
828
                return CommitInfo{}, err
2✔
829
        }
2✔
830

831
        return mapGitHubCommitToCommitInfo(commit), nil
1✔
832
}
833

834
// CreateLabel on GitHub
835
func (client *GitHubClient) CreateLabel(ctx context.Context, owner, repository string, labelInfo LabelInfo) error {
6✔
836
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "LabelInfo.name": labelInfo.Name})
6✔
837
        if err != nil {
10✔
838
                return err
4✔
839
        }
4✔
840

841
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
842
                var ghResponse *github.Response
2✔
843
                _, ghResponse, err = client.ghClient.Issues.CreateLabel(ctx, owner, repository, &github.Label{
2✔
844
                        Name:        &labelInfo.Name,
2✔
845
                        Description: &labelInfo.Description,
2✔
846
                        Color:       &labelInfo.Color,
2✔
847
                })
2✔
848
                return ghResponse, err
2✔
849
        })
2✔
850
}
851

852
// GetLabel on GitHub
853
func (client *GitHubClient) GetLabel(ctx context.Context, owner, repository, name string) (*LabelInfo, error) {
7✔
854
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "name": name})
7✔
855
        if err != nil {
11✔
856
                return nil, err
4✔
857
        }
4✔
858

859
        var labelInfo *LabelInfo
3✔
860
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
861
                var ghResponse *github.Response
3✔
862
                labelInfo, ghResponse, err = client.executeGetLabel(ctx, owner, repository, name)
3✔
863
                return ghResponse, err
3✔
864
        })
3✔
865
        return labelInfo, err
3✔
866
}
867

868
func (client *GitHubClient) executeGetLabel(ctx context.Context, owner, repository, name string) (*LabelInfo, *github.Response, error) {
3✔
869
        label, ghResponse, err := client.ghClient.Issues.GetLabel(ctx, owner, repository, name)
3✔
870
        if err != nil {
5✔
871
                if ghResponse != nil && ghResponse.Response != nil && ghResponse.Response.StatusCode == http.StatusNotFound {
3✔
872
                        return nil, ghResponse, nil
1✔
873
                }
1✔
874
                return nil, ghResponse, err
1✔
875
        }
876

877
        labelInfo := &LabelInfo{
1✔
878
                Name:        *label.Name,
1✔
879
                Description: *label.Description,
1✔
880
                Color:       *label.Color,
1✔
881
        }
1✔
882
        return labelInfo, ghResponse, nil
1✔
883
}
884

885
// ListPullRequestLabels on GitHub
886
func (client *GitHubClient) ListPullRequestLabels(ctx context.Context, owner, repository string, pullRequestID int) ([]string, error) {
5✔
887
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
5✔
888
        if err != nil {
8✔
889
                return nil, err
3✔
890
        }
3✔
891

892
        results := []string{}
2✔
893
        for nextPage := 0; ; nextPage++ {
4✔
894
                options := &github.ListOptions{Page: nextPage}
2✔
895
                var labels []*github.Label
2✔
896
                var ghResponse *github.Response
2✔
897
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
898
                        labels, ghResponse, err = client.ghClient.Issues.ListLabelsByIssue(ctx, owner, repository, pullRequestID, options)
2✔
899
                        return ghResponse, err
2✔
900
                })
2✔
901
                if err != nil {
3✔
902
                        return nil, err
1✔
903
                }
1✔
904
                for _, label := range labels {
2✔
905
                        results = append(results, *label.Name)
1✔
906
                }
1✔
907
                if nextPage+1 >= ghResponse.LastPage {
2✔
908
                        break
1✔
909
                }
910
        }
911
        return results, nil
1✔
912
}
913

914
func (client *GitHubClient) ListPullRequestsAssociatedWithCommit(ctx context.Context, owner, repository string, commitSHA string) ([]PullRequestInfo, error) {
2✔
915
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
2✔
916
        if err != nil {
2✔
UNCOV
917
                return nil, err
×
UNCOV
918
        }
×
919

920
        var pulls []*github.PullRequest
2✔
921
        if err = client.runWithRateLimitRetries(func() (ghResponse *github.Response, err error) {
4✔
922
                pulls, ghResponse, err = client.ghClient.PullRequests.ListPullRequestsWithCommit(ctx, owner, repository, commitSHA, nil)
2✔
923
                return ghResponse, err
2✔
924
        }); err != nil {
3✔
925
                return nil, err
1✔
926
        }
1✔
927
        return mapGitHubPullRequestToPullRequestInfoList(pulls, false)
1✔
928
}
929

930
// UnlabelPullRequest on GitHub
931
func (client *GitHubClient) UnlabelPullRequest(ctx context.Context, owner, repository, name string, pullRequestID int) error {
5✔
932
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository})
5✔
933
        if err != nil {
8✔
934
                return err
3✔
935
        }
3✔
936

937
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
938
                return client.ghClient.Issues.RemoveLabelForIssue(ctx, owner, repository, pullRequestID, name)
2✔
939
        })
2✔
940
}
941

942
// UploadCodeScanning to GitHub Security tab
943
func (client *GitHubClient) UploadCodeScanning(ctx context.Context, owner, repository, branch, sarifContent string) (id string, err error) {
2✔
944
        commit, err := client.GetLatestCommit(ctx, owner, repository, branch)
2✔
945
        if err != nil {
3✔
946
                return
1✔
947
        }
1✔
948

949
        commitSHA := commit.Hash
1✔
950
        branch = vcsutils.AddBranchPrefix(branch)
1✔
951
        client.logger.Debug(vcsutils.UploadingCodeScanning, repository, "/", branch)
1✔
952

1✔
953
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
954
                var ghResponse *github.Response
1✔
955
                id, ghResponse, err = client.executeUploadCodeScanning(ctx, owner, repository, branch, commitSHA, sarifContent)
1✔
956
                return ghResponse, err
1✔
957
        })
1✔
958
        return
1✔
959
}
960

961
func (client *GitHubClient) executeUploadCodeScanning(ctx context.Context, owner, repository, branch, commitSHA, sarifContent string) (id string, ghResponse *github.Response, err error) {
1✔
962
        encodedSarif, err := encodeScanningResult(sarifContent)
1✔
963
        if err != nil {
1✔
UNCOV
964
                return
×
UNCOV
965
        }
×
966

967
        sarifID, ghResponse, err := client.ghClient.CodeScanning.UploadSarif(ctx, owner, repository, &github.SarifAnalysis{
1✔
968
                CommitSHA: &commitSHA,
1✔
969
                Ref:       &branch,
1✔
970
                Sarif:     &encodedSarif,
1✔
971
        })
1✔
972

1✔
973
        // According to go-github API - successful ghResponse will return 202 status code
1✔
974
        // The body of the ghResponse will appear in the error, and the Sarif struct will be empty.
1✔
975
        if err != nil && ghResponse.Response.StatusCode != http.StatusAccepted {
1✔
976
                return
×
UNCOV
977
        }
×
978

979
        id, err = handleGitHubUploadSarifID(sarifID, err)
1✔
980
        return
1✔
981
}
982

983
func handleGitHubUploadSarifID(sarifID *github.SarifID, uploadSarifErr error) (id string, err error) {
1✔
984
        if sarifID != nil && *sarifID.ID != "" {
2✔
985
                id = *sarifID.ID
1✔
986
                return
1✔
987
        }
1✔
988
        var result map[string]string
×
989
        var ghAcceptedError *github.AcceptedError
×
UNCOV
990
        if errors.As(uploadSarifErr, &ghAcceptedError) {
×
UNCOV
991
                if err = json.Unmarshal(ghAcceptedError.Raw, &result); err != nil {
×
UNCOV
992
                        return
×
UNCOV
993
                }
×
UNCOV
994
                id = result["id"]
×
995
        }
UNCOV
996
        return
×
997
}
998

999
// DownloadFileFromRepo on GitHub
1000
func (client *GitHubClient) DownloadFileFromRepo(ctx context.Context, owner, repository, branch, path string) (content []byte, statusCode int, err error) {
3✔
1001
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
6✔
1002
                var ghResponse *github.Response
3✔
1003
                content, statusCode, ghResponse, err = client.executeDownloadFileFromRepo(ctx, owner, repository, branch, path)
3✔
1004
                return ghResponse, err
3✔
1005
        })
3✔
1006
        return
3✔
1007
}
1008

1009
func (client *GitHubClient) executeDownloadFileFromRepo(ctx context.Context, owner, repository, branch, path string) (content []byte, statusCode int, ghResponse *github.Response, err error) {
3✔
1010
        body, ghResponse, err := client.ghClient.Repositories.DownloadContents(ctx, owner, repository, path, &github.RepositoryContentGetOptions{Ref: branch})
3✔
1011
        defer func() {
6✔
1012
                if body != nil {
4✔
1013
                        err = errors.Join(err, body.Close())
1✔
1014
                }
1✔
1015
        }()
1016

1017
        if ghResponse == nil || ghResponse.Response == nil {
4✔
1018
                return
1✔
1019
        }
1✔
1020

1021
        statusCode = ghResponse.StatusCode
2✔
1022
        if err != nil && statusCode != http.StatusOK {
2✔
UNCOV
1023
                err = fmt.Errorf("expected %d status code while received %d status code with error:\n%s", http.StatusOK, ghResponse.StatusCode, err)
×
UNCOV
1024
                return
×
UNCOV
1025
        }
×
1026

1027
        if body != nil {
3✔
1028
                content, err = io.ReadAll(body)
1✔
1029
        }
1✔
1030
        return
2✔
1031
}
1032

1033
// GetRepositoryEnvironmentInfo on GitHub
1034
func (client *GitHubClient) GetRepositoryEnvironmentInfo(ctx context.Context, owner, repository, name string) (RepositoryEnvironmentInfo, error) {
2✔
1035
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "name": name})
2✔
1036
        if err != nil {
2✔
UNCOV
1037
                return RepositoryEnvironmentInfo{}, err
×
UNCOV
1038
        }
×
1039

1040
        var repositoryEnvInfo *RepositoryEnvironmentInfo
2✔
1041
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1042
                var ghResponse *github.Response
2✔
1043
                repositoryEnvInfo, ghResponse, err = client.executeGetRepositoryEnvironmentInfo(ctx, owner, repository, name)
2✔
1044
                return ghResponse, err
2✔
1045
        })
2✔
1046
        return *repositoryEnvInfo, err
2✔
1047
}
1048

1049
func (client *GitHubClient) CreateBranch(ctx context.Context, owner, repository, sourceBranch, newBranch string) error {
2✔
1050
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repository": repository, "sourceBranch": sourceBranch, "newBranch": newBranch})
2✔
1051
        if err != nil {
2✔
NEW
1052
                return err
×
NEW
1053
        }
×
1054

1055
        var sourceBranchRef *github.Branch
2✔
1056
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1057
                sourceBranchRef, _, err = client.ghClient.Repositories.GetBranch(ctx, owner, repository, sourceBranch, 3)
2✔
1058
                if err != nil {
3✔
1059
                        return nil, err
1✔
1060
                }
1✔
1061
                return nil, nil
1✔
1062
        })
1063
        if err != nil {
3✔
1064
                return err
1✔
1065
        }
1✔
1066

1067
        latestCommitSHA := sourceBranchRef.Commit.SHA
1✔
1068
        ref := &github.Reference{
1✔
1069
                Ref:    github.String("refs/heads/" + newBranch),
1✔
1070
                Object: &github.GitObject{SHA: latestCommitSHA},
1✔
1071
        }
1✔
1072

1✔
1073
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
1074
                _, _, err = client.ghClient.Git.CreateRef(ctx, owner, repository, ref)
1✔
1075
                if err != nil {
1✔
NEW
1076
                        return nil, err
×
NEW
1077
                }
×
1078
                return nil, nil
1✔
1079
        })
1080
}
1081

1082
func (client *GitHubClient) AddOrganizationSecret(ctx context.Context, owner, secretName, secretValue string) error {
2✔
1083
        err := validateParametersNotBlank(map[string]string{"secretName": secretName, "owner": owner, "secretValue": secretValue})
2✔
1084
        if err != nil {
2✔
NEW
1085
                return err
×
NEW
1086
        }
×
1087

1088
        publicKey, _, err := client.ghClient.Actions.GetOrgPublicKey(ctx, owner)
2✔
1089
        if err != nil {
3✔
1090
                return err
1✔
1091
        }
1✔
1092

1093
        encryptedValue, err := encryptSecret(publicKey, secretValue)
1✔
1094
        if err != nil {
1✔
NEW
1095
                return err
×
NEW
1096
        }
×
1097

1098
        secret := &github.EncryptedSecret{
1✔
1099
                Name:           secretName,
1✔
1100
                KeyID:          publicKey.GetKeyID(),
1✔
1101
                EncryptedValue: encryptedValue,
1✔
1102
                Visibility:     "all",
1✔
1103
        }
1✔
1104

1✔
1105
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
1106
                _, err = client.ghClient.Actions.CreateOrUpdateOrgSecret(ctx, owner, secret)
1✔
1107
                return nil, err
1✔
1108
        })
1✔
1109
        return err
1✔
1110
}
1111

1112
func (client *GitHubClient) AllowWorkflows(ctx context.Context, owner string) error {
2✔
1113
        err := validateParametersNotBlank(map[string]string{"owner": owner})
2✔
1114
        if err != nil {
2✔
NEW
1115
                return err
×
NEW
1116
        }
×
1117

1118
        requestBody := &github.ActionsPermissions{
2✔
1119
                AllowedActions:      github.String("all"),
2✔
1120
                EnabledRepositories: github.String("all"),
2✔
1121
        }
2✔
1122

2✔
1123
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1124
                _, _, err = client.ghClient.Actions.EditActionsPermissions(ctx, owner, *requestBody)
2✔
1125
                return nil, err
2✔
1126
        })
2✔
1127
        return err
2✔
1128
}
1129

1130
func (client *GitHubClient) GetRepoCollaborators(ctx context.Context, owner, repo, affiliation, permission string) ([]string, error) {
2✔
1131
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repo": repo, "affiliation": affiliation, "permission": permission})
2✔
1132
        if err != nil {
2✔
NEW
1133
                return nil, err
×
NEW
1134
        }
×
1135

1136
        var collaborators []*github.User
2✔
1137
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1138
                var ghResponse *github.Response
2✔
1139
                var err error
2✔
1140
                collaborators, ghResponse, err = client.ghClient.Repositories.ListCollaborators(ctx, owner, repo, &github.ListCollaboratorsOptions{
2✔
1141
                        Affiliation: affiliation,
2✔
1142
                        Permission:  permission,
2✔
1143
                })
2✔
1144
                return ghResponse, err
2✔
1145
        })
2✔
1146
        if err != nil {
3✔
1147
                return nil, err
1✔
1148
        }
1✔
1149

1150
        var names []string
1✔
1151
        for _, collab := range collaborators {
2✔
1152
                names = append(names, collab.GetLogin())
1✔
1153
        }
1✔
1154
        return names, nil
1✔
1155
}
1156

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

1163
        var allTeams []*github.Team
2✔
1164
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1165
                var resp *github.Response
2✔
1166
                var err error
2✔
1167
                allTeams, resp, err = client.ghClient.Repositories.ListTeams(ctx, owner, repo, nil)
2✔
1168
                return resp, err
2✔
1169
        })
2✔
1170
        if err != nil {
3✔
1171
                return nil, err
1✔
1172
        }
1✔
1173

1174
        permMap := make(map[string]bool)
1✔
1175
        for _, p := range permissions {
2✔
1176
                permMap[strings.ToLower(p)] = true
1✔
1177
        }
1✔
1178

1179
        var matchedTeams []int64
1✔
1180
        for _, team := range allTeams {
2✔
1181
                if permMap[strings.ToLower(team.GetPermission())] {
2✔
1182
                        matchedTeams = append(matchedTeams, team.GetID())
1✔
1183
                }
1✔
1184
        }
1185

1186
        return matchedTeams, nil
1✔
1187
}
1188

1189
func (client *GitHubClient) CreateOrUpdateEnvironment(ctx context.Context, owner, repo, envName string, teams []int64, users []string) error {
2✔
1190
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repo": repo, "envName": envName})
2✔
1191
        if err != nil {
2✔
NEW
1192
                return err
×
NEW
1193
        }
×
1194

1195
        var envReviewers []*github.EnvReviewers
2✔
1196
        for _, team := range teams {
4✔
1197
                envReviewers = append(envReviewers, &github.EnvReviewers{
2✔
1198
                        Type: github.String("Team"),
2✔
1199
                        ID:   &team,
2✔
1200
                })
2✔
1201
        }
2✔
1202

1203
        if len(envReviewers) >= ghMaxEnvReviewers {
2✔
NEW
1204
                envReviewers = envReviewers[:ghMaxEnvReviewers]
×
NEW
1205
                _, _, err := client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
×
NEW
1206
                        Reviewers: envReviewers,
×
NEW
1207
                })
×
NEW
1208
                return err
×
NEW
1209
        }
×
1210

1211
        for _, userName := range users {
2✔
NEW
1212
                user, _, err := client.ghClient.Users.Get(ctx, userName)
×
NEW
1213

×
NEW
1214
                if err != nil {
×
NEW
1215
                        return err
×
NEW
1216
                }
×
NEW
1217
                userId := user.GetID()
×
NEW
1218
                envReviewers = append(envReviewers, &github.EnvReviewers{
×
NEW
1219
                        Type: github.String("User"),
×
NEW
1220
                        ID:   github.Int64(userId),
×
NEW
1221
                })
×
1222
        }
1223

1224
        if len(envReviewers) >= ghMaxEnvReviewers {
2✔
NEW
1225
                envReviewers = envReviewers[:ghMaxEnvReviewers]
×
NEW
1226
                _, _, err := client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
×
NEW
1227
                        Reviewers: envReviewers,
×
NEW
1228
                })
×
NEW
1229
                return err
×
NEW
1230
        }
×
1231

1232
        _, _, err = client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
2✔
1233
                Reviewers: envReviewers,
2✔
1234
        })
2✔
1235
        return err
2✔
1236
}
1237

1238
func (client *GitHubClient) CommitAndPushFiles(
1239
        ctx context.Context,
1240
        owner, repo, sourceBranch, commitMessage, authorName, authorEmail string,
1241
        files []FileToCommit,
1242
) error {
2✔
1243
        if len(files) == 0 {
2✔
NEW
1244
                return errors.New("no files provided to commit")
×
NEW
1245
        }
×
1246

1247
        ref, _, err := client.ghClient.Git.GetRef(ctx, owner, repo, "refs/heads/"+sourceBranch)
2✔
1248
        if err != nil {
3✔
1249
                return fmt.Errorf("failed to get branch ref: %w", err)
1✔
1250
        }
1✔
1251

1252
        parentCommit, _, err := client.ghClient.Git.GetCommit(ctx, owner, repo, *ref.Object.SHA)
1✔
1253
        if err != nil {
1✔
NEW
1254
                return fmt.Errorf("failed to get parent commit: %w", err)
×
NEW
1255
        }
×
1256

1257
        var treeEntries []*github.TreeEntry
1✔
1258
        for _, file := range files {
2✔
1259
                blob, _, err := client.ghClient.Git.CreateBlob(ctx, owner, repo, &github.Blob{
1✔
1260
                        Content:  github.String(file.Content),
1✔
1261
                        Encoding: github.String("utf-8"),
1✔
1262
                })
1✔
1263
                if err != nil {
1✔
NEW
1264
                        return fmt.Errorf("failed to create blob for %s: %w", file.Path, err)
×
NEW
1265
                }
×
1266

1267
                // Add each file to the treeEntries
1268
                treeEntries = append(treeEntries, &github.TreeEntry{
1✔
1269
                        Path: github.String(file.Path),
1✔
1270
                        Mode: github.String(regularFileCode),
1✔
1271
                        Type: github.String("blob"),
1✔
1272
                        SHA:  blob.SHA,
1✔
1273
                })
1✔
1274
        }
1275

1276
        tree, _, err := client.ghClient.Git.CreateTree(ctx, owner, repo, *parentCommit.Tree.SHA, treeEntries)
1✔
1277
        if err != nil {
1✔
NEW
1278
                return fmt.Errorf("failed to create tree: %w", err)
×
NEW
1279
        }
×
1280

1281
        commit := &github.Commit{
1✔
1282
                Message: github.String(commitMessage),
1✔
1283
                Tree:    tree,
1✔
1284
                Parents: []*github.Commit{{SHA: parentCommit.SHA}},
1✔
1285
                Author: &github.CommitAuthor{
1✔
1286
                        Name:  github.String(authorName),
1✔
1287
                        Email: github.String(authorEmail),
1✔
1288
                        Date:  &github.Timestamp{Time: time.Now()},
1✔
1289
                },
1✔
1290
        }
1✔
1291

1✔
1292
        newCommit, _, err := client.ghClient.Git.CreateCommit(ctx, owner, repo, commit, nil)
1✔
1293
        if err != nil {
1✔
NEW
1294
                return fmt.Errorf("failed to create commit: %w", err)
×
NEW
1295
        }
×
1296

1297
        ref.Object.SHA = newCommit.SHA
1✔
1298
        _, _, err = client.ghClient.Git.UpdateRef(ctx, owner, repo, ref, false)
1✔
1299
        if err != nil {
1✔
NEW
1300
                return fmt.Errorf("failed to update branch ref: %w", err)
×
NEW
1301
        }
×
1302
        return nil
1✔
1303
}
1304

1305
func (client *GitHubClient) MergePullRequest(ctx context.Context, owner, repo string, prNumber int, commitMessage string) error {
2✔
1306
        err := client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1307
                _, resp, err := client.ghClient.PullRequests.Merge(ctx, owner, repo, prNumber, commitMessage, nil)
2✔
1308
                return resp, err
2✔
1309
        })
2✔
1310
        return err
2✔
1311
}
1312

1313
func (client *GitHubClient) executeGetRepositoryEnvironmentInfo(ctx context.Context, owner, repository, name string) (*RepositoryEnvironmentInfo, *github.Response, error) {
2✔
1314
        environment, ghResponse, err := client.ghClient.Repositories.GetEnvironment(ctx, owner, repository, name)
2✔
1315
        if err != nil {
3✔
1316
                return &RepositoryEnvironmentInfo{}, ghResponse, err
1✔
1317
        }
1✔
1318

1319
        if err = vcsutils.CheckResponseStatusWithBody(ghResponse.Response, http.StatusOK); err != nil {
1✔
UNCOV
1320
                return &RepositoryEnvironmentInfo{}, ghResponse, err
×
1321
        }
×
1322

1323
        reviewers, err := extractGitHubEnvironmentReviewers(environment)
1✔
1324
        if err != nil {
1✔
UNCOV
1325
                return &RepositoryEnvironmentInfo{}, ghResponse, err
×
UNCOV
1326
        }
×
1327

1328
        return &RepositoryEnvironmentInfo{
1✔
1329
                        Name:      environment.GetName(),
1✔
1330
                        Url:       environment.GetURL(),
1✔
1331
                        Reviewers: reviewers,
1✔
1332
                },
1✔
1333
                ghResponse,
1✔
1334
                nil
1✔
1335
}
1336

1337
func (client *GitHubClient) GetModifiedFiles(ctx context.Context, owner, repository, refBefore, refAfter string) ([]string, error) {
6✔
1338
        err := validateParametersNotBlank(map[string]string{
6✔
1339
                "owner":      owner,
6✔
1340
                "repository": repository,
6✔
1341
                "refBefore":  refBefore,
6✔
1342
                "refAfter":   refAfter,
6✔
1343
        })
6✔
1344
        if err != nil {
10✔
1345
                return nil, err
4✔
1346
        }
4✔
1347

1348
        var fileNamesList []string
2✔
1349
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1350
                var ghResponse *github.Response
2✔
1351
                fileNamesList, ghResponse, err = client.executeGetModifiedFiles(ctx, owner, repository, refBefore, refAfter)
2✔
1352
                return ghResponse, err
2✔
1353
        })
2✔
1354
        return fileNamesList, err
2✔
1355
}
1356

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

2✔
1364
        comparison, ghResponse, err := client.ghClient.Repositories.CompareCommits(ctx, owner, repository, refBefore, refAfter, listOptions)
2✔
1365
        if err != nil {
3✔
1366
                return nil, ghResponse, err
1✔
1367
        }
1✔
1368

1369
        if err = vcsutils.CheckResponseStatusWithBody(ghResponse.Response, http.StatusOK); err != nil {
1✔
UNCOV
1370
                return nil, ghResponse, err
×
UNCOV
1371
        }
×
1372

1373
        fileNamesSet := datastructures.MakeSet[string]()
1✔
1374
        for _, file := range comparison.Files {
18✔
1375
                fileNamesSet.Add(vcsutils.DefaultIfNotNil(file.Filename))
17✔
1376
                fileNamesSet.Add(vcsutils.DefaultIfNotNil(file.PreviousFilename))
17✔
1377
        }
17✔
1378

1379
        _ = fileNamesSet.Remove("") // Make sure there are no blank filepath.
1✔
1380
        fileNamesList := fileNamesSet.ToSlice()
1✔
1381
        sort.Strings(fileNamesList)
1✔
1382

1✔
1383
        return fileNamesList, ghResponse, nil
1✔
1384
}
1385

1386
// Extract code reviewers from environment
1387
func extractGitHubEnvironmentReviewers(environment *github.Environment) ([]string, error) {
2✔
1388
        var reviewers []string
2✔
1389
        protectionRules := environment.ProtectionRules
2✔
1390
        if protectionRules == nil {
2✔
UNCOV
1391
                return reviewers, nil
×
UNCOV
1392
        }
×
1393
        reviewerStruct := repositoryEnvironmentReviewer{}
2✔
1394
        for _, rule := range protectionRules {
4✔
1395
                for _, reviewer := range rule.Reviewers {
5✔
1396
                        if err := mapstructure.Decode(reviewer.Reviewer, &reviewerStruct); err != nil {
3✔
UNCOV
1397
                                return []string{}, err
×
UNCOV
1398
                        }
×
1399
                        reviewers = append(reviewers, reviewerStruct.Login)
3✔
1400
                }
1401
        }
1402
        return reviewers, nil
2✔
1403
}
1404

1405
func createGitHubHook(token, payloadURL string, webhookEvents ...vcsutils.WebhookEvent) *github.Hook {
4✔
1406
        return &github.Hook{
4✔
1407
                Events: getGitHubWebhookEvents(webhookEvents...),
4✔
1408
                Config: map[string]interface{}{
4✔
1409
                        "url":          payloadURL,
4✔
1410
                        "content_type": "json",
4✔
1411
                        "secret":       token,
4✔
1412
                },
4✔
1413
        }
4✔
1414
}
4✔
1415

1416
// Get varargs of webhook events and return a slice of GitHub webhook events
1417
func getGitHubWebhookEvents(webhookEvents ...vcsutils.WebhookEvent) []string {
4✔
1418
        events := datastructures.MakeSet[string]()
4✔
1419
        for _, event := range webhookEvents {
16✔
1420
                switch event {
12✔
1421
                case vcsutils.PrOpened, vcsutils.PrEdited, vcsutils.PrMerged, vcsutils.PrRejected:
8✔
1422
                        events.Add("pull_request")
8✔
1423
                case vcsutils.Push, vcsutils.TagPushed, vcsutils.TagRemoved:
4✔
1424
                        events.Add("push")
4✔
1425
                }
1426
        }
1427
        return events.ToSlice()
4✔
1428
}
1429

1430
func getGitHubRepositoryVisibility(repo *github.Repository) RepositoryVisibility {
5✔
1431
        switch *repo.Visibility {
5✔
1432
        case "public":
3✔
1433
                return Public
3✔
1434
        case "internal":
1✔
1435
                return Internal
1✔
1436
        default:
1✔
1437
                return Private
1✔
1438
        }
1439
}
1440

1441
func getGitHubCommitState(commitState CommitStatus) string {
7✔
1442
        switch commitState {
7✔
1443
        case Pass:
1✔
1444
                return "success"
1✔
1445
        case Fail:
1✔
1446
                return "failure"
1✔
1447
        case Error:
3✔
1448
                return "error"
3✔
1449
        case InProgress:
1✔
1450
                return "pending"
1✔
1451
        }
1452
        return ""
1✔
1453
}
1454

1455
func mapGitHubCommitToCommitInfo(commit *github.RepositoryCommit) CommitInfo {
8✔
1456
        parents := make([]string, len(commit.Parents))
8✔
1457
        for i, c := range commit.Parents {
15✔
1458
                parents[i] = c.GetSHA()
7✔
1459
        }
7✔
1460
        details := commit.GetCommit()
8✔
1461
        return CommitInfo{
8✔
1462
                Hash:          commit.GetSHA(),
8✔
1463
                AuthorName:    details.GetAuthor().GetName(),
8✔
1464
                CommitterName: details.GetCommitter().GetName(),
8✔
1465
                Url:           commit.GetURL(),
8✔
1466
                Timestamp:     details.GetCommitter().GetDate().UTC().Unix(),
8✔
1467
                Message:       details.GetMessage(),
8✔
1468
                ParentHashes:  parents,
8✔
1469
                AuthorEmail:   details.GetAuthor().GetEmail(),
8✔
1470
        }
8✔
1471
}
1472

1473
func mapGitHubIssuesCommentToCommentInfoList(commentsList []*github.IssueComment) (res []CommentInfo, err error) {
1✔
1474
        for _, comment := range commentsList {
3✔
1475
                res = append(res, CommentInfo{
2✔
1476
                        ID:      comment.GetID(),
2✔
1477
                        Content: comment.GetBody(),
2✔
1478
                        Created: comment.GetCreatedAt().Time,
2✔
1479
                })
2✔
1480
        }
2✔
1481
        return
1✔
1482
}
1483

1484
func mapGitHubPullRequestToPullRequestInfoList(pullRequestList []*github.PullRequest, withBody bool) (res []PullRequestInfo, err error) {
3✔
1485
        var mappedPullRequest PullRequestInfo
3✔
1486
        for _, pullRequest := range pullRequestList {
6✔
1487
                mappedPullRequest, err = mapGitHubPullRequestToPullRequestInfo(pullRequest, withBody)
3✔
1488
                if err != nil {
3✔
UNCOV
1489
                        return
×
UNCOV
1490
                }
×
1491
                res = append(res, mappedPullRequest)
3✔
1492
        }
1493
        return
3✔
1494
}
1495

1496
func encodeScanningResult(data string) (string, error) {
1✔
1497
        compressedScan, err := base64.EncodeGzip([]byte(data), 6)
1✔
1498
        if err != nil {
1✔
UNCOV
1499
                return "", err
×
UNCOV
1500
        }
×
1501

1502
        return compressedScan, err
1✔
1503
}
1504

1505
type repositoryEnvironmentReviewer struct {
1506
        Login string `mapstructure:"login"`
1507
}
1508

1509
func shouldRetryIfRateLimitExceeded(ghResponse *github.Response, requestError error) bool {
107✔
1510
        if ghResponse == nil || ghResponse.Response == nil {
153✔
1511
                return false
46✔
1512
        }
46✔
1513

1514
        if !slices.Contains(rateLimitRetryStatuses, ghResponse.StatusCode) {
120✔
1515
                return false
59✔
1516
        }
59✔
1517

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

1524
        body, err := io.ReadAll(ghResponse.Body)
1✔
1525
        if err != nil {
1✔
UNCOV
1526
                return false
×
UNCOV
1527
        }
×
1528
        return strings.Contains(string(body), "rate limit")
1✔
1529
}
1530

1531
func isRateLimitAbuseError(requestError error) bool {
4✔
1532
        var abuseRateLimitError *github.AbuseRateLimitError
4✔
1533
        var rateLimitError *github.RateLimitError
4✔
1534
        return errors.As(requestError, &abuseRateLimitError) || errors.As(requestError, &rateLimitError)
4✔
1535
}
4✔
1536

1537
func encryptSecret(publicKey *github.PublicKey, secretValue string) (string, error) {
1✔
1538
        publicKeyBytes, err := base64Utils.StdEncoding.DecodeString(publicKey.GetKey())
1✔
1539
        if err != nil {
1✔
NEW
1540
                return "", err
×
NEW
1541
        }
×
1542

1543
        var publicKeyDecoded [32]byte
1✔
1544
        copy(publicKeyDecoded[:], publicKeyBytes)
1✔
1545

1✔
1546
        encrypted, err := box.SealAnonymous(nil, []byte(secretValue), &publicKeyDecoded, rand.Reader)
1✔
1547
        if err != nil {
1✔
NEW
1548
                return "", err
×
NEW
1549
        }
×
1550

1551
        encryptedBase64 := base64Utils.StdEncoding.EncodeToString(encrypted)
1✔
1552
        return encryptedBase64, nil
1✔
1553
}
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