forked from target/pull-request-code-coverage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.go
More file actions
74 lines (61 loc) · 2.17 KB
/
Copy pathdiff.go
File metadata and controls
74 lines (61 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Package githubdiff fetches a pull request's unified diff directly from the
// GitHub REST API, so the plugin can determine what a PR changed without a git
// checkout. It is an alternative to reading the diff piped in on stdin.
package githubdiff
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/pkg/errors"
"github.com/target/pull-request-code-coverage/internal/plugin/pluginhttp"
)
const httpResponseOK = 200
// Loader retrieves the diff for a single pull request from the GitHub API.
type Loader struct {
apiKey string
apiBaseURL string
pr string
owner string
repo string
httpClient pluginhttp.Client
}
func NewLoader(apiKey string, apiBaseURL string, pr string, owner string, repo string, httpClient pluginhttp.Client) *Loader {
return &Loader{
apiKey: apiKey,
apiBaseURL: apiBaseURL,
pr: pr,
owner: owner,
repo: repo,
httpClient: httpClient,
}
}
// Load requests the pull request diff using the `application/vnd.github.v3.diff`
// media type. GitHub returns the same unified diff it shows reviewers — computed
// against the merge base and carrying context lines — which the unified-diff
// parser handles. The whole response is read into memory and returned as a
// reader so the caller can treat it exactly like the stdin diff.
func (l *Loader) Load() (io.Reader, error) {
url := fmt.Sprintf("%v/repos/%v/%v/pulls/%v", strings.TrimRight(l.apiBaseURL, "/"), l.owner, l.repo, l.pr)
req, newErr := l.httpClient.NewRequest("GET", url, nil)
if newErr != nil {
return nil, errors.Wrap(newErr, "Failed creating request to github")
}
req.Header.Add("Authorization", "token "+l.apiKey)
req.Header.Add("Accept", "application/vnd.github.v3.diff")
resp, doErr := l.httpClient.Do(req)
if doErr != nil {
return nil, errors.Wrap(doErr, "Failed calling github")
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != httpResponseOK {
return nil, errors.Errorf("Failed calling github: bad status code: %v", resp.StatusCode)
}
body, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return nil, errors.Wrap(readErr, "Failed reading diff response from github")
}
return bytes.NewReader(body), nil
}