-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdoit2.py
executable file
·263 lines (203 loc) · 8.07 KB
/
doit2.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
#!/usr/bin/env python3
import argparse
import datetime
import logging
import os
import re
import subprocess
import sys
import requests
import json
import tabulate
class _JSONDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, obj):
ret = {}
for key, value in obj.items():
if key in {"created_at"}:
ret[key] = datetime.datetime.fromisoformat(value)
else:
ret[key] = value
return ret
class _JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.date, datetime.datetime)):
return obj.isoformat()
return json.JSONEncoder.default(obj)
def _headers(args):
headers = {
"Accept": "application/vnd.github+json",
}
if args.token is not None:
headers["Authorization"] = f"Bearer {args.token}"
return headers
def _post_raw(url, **kwargs):
response = requests.post(url, **kwargs)
if not response.ok:
raise Exception(
f"Failed to get reposnse {url}: {response.status_code} {response.text}"
)
return response
def _get_raw(url, **kwargs):
response = requests.get(url, **kwargs)
if not response.ok:
raise Exception(
f"Failed to get reposnse {url}: {response.status_code} {response.text}"
)
return response
def _json_loads(text):
return json.loads(text, cls=_JSONDecoder)
def _json_dumps(data):
return json.dumps(data, cls=_JSONEncoder)
def _get_all(url, **kwargs):
while True:
response = _get_raw(url, **kwargs)
results = _json_loads(response.text)
logging.debug(f"From {url} got {len(results)} results")
for r in results:
yield r
if "next" in response.links:
url = response.links["next"]["url"]
else:
break
def list_commit_statuses_for_reference(args):
url = f"https://api.github.com/repos/{args.owner}/{args.repo}/commits/{args.commit}/statuses"
data = []
for response in _get_all(url, headers=_headers(args)):
data.append(response)
return data
def get_pull_request(args):
url = f"https://api.github.com/repos/{args.owner}/{args.repo}/pulls/{args.pull_number}"
data = _json_loads(_get_raw(url, headers=_headers(args)).text)
return data
def create_issue_comment(args):
url = f"https://api.github.com/repos/{args.owner}/{args.repo}/issues/{args.issue_number}/comments"
_post_raw(url, headers=_headers(args), json={"body": args.body})
def add_comment(args):
create_issue_comment(args)
def _checks_filter(args, data):
if args.latest_by_context:
data_new = {}
for d in data:
if d["context"] not in data_new:
data_new[d["context"]] = d
else:
if d["created_at"] > data_new[d["context"]]["created_at"]:
data_new[d["context"]] = d
data = list(data_new.values())
if args.filter_by_state is not None:
data = [d for d in data if d["state"] == args.filter_by_state]
if args.filter_by_context_re is not None:
data = [
d
for d in data
if d["context"] is not None
and re.search(args.filter_by_context_re, d["context"]) is not None
]
if args.filter_by_target_url_re is not None:
data = [
d
for d in data
if d["target_url"] is not None
and re.search(args.filter_by_target_url_re, d["target_url"]) is not None
]
if args.filter_by_created_at_ge is not None:
data = [d for d in data if d["created_at"] >= args.filter_by_created_at_ge]
return data
def list_checks(args):
data = get_pull_request(args)
args.commit = data["head"]["sha"]
data = list_commit_statuses_for_reference(args)
data = _checks_filter(args, data)
fields = ["created_at", "state", "context", "target_url"]
table = []
for d in data:
logging.debug(f"Processing: {_json_dumps(d)}")
row = [d[f] if f in d else None for f in fields]
table.append(row)
print(tabulate.tabulate(table, headers=fields))
if args.prow_download_path is not None:
print("")
for d in data:
guess_run_id = d["target_url"].split("/")[-1]
guess_job_name = d["target_url"].split("/")[-2]
guess_test_name = d["context"].split("/")[-1]
if not os.path.exists(guess_run_id):
os.makedirs(guess_run_id)
runme = [
"gsutil",
"-m",
"cp",
"-r",
f"gs://test-platform-results/pr-logs/pull/{args.owner}_{args.repo}/{args.pull_number}/{guess_job_name}/{guess_run_id}/artifacts/{guess_test_name}/{args.prow_download_path}",
f"{guess_run_id}/",
]
print(f"Downloading: {' '.join(runme)}")
process = subprocess.Popen(
runme, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
exit_code = process.returncode
if exit_code != 0:
logging.error(f"Failed to run: '{' '.join(runme)}'")
logging.error(f"stdout: {stdout.decode()}")
logging.error(f"stderr: {stderr.decode()}")
logging.error(f"Exit code: {exit_code}")
sys.exit(1)
print(f"...finished with {exit_code}")
def main():
parser = argparse.ArgumentParser(
description="Let's talk to GitHub, record what was done",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--token",
default=os.getenv("GITHUB_TOKEN", None),
help="GitHub personal access token",
)
parser.add_argument("-d", "--debug", action="store_true", help="Show debug output")
subparsers = parser.add_subparsers(help="Sub-command help")
parser_list_checks = subparsers.add_parser("list_checks", help="List checks")
parser_list_checks.set_defaults(func=list_checks)
parser_list_checks.add_argument("--owner", required=True, help="Owner of the repo")
parser_list_checks.add_argument("--repo", required=True, help="Repo name")
parser_list_checks.add_argument("--pull-number", help="PR number")
parser_list_checks.add_argument(
"--filter-by-state", help="Only show checks with this state"
)
parser_list_checks.add_argument(
"--filter-by-context-re",
help="Only show checks with context matching this regexp, check automatically excluded if its context is empty",
)
parser_list_checks.add_argument(
"--filter-by-target-url-re",
help="Only show checks with target_url matching this regexp, check automatically excluded if its target_url is empty",
)
parser_list_checks.add_argument(
"--filter-by-created-at-ge",
type=datetime.datetime.fromisoformat,
help="Only show checks with created_at >= of given date",
)
parser_list_checks.add_argument(
"--latest-by-context",
action="store_true",
help="Only show latest checks for every context by created_at time",
)
parser_list_checks.add_argument(
"--prow-download-path",
help="Download artifacts from Prow at this path (e.g. 'openshift-pipelines-max-concurrency/artifacts/'",
)
parser_add_comment = subparsers.add_parser("add_comment", help="Add comment")
parser_add_comment.set_defaults(func=add_comment)
parser_add_comment.add_argument("--owner", required=True, help="Owner of the repo")
parser_add_comment.add_argument("--repo", required=True, help="Repo name")
parser_add_comment.add_argument("--issue-number", help="Issue (or PR) number")
parser_add_comment.add_argument("--body", help="Comment body")
args = parser.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
logging.debug(f"Args: {args}")
return args.func(args)
if __name__ == "__main__":
sys.exit(main())