forked from jstrieb/github-stats
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithub_api_queries.py
More file actions
270 lines (247 loc) · 9.19 KB
/
Copy pathgithub_api_queries.py
File metadata and controls
270 lines (247 loc) · 9.19 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
#!/usr/bin/python3
from asyncio import Semaphore, sleep
from requests import post, get
from aiohttp import ClientSession
from typing import Dict, Optional, List
from requests import get
from json import loads
###############################################################################
# GitHubApiQueries class
###############################################################################
class GitHubApiQueries(object):
"""
Class with functions to query the GitHub GraphQL (v4) API and the REST (v3)
API. Also includes functions to dynamically generate GraphQL queries.
"""
__GITHUB_API_URL = "https://api.github.com/"
__GRAPHQL_PATH = "graphql"
__REST_QUERY_LIMIT = 60
__ASYNCIO_SLEEP_TIME = 2
__DEFAULT_MAX_CONNECTIONS = 10
def __init__(self,
username: str,
access_token: str,
session: ClientSession,
max_connections: int = __DEFAULT_MAX_CONNECTIONS):
self.username = username
self.access_token = access_token
self.session = session
self.semaphore = Semaphore(max_connections)
self.headers = {
"Authorization": f"Bearer {self.access_token}",
}
async 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
"""
try:
async with self.semaphore:
r_async = await self.session.post(
self.__GITHUB_API_URL + self.__GRAPHQL_PATH,
headers=self.headers,
json={"query": generated_query},
)
result = await r_async.json()
if result is not None:
return result
except:
print("aiohttp failed for GraphQL query")
# Fall back on non-async requests
async with self.semaphore:
r_requests = post(
self.__GITHUB_API_URL + self.__GRAPHQL_PATH,
headers=self.headers,
json={"query": generated_query},
)
result = r_requests.json()
if result is not None:
return result
return dict()
async def query_rest(self,
path: str,
params: Optional[Dict] = None) -> Dict:
"""
Make a request to the REST API
:param path: API path to query
:param params: Query parameters to be passed to the API
:return: deserialized REST JSON output
"""
for i in range(self.__REST_QUERY_LIMIT):
if params is None:
params = dict()
if path.startswith("/"):
path = path[1:]
try:
async with self.semaphore:
r_async = await self.session.get(
self.__GITHUB_API_URL + path,
headers=self.headers,
params=tuple(params.items()),
)
if r_async.status == 202:
print(f"A path returned 202. Retrying...")
await sleep(self.__ASYNCIO_SLEEP_TIME)
continue
result = await r_async.json()
if result is not None:
return result
except:
print("aiohttp failed for REST query attempt #" + str(i + 1))
# Fall back on non-async requests
async with self.semaphore:
r_requests = get(
self.__GITHUB_API_URL + path,
headers=self.headers,
params=tuple(params.items()),
)
if r_requests.status_code == 202:
print(f"A path returned 202. Retrying...")
await sleep(self.__ASYNCIO_SLEEP_TIME)
continue
elif r_requests.status_code == 200:
return r_requests.json()
print("Too many 202s. Data for this repository will be incomplete.")
return dict()
@staticmethod
def repos_overview(contrib_cursor: Optional[str] = None,
owned_cursor: Optional[str] = None) -> str:
"""
:return: GraphQL queries with overview of user repositories
"""
return f"""
{{
viewer {{
login,
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
isFork
isEmpty
isArchived
isPrivate
languages(first: 20, 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
isFork
isEmpty
isArchived
isPrivate
languages(first: 20, orderBy: {{
field: SIZE,
direction: DESC
}}) {{
edges {{
size
node {{
name
color
}}
}}
}}
}}
}}
}}
}}"""
@staticmethod
def contributions_all_years() -> str:
"""
:return: GraphQL query to get all years the user has been a contributor
"""
return """
query {
viewer {
contributionsCollection {
contributionYears
}
}
}"""
@staticmethod
def contributions_by_year(year: str) -> str:
"""
:param year: year to query for
:return: portion of a GraphQL query with desired info for a given year
"""
return f"""
year{year}: contributionsCollection(
from: "{year}-01-01T00:00:00Z",
to: "{int(year) + 1}-01-01T00:00:00Z"
) {{
contributionCalendar {{
totalContributions
}}
}}"""
@classmethod
def all_contributions(cls, years: List[str]) -> str:
"""
:param years: list of years to get contributions for
:return: query to retrieve contribution information for all user years
"""
by_years = "\n".join(map(cls.contributions_by_year, years))
return f"""
query {{
viewer {{
{by_years}
}}
}}"""
@staticmethod
def get_language_colors():
url = get("https://raw.githubusercontent.com/ozh/github-colors/master/colors.json")
return loads(url.text)