-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub_client.go
More file actions
219 lines (207 loc) · 6.69 KB
/
Copy pathgithub_client.go
File metadata and controls
219 lines (207 loc) · 6.69 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"time"
)
const githubAPIVersion = "2022-11-28"
type apiContribution struct {
Number int `json:"number"`
Title string `json:"title"`
State string `json:"state"`
HTMLURL string `json:"html_url"`
CreatedAt time.Time `json:"created_at"`
SubmittedAt time.Time `json:"submitted_at"`
User struct {
Login string `json:"login"`
} `json:"user"`
PullRequest *struct{} `json:"pull_request"`
}
func (c *GitHubClient) listContributionEvidence(ctx context.Context, fullName, username, kind string) ([]ContributionEvidence, error) {
owner, repo, err := splitRepository(fullName)
if err != nil {
return nil, err
}
path := fmt.Sprintf("/repos/%s/%s/%s", url.PathEscape(owner), url.PathEscape(repo), kind)
var all []ContributionEvidence
for page := 1; ; page++ {
q := url.Values{"state": {"all"}, "per_page": {"100"}, "page": {strconv.Itoa(page)}}
var batch []apiContribution
if err := c.get(ctx, path, q, &batch); err != nil {
return nil, err
}
for _, item := range batch {
if item.User.Login == username && (kind != "issues" || item.PullRequest == nil) {
date := item.CreatedAt
if !item.SubmittedAt.IsZero() {
date = item.SubmittedAt
}
all = append(all, ContributionEvidence{Number: item.Number, Title: item.Title, State: item.State, Date: date, URL: item.HTMLURL})
}
}
if len(batch) < 100 {
return all, nil
}
}
}
func (c *GitHubClient) listReviewEvidence(ctx context.Context, fullName, username string) ([]ContributionEvidence, error) {
owner, repo, err := splitRepository(fullName)
if err != nil {
return nil, err
}
base := fmt.Sprintf("/repos/%s/%s/pulls", url.PathEscape(owner), url.PathEscape(repo))
var all []ContributionEvidence
for page := 1; ; page++ {
var pulls []apiContribution
if err := c.get(ctx, base, url.Values{"state": {"all"}, "per_page": {"100"}, "page": {strconv.Itoa(page)}}, &pulls); err != nil {
return nil, err
}
for _, pull := range pulls {
var reviews []apiContribution
if err := c.get(ctx, fmt.Sprintf("%s/%d/reviews", base, pull.Number), url.Values{"per_page": {"100"}}, &reviews); err != nil {
return nil, err
}
for _, review := range reviews {
if review.User.Login == username {
all = append(all, ContributionEvidence{Number: pull.Number, Title: pull.Title, State: review.State, Date: review.SubmittedAt, URL: pull.HTMLURL})
}
}
}
if len(pulls) < 100 {
return all, nil
}
}
}
func (c *GitHubClient) getAuthenticatedUser(ctx context.Context) (User, error) {
var user User
if err := c.get(ctx, "/user", nil, &user); err != nil {
return User{}, err
}
if user.Login == "" {
return User{}, errors.New("GitHub returned an empty username")
}
return user, nil
}
func (c *GitHubClient) listRepositories(ctx context.Context) ([]Repository, error) {
var all []Repository
for page := 1; ; page++ {
query := url.Values{"visibility": {"all"}, "affiliation": {"owner,collaborator,organization_member"}, "sort": {"full_name"}, "direction": {"asc"}, "per_page": {"100"}, "page": {strconv.Itoa(page)}}
var batch []Repository
if err := c.get(ctx, "/user/repos", query, &batch); err != nil {
return nil, err
}
all = append(all, batch...)
if len(batch) < 100 {
return all, nil
}
}
}
func (c *GitHubClient) listUserCommits(ctx context.Context, fullName, username, since string) ([]Commit, error) {
owner, repo, err := splitRepository(fullName)
if err != nil {
return nil, err
}
var all []Commit
for page := 1; ; page++ {
query := url.Values{"author": {username}, "per_page": {"100"}, "page": {strconv.Itoa(page)}}
if since != "" {
sinceTime, err := parseSince(since)
if err != nil {
return nil, err
}
query.Set("since", sinceTime.Format(time.RFC3339))
}
path := fmt.Sprintf("/repos/%s/%s/commits", url.PathEscape(owner), url.PathEscape(repo))
var batch []Commit
if err := c.get(ctx, path, query, &batch); err != nil {
var apiErr *GitHubAPIError
if errors.As(err, &apiErr) && (apiErr.StatusCode == http.StatusConflict || apiErr.StatusCode == http.StatusNotFound) {
return nil, nil
}
return nil, err
}
all = append(all, batch...)
if len(batch) < 100 {
return all, nil
}
}
}
func (c *GitHubClient) getLanguages(ctx context.Context, fullName string) ([]LanguageStat, error) {
owner, repo, err := splitRepository(fullName)
if err != nil {
return nil, err
}
path := fmt.Sprintf("/repos/%s/%s/languages", url.PathEscape(owner), url.PathEscape(repo))
raw := map[string]int64{}
if err := c.get(ctx, path, nil, &raw); err != nil {
return nil, err
}
var total int64
for _, bytes := range raw {
total += bytes
}
languages := make([]LanguageStat, 0, len(raw))
for name, bytes := range raw {
percentage := 0.0
if total > 0 {
percentage = float64(bytes) / float64(total) * 100
}
languages = append(languages, LanguageStat{Name: name, Bytes: bytes, Percentage: round(percentage, 2)})
}
sort.Slice(languages, func(i, j int) bool { return languages[i].Bytes > languages[j].Bytes })
return languages, nil
}
type GitHubAPIError struct {
StatusCode int
Method string
URL string
Message string
Body string
}
func (e *GitHubAPIError) Error() string {
if e.Message != "" {
return fmt.Sprintf("github API %s %s returned %d: %s", e.Method, e.URL, e.StatusCode, e.Message)
}
return fmt.Sprintf("github API %s %s returned %d", e.Method, e.URL, e.StatusCode)
}
func (c *GitHubClient) get(ctx context.Context, path string, query url.Values, target any) error {
endpoint := c.baseURL + path
if len(query) > 0 {
endpoint += "?" + query.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("X-GitHub-Api-Version", githubAPIVersion)
req.Header.Set("User-Agent", "github-cv-evidence-generator")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request GitHub: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if err != nil {
return fmt.Errorf("read GitHub response: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var errorBody struct {
Message string `json:"message"`
}
_ = json.Unmarshal(body, &errorBody)
return &GitHubAPIError{StatusCode: resp.StatusCode, Method: http.MethodGet, URL: endpoint, Message: errorBody.Message, Body: string(body)}
}
if err := json.Unmarshal(body, target); err != nil {
return fmt.Errorf("decode GitHub response from %s: %w", endpoint, err)
}
return nil
}