gitbills 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gitbills/__init__.py +29 -0
- gitbills/__main__.py +3 -0
- gitbills/cli.py +417 -0
- gitbills/diff.py +268 -0
- gitbills/local.py +436 -0
- gitbills/policy.py +449 -0
- gitbills/preflight.py +219 -0
- gitbills/remote.py +676 -0
- gitbills/scan.py +392 -0
- gitbills/slop.py +423 -0
- gitbills/text.py +103 -0
- gitbills/version.py +4 -0
- gitbills/vouch.py +161 -0
- gitbills-0.1.2.dist-info/METADATA +82 -0
- gitbills-0.1.2.dist-info/RECORD +19 -0
- gitbills-0.1.2.dist-info/WHEEL +5 -0
- gitbills-0.1.2.dist-info/entry_points.txt +2 -0
- gitbills-0.1.2.dist-info/licenses/LICENSE +21 -0
- gitbills-0.1.2.dist-info/top_level.txt +1 -0
gitbills/remote.py
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
"""The online commands (src/remote.js): bounded JSON requests to gitbills.com and the GitHub API, and their views.
|
|
2
|
+
|
|
3
|
+
Redirects are refused, every request has one total deadline (a watchdog shuts its connection, since urllib's timeout
|
|
4
|
+
only bounds each read), every answer is read up to a byte cap, and nothing from the network is echoed without being
|
|
5
|
+
checked or shown as display text.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import http.client
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import re
|
|
14
|
+
import socket
|
|
15
|
+
import threading
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
19
|
+
from urllib.parse import urlsplit
|
|
20
|
+
|
|
21
|
+
from .preflight import DEFAULT_ORIGIN
|
|
22
|
+
from .text import GitBillsError, decode_utf8, display_text, fail, js_num, md_code
|
|
23
|
+
from .version import VERSION
|
|
24
|
+
from .vouch import clean_login, clean_repo, vouch_command
|
|
25
|
+
|
|
26
|
+
DEFAULT_GITHUB_API = 'https://api.github.com'
|
|
27
|
+
USER_AGENT = 'gitbills-cli/%s' % VERSION
|
|
28
|
+
TIMEOUT_S = 8
|
|
29
|
+
_MAX_JSON_BYTES = 2_097_152
|
|
30
|
+
_A = re.ASCII
|
|
31
|
+
_SHA_RE = re.compile(r'^[0-9a-f]{40}\Z', _A)
|
|
32
|
+
_LOGIN_RE = re.compile(r'^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}(?:\[bot\])?\Z', _A)
|
|
33
|
+
_API_RE = re.compile(r'^https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~/-]*)?\Z'
|
|
34
|
+
r'|^http://(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~/-]*)?\Z', _A)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def clean_api_base(value, fallback: str = DEFAULT_GITHUB_API) -> str:
|
|
38
|
+
s = re.sub(r'/+\Z', '', value.strip()) if isinstance(value, str) else ''
|
|
39
|
+
return s if s and _API_RE.search(s) else fallback
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
43
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
44
|
+
raise GitBillsError('network_error', 'Could not reach %s (redirects are refused).' % urlsplit(req.full_url).netloc)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _shut(sock):
|
|
48
|
+
try:
|
|
49
|
+
sock.shutdown(socket.SHUT_RDWR)
|
|
50
|
+
except OSError:
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Watch:
|
|
55
|
+
"""One request's total deadline: when it passes, every connection the request opened is shut."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, seconds):
|
|
58
|
+
self.socks, self.fired, self._lock = [], False, threading.Lock()
|
|
59
|
+
self._timer = threading.Timer(seconds, self._fire)
|
|
60
|
+
self._timer.daemon = True
|
|
61
|
+
self._timer.start()
|
|
62
|
+
|
|
63
|
+
def add(self, sock):
|
|
64
|
+
with self._lock:
|
|
65
|
+
self.socks.append(sock)
|
|
66
|
+
fired = self.fired
|
|
67
|
+
if fired:
|
|
68
|
+
_shut(sock)
|
|
69
|
+
|
|
70
|
+
def _fire(self):
|
|
71
|
+
with self._lock:
|
|
72
|
+
self.fired = True
|
|
73
|
+
socks = list(self.socks)
|
|
74
|
+
for s in socks:
|
|
75
|
+
_shut(s)
|
|
76
|
+
|
|
77
|
+
def cancel(self):
|
|
78
|
+
self._timer.cancel()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _opener(watch):
|
|
82
|
+
"""urllib with redirects refused and every socket it connects handed to the watch."""
|
|
83
|
+
class Conn(http.client.HTTPConnection):
|
|
84
|
+
def connect(self):
|
|
85
|
+
super().connect()
|
|
86
|
+
watch.add(self.sock)
|
|
87
|
+
|
|
88
|
+
class SecureConn(http.client.HTTPSConnection):
|
|
89
|
+
def connect(self):
|
|
90
|
+
super().connect()
|
|
91
|
+
watch.add(self.sock)
|
|
92
|
+
|
|
93
|
+
class Plain(urllib.request.HTTPHandler):
|
|
94
|
+
def http_open(self, req):
|
|
95
|
+
return self.do_open(Conn, req)
|
|
96
|
+
|
|
97
|
+
class Secure(urllib.request.HTTPSHandler):
|
|
98
|
+
def https_open(self, req):
|
|
99
|
+
return self.do_open(SecureConn, req, context=self._context)
|
|
100
|
+
|
|
101
|
+
return urllib.request.build_opener(_NoRedirect, Plain, Secure)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def request_json(url, method='GET', body=None, headers=None, timeout_s=TIMEOUT_S, max_bytes=_MAX_JSON_BYTES, opener=None):
|
|
105
|
+
"""One bounded request: {'status', 'json', 'text'}. Raises GitBillsError (timeout, network_error, response_too_large)."""
|
|
106
|
+
host = urlsplit(url).netloc
|
|
107
|
+
h = {'User-Agent': USER_AGENT, 'Accept': 'application/json'}
|
|
108
|
+
for k, v in (headers or {}).items():
|
|
109
|
+
h[k.title() if k.lower() != 'x-github-api-version' else 'X-GitHub-Api-Version'] = v
|
|
110
|
+
data = body.encode('utf-8') if isinstance(body, str) else body
|
|
111
|
+
req = urllib.request.Request(url, data=data, headers=h, method=method)
|
|
112
|
+
watch = _Watch(timeout_s)
|
|
113
|
+
try:
|
|
114
|
+
try:
|
|
115
|
+
res = (opener or _opener(watch)).open(req, timeout=timeout_s)
|
|
116
|
+
except urllib.error.HTTPError as e:
|
|
117
|
+
res = e
|
|
118
|
+
except GitBillsError:
|
|
119
|
+
raise
|
|
120
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as e:
|
|
121
|
+
if watch.fired or isinstance(e, TimeoutError) or 'timed out' in str(e):
|
|
122
|
+
fail('timeout', 'No answer from %s within %d s.' % (host, timeout_s))
|
|
123
|
+
fail('network_error', 'Could not reach %s (redirects are refused).' % host)
|
|
124
|
+
try:
|
|
125
|
+
read1 = getattr(res, 'read1', None)
|
|
126
|
+
if read1 is None:
|
|
127
|
+
raw = res.read(max_bytes + 1)
|
|
128
|
+
else:
|
|
129
|
+
chunks, n = [], 0
|
|
130
|
+
while n <= max_bytes:
|
|
131
|
+
b = read1(min(65_536, max_bytes + 1 - n))
|
|
132
|
+
if not b:
|
|
133
|
+
break
|
|
134
|
+
chunks.append(b)
|
|
135
|
+
n += len(b)
|
|
136
|
+
raw = b''.join(chunks)
|
|
137
|
+
except (OSError, http.client.HTTPException, ValueError) as e:
|
|
138
|
+
fail('timeout' if watch.fired or isinstance(e, TimeoutError) else 'network_error',
|
|
139
|
+
'The answer from %s could not be read.' % host)
|
|
140
|
+
finally:
|
|
141
|
+
try:
|
|
142
|
+
res.close()
|
|
143
|
+
except Exception: # pragma: no cover
|
|
144
|
+
pass
|
|
145
|
+
finally:
|
|
146
|
+
watch.cancel()
|
|
147
|
+
if watch.fired:
|
|
148
|
+
fail('timeout', 'The answer from %s could not be read within %d s.' % (host, timeout_s))
|
|
149
|
+
if len(raw) > max_bytes:
|
|
150
|
+
fail('response_too_large', 'The answer is over %d bytes.' % max_bytes)
|
|
151
|
+
text = decode_utf8(raw)
|
|
152
|
+
try:
|
|
153
|
+
parsed = json.loads(text)
|
|
154
|
+
except (ValueError, RecursionError):
|
|
155
|
+
parsed = None
|
|
156
|
+
return {'status': getattr(res, 'status', None) or res.getcode(), 'json': parsed, 'text': text}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _is_obj(v):
|
|
160
|
+
return isinstance(v, dict)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _expect_shape(j, protocol_re, fields, what):
|
|
164
|
+
proto = j.get('protocol')
|
|
165
|
+
if (isinstance(proto, str) and not re.search(protocol_re, proto)) or not any(k in j for k in fields):
|
|
166
|
+
fail('not_available', 'gitbills.com has no %s yet.' % what)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _github_headers(token):
|
|
170
|
+
h = {'accept': 'application/vnd.github+json', 'x-github-api-version': '2022-11-28'}
|
|
171
|
+
if token:
|
|
172
|
+
h['authorization'] = 'Bearer %s' % token
|
|
173
|
+
return h
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _http_fail(status, host, what):
|
|
177
|
+
if status == 404:
|
|
178
|
+
fail('not_found', '%s was not found on %s (or it is private).' % (what, host))
|
|
179
|
+
if status in (403, 429):
|
|
180
|
+
fail('rate_limited', '%s refused the request (HTTP %s): rate limited or forbidden; retry shortly.' % (host, status))
|
|
181
|
+
fail('http_error', '%s answered HTTP %s for %s.' % (host, status, what))
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
AGENTS_POLICY_PROTOCOL = 'gitbills-agents-policy/1'
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _is_int(v):
|
|
188
|
+
return isinstance(v, int) and not isinstance(v, bool)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
_SERVER_RULES = (
|
|
192
|
+
('agents', lambda v: isinstance(v, str) and v in ('welcome', 'allowed_with_preflight', 'vouch_required', 'maintainers_only')),
|
|
193
|
+
('max_open_prs_per_author', lambda v: v is None or (_is_int(v) and 1 <= v <= 20)),
|
|
194
|
+
('max_diff_lines', lambda v: v is None or (_is_int(v) and 10 <= v <= 10_000)),
|
|
195
|
+
('require_linked_issue', lambda v: isinstance(v, bool)),
|
|
196
|
+
('require_disclosure', lambda v: isinstance(v, bool)),
|
|
197
|
+
('require_tests_for_code', lambda v: isinstance(v, bool)),
|
|
198
|
+
('commercial_vendor_prs', lambda v: isinstance(v, str) and v in ('allow', 'require_vouch', 'require_bond')),
|
|
199
|
+
('scout_vouches', lambda v: isinstance(v, str) and v in ('allow', 'disabled')),
|
|
200
|
+
)
|
|
201
|
+
_SOURCE_RE = re.compile(r'^(?:default|prose_only|inferred_prose|explicit_section)\Z', _A)
|
|
202
|
+
_WARN_KEY_RE = re.compile(r'^[A-Za-z0-9_-]{1,64}\Z', _A)
|
|
203
|
+
_REASON_RE = re.compile(r'^[a-z_]{1,40}\Z', _A)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def normalize_server_policy(j, url):
|
|
207
|
+
"""gitbills.com's gitbills-agents-policy/1 answer, checked field by field; None for anything else."""
|
|
208
|
+
p = j.get('policy') if _is_obj(j) and j.get('protocol') == AGENTS_POLICY_PROTOCOL else None
|
|
209
|
+
if not _is_obj(p) or not _is_obj(p.get('rules')):
|
|
210
|
+
return None
|
|
211
|
+
rules = {k: p['rules'][k] for k, ok in _SERVER_RULES if k in p['rules'] and ok(p['rules'][k])}
|
|
212
|
+
warnings = []
|
|
213
|
+
for w in [w for w in (p['parse_warnings'] if isinstance(p.get('parse_warnings'), list) else []) if _is_obj(w)][:20]:
|
|
214
|
+
line, key, reason = w.get('line'), w.get('key'), w.get('reason')
|
|
215
|
+
warnings.append({'line': line if _is_int(line) and 0 < line <= _SAFE_INT_MAX else None,
|
|
216
|
+
'key': key if isinstance(key, str) and _WARN_KEY_RE.search(key) else None,
|
|
217
|
+
'reason': reason if isinstance(reason, str) and _REASON_RE.search(reason) else 'unknown'})
|
|
218
|
+
return {
|
|
219
|
+
'protocol': AGENTS_POLICY_PROTOCOL,
|
|
220
|
+
'url': url,
|
|
221
|
+
'source': p['source'] if isinstance(p.get('source'), str) and _SOURCE_RE.search(p['source']) else 'unknown',
|
|
222
|
+
'rules': rules,
|
|
223
|
+
'inferred_hints': _code_list(p.get('inferred_hints')),
|
|
224
|
+
'parse_warnings': warnings,
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _js_value(v):
|
|
229
|
+
return 'null' if v is None else ('true' if v else 'false') if isinstance(v, bool) else str(v)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def format_server_policy(s) -> str:
|
|
233
|
+
"""The server's reading as terminal lines (rules in its own key: value form)."""
|
|
234
|
+
if not s:
|
|
235
|
+
return ' gitbills.com reading (gitbills-agents-policy/1): not available'
|
|
236
|
+
lines = [' gitbills.com reading (%s): %s' % (s['protocol'], s['source'])]
|
|
237
|
+
rules = ['%s: %s' % (k, _js_value(v)) for k, v in s['rules'].items()]
|
|
238
|
+
if rules:
|
|
239
|
+
lines.append(' %s' % ', '.join(rules))
|
|
240
|
+
if s['inferred_hints']:
|
|
241
|
+
lines.append(' In prose (advice, never enforced): %s' % ', '.join(s['inferred_hints']))
|
|
242
|
+
for w in s['parse_warnings']:
|
|
243
|
+
lines.append(' Ignored%s%s: %s' % ('' if w['line'] is None else ' line %d' % w['line'],
|
|
244
|
+
'' if w['key'] is None else ' (%s)' % w['key'], w['reason']))
|
|
245
|
+
return '\n'.join(lines)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def fetch_remote_policy(repo, origin=DEFAULT_ORIGIN, github_api=DEFAULT_GITHUB_API, token=None, opener=None) -> dict:
|
|
249
|
+
"""AGENTS.md from the default branch through the GitHub API, with gitbills.com's reading of it when the server has
|
|
250
|
+
one (a 404, a 5xx, a timeout or another shape leaves 'server' None)."""
|
|
251
|
+
slug = clean_repo(repo)
|
|
252
|
+
url = '%s/api/v1/policy/%s' % (origin, slug)
|
|
253
|
+
server = None
|
|
254
|
+
try:
|
|
255
|
+
r = request_json(url, max_bytes=524_288, opener=opener)
|
|
256
|
+
if r['status'] == 200:
|
|
257
|
+
server = normalize_server_policy(r['json'], url)
|
|
258
|
+
except GitBillsError:
|
|
259
|
+
pass
|
|
260
|
+
return dict(_fetch_github_agents_md(slug, github_api, token, opener), server=server)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _fetch_github_agents_md(slug, github_api, token, opener):
|
|
264
|
+
api = '%s/repos/%s/contents/AGENTS.md' % (github_api, slug)
|
|
265
|
+
g = request_json(api, headers=_github_headers(token), max_bytes=524_288, opener=opener)
|
|
266
|
+
if g['status'] == 404:
|
|
267
|
+
return {'repo': slug, 'source': 'https://github.com/%s' % slug, 'text': None}
|
|
268
|
+
if g['status'] != 200:
|
|
269
|
+
_http_fail(g['status'], urlsplit(api).netloc, '%s AGENTS.md' % slug)
|
|
270
|
+
j = g['json']
|
|
271
|
+
if not _is_obj(j) or j.get('type') != 'file' or j.get('encoding') != 'base64' or not isinstance(j.get('content'), str):
|
|
272
|
+
fail('invalid_response', '%s AGENTS.md is not a regular file on the default branch.' % slug)
|
|
273
|
+
data = base64.b64decode(re.sub(r'\s+', '', j['content']))
|
|
274
|
+
if len(data) > 262_144:
|
|
275
|
+
fail('response_too_large', '%s AGENTS.md is over 262144 bytes.' % slug)
|
|
276
|
+
return {'repo': slug, 'source': 'https://github.com/%s/blob/HEAD/AGENTS.md' % slug, 'text': decode_utf8(data)}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
TRIAGE_BUCKETS = (
|
|
280
|
+
('ready_for_review', 'Ready for review'),
|
|
281
|
+
('needs_vouch', 'Needs vouch'),
|
|
282
|
+
('batch_or_defer', 'Batch / defer'),
|
|
283
|
+
('attention_required', 'Attention required'),
|
|
284
|
+
)
|
|
285
|
+
_BUCKET_ALIASES = {
|
|
286
|
+
'ready_for_review': 'ready_for_review', 'attention_required': 'attention_required',
|
|
287
|
+
'newcomers_awaiting_vouch': 'needs_vouch', 'needs_vouch_or_bond': 'needs_vouch', 'needs_vouch': 'needs_vouch',
|
|
288
|
+
'batch_triage_bursts_and_vendors': 'batch_or_defer', 'batch_or_defer': 'batch_or_defer',
|
|
289
|
+
}
|
|
290
|
+
_CODE_RE = re.compile(r'^[a-z0-9_]{1,64}\Z', _A)
|
|
291
|
+
_SAFE_INT_MAX = 9007199254740991
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _pr_number(v):
|
|
295
|
+
return v if isinstance(v, int) and not isinstance(v, bool) and 0 < v <= _SAFE_INT_MAX else None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _login_of(v):
|
|
299
|
+
s = v if isinstance(v, str) else v.get('login') if _is_obj(v) and isinstance(v.get('login'), str) else ''
|
|
300
|
+
return s if _LOGIN_RE.search(s) else None
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _code_list(v):
|
|
304
|
+
return [x for x in v if isinstance(x, str) and _CODE_RE.search(x)][:8] if isinstance(v, list) else []
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _sha_of(v):
|
|
308
|
+
return v.lower() if isinstance(v, str) and _SHA_RE.search(v.lower()) else None
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def commit_url(repo, n, sha):
|
|
312
|
+
"""Where a maintainer reads the exact commit a vouch command names (the head can move after the triage was made)."""
|
|
313
|
+
return 'https://github.com/%s/pull/%d/commits/%s' % (repo, n, sha)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
_VOUCH_HINT = 'Read the commit first; gitbills vouch OWNER/REPO#N SHA --post posts only while that commit is still the head.'
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _first(d, *keys):
|
|
320
|
+
for k in keys:
|
|
321
|
+
if d.get(k) is not None:
|
|
322
|
+
return d.get(k)
|
|
323
|
+
return None
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def normalize_triage(j, repo, source_url) -> dict:
|
|
327
|
+
"""A triage answer as gitbills-triage/1: four buckets of checked rows."""
|
|
328
|
+
j = j if _is_obj(j) else {}
|
|
329
|
+
buckets = {b: [] for b, _ in TRIAGE_BUCKETS}
|
|
330
|
+
by_number = {}
|
|
331
|
+
if _is_obj(j.get('buckets')):
|
|
332
|
+
for bid, lst in j['buckets'].items():
|
|
333
|
+
b = _BUCKET_ALIASES.get(bid)
|
|
334
|
+
if b and isinstance(lst, list):
|
|
335
|
+
for n in lst:
|
|
336
|
+
if _pr_number(n):
|
|
337
|
+
by_number[n] = b
|
|
338
|
+
rows = j['prs'] if isinstance(j.get('prs'), list) else []
|
|
339
|
+
seen = set()
|
|
340
|
+
for row in rows[:100]:
|
|
341
|
+
if not _is_obj(row):
|
|
342
|
+
continue
|
|
343
|
+
number = _pr_number(_first(row, 'pr_number', 'number'))
|
|
344
|
+
if number is None or number in seen:
|
|
345
|
+
continue
|
|
346
|
+
bucket = _BUCKET_ALIASES.get(row.get('bucket')) if isinstance(row.get('bucket'), str) else None
|
|
347
|
+
bucket = bucket or by_number.get(number)
|
|
348
|
+
if not bucket:
|
|
349
|
+
continue
|
|
350
|
+
seen.add(number)
|
|
351
|
+
head = _sha_of(row.get('head_sha') if row.get('head_sha') is not None else (row['head'].get('sha') if _is_obj(row.get('head')) else None))
|
|
352
|
+
reasons = []
|
|
353
|
+
for x in _code_list(_first(row, 'bucket_reasons', 'reasons', 'attention_reasons')) + _code_list(row.get('queue_flags')):
|
|
354
|
+
if x not in reasons:
|
|
355
|
+
reasons.append(x)
|
|
356
|
+
buckets[bucket].append({
|
|
357
|
+
'number': number,
|
|
358
|
+
'title': display_text(row['title'] if isinstance(row.get('title'), str) else '', 120),
|
|
359
|
+
'author': _login_of(_first(row, 'author', 'user')),
|
|
360
|
+
'reasons': reasons,
|
|
361
|
+
'head_sha': head,
|
|
362
|
+
'vouch_command': vouch_command(head) if bucket == 'needs_vouch' and head else None,
|
|
363
|
+
'commit_url': commit_url(repo, number, head) if head else None,
|
|
364
|
+
})
|
|
365
|
+
for n, b in by_number.items():
|
|
366
|
+
if n not in seen:
|
|
367
|
+
buckets[b].append({'number': n, 'title': '', 'author': None, 'reasons': [], 'head_sha': None, 'vouch_command': None,
|
|
368
|
+
'commit_url': None})
|
|
369
|
+
skipped = []
|
|
370
|
+
for s in (j['skipped_too_large'] if isinstance(j.get('skipped_too_large'), list) else []):
|
|
371
|
+
n = _pr_number(_first(s, 'pr_number', 'number') if _is_obj(s) else s)
|
|
372
|
+
if n is not None:
|
|
373
|
+
skipped.append(n)
|
|
374
|
+
summary = j['summary'] if _is_obj(j.get('summary')) else {}
|
|
375
|
+
scanned = _pr_number(summary.get('total_scanned'))
|
|
376
|
+
if scanned is None:
|
|
377
|
+
scanned = sum(len(v) for v in buckets.values())
|
|
378
|
+
return {'protocol': 'gitbills-triage/1', 'repo': repo, 'source_url': source_url, 'scanned': scanned,
|
|
379
|
+
'buckets': buckets, 'skipped_too_large': skipped[:50]}
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def fetch_triage(repo, origin=DEFAULT_ORIGIN, limit=12, opener=None) -> dict:
|
|
383
|
+
slug = clean_repo(repo)
|
|
384
|
+
r = request_json('%s/pilot/v1/gate/triage-repo' % origin, method='POST', timeout_s=60, opener=opener,
|
|
385
|
+
headers={'content-type': 'application/json'}, body=json.dumps({'repo': slug, 'limit': limit}, separators=(',', ':')))
|
|
386
|
+
if r['status'] in (404, 405):
|
|
387
|
+
r = request_json('%s/%s?format=json&limit=%d' % (origin, slug, limit), timeout_s=60, opener=opener)
|
|
388
|
+
if r['status'] != 200 or not _is_obj(r['json']):
|
|
389
|
+
_http_fail(502 if r['status'] == 200 else r['status'], urlsplit(origin).netloc, 'the %s triage' % slug)
|
|
390
|
+
_expect_shape(r['json'], 'triage', ('prs', 'buckets'), 'triage of %s' % slug)
|
|
391
|
+
# A scan has buckets of numbers and rows; the repository page's descriptor (buckets as a list of labels) is no scan.
|
|
392
|
+
if not _is_obj(r['json'].get('buckets')) or not isinstance(r['json'].get('prs'), list):
|
|
393
|
+
fail('not_available', 'gitbills.com has no triage of %s yet.' % slug)
|
|
394
|
+
return normalize_triage(r['json'], slug, '%s/%s' % (origin, slug))
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def fetch_pr_head(repo, number, github_api=DEFAULT_GITHUB_API, token=None, opener=None) -> str:
|
|
398
|
+
url = '%s/repos/%s/pulls/%d' % (github_api, clean_repo(repo), number)
|
|
399
|
+
r = request_json(url, headers=_github_headers(token), opener=opener)
|
|
400
|
+
if r['status'] != 200:
|
|
401
|
+
_http_fail(r['status'], urlsplit(url).netloc, '%s#%d' % (repo, number))
|
|
402
|
+
j = r['json']
|
|
403
|
+
sha = _sha_of(j['head'].get('sha') if _is_obj(j) and _is_obj(j.get('head')) else None)
|
|
404
|
+
if not sha:
|
|
405
|
+
fail('invalid_response', '%s#%d came without a head commit.' % (repo, number))
|
|
406
|
+
return sha
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def fill_head_shas(triage, github_api=DEFAULT_GITHUB_API, token=None, opener=None, max_rows=10) -> dict:
|
|
410
|
+
"""Head commits for the Needs vouch rows that came without one (GitHub's pull request API)."""
|
|
411
|
+
missing = [r for r in triage['buckets']['needs_vouch'] if not r['head_sha']][:max_rows]
|
|
412
|
+
|
|
413
|
+
def one(row):
|
|
414
|
+
try:
|
|
415
|
+
row['head_sha'] = fetch_pr_head(triage['repo'], row['number'], github_api, token, opener)
|
|
416
|
+
row['vouch_command'] = vouch_command(row['head_sha'])
|
|
417
|
+
row['commit_url'] = commit_url(triage['repo'], row['number'], row['head_sha'])
|
|
418
|
+
except GitBillsError:
|
|
419
|
+
pass
|
|
420
|
+
|
|
421
|
+
if missing:
|
|
422
|
+
with ThreadPoolExecutor(max_workers=4) as pool:
|
|
423
|
+
list(pool.map(one, missing))
|
|
424
|
+
return triage
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _gh_pull(repo, n):
|
|
428
|
+
return 'https://github.com/%s/pull/%d' % (repo, n)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def format_triage_terminal(t) -> str:
|
|
432
|
+
lines = ['GitBills triage: %s, %d open pull request(s) scanned' % (t['repo'], t['scanned'])]
|
|
433
|
+
for bid, label in TRIAGE_BUCKETS:
|
|
434
|
+
rows = t['buckets'][bid]
|
|
435
|
+
lines.append(' %s (%d)' % (label, len(rows)))
|
|
436
|
+
for r in rows:
|
|
437
|
+
by = ' by @%s' % r['author'] if r['author'] else ''
|
|
438
|
+
why = ' (%s)' % ', '.join(r['reasons']) if r['reasons'] else ''
|
|
439
|
+
lines.append(' #%d%s%s%s' % (r['number'], ' %s' % r['title'] if r['title'] else '', by, why))
|
|
440
|
+
if bid == 'needs_vouch':
|
|
441
|
+
lines.append(' %s (commit: %s)' % (r['vouch_command'], r['commit_url']) if r['vouch_command']
|
|
442
|
+
else ' gitbills receipt %s#%d (names the head commit to vouch for)' % (t['repo'], r['number']))
|
|
443
|
+
if any(r['vouch_command'] for r in t['buckets']['needs_vouch']):
|
|
444
|
+
lines.append(' ' + _VOUCH_HINT)
|
|
445
|
+
if t['skipped_too_large']:
|
|
446
|
+
lines.append(' Too large to scan: %s' % ', '.join('#%d' % n for n in t['skipped_too_large']))
|
|
447
|
+
lines.append(' Live queue: %s' % t['source_url'])
|
|
448
|
+
return '\n'.join(lines)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def format_triage_markdown(t) -> str:
|
|
452
|
+
out = ['### GitBills triage: %s' % md_code(t['repo']), '', '%d open pull request(s) scanned.' % t['scanned'], '',
|
|
453
|
+
'| Bucket | Pull requests |', '|---|---|']
|
|
454
|
+
for bid, label in TRIAGE_BUCKETS:
|
|
455
|
+
rows = t['buckets'][bid]
|
|
456
|
+
links = ', '.join('[#%d](%s)' % (r['number'], _gh_pull(t['repo'], r['number'])) for r in rows) or '-'
|
|
457
|
+
out.append('| %s (%d) | %s |' % (label, len(rows), links))
|
|
458
|
+
vouch = [r for r in t['buckets']['needs_vouch'] if r['vouch_command']]
|
|
459
|
+
if vouch:
|
|
460
|
+
out += ['', 'Vouch commands (a maintainer comments one after reading that exact commit). ' + _VOUCH_HINT, '']
|
|
461
|
+
for r in vouch:
|
|
462
|
+
out.append('- [#%d](%s) %s: `%s` ([commit](%s))' % (r['number'], _gh_pull(t['repo'], r['number']), md_code(r['title'] or '?', 80),
|
|
463
|
+
r['vouch_command'], r['commit_url']))
|
|
464
|
+
attention = t['buckets']['attention_required']
|
|
465
|
+
if attention:
|
|
466
|
+
out += ['', 'Attention required:', '']
|
|
467
|
+
for r in attention:
|
|
468
|
+
out.append('- [#%d](%s) %s: %s' % (r['number'], _gh_pull(t['repo'], r['number']), md_code(r['title'] or '?', 80),
|
|
469
|
+
', '.join(md_code(x) for x in r['reasons']) or 'see the receipt'))
|
|
470
|
+
if t['skipped_too_large']:
|
|
471
|
+
out += ['', 'Too large to scan: %s' % ', '.join('[#%d](%s)' % (n, _gh_pull(t['repo'], n)) for n in t['skipped_too_large'])]
|
|
472
|
+
out += ['', '[Live queue on GitBills](%s)' % t['source_url']]
|
|
473
|
+
return '\n'.join(out)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
_VERDICT_RE = re.compile(r'^[a-z_]{1,48}\Z', _A)
|
|
477
|
+
_URLISH_RE = re.compile(r'^[A-Za-z0-9:/._~%?=&-]{1,400}\Z', _A)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _same_origin(url, origin):
|
|
481
|
+
return isinstance(url, str) and url.startswith(origin + '/') and bool(_URLISH_RE.search(url))
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def normalize_receipt(j, repo, number, origin) -> dict:
|
|
485
|
+
"""A receipt answer as gitbills-receipt/1: checked fields only, URLs rebuilt from the repository and number."""
|
|
486
|
+
j = j if _is_obj(j) else {}
|
|
487
|
+
sec = j['security'] if _is_obj(j.get('security')) else {}
|
|
488
|
+
l1 = j['layer1'] if _is_obj(j.get('layer1')) else j['slop'] if _is_obj(j.get('slop')) else {}
|
|
489
|
+
standing = j['standing'] if _is_obj(j.get('standing')) else {}
|
|
490
|
+
head = _sha_of(j.get('head_sha'))
|
|
491
|
+
verdict = j['verdict'] if isinstance(j.get('verdict'), str) and _VERDICT_RE.search(j['verdict']) else 'unknown'
|
|
492
|
+
is_open = j.get('state') == 'open' and j.get('merged') is not True
|
|
493
|
+
state = ('merged' if j.get('merged') is True else j['state'] if isinstance(j.get('state'), str)
|
|
494
|
+
and j['state'] in ('open', 'closed') else 'unknown')
|
|
495
|
+
grade = sec.get('risk_grade')
|
|
496
|
+
score = l1.get('score')
|
|
497
|
+
label = standing.get('label') if isinstance(standing.get('label'), str) else j['standing'] if isinstance(j.get('standing'), str) else ''
|
|
498
|
+
png = j.get('og_png_url') if _same_origin(j.get('og_png_url'), origin) else j.get('badge_png_url') if _same_origin(j.get('badge_png_url'), origin) else None
|
|
499
|
+
return {
|
|
500
|
+
'protocol': 'gitbills-receipt/1',
|
|
501
|
+
'repo': repo,
|
|
502
|
+
'pr_number': number,
|
|
503
|
+
'receipt_url': '%s/%s/pull/%d' % (origin, repo, number),
|
|
504
|
+
'pr_url': _gh_pull(repo, number),
|
|
505
|
+
'verdict': verdict,
|
|
506
|
+
'verdict_label': display_text(j['verdict_label'] if isinstance(j.get('verdict_label'), str) else '', 80),
|
|
507
|
+
'reasons': _code_list(j.get('attention_reasons')),
|
|
508
|
+
'state': state,
|
|
509
|
+
'title': display_text(j['title'] if isinstance(j.get('title'), str) else '', 120),
|
|
510
|
+
'author': _login_of(j.get('author')),
|
|
511
|
+
'head_sha': head,
|
|
512
|
+
'risk_grade': grade if isinstance(grade, str) and re.search(r'^[A-F]\Z', grade, _A) else '?',
|
|
513
|
+
'signal_count': _pr_number(sec.get('signal_count')) or 0,
|
|
514
|
+
'slop_score': score if isinstance(score, int) and not isinstance(score, bool) else None,
|
|
515
|
+
'standing': display_text(label, 60),
|
|
516
|
+
'vouch_command': vouch_command(head) if is_open and head and verdict == 'awaiting_maintainer_vouch' else None,
|
|
517
|
+
'commit_url': commit_url(repo, number, head) if head else None,
|
|
518
|
+
'badge_svg_url': '%s/og/pr/%s/%d.svg' % (origin, repo, number),
|
|
519
|
+
'badge_png_url': png,
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def fetch_receipt(repo, number, origin=DEFAULT_ORIGIN, opener=None) -> dict:
|
|
524
|
+
slug = clean_repo(repo)
|
|
525
|
+
r = request_json('%s/%s/pull/%d?format=json' % (origin, slug, number), timeout_s=30, opener=opener)
|
|
526
|
+
if r['status'] != 200 or not _is_obj(r['json']):
|
|
527
|
+
_http_fail(502 if r['status'] == 200 else r['status'], urlsplit(origin).netloc, '%s#%d' % (slug, number))
|
|
528
|
+
_expect_shape(r['json'], 'receipt', ('verdict',), 'receipt for %s#%d' % (slug, number))
|
|
529
|
+
return normalize_receipt(r['json'], slug, number, origin)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _badges(r):
|
|
533
|
+
out = ['[](%s)' % (r['badge_svg_url'], r['receipt_url'])]
|
|
534
|
+
if r['badge_png_url']:
|
|
535
|
+
out.append('[](%s)' % (r['badge_png_url'], r['receipt_url']))
|
|
536
|
+
return out
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def format_receipt_terminal(r) -> str:
|
|
540
|
+
slop = '?' if r['slop_score'] is None else r['slop_score']
|
|
541
|
+
lines = [
|
|
542
|
+
'GitBills receipt: %s#%d (%s)%s' % (r['repo'], r['pr_number'], r['state'], ' %s' % r['title'] if r['title'] else ''),
|
|
543
|
+
' Verdict: %s%s%s' % (r['verdict'], ' (%s)' % r['verdict_label'] if r['verdict_label'] else '',
|
|
544
|
+
': %s' % ', '.join(r['reasons']) if r['reasons'] else ''),
|
|
545
|
+
' Head commit: %s%s' % (r['head_sha'] or 'unknown', ', author @%s' % r['author'] if r['author'] else ''),
|
|
546
|
+
' Security grade %s (%d signal(s)); slop %s/100%s' % (r['risk_grade'], r['signal_count'], slop,
|
|
547
|
+
'; standing: %s' % r['standing'] if r['standing'] else ''),
|
|
548
|
+
]
|
|
549
|
+
if r['vouch_command']:
|
|
550
|
+
lines.append(' Vouch (maintainers, after reading %s): %s' % (r['commit_url'], r['vouch_command']))
|
|
551
|
+
lines.append(' Or run gitbills vouch %s#%d %s --post: it posts only while that commit is still the head.' % (
|
|
552
|
+
r['repo'], r['pr_number'], r['head_sha']))
|
|
553
|
+
lines.append(' Receipt: %s' % r['receipt_url'])
|
|
554
|
+
lines += [' Badge: %s' % b for b in _badges(r)]
|
|
555
|
+
return '\n'.join(lines)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def format_receipt_markdown(r) -> str:
|
|
559
|
+
at = ' at commit `%s`' % r['head_sha'][:12] if r['head_sha'] else ''
|
|
560
|
+
slop = '?' if r['slop_score'] is None else r['slop_score']
|
|
561
|
+
first = '**GitBills receipt:** [%s#%d](%s) `%s`%s, security grade `%s`, slop %s/100' % (
|
|
562
|
+
r['repo'], r['pr_number'], r['receipt_url'], r['verdict'], at, r['risk_grade'], slop)
|
|
563
|
+
return '\n'.join([first] + _badges(r))
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
STANDING_PROTOCOL = 'gitbills-standing/1'
|
|
567
|
+
# The Scout circuit breaker as gitbills.com runs it: tripped once 3 or more avals are judged (merged or rejected as
|
|
568
|
+
# slop) and more than 22% of them were rejected (rejected * 10,000 > judged * 2,200, in integers).
|
|
569
|
+
BREAKER = {'threshold_pct': 22, 'min_judged': 3}
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def breaker_health(judged, rejected) -> dict:
|
|
573
|
+
"""The breaker from the counts: {status: tripped | clear | warming_up | unknown, adverse_pct}."""
|
|
574
|
+
if not (_is_int(judged) and _is_int(rejected)) or judged < 0 or rejected < 0 or rejected > judged:
|
|
575
|
+
return {'status': 'unknown', 'adverse_pct': None}
|
|
576
|
+
pct = math.floor(rejected / judged * 1000 + 0.5) / 10 if judged else 0
|
|
577
|
+
if isinstance(pct, float) and pct.is_integer():
|
|
578
|
+
pct = int(pct)
|
|
579
|
+
if judged < BREAKER['min_judged']:
|
|
580
|
+
return {'status': 'warming_up', 'adverse_pct': pct}
|
|
581
|
+
return {'status': 'tripped' if rejected * 10_000 > judged * BREAKER['threshold_pct'] * 100 else 'clear', 'adverse_pct': pct}
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _count(v):
|
|
585
|
+
return v if _is_int(v) and 0 <= v <= _SAFE_INT_MAX else None
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _rate(v):
|
|
589
|
+
return v if isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and 0 <= v <= 1 else None
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
_STATUS_RE = re.compile(r'^[a-z_]{1,32}\Z', _A)
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _record_ref(x):
|
|
596
|
+
n = _pr_number(x.get('pr_number'))
|
|
597
|
+
if not n or not isinstance(x.get('repo'), str):
|
|
598
|
+
return None
|
|
599
|
+
try:
|
|
600
|
+
return '%s#%d' % (clean_repo(x['repo']), n)
|
|
601
|
+
except GitBillsError:
|
|
602
|
+
return None
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _first_set(*values):
|
|
606
|
+
return next((v for v in values if v is not None), None)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def normalize_standing(j, login, origin) -> dict:
|
|
610
|
+
"""A passport as the CLI's gitbills-standing/1 view: checked counts, and the breaker as gitbills.com and the counts see it."""
|
|
611
|
+
j = j if _is_obj(j) else {}
|
|
612
|
+
st = j['stats'] if _is_obj(j.get('stats')) else {}
|
|
613
|
+
cb = j['circuit_breaker'] if _is_obj(j.get('circuit_breaker')) else {}
|
|
614
|
+
|
|
615
|
+
def records(k):
|
|
616
|
+
return [x for x in (j[k] if isinstance(j.get(k), list) else []) if _is_obj(x)]
|
|
617
|
+
|
|
618
|
+
merged, rejected = _count(st.get('scouted_merged_prs')), _count(st.get('scouted_rejected_prs'))
|
|
619
|
+
judged = merged + rejected if merged is not None and rejected is not None else None
|
|
620
|
+
local = breaker_health(judged, rejected)
|
|
621
|
+
avals = []
|
|
622
|
+
for a in records('scout_avals'):
|
|
623
|
+
ref, status = _record_ref(a), a.get('status')
|
|
624
|
+
if ref:
|
|
625
|
+
avals.append('%s %s' % (ref, status) if isinstance(status, str) and _STATUS_RE.search(status) else ref)
|
|
626
|
+
tripped = cb.get('tripped')
|
|
627
|
+
return {
|
|
628
|
+
'protocol': STANDING_PROTOCOL,
|
|
629
|
+
'login': login,
|
|
630
|
+
'profile_url': '%s/contributors/%s' % (origin, login),
|
|
631
|
+
'known': j['known'] if isinstance(j.get('known'), bool) else None,
|
|
632
|
+
'merged_prs': _first_set(_count(st.get('merged_prs')), len(records('merge_receipts'))),
|
|
633
|
+
'recent_receipts': [r for r in (_record_ref(x) for x in records('merge_receipts')) if r][:5],
|
|
634
|
+
'scout': {'merged': merged, 'rejected': rejected, 'judged': judged},
|
|
635
|
+
'recent_avals': avals[:5],
|
|
636
|
+
'vouch_line_capacity': _count(j.get('vouch_line_capacity')),
|
|
637
|
+
'circuit_breaker': dict({'server': ('tripped' if tripped else 'clear') if isinstance(tripped, bool) else None,
|
|
638
|
+
'local': local['status'],
|
|
639
|
+
'adverse_rate': _first_set(_rate(st.get('adverse_rate')), _rate(cb.get('adverse_rate'))),
|
|
640
|
+
'adverse_pct': local['adverse_pct']}, **BREAKER),
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def fetch_standing(login, origin=DEFAULT_ORIGIN, opener=None) -> dict:
|
|
645
|
+
who = clean_login(login)
|
|
646
|
+
r = request_json('%s/contributors/%s?format=json' % (origin, who), timeout_s=30, opener=opener)
|
|
647
|
+
if r['status'] != 200 or not _is_obj(r['json']):
|
|
648
|
+
_http_fail(502 if r['status'] == 200 else r['status'], urlsplit(origin).netloc, '@%s' % who)
|
|
649
|
+
# Only a passport: the same path once answered with the repository page's descriptor, which is no standing.
|
|
650
|
+
if r['json'].get('protocol') != STANDING_PROTOCOL or not _is_obj(r['json'].get('stats')):
|
|
651
|
+
fail('not_available', 'gitbills.com has no contributor standing for @%s yet.' % who)
|
|
652
|
+
return normalize_standing(r['json'], who, origin)
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def format_standing_terminal(s) -> str:
|
|
656
|
+
def n(v):
|
|
657
|
+
return '?' if v is None else str(v)
|
|
658
|
+
|
|
659
|
+
def recent(lst):
|
|
660
|
+
return ' (recent: %s)' % ', '.join(lst) if lst else ''
|
|
661
|
+
|
|
662
|
+
cb, sc = s['circuit_breaker'], s['scout']
|
|
663
|
+
shown = cb['server'] or ('clear' if cb['local'] == 'warming_up' else cb['local'])
|
|
664
|
+
differs = cb['server'] is not None and cb['local'] != 'unknown' and (cb['server'] == 'tripped') != (cb['local'] == 'tripped')
|
|
665
|
+
pct = ('adverse rate unknown' if cb['adverse_pct'] is None
|
|
666
|
+
else '%s%% of %s judged avals rejected as slop' % (js_num(cb['adverse_pct']), n(sc['judged'])))
|
|
667
|
+
return '\n'.join([
|
|
668
|
+
'GitBills standing: @%s%s' % (s['login'], ' (no record yet: every count starts at 0)' if s['known'] is False else ''),
|
|
669
|
+
' Verified merge receipts: %d%s' % (s['merged_prs'], recent(s['recent_receipts'])),
|
|
670
|
+
' Scout avals: %s merged, %s rejected as slop%s; vouch line %s' % (n(sc['merged']), n(sc['rejected']), recent(s['recent_avals']),
|
|
671
|
+
n(s['vouch_line_capacity'])),
|
|
672
|
+
' Circuit breaker: %s%s%s (%s; trips above %d%% once %d are judged)' % (
|
|
673
|
+
shown, ' (from the counts)' if cb['server'] is None else '', '; the counts here say %s' % cb['local'] if differs else '',
|
|
674
|
+
pct, cb['threshold_pct'], cb['min_judged']),
|
|
675
|
+
' Profile: %s' % s['profile_url'],
|
|
676
|
+
])
|