forked from maropu/predictive-testing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_apis.py
More file actions
421 lines (322 loc) · 16.1 KB
/
Copy pathgithub_apis.py
File metadata and controls
421 lines (322 loc) · 16.1 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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#!/usr/bin/env python3
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
# TODO: Replaces the current GitHub v3 API with v4 one (GraphQL)
import json
import requests # type: ignore
import retrying
import timeout_decorator
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from ptesting import github_utils
from ptesting.github_api_types import *
def _setup_default_logger() -> Any:
from logging import getLogger, NullHandler, DEBUG
logger = getLogger(__name__)
logger.setLevel(DEBUG)
logger.addHandler(NullHandler())
logger.propagate = False
return logger
_default_logger = _setup_default_logger()
def _to_debug_msg(ret: Any) -> str:
if type(ret) == dict:
return f"top-level keys:{','.join(sorted(ret.keys()))}"
elif type(ret) == list:
return f"list length:{len(ret)}"
else:
return "ret:<unknown>"
def _to_error_msg(text: str) -> str:
try:
return (json.loads(text))['message']
except:
return text
def is_rate_limit_exceeded(msg: str) -> bool:
return msg.find('API rate limit exceeded') != -1
def is_not_found(msg: str) -> bool:
return msg.find('Not Found') != -1
# For a list of requests's exceptions, see:
# https://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions
def _retry_if_timeout(caught: Exception) -> bool:
return isinstance(caught, requests.exceptions.Timeout)
@timeout_decorator.timeout(600, timeout_exception=RuntimeError)
@retrying.retry(stop_max_attempt_number=3, wait_exponential_multiplier=1000, wait_exponential_max=4000,
retry_on_exception=_retry_if_timeout,
wrap_exception=False)
def _request_github_api(api: str, token: str, params: Dict[str, str] = {}, pass_thru: bool = False,
logger: Any = _default_logger) -> Any:
headers = {
'Accept': 'application/vnd.github.v3+json',
'Authorization': f'Token {token}', 'User-Agent': 'github-apis'
}
ret = requests.get(f'https://api.github.com/{api}', timeout=10, headers=headers, params=params, verify=False)
if ret.status_code != 200:
error_msg = "{} request (params={}) failed because: {}"
if ret.status_code == 403 and is_rate_limit_exceeded(ret.text):
error_msg = error_msg.format(api, str(params), 'the GitHub API rate limit exceeded')
else:
error_msg = error_msg.format(
api, str(params), f"status_code={ret.status_code}, msg='{_to_error_msg(ret.text)}'")
raise RuntimeError(error_msg)
if not pass_thru:
result = json.loads(ret.text)
logger.info(f"api:/{api}, params:{params}, {_to_debug_msg(result)}")
logger.debug(f"ret:{json.dumps(result, indent=4)}")
return result
else:
return ret.text
def _assert_github_prams(owner: str, repo: str, token: str) -> None:
def is_valid_str(s: str) -> bool:
return type(s) is str and len(s) > 0
assert is_valid_str(owner) and is_valid_str(repo) and is_valid_str(token), \
f"Invalid input found: owner={owner}, repo={repo}, token={token}"
def _always_false(d: str) -> bool:
return False
def _create_until_validator(until: Optional[datetime]) -> Any:
def validator(d: Optional[str]) -> bool:
return until < github_utils.from_github_datetime(d) if d is not None else False # type: ignore
return validator if until is not None else _always_false
def _create_since_validator(since: Optional[datetime]) -> Any:
def validator(d: Optional[str]) -> bool:
return since >= github_utils.from_github_datetime(d) if d is not None else False # type: ignore
return validator if since is not None else _always_false
def _create_date_filter(until: Optional[datetime], since: Optional[datetime]) -> Tuple[Any, Any]:
return _create_until_validator(until), _create_since_validator(since)
# https://docs.github.com/en/rest/reference/rate-limit#get-rate-limit-status-for-the-authenticated-user
def get_rate_limit(token: str, logger: Any = None) -> Dict[str, Any]:
rl = _request_github_api(f"rate_limit", token)
rl = RateLimits.parse_obj(rl)
return rl.dict()
# https://docs.github.com/en/rest/reference/pulls#list-pull-requests
def list_pullreqs(owner: str, repo: str, token: str,
until: Optional[datetime] = None, since: Optional[datetime] = None,
nmax: int = 100000,
logger: Any = None) -> List[Tuple[str, str, str, str, str, str, str, str]]:
_assert_github_prams(owner, repo, token)
logger = logger or _default_logger
pullreqs: List[Tuple[str, str, str, str, str, str, str, str]] = []
check_until_date, check_since_date = _create_date_filter(until, since)
rem_pages = nmax
npage = 1
while True:
per_page = 100 if rem_pages >= 100 else rem_pages
params = {'page': str(npage), 'per_page': str(per_page), 'state': 'all', 'sort': 'updated', 'direction': 'desc'}
prs = _request_github_api(f"repos/{owner}/{repo}/pulls", token, params=params, logger=logger)
for pullreq in prs:
pr = PullRequest.parse_obj(pullreq)
if check_until_date(pr.updated_at):
continue
if check_since_date(pr.updated_at):
return pullreqs
if pr.head.repo is not None:
pr_number = str(pr.number)
pr_created_at = pr.created_at
pr_updated_at = pr.updated_at
pr_title = pr.title
pr_body = pr.body
pr_user = pr.user.login # type: ignore
pr_repo = pr.head.repo.name
pr_branch = pr.head.ref
pullreqs.append((pr_number, pr_created_at, pr_updated_at, pr_title, pr_body, # type: ignore
pr_user, pr_repo, pr_branch))
else:
logger.warning(f"repository not found: pr_number={str(pr.number)}, " # type: ignore
f"pr_user={pr.user.login}")
rem_pages -= per_page
npage += 1
if len(prs) == 0 or rem_pages == 0:
return pullreqs
assert False, 'unreachable path'
return []
# https://docs.github.com/en/rest/reference/pulls#list-commits-on-a-pull-request
def list_commits_for(pr_number: str, owner: str, repo: str, token: str,
until: Optional[datetime] = None, since: Optional[datetime] = None,
nmax: int = 100000,
logger: Any = None) -> List[Tuple[str, str, str]]:
_assert_github_prams(owner, repo, token)
logger = logger or _default_logger
commits: List[Tuple[str, str, str]] = []
check_until_date, check_since_date = _create_date_filter(until, since)
rem_pages = nmax
npage = 1
while True:
per_page = 100 if rem_pages >= 100 else rem_pages
params = {'page': str(npage), 'per_page': str(per_page)}
pr_commits = _request_github_api(f"repos/{owner}/{repo}/pulls/{pr_number}/commits", token,
params=params, logger=logger)
for commit in pr_commits:
c = RepoCommit.parse_obj(commit)
commit_date = c.commit.author.date
# TODO: Are 'pr_commits' always sorted by 'commit_date'?
if check_until_date(commit_date):
continue
if check_since_date(commit_date):
return commits
commits.append((c.sha, commit_date, c.commit.message))
rem_pages -= per_page
npage += 1
if len(pr_commits) == 0 or rem_pages == 0:
return commits
assert False, 'unreachable path'
return []
# https://docs.github.com/en/rest/reference/repos#list-commits
def list_repo_commits(owner: str, repo: str, token: str,
path: Optional[str] = None, since: Optional[str] = None, until: Optional[str] = None,
nmax: int = 100000, logger: Any = None) -> List[Tuple[str, str, str, str]]:
_assert_github_prams(owner, repo, token)
logger = logger or _default_logger
# Adds some optional params if necessary
extra_params = {}
if path is not None:
extra_params['path'] = str(path)
if since is not None:
extra_params['since'] = str(since)
if until is not None:
extra_params['until'] = str(until)
commits: List[Tuple[str, str, str, str]] = []
rem_pages = nmax
npage = 1
while True:
per_page = 100 if rem_pages >= 100 else rem_pages
params = {'page': str(npage), 'per_page': str(per_page)}
params.update(extra_params)
file_commits = _request_github_api(f"repos/{owner}/{repo}/commits", token,
params=params, logger=logger)
for commit in file_commits:
c = RepoCommit.parse_obj(commit)
commit_user = ''
if c.author is not None:
commit_user = c.author.login # type: ignore
elif c.committer is not None:
commit_user = c.committer.login # type: ignore
commits.append((c.sha, commit_user, c.commit.author.date, c.commit.message))
rem_pages -= per_page
npage += 1
if len(file_commits) == 0 or rem_pages == 0:
return commits
assert False, 'unreachable path'
return []
def _list_change_files(api: str, token: str, logger: Any) -> Tuple[str, str, List[Tuple[str, str, str, str]]]:
logger = logger or _default_logger
latest_page = _request_github_api(api, token, params={'per_page': '1'}, logger=logger)
fc = FileCommits.parse_obj(latest_page)
latest_commit = fc.commits[0].commit if fc.commits is not None and len(fc.commits) > 0 \
else fc.commit
commit_date = latest_commit.author.date # type: ignore
commit_message = latest_commit.message # type: ignore
files: List[Tuple[str, str, List[Tuple[str, str, str, str]]]] = []
npage = 1
while True:
params = {'page': str(npage), 'per_page': '100'}
changed_files = _request_github_api(api, token, params=params, logger=logger)
cf = ChangedFiles.parse_obj(changed_files)
for f in cf.files:
files.append((f.filename, str(f.additions), str(f.deletions), str(f.changes))) # type: ignore
if len(cf.files) < 100:
return commit_date, commit_message, files # type: ignore
npage += 1
assert False, 'unreachable path'
return []
# https://docs.github.com/en/rest/reference/repos#get-a-commit
def list_change_files_from(ref: str, owner: str, repo: str, token: str,
logger: Any = None) -> Tuple[str, str, List[Tuple[str, str, str, str]]]:
_assert_github_prams(owner, repo, token)
return _list_change_files(f"repos/{owner}/{repo}/commits/{ref}", token, logger)
# https://docs.github.com/en/rest/reference/repos#compare-two-commits
def list_change_files_between(base: str, head: str, owner: str, repo: str, token: str,
logger: Any = None) -> Tuple[str, str, List[Tuple[str, str, str, str]]]:
_assert_github_prams(owner, repo, token)
return _list_change_files(f"repos/{owner}/{repo}/compare/{base}...{head}", token, logger)
# https://docs.github.com/en/rest/reference/actions#list-workflow-runs-for-a-repository
def list_workflow_runs(owner: str, repo: str, token: str,
until: Optional[datetime] = None, since: Optional[datetime] = None,
nmax: int = 100000, logger: Any = None) -> List[Tuple[str, str, str, str, str, str, str, str]]:
_assert_github_prams(owner, repo, token)
logger = logger or _default_logger
api = f'repos/{owner}/{repo}/actions/runs'
latest_run = _request_github_api(api, token, params={'per_page': '1'}, logger=logger)
wruns = WorkflowRuns.parse_obj(latest_run)
runs: List[Tuple[str, str, str, str, str, str, str, str]] = []
check_until_date, check_since_date = _create_date_filter(until, since)
num_pages = int(wruns.total_count / 100) + 1
rem_pages = nmax
for page in range(0, num_pages):
per_page = 100 if rem_pages >= 100 else rem_pages
params = {'page': str(page), 'per_page': str(per_page)}
wruns = _request_github_api(api, token=token, params=params, logger=logger)
for run in wruns['workflow_runs']: # type: ignore
run = WorkflowRun.parse_obj(run)
# TODO: Are 'wruns' always sorted by 'run.updated_at'?
if check_until_date(run.updated_at):
continue
if check_since_date(run.updated_at):
return runs
if run.status == 'completed':
if len(run.pull_requests) == 0:
pr_number, pr_head, pr_base = '', '', ''
else:
pr = run.pull_requests[0]
pr_number = str(pr.number)
pr_head = pr.head.sha
pr_base = pr.base.sha
runs.append((str(run.id), run.name, run.head_sha, run.event, run.conclusion,
pr_number, pr_head, pr_base))
rem_pages -= per_page
if len(wruns['workflow_runs']) == 0 or rem_pages == 0: # type: ignore
return runs
return runs
# https://docs.github.com/en/rest/reference/actions#list-jobs-for-a-workflow-run
def list_workflow_jobs(run_id: str, owner: str, repo: str, token: str, nmax: int = 100000,
logger: Any = None) -> List[Tuple[str, str, str]]:
_assert_github_prams(owner, repo, token)
logger = logger or _default_logger
api = f'repos/{owner}/{repo}/actions/runs/{run_id}/jobs'
latest_job = _request_github_api(api, token, params={'per_page': '1'}, logger=logger)
wjobs = WorkflowJobs.parse_obj(latest_job)
jobs: List[Tuple[str, str, str]] = []
num_pages = int(wjobs.total_count / 100) + 1
rem_pages = nmax
for page in range(0, num_pages):
per_page = 100 if rem_pages >= 100 else rem_pages
params = {'page': str(page), 'per_page': str(per_page)}
wjobs = _request_github_api(api, token=token, params=params, logger=logger)
for job in wjobs['jobs']: # type: ignore
job = WorkflowJob.parse_obj(job)
jobs.append((str(job.id), job.name, job.conclusion))
rem_pages -= per_page
if len(wjobs['jobs']) == 0 or rem_pages == 0: # type: ignore
return jobs
return jobs
# https://docs.github.com/en/rest/reference/actions#download-job-logs-for-a-workflow-run
def get_workflow_job_logs(job_id: str, owner: str, repo: str, token: str, logger: Any = None) -> str:
_assert_github_prams(owner, repo, token)
try:
return _request_github_api(f'repos/{owner}/{repo}/actions/jobs/{job_id}/logs', token, pass_thru=True)
except:
logger = logger or _default_logger
logger.warning(f"Job logs (job_id={job_id}) not found in {owner}/{repo}")
return ''
# https://docs.github.com/en/rest/reference/repos#get-all-contributor-commit-activity
def list_contributor_stats(owner: str, repo: str, token: str, logger: Any = None) -> List[Tuple[str, int]]:
_assert_github_prams(owner, repo, token)
logger = logger or _default_logger
contributors: List[Tuple[str, int]] = []
stats = _request_github_api(f"repos/{owner}/{repo}/stats/contributors", token, logger=logger)
for stat in stats:
stat = ContributorStat.parse_obj(stat)
contributors.append((stat.author.login, stat.total))
res = sorted(contributors, key=lambda c: c[1], reverse=True) # Sorted by 'total'
return res