/
repository.go
380 lines (312 loc) · 9.36 KB
/
repository.go
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// # Copyright 2020 Jon Engelsman
// # Copyright 2020 Google LLC
// #
// # Licensed under the Apache License, Version 2.0 (the "License");
// # you may not use this file except in compliance with the License.
// # You may obtain a copy of the License at
// #
// # http://www.apache.org/licenses/LICENSE-2.0
// #
// # Unless required by applicable law or agreed to in writing, software
// # distributed under the License is distributed on an "AS IS" BASIS,
// # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// # See the License for the specific language governing permissions and
// # limitations under the License.
package criticalityscore
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"math"
"net/http"
"net/url"
"strconv"
"time"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
var (
ErrRepoNotProvided error = fmt.Errorf("please provided a repo url")
ErrInvalidGitHubURL error = fmt.Errorf("invalid github url")
ErrRepoNotFound error = fmt.Errorf("repo not found")
ErrAPIResponseError error = fmt.Errorf("github api response error, please try again")
ErrCommitFrequencyBeingCalculated error = fmt.Errorf("commit frequency is being calculated by github, please try again")
)
// GitHubRepository is an object that provides a GitHub client interface for a single repository.
type GitHubRepository struct {
ctx context.Context
client *github.Client
R *github.Repository
Error error
}
// LoadRepository returns a GitHubRepository object from a GitHub repository URL
// and an authorized GitHUB personal access token.
func LoadRepository(repoURL, token string) (GitHubRepository, error) {
if repoURL == "" {
return GitHubRepository{}, ErrRepoNotProvided
}
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
pauseIfGitHubRateLimitExceeded(client, ctx)
owner, name := parseRepoURL(repoURL)
if owner == "" || name == "" {
return GitHubRepository{}, ErrInvalidGitHubURL
}
r, _, err := client.Repositories.Get(ctx, owner, name)
if err != nil {
return GitHubRepository{}, ErrRepoNotFound
}
return GitHubRepository{
ctx: ctx,
client: client,
R: r,
}, nil
}
// Criteria important for ranking.
// CreatedSince returns the number of months since the repository was created.
func (ghr GitHubRepository) CreatedSince() int {
difference := time.Since(ghr.R.CreatedAt.Time)
return int(math.Round(difference.Hours() / 24.0 / 30.0))
}
// UpdatedSince returns the number of months since the last commit.
func (ghr GitHubRepository) UpdatedSince() int {
commits, _, err := ghr.client.Repositories.ListCommits(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName(), nil)
if err != nil {
ghr.Error = err
return 0
}
lastCommit := commits[0]
difference := time.Since(lastCommit.Commit.Author.GetDate())
return int(math.Round(difference.Hours() / 24.0 / 30.0))
}
// Contributors returns the number of all contributors.
func (ghr GitHubRepository) Contributors() int {
opts := &github.ListContributorsOptions{
Anon: "true",
ListOptions: github.ListOptions{
PerPage: 1,
},
}
contributors, resp, err := ghr.client.Repositories.ListContributors(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName(), opts)
if err != nil {
ghr.Error = err
return 0
}
if resp.Header.Get("link") == "" {
return len(contributors)
}
return totalCount(resp)
}
// ContributorOrgs returns a map of companies associated with each of the top contributors.
func (ghr GitHubRepository) ContributorOrgs() map[string]bool {
opts := &github.ListContributorsOptions{
Anon: "false",
ListOptions: github.ListOptions{
PerPage: 25,
},
}
var allContributors []*github.Contributor
for {
contributors, resp, err := ghr.client.Repositories.ListContributors(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName(), opts)
if err != nil {
ghr.Error = err
return nil
}
allContributors = append(allContributors, contributors...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
if len(allContributors) > TopContributorCount {
break
}
}
orgs := make(map[string]bool)
if len(allContributors) > 5000 {
for i := 0; i < 10; i++ {
orgs[string(i)] = true
}
return orgs
}
maxContributorCount := len(allContributors) - 1
if maxContributorCount > TopContributorCount {
maxContributorCount = TopContributorCount
}
var allUsers []*github.User
for _, contributor := range allContributors[:maxContributorCount] {
user, _, err := ghr.client.Users.GetByID(ghr.ctx, contributor.GetID())
if err != nil {
continue
}
allUsers = append(allUsers, user)
company := user.GetCompany()
if company == "" {
continue
}
name := filterOrgName(company)
orgs[name] = true
}
return orgs
}
// CommitFrequency returns the weekly average number of commits.
func (ghr GitHubRepository) CommitFrequency() float64 {
weekStats, resp, err := ghr.client.Repositories.ListCommitActivity(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName())
if err != nil {
if resp.StatusCode == 202 {
ghr.Error = ErrCommitFrequencyBeingCalculated
return 0
}
ghr.Error = err
return 0
}
total := 0
for _, weekStat := range weekStats {
total += weekStat.GetTotal()
}
return math.Round(float64(total)/52.0*10.0) / 10
}
// RecentReleases returns the number of recent repository releases.
// If none found within the number of ReleaseLookbackDays, then an estimate
// is calculated based on totalTags / daysSinceCreation * ReleaseLookbackDays.
func (ghr GitHubRepository) RecentReleases() int {
opts := &github.ListOptions{
PerPage: 100,
}
var allReleases []*github.RepositoryRelease
for {
releases, resp, err := ghr.client.Repositories.ListReleases(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName(), opts)
if err != nil {
ghr.Error = err
return 0
}
allReleases = append(allReleases, releases...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
total := 0
for _, release := range allReleases {
if time.Since(release.CreatedAt.Time).Hours()/24.0 > ReleaseLookbackDays {
continue
}
total++
}
if total != 0 {
return total
}
daysSinceCreation := int(time.Since(ghr.R.CreatedAt.Time).Hours() / 24.0)
if daysSinceCreation == 0 {
return 0
}
opts = &github.ListOptions{
PerPage: 1,
}
_, resp2, err := ghr.client.Repositories.ListTags(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName(), opts)
if err != nil {
ghr.Error = err
return 0
}
totalTags := totalCount(resp2)
return int(math.Round(float64(totalTags) / float64(daysSinceCreation) * ReleaseLookbackDays))
}
// UpdatedIssues returns the number of all repository issues.
func (ghr GitHubRepository) UpdatedIssues() int {
issuesSinceTime := time.Now().Add(-IssueLookbackDays * 24.0 * time.Hour)
opts := &github.IssueListByRepoOptions{
State: "all",
Since: issuesSinceTime,
ListOptions: github.ListOptions{
PerPage: 1,
},
}
issues, resp, err := ghr.client.Issues.ListByRepo(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName(), opts)
if err != nil {
ghr.Error = err
return 0
}
if resp.Header.Get("link") == "" {
return len(issues)
}
return totalCount(resp)
}
// ClosedIssues returns the number of closed repository issues.
func (ghr GitHubRepository) ClosedIssues() int {
issuesSinceTime := time.Now().Add(-IssueLookbackDays * 24.0 * time.Hour)
opts := &github.IssueListByRepoOptions{
State: "closed",
Since: issuesSinceTime,
ListOptions: github.ListOptions{
PerPage: 1,
},
}
issues, resp, err := ghr.client.Issues.ListByRepo(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName(), opts)
if err != nil {
ghr.Error = err
return 0
}
if resp.Header.Get("link") == "" {
return len(issues)
}
return totalCount(resp)
}
// CommentFrequency returns the ratio of comments to issues.
func (ghr GitHubRepository) CommentFrequency(issueCount int) float64 {
if issueCount == 0 {
return 0
}
issuesSinceTime := time.Now().Add(-IssueLookbackDays * 24.0 * time.Hour)
opts := &github.IssueListCommentsOptions{
Since: issuesSinceTime,
ListOptions: github.ListOptions{
PerPage: 1,
},
}
comments, resp, err := ghr.client.Issues.ListComments(ghr.ctx, ghr.R.GetOwner().GetLogin(), ghr.R.GetName(), 0, opts)
if err != nil {
ghr.Error = err
return 0
}
var commentCount int
if resp.Header.Get("link") == "" {
commentCount = len(comments)
} else {
commentCount = totalCount(resp)
}
return math.Round(float64(commentCount)/float64(issueCount)*10) / 10
}
// Dependents returns the number of search results that contain the repository name as in a commit.
func (ghr GitHubRepository) Dependents() int {
params := url.Values{}
params.Add("q", fmt.Sprintf(`"%s/%s"`, ghr.R.GetOwner().GetLogin(), ghr.R.GetName()))
params.Add("type", "commits")
dependentsURL := fmt.Sprintf(`https://github.com/search?%s`, params.Encode())
var content []byte
for i := 1; i <= 3; i++ {
resp, err := http.Get(dependentsURL)
if err != nil {
continue
}
if resp.StatusCode == 200 {
content, err = ioutil.ReadAll(resp.Body)
if err != nil {
continue
}
break
}
time.Sleep(10 * time.Second)
}
match := DependentsRegex.FindSubmatch(content)
if len(match) == 0 {
return 0
}
b := bytes.ReplaceAll(match[1], []byte(","), []byte(""))
b = bytes.TrimSpace(b)
dependentsCount, _ := strconv.Atoi(string(b))
return dependentsCount
}