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

jfrog / froggit-go / 16412540450

21 Jul 2025 08:51AM UTC coverage: 84.746% (-0.1%) from 84.874%
16412540450

Pull #159

github

eranturgeman
fix static analysis
Pull Request #159: GitHub: Dependency Submission API

68 of 93 new or added lines in 6 files covered. (73.12%)

1 existing line in 1 file now uncovered.

4500 of 5310 relevant lines covered (84.75%)

6.4 hits per line

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

87.65
/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 {
109✔
48
        ghe.ExecutionHandler = func() (bool, error) {
218✔
49
                ghResponse, err := ghe.GitHubRateLimitExecutionHandler()
109✔
50
                return shouldRetryIfRateLimitExceeded(ghResponse, err), err
109✔
51
        }
109✔
52
        return ghe.RetryExecutor.Execute()
109✔
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 {
109✔
82
        client.rateLimitRetryExecutor.GitHubRateLimitExecutionHandler = handler
109✔
83
        return client.rateLimitRetryExecutor.Execute()
109✔
84
}
109✔
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
// TODO eran - check usage of this api. make sure it doesnt break
135
// ListRepositories on GitHub
136
func (client *GitHubClient) ListRepositories(ctx context.Context) (results map[string][]string, err error) {
5✔
137
        results = make(map[string][]string)
5✔
138
        for nextPage := 1; ; nextPage++ {
11✔
139
                var repositoriesInPage []*github.Repository
6✔
140
                var ghResponse *github.Response
6✔
141
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
12✔
142
                        repositoriesInPage, ghResponse, err = client.executeListRepositoriesInPage(ctx, nextPage)
6✔
143
                        return ghResponse, err
6✔
144
                })
6✔
145
                if err != nil {
8✔
146
                        return
2✔
147
                }
2✔
148

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

362
        return prInfo, err
2✔
363
}
364

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

637
        return reviewInfos, nil
1✔
638
}
639

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

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

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

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

674
        return mapGitHubIssuesCommentToCommentInfoList(commentsList)
1✔
675
}
676

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

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

693
        }
694
        return nil
1✔
695
}
696

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

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

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

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

730
        return ghResponse, nil
1✔
731
}
732

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1006
        id = extractIdFronSarifIDIfExists(sarifID)
1✔
1007
        return
1✔
1008
}
1009

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

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

1025
        return
3✔
1026
}
1027

1028
func (client *GitHubClient) executeDownloadFileFromRepo(ctx context.Context, owner, repository, branch, path string) (content []byte, statusCode int, ghResponse *github.Response, err error) {
3✔
1029
        body, ghResponse, err := client.ghClient.Repositories.DownloadContents(ctx, owner, repository, path, &github.RepositoryContentGetOptions{Ref: branch})
3✔
1030
        defer func() {
6✔
1031
                if body != nil {
4✔
1032
                        err = errors.Join(err, body.Close())
1✔
1033
                }
1✔
1034
        }()
1035

1036
        if ghResponse == nil || ghResponse.Response == nil {
4✔
1037
                return
1✔
1038
        }
1✔
1039

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

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

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

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

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

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

1086
        latestCommitSHA := sourceBranchRef.Commit.SHA
1✔
1087
        ref := &github.Reference{
1✔
1088
                Ref:    github.String("refs/heads/" + newBranch),
1✔
1089
                Object: &github.GitObject{SHA: latestCommitSHA},
1✔
1090
        }
1✔
1091

1✔
1092
        return client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
1093
                _, _, err = client.ghClient.Git.CreateRef(ctx, owner, repository, ref)
1✔
1094
                if err != nil {
1✔
1095
                        return nil, err
×
1096
                }
×
1097
                return nil, nil
1✔
1098
        })
1099
}
1100

1101
func (client *GitHubClient) AddOrganizationSecret(ctx context.Context, owner, secretName, secretValue string) error {
2✔
1102
        err := validateParametersNotBlank(map[string]string{"secretName": secretName, "owner": owner, "secretValue": secretValue})
2✔
1103
        if err != nil {
2✔
1104
                return err
×
1105
        }
×
1106

1107
        publicKey, _, err := client.ghClient.Actions.GetOrgPublicKey(ctx, owner)
2✔
1108
        if err != nil {
3✔
1109
                return err
1✔
1110
        }
1✔
1111

1112
        encryptedValue, err := encryptSecret(publicKey, secretValue)
1✔
1113
        if err != nil {
1✔
1114
                return err
×
1115
        }
×
1116

1117
        secret := &github.EncryptedSecret{
1✔
1118
                Name:           secretName,
1✔
1119
                KeyID:          publicKey.GetKeyID(),
1✔
1120
                EncryptedValue: encryptedValue,
1✔
1121
                Visibility:     "all",
1✔
1122
        }
1✔
1123

1✔
1124
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
2✔
1125
                _, err = client.ghClient.Actions.CreateOrUpdateOrgSecret(ctx, owner, secret)
1✔
1126
                return nil, err
1✔
1127
        })
1✔
1128
        return err
1✔
1129
}
1130

1131
func (client *GitHubClient) CreateOrgVariable(ctx context.Context, owner, variableName, variableValue string) error {
2✔
1132
        err := validateParametersNotBlank(map[string]string{"owner": owner, "variableName": variableName, "variableValue": variableValue})
2✔
1133
        if err != nil {
2✔
1134
                return err
×
1135
        }
×
1136

1137
        variable := &github.ActionsVariable{
2✔
1138
                Name:       variableName,
2✔
1139
                Value:      variableValue,
2✔
1140
                Visibility: github.String("all"),
2✔
1141
        }
2✔
1142

2✔
1143
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1144
                _, err = client.ghClient.Actions.CreateOrgVariable(ctx, owner, variable)
2✔
1145
                return nil, err
2✔
1146
        })
2✔
1147
        return err
2✔
1148
}
1149

1150
func (client *GitHubClient) AllowWorkflows(ctx context.Context, owner string) error {
2✔
1151
        err := validateParametersNotBlank(map[string]string{"owner": owner})
2✔
1152
        if err != nil {
2✔
1153
                return err
×
1154
        }
×
1155

1156
        requestBody := &github.ActionsPermissions{
2✔
1157
                AllowedActions:      github.String("all"),
2✔
1158
                EnabledRepositories: github.String("all"),
2✔
1159
        }
2✔
1160

2✔
1161
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1162
                _, _, err = client.ghClient.Actions.EditActionsPermissions(ctx, owner, *requestBody)
2✔
1163
                return nil, err
2✔
1164
        })
2✔
1165
        return err
2✔
1166
}
1167

1168
func (client *GitHubClient) GetRepoCollaborators(ctx context.Context, owner, repo, affiliation, permission string) ([]string, error) {
2✔
1169
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repo": repo, "affiliation": affiliation, "permission": permission})
2✔
1170
        if err != nil {
2✔
1171
                return nil, err
×
1172
        }
×
1173

1174
        var collaborators []*github.User
2✔
1175
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1176
                var ghResponse *github.Response
2✔
1177
                var err error
2✔
1178
                collaborators, ghResponse, err = client.ghClient.Repositories.ListCollaborators(ctx, owner, repo, &github.ListCollaboratorsOptions{
2✔
1179
                        Affiliation: affiliation,
2✔
1180
                        Permission:  permission,
2✔
1181
                })
2✔
1182
                return ghResponse, err
2✔
1183
        })
2✔
1184
        if err != nil {
3✔
1185
                return nil, err
1✔
1186
        }
1✔
1187

1188
        var names []string
1✔
1189
        for _, collab := range collaborators {
2✔
1190
                names = append(names, collab.GetLogin())
1✔
1191
        }
1✔
1192
        return names, nil
1✔
1193
}
1194

1195
func (client *GitHubClient) GetRepoTeamsByPermissions(ctx context.Context, owner, repo string, permissions []string) ([]int64, error) {
2✔
1196
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repo": repo, "permissions": strings.Join(permissions, ",")})
2✔
1197
        if err != nil {
2✔
1198
                return nil, err
×
1199
        }
×
1200

1201
        var allTeams []*github.Team
2✔
1202
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1203
                var resp *github.Response
2✔
1204
                var err error
2✔
1205
                allTeams, resp, err = client.ghClient.Repositories.ListTeams(ctx, owner, repo, nil)
2✔
1206
                return resp, err
2✔
1207
        })
2✔
1208
        if err != nil {
3✔
1209
                return nil, err
1✔
1210
        }
1✔
1211

1212
        permMap := make(map[string]bool)
1✔
1213
        for _, p := range permissions {
2✔
1214
                permMap[strings.ToLower(p)] = true
1✔
1215
        }
1✔
1216

1217
        var matchedTeams []int64
1✔
1218
        for _, team := range allTeams {
2✔
1219
                if permMap[strings.ToLower(team.GetPermission())] {
2✔
1220
                        matchedTeams = append(matchedTeams, team.GetID())
1✔
1221
                }
1✔
1222
        }
1223

1224
        return matchedTeams, nil
1✔
1225
}
1226

1227
func (client *GitHubClient) CreateOrUpdateEnvironment(ctx context.Context, owner, repo, envName string, teams []int64, users []string) error {
2✔
1228
        err := validateParametersNotBlank(map[string]string{"owner": owner, "repo": repo, "envName": envName})
2✔
1229
        if err != nil {
2✔
1230
                return err
×
1231
        }
×
1232

1233
        var envReviewers []*github.EnvReviewers
2✔
1234
        for _, team := range teams {
4✔
1235
                envReviewers = append(envReviewers, &github.EnvReviewers{
2✔
1236
                        Type: github.String("Team"),
2✔
1237
                        ID:   &team,
2✔
1238
                })
2✔
1239
        }
2✔
1240

1241
        if len(envReviewers) >= ghMaxEnvReviewers {
2✔
1242
                envReviewers = envReviewers[:ghMaxEnvReviewers]
×
1243
                _, _, err := client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
×
1244
                        Reviewers: envReviewers,
×
1245
                })
×
1246
                return err
×
1247
        }
×
1248

1249
        for _, userName := range users {
2✔
1250
                user, _, err := client.ghClient.Users.Get(ctx, userName)
×
1251

×
1252
                if err != nil {
×
1253
                        return err
×
1254
                }
×
1255
                userId := user.GetID()
×
1256
                envReviewers = append(envReviewers, &github.EnvReviewers{
×
1257
                        Type: github.String("User"),
×
1258
                        ID:   github.Int64(userId),
×
1259
                })
×
1260
        }
1261

1262
        if len(envReviewers) >= ghMaxEnvReviewers {
2✔
1263
                envReviewers = envReviewers[:ghMaxEnvReviewers]
×
1264
                _, _, err := client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
×
1265
                        Reviewers: envReviewers,
×
1266
                })
×
1267
                return err
×
1268
        }
×
1269

1270
        _, _, err = client.ghClient.Repositories.CreateUpdateEnvironment(ctx, owner, repo, envName, &github.CreateUpdateEnvironment{
2✔
1271
                Reviewers: envReviewers,
2✔
1272
        })
2✔
1273
        return err
2✔
1274
}
1275

1276
func (client *GitHubClient) CommitAndPushFiles(
1277
        ctx context.Context,
1278
        owner, repo, sourceBranch, commitMessage, authorName, authorEmail string,
1279
        files []FileToCommit,
1280
) error {
2✔
1281
        if len(files) == 0 {
2✔
1282
                return errors.New("no files provided to commit")
×
1283
        }
×
1284

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

1290
        parentCommit, _, err := client.ghClient.Git.GetCommit(ctx, owner, repo, *ref.Object.SHA)
1✔
1291
        if err != nil {
1✔
1292
                return fmt.Errorf("failed to get parent commit: %w", err)
×
1293
        }
×
1294

1295
        var treeEntries []*github.TreeEntry
1✔
1296
        for _, file := range files {
2✔
1297
                blob, _, err := client.ghClient.Git.CreateBlob(ctx, owner, repo, &github.Blob{
1✔
1298
                        Content:  github.String(file.Content),
1✔
1299
                        Encoding: github.String("utf-8"),
1✔
1300
                })
1✔
1301
                if err != nil {
1✔
1302
                        return fmt.Errorf("failed to create blob for %s: %w", file.Path, err)
×
1303
                }
×
1304

1305
                // Add each file to the treeEntries
1306
                treeEntries = append(treeEntries, &github.TreeEntry{
1✔
1307
                        Path: github.String(file.Path),
1✔
1308
                        Mode: github.String(regularFileCode),
1✔
1309
                        Type: github.String("blob"),
1✔
1310
                        SHA:  blob.SHA,
1✔
1311
                })
1✔
1312
        }
1313

1314
        tree, _, err := client.ghClient.Git.CreateTree(ctx, owner, repo, *parentCommit.Tree.SHA, treeEntries)
1✔
1315
        if err != nil {
1✔
1316
                return fmt.Errorf("failed to create tree: %w", err)
×
1317
        }
×
1318

1319
        commit := &github.Commit{
1✔
1320
                Message: github.String(commitMessage),
1✔
1321
                Tree:    tree,
1✔
1322
                Parents: []*github.Commit{{SHA: parentCommit.SHA}},
1✔
1323
                Author: &github.CommitAuthor{
1✔
1324
                        Name:  github.String(authorName),
1✔
1325
                        Email: github.String(authorEmail),
1✔
1326
                        Date:  &github.Timestamp{Time: time.Now()},
1✔
1327
                },
1✔
1328
        }
1✔
1329

1✔
1330
        newCommit, _, err := client.ghClient.Git.CreateCommit(ctx, owner, repo, commit, nil)
1✔
1331
        if err != nil {
1✔
1332
                return fmt.Errorf("failed to create commit: %w", err)
×
1333
        }
×
1334

1335
        ref.Object.SHA = newCommit.SHA
1✔
1336
        _, _, err = client.ghClient.Git.UpdateRef(ctx, owner, repo, ref, false)
1✔
1337
        if err != nil {
1✔
1338
                return fmt.Errorf("failed to update branch ref: %w", err)
×
1339
        }
×
1340
        return nil
1✔
1341
}
1342

1343
func (client *GitHubClient) MergePullRequest(ctx context.Context, owner, repo string, prNumber int, commitMessage string) error {
2✔
1344
        err := client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1345
                _, resp, err := client.ghClient.PullRequests.Merge(ctx, owner, repo, prNumber, commitMessage, nil)
2✔
1346
                return resp, err
2✔
1347
        })
2✔
1348
        return err
2✔
1349
}
1350

1351
func (client *GitHubClient) executeGetRepositoryEnvironmentInfo(ctx context.Context, owner, repository, name string) (*RepositoryEnvironmentInfo, *github.Response, error) {
2✔
1352
        environment, ghResponse, err := client.ghClient.Repositories.GetEnvironment(ctx, owner, repository, name)
2✔
1353
        if err != nil {
3✔
1354
                return &RepositoryEnvironmentInfo{}, ghResponse, err
1✔
1355
        }
1✔
1356

1357
        if err = vcsutils.CheckResponseStatusWithBody(ghResponse.Response, http.StatusOK); err != nil {
1✔
1358
                return &RepositoryEnvironmentInfo{}, ghResponse, err
×
1359
        }
×
1360

1361
        reviewers, err := extractGitHubEnvironmentReviewers(environment)
1✔
1362
        if err != nil {
1✔
1363
                return &RepositoryEnvironmentInfo{}, ghResponse, err
×
1364
        }
×
1365

1366
        return &RepositoryEnvironmentInfo{
1✔
1367
                        Name:      environment.GetName(),
1✔
1368
                        Url:       environment.GetURL(),
1✔
1369
                        Reviewers: reviewers,
1✔
1370
                },
1✔
1371
                ghResponse,
1✔
1372
                nil
1✔
1373
}
1374

1375
func (client *GitHubClient) GetModifiedFiles(ctx context.Context, owner, repository, refBefore, refAfter string) ([]string, error) {
6✔
1376
        err := validateParametersNotBlank(map[string]string{
6✔
1377
                "owner":      owner,
6✔
1378
                "repository": repository,
6✔
1379
                "refBefore":  refBefore,
6✔
1380
                "refAfter":   refAfter,
6✔
1381
        })
6✔
1382
        if err != nil {
10✔
1383
                return nil, err
4✔
1384
        }
4✔
1385

1386
        var fileNamesList []string
2✔
1387
        err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1388
                var ghResponse *github.Response
2✔
1389
                fileNamesList, ghResponse, err = client.executeGetModifiedFiles(ctx, owner, repository, refBefore, refAfter)
2✔
1390
                return ghResponse, err
2✔
1391
        })
2✔
1392
        return fileNamesList, err
2✔
1393
}
1394

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

2✔
1402
        comparison, ghResponse, err := client.ghClient.Repositories.CompareCommits(ctx, owner, repository, refBefore, refAfter, listOptions)
2✔
1403
        if err != nil {
3✔
1404
                return nil, ghResponse, err
1✔
1405
        }
1✔
1406

1407
        if err = vcsutils.CheckResponseStatusWithBody(ghResponse.Response, http.StatusOK); err != nil {
1✔
1408
                return nil, ghResponse, err
×
1409
        }
×
1410

1411
        fileNamesSet := datastructures.MakeSet[string]()
1✔
1412
        for _, file := range comparison.Files {
18✔
1413
                fileNamesSet.Add(vcsutils.DefaultIfNotNil(file.Filename))
17✔
1414
                fileNamesSet.Add(vcsutils.DefaultIfNotNil(file.PreviousFilename))
17✔
1415
        }
17✔
1416

1417
        _ = fileNamesSet.Remove("") // Make sure there are no blank filepath.
1✔
1418
        fileNamesList := fileNamesSet.ToSlice()
1✔
1419
        sort.Strings(fileNamesList)
1✔
1420

1✔
1421
        return fileNamesList, ghResponse, nil
1✔
1422
}
1423

1424
// Extract code reviewers from environment
1425
func extractGitHubEnvironmentReviewers(environment *github.Environment) ([]string, error) {
2✔
1426
        var reviewers []string
2✔
1427
        protectionRules := environment.ProtectionRules
2✔
1428
        if protectionRules == nil {
2✔
1429
                return reviewers, nil
×
1430
        }
×
1431
        reviewerStruct := repositoryEnvironmentReviewer{}
2✔
1432
        for _, rule := range protectionRules {
4✔
1433
                for _, reviewer := range rule.Reviewers {
5✔
1434
                        if err := mapstructure.Decode(reviewer.Reviewer, &reviewerStruct); err != nil {
3✔
1435
                                return []string{}, err
×
1436
                        }
×
1437
                        reviewers = append(reviewers, reviewerStruct.Login)
3✔
1438
                }
1439
        }
1440
        return reviewers, nil
2✔
1441
}
1442

1443
func createGitHubHook(token, payloadURL string, webhookEvents ...vcsutils.WebhookEvent) *github.Hook {
4✔
1444
        contentType := "json"
4✔
1445
        return &github.Hook{
4✔
1446
                Events: getGitHubWebhookEvents(webhookEvents...),
4✔
1447
                Config: &github.HookConfig{
4✔
1448
                        ContentType: &contentType,
4✔
1449
                        URL:         &payloadURL,
4✔
1450
                        Secret:      &token,
4✔
1451
                },
4✔
1452
        }
4✔
1453
}
4✔
1454

1455
// Get varargs of webhook events and return a slice of GitHub webhook events
1456
func getGitHubWebhookEvents(webhookEvents ...vcsutils.WebhookEvent) []string {
4✔
1457
        events := datastructures.MakeSet[string]()
4✔
1458
        for _, event := range webhookEvents {
16✔
1459
                switch event {
12✔
1460
                case vcsutils.PrOpened, vcsutils.PrEdited, vcsutils.PrMerged, vcsutils.PrRejected:
8✔
1461
                        events.Add("pull_request")
8✔
1462
                case vcsutils.Push, vcsutils.TagPushed, vcsutils.TagRemoved:
4✔
1463
                        events.Add("push")
4✔
1464
                }
1465
        }
1466
        return events.ToSlice()
4✔
1467
}
1468

1469
func getGitHubRepositoryVisibility(repo *github.Repository) RepositoryVisibility {
5✔
1470
        switch *repo.Visibility {
5✔
1471
        case "public":
3✔
1472
                return Public
3✔
1473
        case "internal":
1✔
1474
                return Internal
1✔
1475
        default:
1✔
1476
                return Private
1✔
1477
        }
1478
}
1479

1480
func getGitHubCommitState(commitState CommitStatus) string {
7✔
1481
        switch commitState {
7✔
1482
        case Pass:
1✔
1483
                return "success"
1✔
1484
        case Fail:
1✔
1485
                return "failure"
1✔
1486
        case Error:
3✔
1487
                return "error"
3✔
1488
        case InProgress:
1✔
1489
                return "pending"
1✔
1490
        }
1491
        return ""
1✔
1492
}
1493

1494
func mapGitHubCommitToCommitInfo(commit *github.RepositoryCommit) CommitInfo {
8✔
1495
        parents := make([]string, len(commit.Parents))
8✔
1496
        for i, c := range commit.Parents {
15✔
1497
                parents[i] = c.GetSHA()
7✔
1498
        }
7✔
1499
        details := commit.GetCommit()
8✔
1500
        return CommitInfo{
8✔
1501
                Hash:          commit.GetSHA(),
8✔
1502
                AuthorName:    details.GetAuthor().GetName(),
8✔
1503
                CommitterName: details.GetCommitter().GetName(),
8✔
1504
                Url:           commit.GetURL(),
8✔
1505
                Timestamp:     details.GetCommitter().GetDate().UTC().Unix(),
8✔
1506
                Message:       details.GetMessage(),
8✔
1507
                ParentHashes:  parents,
8✔
1508
                AuthorEmail:   details.GetAuthor().GetEmail(),
8✔
1509
        }
8✔
1510
}
1511

1512
func mapGitHubIssuesCommentToCommentInfoList(commentsList []*github.IssueComment) (res []CommentInfo, err error) {
1✔
1513
        for _, comment := range commentsList {
3✔
1514
                res = append(res, CommentInfo{
2✔
1515
                        ID:      comment.GetID(),
2✔
1516
                        Content: comment.GetBody(),
2✔
1517
                        Created: comment.GetCreatedAt().Time,
2✔
1518
                })
2✔
1519
        }
2✔
1520
        return
1✔
1521
}
1522

1523
func mapGitHubPullRequestToPullRequestInfoList(pullRequestList []*github.PullRequest, withBody bool) (res []PullRequestInfo, err error) {
3✔
1524
        var mappedPullRequest PullRequestInfo
3✔
1525
        for _, pullRequest := range pullRequestList {
6✔
1526
                mappedPullRequest, err = mapGitHubPullRequestToPullRequestInfo(pullRequest, withBody)
3✔
1527
                if err != nil {
3✔
1528
                        return
×
1529
                }
×
1530
                res = append(res, mappedPullRequest)
3✔
1531
        }
1532
        return
3✔
1533
}
1534

1535
func encodeScanningResult(data string) (string, error) {
1✔
1536
        compressedScan, err := base64.EncodeGzip([]byte(data), 6)
1✔
1537
        if err != nil {
1✔
1538
                return "", err
×
1539
        }
×
1540

1541
        return compressedScan, err
1✔
1542
}
1543

1544
type repositoryEnvironmentReviewer struct {
1545
        Login string `mapstructure:"login"`
1546
}
1547

1548
func shouldRetryIfRateLimitExceeded(ghResponse *github.Response, requestError error) bool {
113✔
1549
        if ghResponse == nil || ghResponse.Response == nil {
163✔
1550
                return false
50✔
1551
        }
50✔
1552

1553
        if !slices.Contains(rateLimitRetryStatuses, ghResponse.StatusCode) {
124✔
1554
                return false
61✔
1555
        }
61✔
1556

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

1563
        body, err := io.ReadAll(ghResponse.Body)
1✔
1564
        if err != nil {
1✔
1565
                return false
×
1566
        }
×
1567
        return strings.Contains(string(body), "rate limit")
1✔
1568
}
1569

1570
func isRateLimitAbuseError(requestError error) bool {
4✔
1571
        var abuseRateLimitError *github.AbuseRateLimitError
4✔
1572
        var rateLimitError *github.RateLimitError
4✔
1573
        return errors.As(requestError, &abuseRateLimitError) || errors.As(requestError, &rateLimitError)
4✔
1574
}
4✔
1575

1576
func encryptSecret(publicKey *github.PublicKey, secretValue string) (string, error) {
1✔
1577
        publicKeyBytes, err := base64Utils.StdEncoding.DecodeString(publicKey.GetKey())
1✔
1578
        if err != nil {
1✔
1579
                return "", err
×
1580
        }
×
1581

1582
        var publicKeyDecoded [32]byte
1✔
1583
        copy(publicKeyDecoded[:], publicKeyBytes)
1✔
1584

1✔
1585
        encrypted, err := box.SealAnonymous(nil, []byte(secretValue), &publicKeyDecoded, rand.Reader)
1✔
1586
        if err != nil {
1✔
1587
                return "", err
×
1588
        }
×
1589

1590
        encryptedBase64 := base64Utils.StdEncoding.EncodeToString(encrypted)
1✔
1591
        return encryptedBase64, nil
1✔
1592
}
1593

1594
func (client *GitHubClient) ListAppRepositories(ctx context.Context) ([]AppRepositoryInfo, error) {
2✔
1595
        var results []AppRepositoryInfo
2✔
1596

2✔
1597
        var allRepositories []*github.Repository
2✔
1598
        for nextPage := 1; ; nextPage++ {
4✔
1599
                var repositoriesInPage *github.ListRepositories
2✔
1600
                var ghResponse *github.Response
2✔
1601
                var err error
2✔
1602
                err = client.runWithRateLimitRetries(func() (*github.Response, error) {
4✔
1603
                        repositoriesInPage, ghResponse, err = client.ghClient.Apps.ListRepos(ctx, &github.ListOptions{Page: nextPage})
2✔
1604
                        return ghResponse, err
2✔
1605
                })
2✔
1606
                if err != nil {
3✔
1607
                        return nil, err
1✔
1608
                }
1✔
1609
                allRepositories = append(allRepositories, repositoriesInPage.Repositories...)
1✔
1610
                if nextPage+1 > ghResponse.LastPage {
2✔
1611
                        break
1✔
1612
                }
1613
        }
1614

1615
        for _, repo := range allRepositories {
2✔
1616
                if repo == nil || repo.Owner == nil || repo.Owner.Login == nil || repo.Name == nil {
1✔
1617
                        continue
×
1618
                }
1619
                repoInfo := AppRepositoryInfo{
1✔
1620
                        ID:            repo.GetID(),
1✔
1621
                        Name:          vcsutils.DefaultIfNotNil(repo.Name),
1✔
1622
                        FullName:      vcsutils.DefaultIfNotNil(repo.FullName),
1✔
1623
                        Owner:         vcsutils.DefaultIfNotNil(repo.Owner.Login),
1✔
1624
                        Private:       repo.GetPrivate(),
1✔
1625
                        Description:   vcsutils.DefaultIfNotNil(repo.Description),
1✔
1626
                        URL:           vcsutils.DefaultIfNotNil(repo.HTMLURL),
1✔
1627
                        CloneURL:      vcsutils.DefaultIfNotNil(repo.CloneURL),
1✔
1628
                        SSHURL:        vcsutils.DefaultIfNotNil(repo.SSHURL),
1✔
1629
                        DefaultBranch: vcsutils.DefaultIfNotNil(repo.DefaultBranch),
1✔
1630
                }
1✔
1631
                results = append(results, repoInfo)
1✔
1632
        }
1633

1634
        return results, nil
1✔
1635
}
1636
func (client *GitHubClient) UploadSnapshotToDependencyGraph(ctx context.Context, owner, repo string, snapshot SbomSnapshot) error {
2✔
1637
        // Convert our SbomSnapshot to go-github's DependencyGraphSnapshot
2✔
1638
        ghSnapshot, err := convertToGitHubSnapshot(snapshot)
2✔
1639
        if err != nil {
2✔
NEW
1640
                return fmt.Errorf("failed to convert snapshot to GitHub format: %w", err)
×
NEW
1641
        }
×
1642

1643
        // Call the GitHub API to create the snapshot
1644
        _, ghResponse, err := client.ghClient.DependencyGraph.CreateSnapshot(ctx, owner, repo, ghSnapshot)
2✔
1645
        if err != nil {
3✔
1646
                return fmt.Errorf("failed to upload snapshot to dependency graph: %w", err)
1✔
1647
        }
1✔
1648

1649
        client.logger.Info("Successfully uploaded snapshot to dependency graph, status:", ghResponse.StatusCode)
1✔
1650
        return nil
1✔
1651
}
1652

1653
// Converts our SbomSnapshot to go-github's DependencyGraphSnapshot
1654
func convertToGitHubSnapshot(snapshot SbomSnapshot) (*github.DependencyGraphSnapshot, error) {
2✔
1655
        ghSnapshot := &github.DependencyGraphSnapshot{
2✔
1656
                Version: snapshot.Version,
2✔
1657
                Sha:     &snapshot.Sha,
2✔
1658
                Ref:     &snapshot.Ref,
2✔
1659
                Scanned: &github.Timestamp{Time: snapshot.Scanned}, // Use current time if not provided
2✔
1660
        }
2✔
1661

2✔
1662
        // Convert Job info
2✔
1663
        if snapshot.Job == nil {
2✔
NEW
1664
                return nil, fmt.Errorf("job information is required in the snapshot")
×
NEW
1665
        }
×
1666
        ghSnapshot.Job = &github.DependencyGraphSnapshotJob{
2✔
1667
                Correlator: &snapshot.Job.Correlator,
2✔
1668
                ID:         &snapshot.Job.ID,
2✔
1669
        }
2✔
1670

2✔
1671
        // Convert Detector info
2✔
1672
        if snapshot.Detector == nil {
2✔
NEW
1673
                return nil, fmt.Errorf("detector information is required in the snapshot")
×
NEW
1674
        }
×
1675
        ghSnapshot.Detector = &github.DependencyGraphSnapshotDetector{
2✔
1676
                Name:    &snapshot.Detector.Name,
2✔
1677
                Version: &snapshot.Detector.Version,
2✔
1678
                URL:     &snapshot.Detector.Url,
2✔
1679
        }
2✔
1680

2✔
1681
        // Convert Manifests
2✔
1682
        if len(snapshot.Manifests) == 0 {
2✔
NEW
1683
                return nil, fmt.Errorf("at least one manifest is required in the snapshot")
×
NEW
1684
        }
×
1685
        ghSnapshot.Manifests = make(map[string]*github.DependencyGraphSnapshotManifest)
2✔
1686
        for manifestName, manifest := range snapshot.Manifests {
4✔
1687
                ghManifest := &github.DependencyGraphSnapshotManifest{
2✔
1688
                        Name: &manifest.Name,
2✔
1689
                }
2✔
1690

2✔
1691
                // Convert File info
2✔
1692
                if manifest.File == nil {
2✔
NEW
1693
                        return nil, fmt.Errorf("manifest %s is missing file information", manifestName)
×
NEW
1694
                }
×
1695
                ghManifest.File = &github.DependencyGraphSnapshotManifestFile{SourceLocation: &manifest.File.SourceLocation}
2✔
1696

2✔
1697
                // Convert Resolved dependencies
2✔
1698
                if len(manifest.Resolved) == 0 {
2✔
NEW
1699
                        return nil, fmt.Errorf("manifest %s must have at least one resolved dependency", manifestName)
×
NEW
1700
                }
×
1701
                ghManifest.Resolved = make(map[string]*github.DependencyGraphSnapshotResolvedDependency)
2✔
1702
                for depName, dep := range manifest.Resolved {
8✔
1703
                        ghDep := &github.DependencyGraphSnapshotResolvedDependency{
6✔
1704
                                PackageURL:   &dep.PackageURL,
6✔
1705
                                Dependencies: dep.Dependencies,
6✔
1706
                        }
6✔
1707
                        ghManifest.Resolved[depName] = ghDep
6✔
1708
                }
6✔
1709

1710
                ghSnapshot.Manifests[manifestName] = ghManifest
2✔
1711
        }
1712

1713
        return ghSnapshot, nil
2✔
1714
}
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