@bbcsoftwarefactory/commands 0.1.1 → 1.1.2

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.
@@ -1,347 +0,0 @@
1
- #!/usr/bin/env python3
2
- """sweep-github.py: the only part of /issue-clean-and-close that talks to GitHub.
3
-
4
- `fetch` reads every open issue with one paginated GraphQL query and writes the snapshot
5
- that sweep-issues.py evaluates. `apply` performs exactly the writes a plan lists, in order,
6
- and nothing else. Both use the `gh` CLI. Policy: references/policy.md.
7
- """
8
-
9
- from datetime import datetime, timezone
10
- import json
11
- import os
12
- import re
13
- import subprocess
14
- import sys
15
- from urllib.parse import quote
16
-
17
- DEFAULT_SWEEPER = 'github-actions[bot]'
18
- PAGE_SIZE = 30
19
- MAX_PAGES = 100
20
- PR_TEXT_LIMIT = 4000
21
- ISSUE_REFERENCE = re.compile(r'#\d|/issues/\d')
22
- MARKER = re.compile(r'<!-- issue-sweeper:([A-Za-z0-9]+) -->')
23
- REPORT_MARKER = '<!-- issue-sweeper:report -->'
24
- PR_FIELDS = 'number url state mergedAt title body repository { nameWithOwner } mergeCommit { oid }'
25
- QUERY = '''
26
- query($owner: String!, $name: String!, $cursor: String) {
27
- repository(owner: $owner, name: $name) {
28
- nameWithOwner
29
- labels(first: 100) { nodes { name } }
30
- issues(states: OPEN, first: %d, after: $cursor, orderBy: {field: CREATED_AT, direction: ASC}) {
31
- pageInfo { hasNextPage endCursor }
32
- nodes {
33
- number title url createdAt body
34
- author { login }
35
- labels(first: 50) { nodes { name } }
36
- assignees(first: 10) { nodes { login } }
37
- refs: timelineItems(first: 25, itemTypes: [CONNECTED_EVENT, DISCONNECTED_EVENT, CROSS_REFERENCED_EVENT]) {
38
- pageInfo { hasNextPage }
39
- nodes {
40
- __typename
41
- ... on ConnectedEvent { createdAt subject { ... on PullRequest { %s } } }
42
- ... on DisconnectedEvent { createdAt subject { ... on PullRequest { %s } } }
43
- ... on CrossReferencedEvent { createdAt willCloseTarget source { ... on PullRequest { %s } } }
44
- }
45
- }
46
- recent: timelineItems(last: 25, itemTypes: [ISSUE_COMMENT, LABELED_EVENT, UNLABELED_EVENT, REOPENED_EVENT]) {
47
- nodes {
48
- __typename
49
- ... on IssueComment { createdAt author { login } body }
50
- ... on LabeledEvent { createdAt actor { login } label { name } }
51
- ... on UnlabeledEvent { createdAt actor { login } label { name } }
52
- ... on ReopenedEvent { createdAt actor { login } }
53
- }
54
- }
55
- }
56
- }
57
- }
58
- }
59
- ''' % (PAGE_SIZE, PR_FIELDS, PR_FIELDS, PR_FIELDS)
60
- LABEL_EVENTS = {'LabeledEvent': 'labeled', 'UnlabeledEvent': 'unlabeled'}
61
-
62
- HELP = (
63
- 'Usage: python3 -I -B scripts/sweep-github.py fetch --repo <owner/repo> --out <snapshot.json>'
64
- ' [--sweeper-login github-actions[bot]]\n'
65
- ' python3 -I -B scripts/sweep-github.py apply --repo <owner/repo> --plan <plan.json> [--only 12,15] [--dry-run]\n'
66
- 'Needs an authenticated gh CLI (SWEEP_GH overrides the command); sweep.py runs both steps.\n'
67
- 'Exit 0: done; 1: some writes failed (listed); 2: unusable input.'
68
- )
69
-
70
-
71
- class Unusable(Exception):
72
- """The arguments, plan, or GitHub response cannot be used."""
73
-
74
-
75
- def _write_out(text):
76
- sys.stdout.buffer.write((text + '\n').encode('utf-8', 'surrogateescape'))
77
-
78
-
79
- def _fold(value):
80
- return value.strip().casefold() if isinstance(value, str) else ''
81
-
82
-
83
- def _login(value):
84
- login = value.get('login') if isinstance(value, dict) else None
85
- return login if isinstance(login, str) and login else 'ghost'
86
-
87
-
88
- def _nodes(value):
89
- nodes = value.get('nodes') if isinstance(value, dict) else None
90
- return [node for node in nodes or [] if isinstance(node, dict)]
91
-
92
-
93
- def _pull(node):
94
- """The pull request in a timeline node, or None for issues and inaccessible sources."""
95
- return node if isinstance(node, dict) and 'state' in node and isinstance(node.get('number'), int) else None
96
-
97
-
98
- def _pr_entry(pr, at):
99
- body = pr.get('body') if isinstance(pr.get('body'), str) else ''
100
- references = [line.strip() for line in body.splitlines() if ISSUE_REFERENCE.search(line)]
101
- text = '\n'.join([pr.get('title') or ''] + references)[:PR_TEXT_LIMIT]
102
- merge = pr.get('mergeCommit') if isinstance(pr.get('mergeCommit'), dict) else {}
103
- repo = pr.get('repository') if isinstance(pr.get('repository'), dict) else {}
104
- return {'number': pr['number'], 'repo': repo.get('nameWithOwner'), 'state': pr.get('state'),
105
- 'merged_at': pr.get('mergedAt'), 'merge_commit': merge.get('oid'), 'url': pr.get('url'),
106
- 'will_close': False, 'manual_link': False, 'text': text, 'referenced_at': at}
107
-
108
-
109
- def _prs(refs):
110
- found = {}
111
- for node in sorted(_nodes(refs), key=lambda item: item.get('createdAt') or ''):
112
- kind = node.get('__typename')
113
- pr = _pull(node.get('source') if kind == 'CrossReferencedEvent' else node.get('subject'))
114
- if pr is None:
115
- continue
116
- key = (_fold((pr.get('repository') or {}).get('nameWithOwner')), pr['number'])
117
- entry = found.setdefault(key, _pr_entry(pr, node.get('createdAt')))
118
- if kind == 'CrossReferencedEvent':
119
- entry['will_close'] = entry['will_close'] or node.get('willCloseTarget') is True
120
- else:
121
- entry['manual_link'] = kind == 'ConnectedEvent'
122
- return list(found.values())
123
-
124
-
125
- def _events(recent):
126
- events = []
127
- for node in _nodes(recent):
128
- kind = node.get('__typename')
129
- at = node.get('createdAt')
130
- if kind == 'IssueComment':
131
- body = node.get('body') if isinstance(node.get('body'), str) else ''
132
- match = MARKER.search(body)
133
- events.append({'type': 'comment', 'at': at, 'actor': _login(node.get('author')),
134
- 'marker': match.group(1) if match else None})
135
- elif kind in LABEL_EVENTS:
136
- label = node.get('label') if isinstance(node.get('label'), dict) else {}
137
- events.append({'type': LABEL_EVENTS[kind], 'label': label.get('name'), 'at': at,
138
- 'actor': _login(node.get('actor'))})
139
- elif kind == 'ReopenedEvent':
140
- events.append({'type': 'reopened', 'at': at, 'actor': _login(node.get('actor'))})
141
- return events
142
-
143
-
144
- def _bare(login):
145
- folded = _fold(login)
146
- return folded[:-5] if folded.endswith('[bot]') else folded
147
-
148
-
149
- def to_snapshot(pages, fetched_at, sweeper_login=DEFAULT_SWEEPER):
150
- """GraphQL pages -> the snapshot sweep-issues.py reads. Bodies never leave this function.
151
-
152
- Only an issue the sweeper itself opened can be the report issue, so nobody can get
153
- another issue's body overwritten by copying the marker into it.
154
- """
155
- sweeper = _bare(sweeper_login)
156
- if not pages:
157
- raise Unusable('No GraphQL pages.')
158
- repos = [((page or {}).get('data') or {}).get('repository') for page in pages]
159
- if not all(isinstance(repo, dict) for repo in repos):
160
- raise Unusable('GraphQL response has no repository; check the name and the token.')
161
- snapshot = {'repo': repos[0].get('nameWithOwner'), 'fetched_at': fetched_at,
162
- 'labels': [node.get('name') for node in _nodes(repos[0].get('labels'))],
163
- 'report_issue': None, 'issues': []}
164
- for repo in repos:
165
- for node in _nodes(repo.get('issues')):
166
- body = node.get('body') if isinstance(node.get('body'), str) else ''
167
- if REPORT_MARKER in body and _bare(_login(node.get('author'))) == sweeper:
168
- snapshot['report_issue'] = snapshot['report_issue'] or node.get('number')
169
- continue
170
- refs = node.get('refs') if isinstance(node.get('refs'), dict) else {}
171
- snapshot['issues'].append({
172
- 'number': node.get('number'), 'title': node.get('title'), 'url': node.get('url'),
173
- 'author': _login(node.get('author')), 'created_at': node.get('createdAt'),
174
- 'labels': [label.get('name') for label in _nodes(node.get('labels'))],
175
- 'assignees': [_login(user) for user in _nodes(node.get('assignees'))],
176
- 'prs': _prs(refs), 'events': _events(node.get('recent')),
177
- 'incomplete': (refs.get('pageInfo') or {}).get('hasNextPage') is True,
178
- })
179
- return snapshot
180
-
181
-
182
- def issue_commands(plan, repo):
183
- """[(issue, gh argv)] for every step of every action, in plan order."""
184
- commands = []
185
- for entry in plan.get('actions') or []:
186
- base = 'repos/' + repo + '/issues/' + str(entry['issue'])
187
- for step in entry.get('steps') or []:
188
- action = step.get('action')
189
- if action == 'comment':
190
- argv = ['api', '-X', 'POST', base + '/comments', '-f', 'body=' + step['body']]
191
- elif action == 'close':
192
- argv = ['api', '-X', 'PATCH', base, '-f', 'state=closed', '-f', 'state_reason=' + step['state_reason']]
193
- elif action == 'add-label':
194
- argv = ['api', '-X', 'POST', base + '/labels', '-f', 'labels[]=' + step['label']]
195
- elif action == 'remove-label':
196
- argv = ['api', '-X', 'DELETE', base + '/labels/' + quote(step['label'], safe='')]
197
- else:
198
- raise Unusable('Unknown plan step: ' + str(action))
199
- commands.append((entry['issue'], argv))
200
- return commands
201
-
202
-
203
- def report_command(plan, repo):
204
- body = 'body=' + plan['report_markdown']
205
- if isinstance(plan.get('report_issue'), int):
206
- return ['api', '-X', 'PATCH', 'repos/' + repo + '/issues/' + str(plan['report_issue']), '-f', body]
207
- return ['api', '-X', 'POST', 'repos/' + repo + '/issues', '-f', 'title=' + plan['report_title'], '-f', body]
208
-
209
-
210
- def _gh_command():
211
- """`gh`, or SWEEP_GH: a path, or a JSON array such as ["python3", "fake_gh.py"] for tests."""
212
- value = os.environ.get('SWEEP_GH', '').strip()
213
- return json.loads(value) if value.startswith('[') else [value or 'gh']
214
-
215
-
216
- def _gh(argv):
217
- try:
218
- result = subprocess.run(_gh_command() + argv, capture_output=True, text=True, encoding='utf-8')
219
- except OSError as error:
220
- raise Unusable('gh CLI is not available: ' + str(error))
221
- return result.returncode, result.stdout, result.stderr.strip()[:500]
222
-
223
-
224
- def fetch(repo, out, sweeper_login):
225
- owner, name = repo.split('/', 1)
226
- pages, cursor = [], None
227
- for _ in range(MAX_PAGES):
228
- argv = ['api', 'graphql', '-f', 'query=' + QUERY, '-f', 'owner=' + owner, '-f', 'name=' + name]
229
- if cursor:
230
- argv += ['-f', 'cursor=' + cursor]
231
- code, stdout, stderr = _gh(argv)
232
- if code != 0:
233
- raise Unusable('GraphQL query failed: ' + stderr)
234
- try:
235
- page = json.loads(stdout)
236
- except ValueError:
237
- raise Unusable('GraphQL response is not JSON.')
238
- pages.append(page)
239
- info = (((page.get('data') or {}).get('repository') or {}).get('issues') or {}).get('pageInfo') or {}
240
- if not info.get('hasNextPage'):
241
- break
242
- cursor = info.get('endCursor')
243
- else:
244
- raise Unusable('More than ' + str(MAX_PAGES * PAGE_SIZE) + ' open issues; raise MAX_PAGES deliberately.')
245
- snapshot = to_snapshot(pages, datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), sweeper_login)
246
- with open(out, 'w', encoding='utf-8') as handle:
247
- json.dump(snapshot, handle, ensure_ascii=False, indent=2)
248
- return {'snapshot': out, 'issues': len(snapshot['issues']), 'pages': len(pages),
249
- 'report_issue': snapshot['report_issue']}
250
-
251
-
252
- def load_plan(path, repo):
253
- try:
254
- with open(path, encoding='utf-8') as handle:
255
- plan = json.load(handle)
256
- except (OSError, ValueError):
257
- raise Unusable('Plan cannot be read as JSON.')
258
- if not isinstance(plan, dict) or plan.get('verdict') != 'ok':
259
- raise Unusable('Plan verdict is not ok; nothing is written.')
260
- if _fold(plan.get('repo')) != _fold(repo):
261
- raise Unusable('Plan is for ' + str(plan.get('repo')) + ', not ' + repo + '.')
262
- if not isinstance(plan.get('actions'), list) or not isinstance(plan.get('report_markdown'), str):
263
- raise Unusable('Plan needs actions and report_markdown.')
264
- return plan
265
-
266
-
267
- def select(plan, only):
268
- """The plan restricted to the approved issue numbers; an unknown number is refused, not ignored."""
269
- if only is None:
270
- return plan
271
- planned = {entry['issue'] for entry in plan['actions']}
272
- unknown = sorted(only - planned)
273
- if unknown:
274
- raise Unusable('--only lists issues the plan does not act on: ' + ', '.join(map(str, unknown)))
275
- return dict(plan, actions=[entry for entry in plan['actions'] if entry['issue'] in only])
276
-
277
-
278
- def apply(repo, plan_path, dry_run, only=None):
279
- plan = select(load_plan(plan_path, repo), only)
280
- commands = issue_commands(plan, repo)
281
- commands.append(('report', report_command(plan, repo)))
282
- if dry_run:
283
- return {'dry_run': True, 'writes': [{'issue': issue, 'argv': argv} for issue, argv in commands]}, 0
284
- applied, errors, failed = [], [], set()
285
- for issue, argv in commands:
286
- if issue in failed:
287
- errors.append({'issue': issue, 'argv': argv[:4], 'error': 'skipped after an earlier failure'})
288
- continue
289
- code, _, stderr = _gh(argv)
290
- if code == 0:
291
- applied.append({'issue': issue, 'argv': argv[:4]})
292
- else:
293
- failed.add(issue)
294
- errors.append({'issue': issue, 'argv': argv[:4], 'error': stderr})
295
- return {'dry_run': False, 'applied': applied, 'errors': errors}, 1 if errors else 0
296
-
297
-
298
- def parse_args(argv):
299
- if not argv or argv[0] in ('--help', '-h') or '--help' in argv:
300
- return None
301
- command, rest = argv[0], argv[1:]
302
- if command not in ('fetch', 'apply'):
303
- raise Unusable('Unknown command: ' + command)
304
- args = {'command': command, 'dry_run': '--dry-run' in rest}
305
- rest = [item for item in rest if item != '--dry-run']
306
- required = ('--repo', '--out') if command == 'fetch' else ('--repo', '--plan')
307
- allowed = required + (('--sweeper-login',) if command == 'fetch' else ('--only',))
308
- args['sweeper-login'] = DEFAULT_SWEEPER
309
- for index in range(0, len(rest), 2):
310
- if rest[index] not in allowed or index + 1 >= len(rest):
311
- raise Unusable('Unknown or incomplete argument: ' + rest[index])
312
- args[rest[index][2:]] = rest[index + 1]
313
- for key in required:
314
- if key[2:] not in args:
315
- raise Unusable('Missing ' + key + '.')
316
- if not re.fullmatch(r'[\w.-]+/[\w.-]+', args['repo']):
317
- raise Unusable('--repo must be owner/name.')
318
- args['only'] = parse_only(args['only']) if 'only' in args else None
319
- return args
320
-
321
-
322
- def parse_only(value):
323
- numbers = [item.strip().lstrip('#') for item in value.split(',') if item.strip()]
324
- if not numbers or not all(item.isdigit() for item in numbers):
325
- raise Unusable('--only must be issue numbers separated by commas, e.g. 12,15.')
326
- return {int(item) for item in numbers}
327
-
328
-
329
- def main(argv):
330
- try:
331
- args = parse_args(argv)
332
- if args is None:
333
- _write_out(HELP)
334
- return 0
335
- if args['command'] == 'fetch':
336
- result, code = fetch(args['repo'], args['out'], args['sweeper-login']), 0
337
- else:
338
- result, code = apply(args['repo'], args['plan'], args['dry_run'], args['only'])
339
- except Unusable as error:
340
- _write_out(json.dumps({'verdict': 'unusable', 'reason': str(error)}, ensure_ascii=False))
341
- return 2
342
- _write_out(json.dumps(result, ensure_ascii=False, indent=2))
343
- return code
344
-
345
-
346
- if __name__ == '__main__':
347
- sys.exit(main(sys.argv[1:]))