-
Notifications
You must be signed in to change notification settings - Fork 602
/
github_stats.py
395 lines (351 loc) · 11.7 KB
/
github_stats.py
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#!/usr/bin/python3
import json
import hashlib
import os
import time
from typing import Dict, List, Optional, Set, Tuple
import requests
###############################################################################
# Main Classes
###############################################################################
class Queries(object):
def __init__(self, username: str, access_token: str):
self.username = username
self.access_token = access_token
self.session = requests.Session()
def query(self, generated_query: str) -> Dict:
"""
Make a request to the GraphQL API using the authentication token from
the environment
:param generated_query: string query to be sent to the API
:return: decoded GraphQL JSON output
"""
headers = {
"Authorization": f"Bearer {self.access_token}",
}
r = self.session.post("https://api.github.com/graphql", headers=headers,
json={"query": generated_query})
return r.json()
def query_rest(self, path: str, params: Optional[Dict] = None) -> Dict:
while True:
headers = {
"Authorization": f"token {self.access_token}",
}
auth = (self.username, self.access_token)
if params is None:
params = dict()
if path.startswith("/"):
path = path[1:]
r = self.session.get(f"https://api.github.com/{path}", headers=headers,
params=tuple(params.items()))
if r.status_code == 202:
print(f"{path} returned 202. Retrying...")
time.sleep(1)
continue
return r.json()
@staticmethod
def repos_overview(contrib_cursor: Optional[str] = None,
owned_cursor: Optional[str] = None) -> str:
return f"""{{
viewer {{
name
repositories(
first: 100,
orderBy: {{
field: UPDATED_AT,
direction: DESC
}},
after: {"null" if owned_cursor is None else '"'+ owned_cursor +'"'}
) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
nameWithOwner
stargazers {{
totalCount
}}
forkCount
languages(first: 10, orderBy: {{field: SIZE, direction: DESC}}) {{
edges {{
size
node {{
name
color
}}
}}
}}
}}
}}
repositoriesContributedTo(
first: 100,
includeUserRepositories: false,
orderBy: {{
field: UPDATED_AT,
direction: DESC
}},
contributionTypes: [
COMMIT,
PULL_REQUEST,
REPOSITORY,
PULL_REQUEST_REVIEW
]
after: {"null" if contrib_cursor is None else '"'+ contrib_cursor +'"'}
) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
nameWithOwner
stargazers {{
totalCount
}}
forkCount
languages(first: 10, orderBy: {{field: SIZE, direction: DESC}}) {{
edges {{
size
node {{
name
color
}}
}}
}}
}}
}}
}}
}}
"""
@staticmethod
def contrib_years() -> str:
return """
query {
viewer {
contributionsCollection {
contributionYears
}
}
}
"""
@staticmethod
def contribs_by_year(year: str) -> str:
return f"""
year{year}: contributionsCollection(
from: "{year}-01-01T00:00:00Z",
to: "{int(year) + 1}-01-01T00:00:00Z"
) {{
contributionCalendar {{
totalContributions
}}
}}
"""
@classmethod
def all_contribs(cls, years: List[str]) -> str:
by_years = "\n".join(map(cls.contribs_by_year, years))
return f"""
query {{
viewer {{
{by_years}
}}
}}
"""
class Stats(object):
def __init__(self, username: str, access_token: str,
exclude_repos: Optional[Set] = None):
self.username = username
self._exclude_repos = set() if exclude_repos is None else exclude_repos
self.queries = Queries(username, access_token)
self._name = None
self._stargazers = None
self._forks = None
self._total_contributions = None
self._languages = None
self._repos = None
self._lines_changed = None
self._views = None
def __str__(self) -> str:
formatted_languages = "\n - ".join(
[f"{k}: {v:0.4f}%" for k, v in self.languages.items()]
)
return f"""Name: {self.name}
Stargazers: {self.stargazers:,}
Forks: {self.forks:,}
All-time contributions: {self.total_contributions:,}
Repositories with contributions: {len(self.repos)}
Lines of code added: {self.lines_changed[0]:,}
Lines of code deleted: {self.lines_changed[1]:,}
Lines of code changed: {self.lines_changed[0] + self.lines_changed[1]:,}
Project page views: {self.views:,}
Languages:
- {formatted_languages}"""
def get_stats(self) -> None:
self._stargazers = 0
self._forks = 0
self._languages = dict()
self._repos = set()
next_owned = None
next_contrib = None
while True:
raw_results = self.queries.query(
Queries.repos_overview(owned_cursor=next_owned,
contrib_cursor=next_contrib)
)
self._name = (raw_results
.get("data", {})
.get("viewer", {})
.get("name", "No Name"))
contrib_repos = (raw_results
.get("data", {})
.get("viewer", {})
.get("repositoriesContributedTo", {}))
owned_repos = (raw_results
.get("data", {})
.get("viewer", {})
.get("repositories", {}))
repos = (contrib_repos.get("nodes", [])
+ owned_repos.get("nodes", []))
for repo in repos:
name = repo.get("nameWithOwner")
if name in self._repos:
continue
self._repos.add(name)
self._stargazers += repo.get("stargazers").get("totalCount", 0)
self._forks += repo.get("forkCount", 0)
if name in self._exclude_repos:
continue
for lang in repo.get("languages", {}).get("edges", []):
name = lang.get("node", {}).get("name", "Other")
if name in self.languages:
self.languages[name]["size"] += lang.get("size", 0)
self.languages[name]["occurrences"] += 1
else:
self.languages[name] = {
"size": lang.get("size", 0),
"occurrences": 1,
"color": lang.get("color")
}
if owned_repos.get("pageInfo", {}).get("hasNextPage", False) or \
contrib_repos.get("pageInfo", {}).get("hasNextPage", False):
next_owned = (owned_repos
.get("pageInfo", {})
.get("endCursor", next_owned))
next_contrib = (contrib_repos
.get("pageInfo", {})
.get("endCursor", next_contrib))
else:
break
@property
def name(self) -> str:
if self._name is not None:
return self._name
self.get_stats()
assert(self._name is not None)
return self._name
@property
def stargazers(self) -> int:
if self._stargazers is not None:
return self._stargazers
self.get_stats()
assert(self._stargazers is not None)
return self._stargazers
@property
def forks(self) -> int:
if self._forks is not None:
return self._forks
self.get_stats()
assert(self._forks is not None)
return self._forks
@property
def languages(self) -> Dict:
if self._languages is not None:
return self._languages
self.get_stats()
assert(self._languages is not None)
# TODO: Improve languages to scale by number of contributions to
# specific filetypes
langs_total = sum([v.get("size", 0) for v in self._languages.values()])
langs = {
k: 100 * (v.get("size", 0) / langs_total)
for k, v in self._languages.items()
}
return langs
@property
def repos(self) -> List[str]:
if self._repos is not None:
return self._repos
self.get_stats()
assert(self._repos is not None)
return self._repos
@property
def total_contributions(self) -> int:
if self._total_contributions is not None:
return self._total_contributions
self._total_contributions = 0
years = self.queries.query(Queries.contrib_years()) \
.get("data", {}) \
.get("viewer", {}) \
.get("contributionsCollection", {}) \
.get("contributionYears", [])
by_year = self.queries.query(Queries.all_contribs(years)) \
.get("data", {}) \
.get("viewer", {}).values()
for year in by_year:
self._total_contributions += year \
.get("contributionCalendar", {}) \
.get("totalContributions", 0)
return self._total_contributions
@property
def lines_changed(self) -> Tuple[int, int]:
if self._lines_changed is not None:
return self._lines_changed
additions = 0
deletions = 0
for repo in self.repos:
r = self.queries.query_rest(f"/repos/{repo}/stats/contributors")
for author_obj in r:
author = author_obj.get("author", {}).get("login", "")
if author != self.username:
continue
for week in author_obj.get("weeks", []):
additions += week.get("a", 0)
deletions += week.get("d", 0)
time.sleep(0.5)
self._lines_changed = (additions, deletions)
return self._lines_changed
@property
def views(self) -> int:
if self._views is not None:
return self._views
try:
with open("data/views_log.json", "r") as f:
views = json.load(f)
except FileNotFoundError:
views = dict()
for repo in self.repos:
key = hashlib.md5(repo.encode("utf-8")).hexdigest()
if key not in views:
views[key] = dict()
r = self.queries.query_rest(f"/repos/{repo}/traffic/views")
for view in r.get("views", []):
views[key][view.get("timestamp")] = view
time.sleep(0.5)
if not os.path.isdir("data"):
os.mkdir("data")
with open("data/views_log.json", "w") as f:
json.dump(views, f, indent=2)
total = 0
for repo in views.values():
for day in repo.values():
total += day.get("count", 0)
self._views = total
return total
###############################################################################
# Main Function
###############################################################################
def main() -> None:
access_token = os.getenv("ACCESS_TOKEN")
s = Stats("jstrieb", access_token)
print(s)
if __name__ == "__main__":
main()