forked from ashkulz/committers.top
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.go
More file actions
303 lines (265 loc) · 8.17 KB
/
github.go
File metadata and controls
303 lines (265 loc) · 8.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
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
package github
import (
"encoding/json"
"fmt"
"log"
"net/http"
"regexp"
"strings"
"time"
"most-active-github-users-counter/net"
)
const root string = "https://api.github.com/"
type HTTPGithubClient struct {
wrappers []net.Wrapper
}
func (client HTTPGithubClient) Request(url string, body string) ([]byte, error) {
httpClient := &http.Client{}
var req *http.Request
var err error
if body != "" {
req, err = http.NewRequest("POST", url, strings.NewReader(body))
} else {
req, err = http.NewRequest("GET", url, nil)
}
if err != nil {
return []byte{}, err
}
return net.Compose(client.wrappers...)(net.MakeRequester(httpClient))(req)
}
func (client HTTPGithubClient) CurrentUser() (User, error) {
body, err := client.Request(fmt.Sprintf("%suser", root), "")
if err != nil {
return User{}, err
}
user := User{}
if err := json.Unmarshal(body, &user); err != nil {
return User{}, err
}
return user, nil
}
func (client HTTPGithubClient) User(login string) (User, error) {
body, err := client.Request(fmt.Sprintf("%susers/%s", root, login), "")
if err != nil {
return User{}, err
}
user := User{}
if err := json.Unmarshal(body, &user); err != nil {
return User{}, err
}
return user, nil
}
func (client HTTPGithubClient) SearchUsers(query UserSearchQuery) (GithubSearchResults, error) {
users := []User{}
userLogins := map[string]bool{}
totalCount := 0
minFollowerCount := -1
maxPerQuery := 1000
perPage := 5
totalUsersCount := 0
retryCount := 0
maxRetryCount := 10
Pages:
for totalCount < query.MaxUsers {
previousCursor := ""
followerCountQueryStr := ""
if minFollowerCount >= 0 {
followerCountQueryStr = fmt.Sprintf(" followers:<%d", minFollowerCount)
}
for currentPage := 1; currentPage <= (maxPerQuery / perPage); currentPage++ {
cursorQueryStr := ""
if previousCursor != "" {
cursorQueryStr = fmt.Sprintf(", after: \\\"%s\\\"", previousCursor)
}
graphQlString := fmt.Sprintf(`{ "query": "query {
search(type: USER, query:\"%s%s sort:%s-%s\", first: %d%s) {
userCount
edges {
node {
__typename
... on User {
login,
avatarUrl,
name,
company,
organizations(first: 100) {
nodes {
login
}
}
followers {
totalCount
}
contributionsCollection {
contributionCalendar {
totalContributions
},
totalCommitContributions,
totalPullRequestContributions,
restrictedContributionsCount
}
}
},
cursor
}
}
}" }`, query.Q, followerCountQueryStr, query.Sort, query.Order, perPage, cursorQueryStr)
re := regexp.MustCompile(`\r?\n`)
graphQlString = re.ReplaceAllString(graphQlString, " ")
body, err := client.Request("https://api.github.com/graphql", graphQlString)
if err != nil {
retryCount++
if retryCount < maxRetryCount {
log.Println("error making graphql request... retrying")
time.Sleep(10 * time.Second)
continue Pages
} else {
log.Fatalln("Too many errors received. Quitting.")
}
}
var response interface{}
if err := json.Unmarshal(body, &response); err != nil {
retryCount++
if retryCount < maxRetryCount {
log.Println("error unmarshalling JSON response... retrying")
time.Sleep(10 * time.Second)
continue Pages
} else {
log.Fatalln("Too many errors received. Quitting.")
}
}
rootNode := response.(map[string]interface{})
if val, ok := rootNode["errors"]; ok {
retryCount++
if retryCount < maxRetryCount {
log.Printf("Received error response (retrying): %+v", val)
time.Sleep(10 * time.Second)
continue Pages
} else {
log.Fatalln("Too many errors received. Quitting.")
}
}
dataNode, ok := rootNode["data"].(map[string]interface{})
if !ok {
retryCount++
if retryCount < maxRetryCount {
log.Println("Error accessing data element")
time.Sleep(10 * time.Second)
continue Pages
} else {
log.Fatalln("Too many errors received. Quitting.")
}
}
searchNode := dataNode["search"].(map[string]interface{})
totalUsersCount = int(searchNode["userCount"].(float64))
edgeNodes := searchNode["edges"].([]interface{})
if len(edgeNodes) == 0 {
break Pages
}
totalCount += len(edgeNodes)
Edges:
for _, edge := range edgeNodes {
edgeNode := edge.(map[string]interface{})
userNode := edgeNode["node"].(map[string]interface{})
typename := userNode["__typename"].(string)
if typename != "User" {
continue Edges
}
login := userNode["login"].(string)
avatarURL := userNode["avatarUrl"].(string)
name := strPropOrEmpty(userNode, "name")
company := strPropOrEmpty(userNode, "company")
organizations := []string{}
orgNodes := userNode["organizations"].(map[string]interface{})["nodes"].([]interface{})
for _, orgNode := range orgNodes {
organizations = append(organizations, orgNode.(map[string]interface{})["login"].(string))
}
followerCount := int(userNode["followers"].(map[string]interface{})["totalCount"].(float64))
contributionsCollection := userNode["contributionsCollection"].(map[string]interface{})
contributionCount := int(contributionsCollection["contributionCalendar"].(map[string]interface{})["totalContributions"].(float64))
privateContributionCount := int(contributionsCollection["restrictedContributionsCount"].(float64))
commitsCount := int(contributionsCollection["totalCommitContributions"].(float64))
pullRequestsCount := int(contributionsCollection["totalPullRequestContributions"].(float64))
user := User{
Login: login,
AvatarURL: avatarURL,
Name: name,
Company: company,
Organizations: organizations,
FollowerCount: followerCount,
ContributionCount: contributionCount,
PublicContributionCount: (contributionCount - privateContributionCount),
PrivateContributionCount: privateContributionCount,
CommitsCount: commitsCount,
PullRequestsCount: pullRequestsCount}
if !userLogins[login] {
userLogins[login] = true
users = append(users, user)
}
previousCursor = edgeNode["cursor"].(string)
minFollowerCount = int(followerCount)
}
}
}
return GithubSearchResults{
Users: users,
MinimumFollowerCount: minFollowerCount,
TotalUserCount: totalUsersCount}, nil
}
func strPropOrEmpty(obj map[string]interface{}, prop string) string {
switch t := obj[prop].(type) {
case string:
return t
default:
return ""
}
}
func (client HTTPGithubClient) Organizations(login string) ([]string, error) {
url := fmt.Sprintf("https://api.github.com/users/%s/orgs", login)
body, err := client.Request(url, "")
if err != nil {
log.Fatalf("error requesting organizations for user %+v", login)
return []string{}, err
}
orgResp := []OrgResponse{}
err = json.Unmarshal(body, &orgResp)
if err != nil {
log.Fatalf("error parsing organizations JSON for user %+v", login)
return []string{}, err
}
orgs := []string{}
for _, org := range orgResp {
orgs = append(orgs, org.Organization)
}
return orgs, err
}
type OrgResponse struct {
Organization string `json:"login"`
}
func NewGithubClient(wrappers ...net.Wrapper) HTTPGithubClient {
return HTTPGithubClient{wrappers: wrappers}
}
type User struct {
Login string
AvatarURL string
Name string
Company string
Organizations []string
FollowerCount int
ContributionCount int
PublicContributionCount int
PrivateContributionCount int
CommitsCount int
PullRequestsCount int
}
type UserSearchQuery struct {
Q string
Sort string
Order string
MaxUsers int
}
type GithubSearchResults struct {
Users []User
MinimumFollowerCount int
TotalUserCount int
}