@bbcsoftwarefactory/commands 0.1.1 → 1.1.3

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,181 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -euo pipefail
3
- cd -- "${BASH_SOURCE[0]%/*}/.."
4
-
5
- SCRIPT="$PWD/scripts/sweep.py"
6
- PYTHON_BIN=$(command -v python3 || command -v python)
7
- "$PYTHON_BIN" -I -B - "$SCRIPT" <<'PY'
8
- from datetime import datetime, timedelta, timezone
9
- import json
10
- import os
11
- from pathlib import Path
12
- import subprocess
13
- import sys
14
- import tempfile
15
-
16
- script = Path(sys.argv[1]).resolve()
17
- if not script.is_file():
18
- sys.exit('FAIL: missing script ' + str(script))
19
- scratch = Path(tempfile.mkdtemp())
20
- checks = 0
21
- failures = []
22
- REPO = 'example/repo'
23
-
24
-
25
- def check(label, condition, detail=''):
26
- global checks
27
- checks += 1
28
- if not condition:
29
- failures.append(label + ' ' + str(detail)[:600])
30
-
31
-
32
- # A fake gh: answers the login, the optional policy file, and the GraphQL page; logs every write.
33
- fake_gh = scratch / 'fake_gh.py'
34
- fake_gh.write_text(r'''
35
- import json, os, sys
36
- args = sys.argv[1:]
37
- state = os.environ['FAKE_DIR']
38
- if args[:2] == ['api', 'user']:
39
- print('pm-login'); sys.exit(0)
40
- if any(a.endswith('contents/.github/issue-sweeper.json') for a in args):
41
- path = os.path.join(state, 'config.json')
42
- if not os.path.exists(path):
43
- sys.stderr.write('gh: Not Found (HTTP 404)'); sys.exit(1)
44
- print(open(path, encoding='utf-8').read()); sys.exit(0)
45
- if args[:2] == ['api', 'graphql']:
46
- print(open(os.path.join(state, 'page.json'), encoding='utf-8').read()); sys.exit(0)
47
- with open(os.path.join(state, 'writes.log'), 'a', encoding='utf-8') as handle:
48
- handle.write(json.dumps(args[:4]) + '\n')
49
- print('{}')
50
- ''', encoding='utf-8')
51
-
52
-
53
- def page(issues):
54
- return {'data': {'repository': {'nameWithOwner': REPO, 'labels': {'nodes': [{'name': 'bug'}]},
55
- 'issues': {'pageInfo': {'hasNextPage': False, 'endCursor': None}, 'nodes': issues}}}}
56
-
57
-
58
- def merged(number, closes=True):
59
- return {'number': number, 'title': 'T', 'url': 'https://github.com/example/repo/issues/' + str(number),
60
- 'createdAt': '2026-10-01T10:00:00Z', 'body': '', 'author': {'login': 'carla'}, 'labels': {'nodes': []},
61
- 'assignees': {'nodes': []}, 'recent': {'nodes': []},
62
- 'refs': {'pageInfo': {'hasNextPage': False}, 'nodes': [
63
- {'__typename': 'CrossReferencedEvent', 'createdAt': '2026-11-19T10:00:00Z', 'willCloseTarget': False,
64
- 'source': {'number': 100 + number, 'url': 'https://github.com/example/repo/pull/' + str(100 + number),
65
- 'state': 'MERGED', 'mergedAt': '2026-11-20T10:00:00Z', 'title': 'Fix',
66
- 'body': ('Closes #' if closes else 'Refs #') + str(number),
67
- 'repository': {'nameWithOwner': REPO}, 'mergeCommit': {'oid': 'abcdef1234567'}}}]}}
68
-
69
-
70
- def setup(name, config=None, issues=None):
71
- fake_dir = scratch / name
72
- fake_dir.mkdir()
73
- if config is not None:
74
- (fake_dir / 'config.json').write_text(config if isinstance(config, str) else json.dumps(config), encoding='utf-8')
75
- issues = [merged(12), merged(15)] if issues is None else issues
76
- (fake_dir / 'page.json').write_text(json.dumps(page(issues)), encoding='utf-8')
77
- return fake_dir
78
-
79
-
80
- def sweep(fake_dir, *args, cwd=None):
81
- environ = dict(os.environ, FAKE_DIR=str(fake_dir), SWEEP_HOME=str(fake_dir / 'home'),
82
- SWEEP_GH=json.dumps([sys.executable, str(fake_gh)]))
83
- result = subprocess.run([sys.executable, '-I', '-B', str(script), *args], capture_output=True, text=True,
84
- encoding='utf-8', env=environ, cwd=cwd or str(fake_dir))
85
- try:
86
- return result.returncode, json.loads(result.stdout)
87
- except ValueError:
88
- return result.returncode, {'raw': result.stdout + result.stderr}
89
-
90
-
91
- def writes(fake_dir):
92
- path = fake_dir / 'writes.log'
93
- return [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] if path.exists() else []
94
-
95
-
96
- def runs(fake_dir):
97
- path = fake_dir / 'home' / 'example__repo' / 'runs.log'
98
- return [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] if path.exists() else []
99
-
100
-
101
- # plan: reads, decides, writes nothing to GitHub
102
- fake = setup('plan')
103
- code, out = sweep(fake, 'plan', '--repo', REPO)
104
- check('plan succeeds without a policy file (defaults)', code == 0 and out.get('verdict') == 'planned'
105
- and out.get('config') == 'defaults', out)
106
- check('plan writes nothing to GitHub', writes(fake) == [], writes(fake))
107
- check('plan lists the actions for the gate', [(a['issue'], a['rule']) for a in out.get('actions', [])]
108
- == [(12, 'SW1'), (15, 'SW1')] and all(a.get('url') and a.get('steps') for a in out['actions']), out)
109
- plan_path = Path(out.get('plan', 'missing'))
110
- check('the plan file is kept for traceability', plan_path.is_file() and plan_path.parent.name == 'plans', out)
111
- check('plan includes metrics and the report', out.get('metrics', {}).get('open') == 2
112
- and 'issue-sweeper:report' in out.get('report_markdown', ''), out)
113
- check('plan is logged', [r.get('step') for r in runs(fake)] == ['plan'], runs(fake))
114
-
115
- # apply: exactly the approved plan
116
- code, out = sweep(fake, 'apply', '--repo', REPO, '--plan', str(plan_path), '--dry-run')
117
- check('--dry-run writes nothing', code == 0 and writes(fake) == [] and len(out.get('writes', [])) == 5, out)
118
- code, out = sweep(fake, 'apply', '--repo', REPO, '--plan', str(plan_path), '--only', '15')
119
- check('--only applies only the approved issues, then the report', code == 0 and writes(fake) == [
120
- ['api', '-X', 'POST', 'repos/example/repo/issues/15/comments'],
121
- ['api', '-X', 'PATCH', 'repos/example/repo/issues/15'], ['api', '-X', 'POST', 'repos/example/repo/issues']],
122
- writes(fake))
123
- log = runs(fake)
124
- check('apply is logged with what it did', log[-1].get('step') == 'apply' and log[-1].get('applied') == 3
125
- and log[-1].get('only') == [15] and log[-1].get('errors') == [], log)
126
- code, out = sweep(fake, 'apply', '--repo', REPO, '--plan', str(plan_path), '--only', '99')
127
- check('an issue outside the plan is refused', code == 2 and len(writes(fake)) == 3, out)
128
-
129
- # apply: guards
130
- stale = json.loads(plan_path.read_text(encoding='utf-8'))
131
- stale['generated_at'] = (datetime.now(timezone.utc) - timedelta(hours=2)).strftime('%Y-%m-%dT%H:%M:%SZ')
132
- old_path = scratch / 'old-plan.json'
133
- old_path.write_text(json.dumps(stale), encoding='utf-8')
134
- code, out = sweep(fake, 'apply', '--repo', REPO, '--plan', str(old_path))
135
- check('a plan older than 60 minutes must be planned again', code == 2 and 'plan' in out.get('reason', '')
136
- and len(writes(fake)) == 3, out)
137
- code, out = sweep(fake, 'apply', '--repo', 'other/repo', '--plan', str(plan_path))
138
- check('a plan for another repository is refused', code == 2 and len(writes(fake)) == 3, out)
139
- code, out = sweep(fake, 'apply', '--repo', REPO)
140
- check('apply needs the exact plan file', code == 2, out)
141
-
142
- # repository detection from the current checkout
143
- for label, url in (('https remote', 'https://github.com/example/repo.git'), ('ssh remote', 'git@github.com:example/repo.git')):
144
- fake = setup('detect-' + label.split()[0])
145
- checkout = fake / 'checkout'
146
- checkout.mkdir()
147
- subprocess.run(['git', 'init', '-q', str(checkout)], check=True)
148
- subprocess.run(['git', '-C', str(checkout), 'remote', 'add', 'origin', url], check=True)
149
- code, out = sweep(fake, 'plan', cwd=str(checkout))
150
- check('the repository comes from origin (' + label + ')', code == 0 and out.get('repo') == REPO, out)
151
- fake = setup('no-git')
152
- code, out = sweep(fake, 'plan', cwd=str(fake))
153
- check('outside a GitHub checkout --repo is required', code == 2, out)
154
-
155
- # optional policy file on the default branch
156
- fake = setup('english', {'language': 'en'})
157
- code, out = sweep(fake, 'plan', '--repo', REPO)
158
- body = json.loads(Path(out['plan']).read_text(encoding='utf-8'))['actions'][0]['steps'][0]['body'] if code == 0 else ''
159
- check('the repository policy file tunes the plan', code == 0 and out.get('config') == '.github/issue-sweeper.json'
160
- and 'Closing' in body, out)
161
- fake = setup('broken-config', '{not json')
162
- code, out = sweep(fake, 'plan', '--repo', REPO)
163
- check('a broken policy file stops the plan', code == 2 and writes(fake) == [], out)
164
- fake = setup('keep')
165
- for _ in range(3):
166
- sweep(fake, 'plan', '--repo', REPO, '--keep', '2')
167
- check('old plans are pruned', len(list((fake / 'home' / 'example__repo' / 'plans').glob('*.json'))) == 2, '')
168
-
169
- for label, args in (('bad repo', ('plan', '--repo', 'nope')), ('unknown command', ('install', '--repo', REPO)),
170
- ('bad keep', ('plan', '--repo', REPO, '--keep', '0'))):
171
- code, out = sweep(setup('args-' + label.replace(' ', '-')), *args)
172
- check(label + ' is unusable', code == 2, out)
173
- result = subprocess.run([sys.executable, '-I', '-B', str(script), '--help'], capture_output=True, text=True)
174
- check('--help', result.returncode == 0 and 'Usage' in result.stdout, result.stdout)
175
-
176
- if failures:
177
- for item in failures:
178
- print('FAIL:', item, file=sys.stderr)
179
- sys.exit(1)
180
- print(f'PASS {checks} checks')
181
- PY