-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackend.py
261 lines (238 loc) · 7.8 KB
/
backend.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
# MIT License
#
# Copyright (c) 2019 Tomas Tomecek
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Getting the data from a backend: GitHub
"""
import json
import logging
from datetime import date
from typing import Dict, List
import requests
from show_me.constants import URL
logger = logging.getLogger(__name__)
START_DATE = "{year}-01-01T00:00:00"
END_DATE = "{year}-12-31T23:59:59"
INSANITY_QUERY = """
{{
viewer {{
contributionsCollection(from: "{start_date}", to: "{end_date}") {{
commitContributionsByRepository {{
contributions(first: 100{commit_cursor}) {{
edges {{
cursor
node {{
commitCount
repository {{
nameWithOwner
stargazers {{
totalCount
}}
}}
}}
}}
}}
}}
pullRequestReviewContributions(first: 100{review_cursor}) {{
edges {{
cursor
node {{
repository {{
nameWithOwner
stargazers {{
totalCount
}}
}}
}}
}}
}}
pullRequestContributions(first: 100{pr_cursor}) {{
edges {{
cursor
node {{
pullRequest {{
commits {{
totalCount
}}
title
repository {{
nameWithOwner
stargazers {{
totalCount
}}
}}
}}
}}
}}
}}
issueContributions(first: 100{issue_cursor}) {{
edges {{
cursor
node {{
issue {{
title,
repository {{
nameWithOwner
stargazers {{
totalCount
}}
}}
}}
}}
}}
}}
}}
}}
}}
"""
def render_template_query(
year, issue_cursor="", pr_cursor="", review_cursor="", commit_cursor=""
):
if issue_cursor:
issue_cursor = f', after: "{issue_cursor}"'
if pr_cursor:
pr_cursor = f', after: "{pr_cursor}"'
if review_cursor:
review_cursor = f', after: "{review_cursor}"'
if commit_cursor:
commit_cursor = f', after: "{commit_cursor}"'
q = INSANITY_QUERY.format(
start_date=START_DATE.format(year=year),
end_date=END_DATE.format(year=year),
issue_cursor=issue_cursor,
pr_cursor=pr_cursor,
review_cursor=review_cursor,
commit_cursor=commit_cursor,
)
return q
class G:
""" GraphQL client """
issue_cursor: str
pr_cursor: str
review_cursor: str
commit_cursor: str
def __init__(self, token):
self.session = requests.Session()
self.token = token
self.session.headers.update({"Authorization": f"bearer {token}"})
self.reset_cursors()
def reset_cursors(self):
self.issue_cursor = ""
self.pr_cursor = ""
self.review_cursor = ""
self.commit_cursor = ""
def request(self, query):
"""
do a GraphQL request
"""
if not self.token:
raise RuntimeError(
"Please set an environment variable GITHUB_TOKEN with your GitHub API token.\n"
'You can obtain it at "https://github.com/settings/tokens".'
)
assert self.token, "Please set a github token."
logger.debug(f"query = {query}")
response = self.session.post(url=URL, json={"query": query})
return response
def _get_i_cursor(self, contrib_collection):
i_edges = contrib_collection["issueContributions"]["edges"]
if i_edges:
self.issue_cursor = i_edges[-1]["cursor"]
return True
def _get_pr_cursor(self, contrib_collection):
pr_edges = contrib_collection["pullRequestContributions"]["edges"]
if pr_edges:
self.pr_cursor = pr_edges[-1]["cursor"]
return True
def _get_r_cursor(self, contrib_collection):
r_edges = contrib_collection["pullRequestReviewContributions"]["edges"]
if r_edges:
self.review_cursor = r_edges[-1]["cursor"]
return True
def _get_c_cursor(self, contrib_collection):
response = None
max = 0
for c in contrib_collection["commitContributionsByRepository"]:
edges = c["contributions"]["edges"]
if not edges:
continue
num = len(edges)
cursor = edges[-1]["cursor"]
if num > max:
response = cursor
max = num
logger.debug(f"items = {num}, cursor = {cursor}")
if response:
self.commit_cursor = response
return response
def _get_template_query(self, year, last_response=None):
if last_response:
cc = last_response["data"]["viewer"]["contributionsCollection"]
if not any(
(
self._get_i_cursor(cc),
self._get_pr_cursor(cc),
self._get_r_cursor(cc),
self._get_c_cursor(cc),
)
):
logger.debug("we know everything now")
# everything is processed
return
return render_template_query(
year,
issue_cursor=self.issue_cursor,
pr_cursor=self.pr_cursor,
review_cursor=self.review_cursor,
commit_cursor=self.commit_cursor,
)
def get_contributions(self, start_year: int) -> List[Dict]:
"""
Query GitHub using GraphQL and return a list of responses
We need to paginate because GitHub does not return:
* more than 100 entries per collection
* for more than one year
:param start_year: int
"""
# we could make this function async and display stuff real-time
json_set = []
j = None
current_year = date.today().year
if start_year >= current_year:
raise RuntimeError(f"The start year should be smaller than {current_year}.")
years_to_scan = iter(range(start_year, current_year))
year = next(years_to_scan)
while True:
query = self._get_template_query(year, last_response=j)
if not query:
self.reset_cursors()
j = None
try:
year = next(years_to_scan)
except StopIteration:
break
continue
j = self.request(query).json()
if "errors" in j:
raise RuntimeError(json.dumps(j, indent=2))
json_set.append(j) # we would yield here instead
logger.debug("# of queries = %d", len(json_set))
return json_set