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/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""gitbills: offline PR security X-Ray (14 rules), anti-slop and AGENTS.md policy preflight, queue triage and contributor
|
|
2
|
+
standing for GitHub pull requests. Standard library only; the same answers as the Node package, byte for byte."""
|
|
3
|
+
from .diff import MAX_DIFF_BYTES, is_unsafe_path, parse_diff
|
|
4
|
+
from .local import collect_git_diff, detect_github_repo, find_executable, preflight_checkout, safe_read_file
|
|
5
|
+
from .policy import (POLICY_BLOCK, POLICY_HEADING, POLICY_PROTOCOL, append_policy_block, evaluate_policy,
|
|
6
|
+
format_policy_terminal, matches_protected, parse_policy)
|
|
7
|
+
from .preflight import (DEFAULT_ORIGIN, PREFLIGHT_PROTOCOL, clean_origin, evaluate_preflight, format_preflight_terminal,
|
|
8
|
+
receipt_markdown, render_agent_rule)
|
|
9
|
+
from .remote import (breaker_health, fetch_receipt, fetch_remote_policy, fetch_standing, fetch_triage,
|
|
10
|
+
normalize_receipt, normalize_standing, normalize_triage)
|
|
11
|
+
from .scan import REMEDIATIONS, RULE_IDS, RULES, looks_fake_secret, scan_diff
|
|
12
|
+
from .slop import SLOP_POINTS, SLOP_THRESHOLD, evaluate_slop
|
|
13
|
+
from .text import GitBillsError, ascii_json, display_text, md_code
|
|
14
|
+
from .version import NPX_COMMAND, UVX_COMMAND, VERSION
|
|
15
|
+
from .vouch import (clean_login, clean_repo, clean_sha, lookup_vouched_td, parse_pr_ref, parse_vouch_comment,
|
|
16
|
+
parse_vouched_td, vouch_command)
|
|
17
|
+
|
|
18
|
+
__version__ = VERSION
|
|
19
|
+
__all__ = [
|
|
20
|
+
'MAX_DIFF_BYTES', 'is_unsafe_path', 'parse_diff', 'collect_git_diff', 'detect_github_repo', 'find_executable',
|
|
21
|
+
'preflight_checkout', 'safe_read_file', 'POLICY_BLOCK', 'POLICY_HEADING', 'POLICY_PROTOCOL', 'append_policy_block',
|
|
22
|
+
'evaluate_policy', 'format_policy_terminal', 'matches_protected', 'parse_policy', 'DEFAULT_ORIGIN', 'NPX_COMMAND',
|
|
23
|
+
'PREFLIGHT_PROTOCOL', 'UVX_COMMAND', 'clean_origin', 'evaluate_preflight', 'format_preflight_terminal',
|
|
24
|
+
'receipt_markdown', 'render_agent_rule', 'VERSION', 'breaker_health', 'fetch_receipt', 'fetch_remote_policy',
|
|
25
|
+
'fetch_standing', 'fetch_triage', 'normalize_receipt', 'normalize_standing', 'normalize_triage', 'REMEDIATIONS',
|
|
26
|
+
'RULE_IDS', 'RULES', 'looks_fake_secret', 'scan_diff', 'SLOP_POINTS', 'SLOP_THRESHOLD', 'evaluate_slop',
|
|
27
|
+
'GitBillsError', 'ascii_json', 'display_text', 'md_code', 'clean_login', 'clean_repo', 'clean_sha',
|
|
28
|
+
'lookup_vouched_td', 'parse_pr_ref', 'parse_vouch_comment', 'parse_vouched_td', 'vouch_command', '__version__',
|
|
29
|
+
]
|
gitbills/__main__.py
ADDED
gitbills/cli.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
"""The gitbills command line (src/cli.js): main(argv) returns the exit code.
|
|
2
|
+
|
|
3
|
+
0 ready or done, 1 blocked or a remote failure, 2 invalid usage or input.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from .diff import MAX_DIFF_BYTES
|
|
13
|
+
from .local import (READ_ERRORS, collect_git_diff, detect_github_repo, find_executable, find_repo_root, read_policy_file,
|
|
14
|
+
read_stdin_bounded, repo_path, safe_read_file)
|
|
15
|
+
from .policy import POLICY_BLOCK, POLICY_PROTOCOL, append_policy_block, format_policy_terminal, parse_policy
|
|
16
|
+
from .preflight import MAX_BODY_CHARS, clean_origin, evaluate_preflight, format_preflight_terminal, render_agent_rule
|
|
17
|
+
from .remote import (clean_api_base, fetch_receipt, fetch_remote_policy, fetch_standing, fetch_triage,
|
|
18
|
+
fill_head_shas, format_receipt_markdown, format_receipt_terminal, format_server_policy,
|
|
19
|
+
format_standing_terminal, format_triage_markdown, format_triage_terminal)
|
|
20
|
+
from .text import GitBillsError, ascii_json, decode_utf8, display_text
|
|
21
|
+
from .version import VERSION
|
|
22
|
+
from .vouch import clean_login, clean_repo, clean_sha, parse_pr_ref, vouch_command
|
|
23
|
+
|
|
24
|
+
USAGE = '''gitbills %s: PR security X-Ray, AGENTS.md policy, queue triage and standing for GitHub pull requests.
|
|
25
|
+
|
|
26
|
+
Usage:
|
|
27
|
+
gitbills preflight [--diff FILE|- | --base REF] [--title TEXT] [--body TEXT | --body-file FILE|-]
|
|
28
|
+
[--repo OWNER/REPO] [--pr N] [--policy FILE | --no-policy] [--cwd DIR]
|
|
29
|
+
[--markdown | --json | --claude-rule]
|
|
30
|
+
gitbills policy [PATH | OWNER/REPO] [--init [--write]] [--json]
|
|
31
|
+
gitbills triage OWNER/REPO [--limit N] [--json | --markdown]
|
|
32
|
+
gitbills receipt OWNER/REPO#N | PR-URL [--markdown | --json]
|
|
33
|
+
gitbills vouch OWNER/REPO#N SHA [--scout] [--post]
|
|
34
|
+
gitbills standing LOGIN [--json]
|
|
35
|
+
|
|
36
|
+
preflight runs offline and sends nothing. policy OWNER/REPO, triage, receipt and standing read gitbills.com
|
|
37
|
+
(GITBILLS_ORIGIN overrides it) and the GitHub API (GITHUB_TOKEN or GH_TOKEN is used when set).
|
|
38
|
+
Exit codes: 0 ready or done; 1 blocked, or a remote failure; 2 invalid usage or input.
|
|
39
|
+
Run gitbills <command> --help for one command.''' % VERSION
|
|
40
|
+
|
|
41
|
+
HELP = {
|
|
42
|
+
'preflight': """Usage: gitbills preflight [options] (offline: the 14 security rules, slop heuristics, AGENTS.md policy)
|
|
43
|
+
--diff FILE|- a unified diff file, or - for standard input (at most %d bytes)
|
|
44
|
+
--base REF git diff REF...HEAD (default: the working tree against the merge base with upstream's, else
|
|
45
|
+
origin's, default branch; exit 2 when that base is missing or already holds HEAD)
|
|
46
|
+
--title, --body the pull request title and body (--body-file FILE|- reads the body)
|
|
47
|
+
--repo, --pr for the receipt link https://gitbills.com/OWNER/REPO/pull/N (repo default: the origin remote)
|
|
48
|
+
--policy FILE a policy file instead of AGENTS.md as the base commit holds it; --no-policy skips the policy
|
|
49
|
+
--cwd DIR run in DIR
|
|
50
|
+
--markdown | --json | --claude-rule the PR receipt, the gitbills-preflight/1 report, or the CLAUDE.md rule
|
|
51
|
+
Exit 0: ready, review_recommended or nothing to check; 1: blocked_security, blocked_slop or blocked_policy; 2: bad input.""" % MAX_DIFF_BYTES,
|
|
52
|
+
'policy': """Usage: gitbills policy [PATH | OWNER/REPO] [--init [--write]] [--json]
|
|
53
|
+
Read the "## Pull requests from agents" section of a local AGENTS.md or a public repository's (from GitHub, with
|
|
54
|
+
gitbills.com's reading beside it). --init prints the six-line block; --init --write appends it to the local AGENTS.md.
|
|
55
|
+
Exit 0: found or written; 1: none; 2: bad input.""",
|
|
56
|
+
'triage': """Usage: gitbills triage OWNER/REPO [--limit 1-20] [--json | --markdown]
|
|
57
|
+
Sort the open queue on gitbills.com: Ready for review, Needs vouch (with /gitbills vouch <sha>), Batch / defer, Attention required.""",
|
|
58
|
+
'receipt': """Usage: gitbills receipt OWNER/REPO#N | PR-URL [--markdown | --json]
|
|
59
|
+
A pull request's commit-pinned GitBills receipt and badge Markdown.""",
|
|
60
|
+
'vouch': """Usage: gitbills vouch OWNER/REPO#N SHA [--scout] [--post]
|
|
61
|
+
The vouch comment for one exact 40-hex commit (short SHAs are refused); --post checks the head and posts it with gh.""",
|
|
62
|
+
'standing': """Usage: gitbills standing LOGIN [--json]
|
|
63
|
+
Verified merge receipts, Scout avals, vouch line and circuit breaker (trips above 22% slop once 3 avals are judged).""",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
_USAGE_CODES = {'usage', 'invalid_repo', 'invalid_pr', 'invalid_login', 'invalid_sha', 'invalid_field', 'invalid_diff',
|
|
67
|
+
'diff_too_large', 'invalid_options'}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _usage(message):
|
|
71
|
+
raise GitBillsError('usage', message)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _parse_args(args, values=(), bools=()):
|
|
75
|
+
opts, pos = {}, []
|
|
76
|
+
v, b = set(values), set(bools) | {'--help', '-h'}
|
|
77
|
+
i = 0
|
|
78
|
+
while i < len(args):
|
|
79
|
+
a = args[i]
|
|
80
|
+
if a == '--':
|
|
81
|
+
pos += args[i + 1:]
|
|
82
|
+
break
|
|
83
|
+
if a in b:
|
|
84
|
+
opts['--help' if a == '-h' else a] = True
|
|
85
|
+
i += 1
|
|
86
|
+
continue
|
|
87
|
+
eq = a.find('=') if a.startswith('--') else -1
|
|
88
|
+
name = a[:eq] if eq > 0 else a
|
|
89
|
+
if name in v:
|
|
90
|
+
if name in opts:
|
|
91
|
+
_usage('%s given twice' % name)
|
|
92
|
+
if eq > 0:
|
|
93
|
+
opts[name] = a[eq + 1:]
|
|
94
|
+
else:
|
|
95
|
+
nxt = args[i + 1] if i + 1 < len(args) else None
|
|
96
|
+
if nxt is None or (nxt.startswith('--') and len(nxt) > 2):
|
|
97
|
+
_usage('%s needs a value' % name)
|
|
98
|
+
opts[name] = nxt
|
|
99
|
+
i += 1
|
|
100
|
+
i += 1
|
|
101
|
+
continue
|
|
102
|
+
if name in b:
|
|
103
|
+
_usage('%s takes no value' % name)
|
|
104
|
+
if a.startswith('-') and a != '-':
|
|
105
|
+
_usage('unknown option %s' % display_text(a, 60))
|
|
106
|
+
pos.append(a)
|
|
107
|
+
i += 1
|
|
108
|
+
return opts, pos
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _exclusive(opts, names):
|
|
112
|
+
given = [n for n in names if n in opts]
|
|
113
|
+
if len(given) > 1:
|
|
114
|
+
_usage('%s cannot be combined' % ' and '.join(given))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _read_input(src, ctx, max_bytes, what):
|
|
118
|
+
if src == '':
|
|
119
|
+
_usage('%s needs a file path, or - for standard input' % what)
|
|
120
|
+
if src == '-':
|
|
121
|
+
r = ctx['read_stdin'](max_bytes)
|
|
122
|
+
if r.get('over'):
|
|
123
|
+
_usage('%s from standard input is over %d bytes' % (what, max_bytes))
|
|
124
|
+
return decode_utf8(r['bytes'])
|
|
125
|
+
r = safe_read_file(os.path.join(ctx['cwd'], src), max_bytes, ctx['cwd'])
|
|
126
|
+
if 'error' in r:
|
|
127
|
+
_usage('%s %s: %s' % (what, display_text(src, 200), READ_ERRORS[r['error']]))
|
|
128
|
+
return decode_utf8(r['bytes'])
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _cmd_preflight(args, ctx):
|
|
132
|
+
opts, pos = _parse_args(args, ['--diff', '--base', '--title', '--body', '--body-file', '--repo', '--pr', '--policy', '--cwd'],
|
|
133
|
+
['--json', '--markdown', '--claude-rule', '--no-policy'])
|
|
134
|
+
if opts.get('--help'):
|
|
135
|
+
ctx['out'](HELP['preflight'])
|
|
136
|
+
return 0
|
|
137
|
+
if pos:
|
|
138
|
+
_usage('unexpected argument %s' % display_text(pos[0], 60))
|
|
139
|
+
for group in (['--json', '--markdown', '--claude-rule'], ['--diff', '--base'], ['--body', '--body-file'], ['--policy', '--no-policy']):
|
|
140
|
+
_exclusive(opts, group)
|
|
141
|
+
work = os.path.abspath(os.path.join(ctx['cwd'], opts.get('--cwd', '.')))
|
|
142
|
+
if not os.path.isdir(work):
|
|
143
|
+
_usage('--cwd is not a folder')
|
|
144
|
+
root = find_repo_root(work)
|
|
145
|
+
repo = None
|
|
146
|
+
if '--repo' in opts:
|
|
147
|
+
repo = clean_repo(opts['--repo'])
|
|
148
|
+
elif '--diff' not in opts:
|
|
149
|
+
try:
|
|
150
|
+
d = detect_github_repo(root)
|
|
151
|
+
repo = clean_repo(d) if d else None
|
|
152
|
+
except GitBillsError:
|
|
153
|
+
repo = None
|
|
154
|
+
if opts.get('--claude-rule'):
|
|
155
|
+
if any(k in opts for k in ('--diff', '--base', '--title', '--body', '--body-file', '--pr', '--policy', '--no-policy')):
|
|
156
|
+
_usage('--claude-rule takes only --repo and --cwd')
|
|
157
|
+
ctx['out'](render_agent_rule(repo))
|
|
158
|
+
return 0
|
|
159
|
+
pr_number = None
|
|
160
|
+
if '--pr' in opts:
|
|
161
|
+
if not re.match(r'^[1-9][0-9]{0,8}\Z', opts['--pr'], re.ASCII) or not opts['--pr'].isascii():
|
|
162
|
+
_usage('--pr must be a whole number from 1')
|
|
163
|
+
pr_number = int(opts['--pr'])
|
|
164
|
+
body = _read_input(opts['--body-file'], ctx, MAX_BODY_CHARS * 4, '--body-file') if '--body-file' in opts else opts.get('--body', '')
|
|
165
|
+
file = None if opts.get('--no-policy') or '--policy' not in opts else os.path.abspath(os.path.join(ctx['cwd'], opts['--policy']))
|
|
166
|
+
roots, note, base_policy = [], None, None
|
|
167
|
+
if '--diff' in opts:
|
|
168
|
+
diff = _read_input(opts['--diff'], ctx, MAX_DIFF_BYTES, '--diff')
|
|
169
|
+
label = 'standard input' if opts['--diff'] == '-' else display_text(opts['--diff'], 200)
|
|
170
|
+
else:
|
|
171
|
+
# git mode: the policy is AGENTS.md as the base commit holds it, never the change's own copy.
|
|
172
|
+
r = collect_git_diff(work, opts.get('--base'), ctx['env'], MAX_DIFF_BYTES, not opts.get('--no-policy') and file is None)
|
|
173
|
+
if 'error' in r:
|
|
174
|
+
ctx['err']('gitbills preflight: %s' % r['error'])
|
|
175
|
+
return 2
|
|
176
|
+
diff, roots, note, label = r['diff'], r['roots'], r['note'], r['label']
|
|
177
|
+
base_policy = r.get('policy')
|
|
178
|
+
policy = source = policy_path = None
|
|
179
|
+
if not opts.get('--no-policy'):
|
|
180
|
+
p = base_policy if base_policy is not None else read_policy_file(root or work, file)
|
|
181
|
+
shown = 'AGENTS.md' if file is None else display_text(opts['--policy'], 200)
|
|
182
|
+
if 'error' in p:
|
|
183
|
+
_usage('%s: %s' % (display_text(p['source'], 200) if base_policy is not None else shown, READ_ERRORS[p['error']]))
|
|
184
|
+
policy = p['text']
|
|
185
|
+
source = None if policy is None else p['source'] if base_policy is not None else shown
|
|
186
|
+
policy_path = 'AGENTS.md' if file is None else repo_path(root, file)
|
|
187
|
+
report = evaluate_preflight(diff, opts.get('--title', ''), body, repo, pr_number, policy, source, roots,
|
|
188
|
+
clean_origin(ctx['env'].get('GITBILLS_ORIGIN')), True, policy_path)
|
|
189
|
+
if opts.get('--json'):
|
|
190
|
+
ctx['out'](ascii_json(report))
|
|
191
|
+
elif opts.get('--markdown'):
|
|
192
|
+
ctx['out'](report['markdown_receipt'])
|
|
193
|
+
else:
|
|
194
|
+
ctx['out']('%s\n Diff: %s' % (format_preflight_terminal(report), label))
|
|
195
|
+
if note:
|
|
196
|
+
ctx['err']('gitbills preflight: note: %s' % note)
|
|
197
|
+
return report['exit_code']
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _policy_target(target, ctx):
|
|
201
|
+
if target is None:
|
|
202
|
+
root = find_repo_root(ctx['cwd']) or ctx['cwd']
|
|
203
|
+
return {'kind': 'local', 'file': os.path.join(root, 'AGENTS.md'), 'label': 'AGENTS.md'}
|
|
204
|
+
path = os.path.abspath(os.path.join(ctx['cwd'], target))
|
|
205
|
+
if os.path.lexists(path):
|
|
206
|
+
return {'kind': 'local', 'file': os.path.join(path, 'AGENTS.md') if os.path.isdir(path) and not os.path.islink(path) else path,
|
|
207
|
+
'label': display_text(target, 200)}
|
|
208
|
+
if re.match(r'^https://', target, re.I) or re.match(r'^[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9_.-]+\Z', target, re.ASCII):
|
|
209
|
+
return {'kind': 'remote', 'repo': clean_repo(target)}
|
|
210
|
+
_usage('%s: no such file, and not OWNER/REPO' % display_text(target, 200))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _remote_opts(ctx):
|
|
214
|
+
env = ctx['env']
|
|
215
|
+
return {'origin': clean_origin(env.get('GITBILLS_ORIGIN')), 'github_api': clean_api_base(env.get('GITBILLS_GITHUB_API')),
|
|
216
|
+
'token': env.get('GITHUB_TOKEN') or env.get('GH_TOKEN') or None}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _cmd_policy(args, ctx):
|
|
220
|
+
opts, pos = _parse_args(args, (), ['--init', '--write', '--json'])
|
|
221
|
+
if opts.get('--help'):
|
|
222
|
+
ctx['out'](HELP['policy'])
|
|
223
|
+
return 0
|
|
224
|
+
if len(pos) > 1:
|
|
225
|
+
_usage('unexpected argument %s' % display_text(pos[1], 60))
|
|
226
|
+
if opts.get('--write') and not opts.get('--init'):
|
|
227
|
+
_usage('--write needs --init')
|
|
228
|
+
if opts.get('--init'):
|
|
229
|
+
if not opts.get('--write'):
|
|
230
|
+
ctx['out'](ascii_json({'protocol': POLICY_PROTOCOL, 'block': POLICY_BLOCK}) if opts.get('--json') else POLICY_BLOCK)
|
|
231
|
+
return 0
|
|
232
|
+
t = _policy_target(pos[0] if pos else None, ctx)
|
|
233
|
+
if t['kind'] != 'local':
|
|
234
|
+
_usage('--init --write writes a local AGENTS.md: pass a folder or a file path')
|
|
235
|
+
existing = ''
|
|
236
|
+
if os.path.lexists(t['file']):
|
|
237
|
+
r = safe_read_file(t['file'], 262_144)
|
|
238
|
+
if 'error' in r:
|
|
239
|
+
_usage('%s: %s' % (t['label'], READ_ERRORS[r['error']]))
|
|
240
|
+
existing = decode_utf8(r['bytes'])
|
|
241
|
+
try:
|
|
242
|
+
nxt = append_policy_block(existing)
|
|
243
|
+
except ValueError as e:
|
|
244
|
+
ctx['err']('gitbills policy: %s' % e)
|
|
245
|
+
return 1
|
|
246
|
+
suffix = nxt[len(existing):]
|
|
247
|
+
flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_BINARY', 0)
|
|
248
|
+
fd = os.open(t['file'], flags, 0o644)
|
|
249
|
+
try:
|
|
250
|
+
os.write(fd, suffix.encode('utf-8'))
|
|
251
|
+
finally:
|
|
252
|
+
os.close(fd)
|
|
253
|
+
ctx['out']('gitbills policy: added "## Pull requests from agents" to %s' % t['label'])
|
|
254
|
+
return 0
|
|
255
|
+
t = _policy_target(pos[0] if pos else None, ctx)
|
|
256
|
+
remote = t['kind'] == 'remote'
|
|
257
|
+
server = None
|
|
258
|
+
if remote:
|
|
259
|
+
o = _remote_opts(ctx)
|
|
260
|
+
r = fetch_remote_policy(t['repo'], o['origin'], o['github_api'], o['token'], ctx['opener'])
|
|
261
|
+
text = r['text'] or ''
|
|
262
|
+
source = '%s (no AGENTS.md)' % r['source'] if r['text'] is None else r['source']
|
|
263
|
+
server = r['server']
|
|
264
|
+
else:
|
|
265
|
+
r = safe_read_file(t['file'], 262_144)
|
|
266
|
+
if r.get('error') == 'missing':
|
|
267
|
+
text, source = '', '%s (missing)' % t['label']
|
|
268
|
+
elif 'error' in r:
|
|
269
|
+
_usage('%s: %s' % (t['label'], READ_ERRORS[r['error']]))
|
|
270
|
+
else:
|
|
271
|
+
text, source = decode_utf8(r['bytes']), t['label']
|
|
272
|
+
p = parse_policy(text)
|
|
273
|
+
if opts.get('--json'):
|
|
274
|
+
ctx['out'](ascii_json(dict(p, source=source, server=server) if remote else dict(p, source=source)))
|
|
275
|
+
else:
|
|
276
|
+
ctx['out'](format_policy_terminal(p, source) + ('\n' + format_server_policy(server) if remote else ''))
|
|
277
|
+
return 0 if p['found'] else 1
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _cmd_triage(args, ctx):
|
|
281
|
+
opts, pos = _parse_args(args, ['--limit'], ['--json', '--markdown'])
|
|
282
|
+
if opts.get('--help'):
|
|
283
|
+
ctx['out'](HELP['triage'])
|
|
284
|
+
return 0
|
|
285
|
+
_exclusive(opts, ['--json', '--markdown'])
|
|
286
|
+
if len(pos) != 1:
|
|
287
|
+
_usage('name one repository: gitbills triage OWNER/REPO')
|
|
288
|
+
repo = clean_repo(pos[0])
|
|
289
|
+
limit = 12
|
|
290
|
+
if '--limit' in opts:
|
|
291
|
+
if not re.match(r'^[0-9]{1,2}\Z', opts['--limit'], re.ASCII) or not 1 <= int(opts['--limit']) <= 20:
|
|
292
|
+
_usage('--limit must be 1 to 20')
|
|
293
|
+
limit = int(opts['--limit'])
|
|
294
|
+
o = _remote_opts(ctx)
|
|
295
|
+
t = fetch_triage(repo, o['origin'], limit, ctx['opener'])
|
|
296
|
+
fill_head_shas(t, o['github_api'], o['token'], ctx['opener'])
|
|
297
|
+
ctx['out'](ascii_json(t) if opts.get('--json') else format_triage_markdown(t) if opts.get('--markdown') else format_triage_terminal(t))
|
|
298
|
+
return 0
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _cmd_receipt(args, ctx):
|
|
302
|
+
opts, pos = _parse_args(args, (), ['--json', '--markdown'])
|
|
303
|
+
if opts.get('--help'):
|
|
304
|
+
ctx['out'](HELP['receipt'])
|
|
305
|
+
return 0
|
|
306
|
+
_exclusive(opts, ['--json', '--markdown'])
|
|
307
|
+
if len(pos) != 1:
|
|
308
|
+
_usage('name one pull request: gitbills receipt OWNER/REPO#N')
|
|
309
|
+
repo, number = parse_pr_ref(pos[0])
|
|
310
|
+
r = fetch_receipt(repo, number, _remote_opts(ctx)['origin'], ctx['opener'])
|
|
311
|
+
ctx['out'](ascii_json(r) if opts.get('--json') else format_receipt_markdown(r) if opts.get('--markdown') else format_receipt_terminal(r))
|
|
312
|
+
return 0
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
_GH_ENV = {'GH_PROMPT_DISABLED': '1', 'GH_NO_UPDATE_NOTIFIER': '1', 'NO_COLOR': '1', 'GH_PAGER': 'cat'}
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _default_run(file, args, cwd, env, input_text=None):
|
|
319
|
+
"""Run a program without a shell: {'ok', 'stdout'}. The body travels on stdin, never through argv or a shell."""
|
|
320
|
+
full = dict(env)
|
|
321
|
+
full.update(_GH_ENV)
|
|
322
|
+
try:
|
|
323
|
+
p = subprocess.run([file, *args], cwd=cwd, env=full, input=(input_text or '').encode('utf-8'),
|
|
324
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60, shell=False, check=False)
|
|
325
|
+
except (OSError, subprocess.SubprocessError):
|
|
326
|
+
return {'ok': False, 'stdout': ''}
|
|
327
|
+
return {'ok': p.returncode == 0, 'stdout': decode_utf8(p.stdout)}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _cmd_vouch(args, ctx):
|
|
331
|
+
opts, pos = _parse_args(args, (), ['--scout', '--post'])
|
|
332
|
+
if opts.get('--help'):
|
|
333
|
+
ctx['out'](HELP['vouch'])
|
|
334
|
+
return 0
|
|
335
|
+
if len(pos) != 2:
|
|
336
|
+
_usage('usage: gitbills vouch OWNER/REPO#N SHA [--scout] [--post]')
|
|
337
|
+
repo, number = parse_pr_ref(pos[0])
|
|
338
|
+
sha = clean_sha(pos[1])
|
|
339
|
+
command = vouch_command(sha, bool(opts.get('--scout')))
|
|
340
|
+
if not opts.get('--post'):
|
|
341
|
+
ctx['out'](command)
|
|
342
|
+
return 0
|
|
343
|
+
gh = find_executable('gh', ctx['env'], (ctx['cwd'], find_repo_root(ctx['cwd']) or ctx['cwd']))
|
|
344
|
+
if not gh:
|
|
345
|
+
ctx['err']('gitbills vouch: gh (GitHub CLI) was not found on PATH outside this checkout; paste this comment yourself:')
|
|
346
|
+
ctx['out'](command)
|
|
347
|
+
return 1
|
|
348
|
+
head = ctx['run'](gh, ['api', 'repos/%s/pulls/%d' % (repo, number), '--jq', '.head.sha'], ctx['cwd'], ctx['env'])
|
|
349
|
+
head_sha = head['stdout'].strip().lower() if head['ok'] else ''
|
|
350
|
+
if not re.match(r'^[0-9a-f]{40}\Z', head_sha, re.ASCII):
|
|
351
|
+
ctx['err']('gitbills vouch: could not read the head commit of %s#%d with gh api' % (repo, number))
|
|
352
|
+
return 1
|
|
353
|
+
if head_sha != sha:
|
|
354
|
+
ctx['err']('gitbills vouch: not posted: %s#%d is now at %s, not %s. Review that commit, then vouch for it.' % (repo, number, head_sha, sha))
|
|
355
|
+
return 1
|
|
356
|
+
posted = ctx['run'](gh, ['pr', 'comment', str(number), '--repo', repo, '--body-file', '-'], ctx['cwd'], ctx['env'], command + '\n')
|
|
357
|
+
if not posted['ok']:
|
|
358
|
+
ctx['err']('gitbills vouch: gh pr comment failed for %s#%d' % (repo, number))
|
|
359
|
+
return 1
|
|
360
|
+
ctx['out']('Posted on %s#%d: %s' % (repo, number, command))
|
|
361
|
+
return 0
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _cmd_standing(args, ctx):
|
|
365
|
+
opts, pos = _parse_args(args, (), ['--json'])
|
|
366
|
+
if opts.get('--help'):
|
|
367
|
+
ctx['out'](HELP['standing'])
|
|
368
|
+
return 0
|
|
369
|
+
if len(pos) != 1:
|
|
370
|
+
_usage('name one GitHub login: gitbills standing LOGIN')
|
|
371
|
+
s = fetch_standing(clean_login(pos[0]), _remote_opts(ctx)['origin'], ctx['opener'])
|
|
372
|
+
ctx['out'](ascii_json(s) if opts.get('--json') else format_standing_terminal(s))
|
|
373
|
+
return 0
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
_COMMANDS = {'preflight': _cmd_preflight, 'policy': _cmd_policy, 'triage': _cmd_triage, 'receipt': _cmd_receipt,
|
|
377
|
+
'vouch': _cmd_vouch, 'standing': _cmd_standing}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _print_to(stream):
|
|
381
|
+
def write(s):
|
|
382
|
+
stream.write(s + '\n')
|
|
383
|
+
stream.flush()
|
|
384
|
+
return write
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def main(argv=None, out=None, err=None, env=None, cwd=None, read_stdin=None, run=None, opener=None) -> int:
|
|
388
|
+
if out is None or err is None:
|
|
389
|
+
for stream in (sys.stdout, sys.stderr):
|
|
390
|
+
try:
|
|
391
|
+
stream.reconfigure(encoding='utf-8', errors='replace', newline='\n')
|
|
392
|
+
except (AttributeError, ValueError): # pragma: no cover
|
|
393
|
+
pass
|
|
394
|
+
ctx = {'out': out or _print_to(sys.stdout), 'err': err or _print_to(sys.stderr),
|
|
395
|
+
'env': dict(os.environ) if env is None else env, 'cwd': cwd or os.getcwd(),
|
|
396
|
+
'read_stdin': read_stdin or read_stdin_bounded, 'run': run or _default_run, 'opener': opener}
|
|
397
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
398
|
+
if not argv or argv[0] in ('--help', '-h', 'help'):
|
|
399
|
+
ctx['out'](USAGE)
|
|
400
|
+
return 0
|
|
401
|
+
if argv[0] in ('--version', '-v', 'version'):
|
|
402
|
+
ctx['out'](VERSION)
|
|
403
|
+
return 0
|
|
404
|
+
cmd, rest = argv[0], argv[1:]
|
|
405
|
+
handler = _COMMANDS.get(cmd)
|
|
406
|
+
if handler is None:
|
|
407
|
+
ctx['err']('gitbills: unknown command %s\n\n%s' % (display_text(cmd, 60), USAGE))
|
|
408
|
+
return 2
|
|
409
|
+
try:
|
|
410
|
+
return handler(rest, ctx)
|
|
411
|
+
except GitBillsError as e:
|
|
412
|
+
ctx['err']('gitbills %s: %s' % (cmd, e.message))
|
|
413
|
+
return 2 if e.code in _USAGE_CODES else 1
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
if __name__ == '__main__': # pragma: no cover
|
|
417
|
+
raise SystemExit(main())
|