@bbcsoftwarefactory/commands 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,487 @@
1
+ #!/usr/bin/env python3
2
+ """sweep-issues.py: decide what /issue-clean-and-close proposes for every open issue.
3
+
4
+ Pure and offline: it reads the snapshot written by `sweep-github.py fetch` and, when the
5
+ repository has one, `.github/issue-sweeper.json` (thresholds only), and prints a plan.
6
+ It never calls GitHub. Rules SW1-SW8 are defined in references/policy.md.
7
+ """
8
+
9
+ from datetime import datetime, timezone
10
+ import json
11
+ import math
12
+ import re
13
+ import sys
14
+
15
+ LANGUAGES = ('es', 'en')
16
+ DEFAULTS = {
17
+ 'language': 'es', 'max_writes_per_run': 20, 'needs_info_days': 14,
18
+ 'claim_stale_days': 7, 'inactive_days': 30, 'sweeper_login': 'github-actions[bot]',
19
+ 'labels': {'stale': 'stale', 'needs_info': 'needs-info', 'close_review': 'needs-close-review',
20
+ 'claim': 'status:in-progress'},
21
+ 'exempt_labels': ['security', 'frozen', 'lifecycle/frozen', 'pinned'],
22
+ 'exempt_priorities': ['P0', 'P1'], 'report_title': 'Estado de issues',
23
+ }
24
+ INT_KEYS = ('max_writes_per_run', 'needs_info_days', 'claim_stale_days', 'inactive_days')
25
+ # Writes are taken in this order when the per-run cap is reached.
26
+ WRITE_ORDER = ('SW1', 'SW3', 'SW2', 'SW5', 'SW7', 'SW6')
27
+ CLOSING = re.compile(r'\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\b\s*:?\s+'
28
+ r'(?:https://github\.com/([\w.-]+/[\w.-]+)/issues/|([\w.-]+/[\w.-]+)?#)(\d+)\b', re.I)
29
+ PRIORITY_NAME = re.compile(r'(?:priority|prioridad|prio)\s*[:/_ -]\s*(.+)|(p[0-3])\b.*')
30
+ LEVEL_WORDS = {
31
+ 'p0': 0, 'critical': 0, 'critica': 0, 'crítica': 0, 'urgent': 0, 'urgente': 0, 'blocker': 0,
32
+ 'p1': 1, 'high': 1, 'alta': 1,
33
+ 'p2': 2, 'medium': 2, 'media': 2, 'normal': 2,
34
+ 'p3': 3, 'low': 3, 'baja': 3, 'minor': 3,
35
+ }
36
+ MARKER = '<!-- issue-sweeper:{} -->'
37
+ GAP_LINE = {
38
+ 'es': '🟡 GAP visual: no hay captura; la evidencia es {}.',
39
+ 'en': '🟡 GAP visual: no screenshot; the evidence is {}.',
40
+ }
41
+ TEXT = {
42
+ 'es': {
43
+ 'SW1': 'Cierro esta issue: el PR {pr} declara cerrarla y se fusionó el {date} (commit `{sha}`).',
44
+ 'SW2': '{who}: el PR {pr} se fusionó el {date} y menciona esta issue, pero no declara cerrarla. '
45
+ '¿Está resuelta? Si es así, ciérrenla; si no, comenten qué falta.',
46
+ 'SW3': 'Cierro esta issue como no planificada: `{label}` lleva {days} días sin respuesta de @{author}. '
47
+ 'Si aportas la información, se puede reabrir.',
48
+ 'SW5': '{who}: esta issue está reclamada pero lleva {days} días sin actividad ni PR abierto. '
49
+ '¿Sigue en curso? Si no, liberen el reclamo.',
50
+ 'SW6': 'Marco esta issue como `{label}`: {days} días sin actividad, sin PR y sin responsable. '
51
+ 'No se cerrará por esto; cualquier comentario quita la marca.',
52
+ 'pr_evidence': 'el PR enlazado', 'timeline_evidence': 'la línea de tiempo de la issue',
53
+ },
54
+ 'en': {
55
+ 'SW1': 'Closing this issue: pull request {pr} declares closing it and was merged on {date} (commit `{sha}`).',
56
+ 'SW2': '{who}: pull request {pr} was merged on {date} and mentions this issue without declaring it closed. '
57
+ 'Is it resolved? If so, close it; if not, comment on what is missing.',
58
+ 'SW3': 'Closing this issue as not planned: `{label}` has had no answer from @{author} for {days} days. '
59
+ 'It can be reopened once the information is provided.',
60
+ 'SW5': '{who}: this issue is claimed but has had no activity or open pull request for {days} days. '
61
+ 'Is it still in progress? If not, please release the claim.',
62
+ 'SW6': 'Marking this issue `{label}`: {days} days without activity, a pull request, or an owner. '
63
+ 'It will not be closed for this; any comment removes the label.',
64
+ 'pr_evidence': 'the linked pull request', 'timeline_evidence': 'the issue timeline',
65
+ },
66
+ }
67
+ REPORT_TEXT = {
68
+ 'es': {'title': 'Estado de issues', 'generated': 'Generado', 'run_by': 'Ejecutado por',
69
+ 'metric': 'Métrica', 'value': 'Valor', 'actions': 'Acciones', 'deferred': 'Diferidas por el tope por ejecución',
70
+ 'report_only': 'Solo informe', 'gaps': 'Brechas', 'none': 'Ninguna.', 'missing-label': 'falta la etiqueta',
71
+ 'incomplete': 'línea de tiempo incompleta', 'evidence': 'el snapshot de esta ejecución'},
72
+ 'en': {'title': 'Issue status', 'generated': 'Generated', 'run_by': 'Run by',
73
+ 'metric': 'Metric', 'value': 'Value', 'actions': 'Actions', 'deferred': 'Deferred by the per-run cap',
74
+ 'report_only': 'Report only', 'gaps': 'Gaps', 'none': 'None.', 'missing-label': 'missing label',
75
+ 'incomplete': 'incomplete timeline', 'evidence': 'the snapshot of this run'},
76
+ }
77
+ # Keeps the report issue well under GitHub's 65,536-character body limit.
78
+ REPORT_ROWS = 100
79
+ METRIC_KEYS = ('open', 'with_pr', 'assigned', 'merged_but_open', 'stale_claims', 'duplicate_work',
80
+ 'waiting_info', 'inactive', 'exempt', 'age_days_p50', 'age_days_p90')
81
+
82
+ HELP = (
83
+ 'Usage: python3 -I -B scripts/sweep-issues.py --snapshot <file> --sweeper-login <login>\n'
84
+ ' [--config <file>] [--now <ISO-8601>]\n'
85
+ ' --snapshot <file> output of: sweep-github.py fetch --repo <owner/repo> --out <file>\n'
86
+ ' --sweeper-login <login> the gh account that will apply the plan (its sweep writes are not activity)\n'
87
+ ' --config <file> optional .github/issue-sweeper.json: thresholds, labels, exemptions, language\n'
88
+ 'Prints the plan as JSON. Exit 0: plan ready; 2: unusable input or config.'
89
+ )
90
+
91
+
92
+ class Unusable(Exception):
93
+ """The snapshot or the configuration cannot be evaluated."""
94
+
95
+
96
+ def _write_out(text):
97
+ sys.stdout.buffer.write((text + '\n').encode('utf-8', 'surrogateescape'))
98
+
99
+
100
+ def _fold(value):
101
+ return value.strip().casefold() if isinstance(value, str) else ''
102
+
103
+
104
+ def _time(value):
105
+ if not isinstance(value, str):
106
+ return None
107
+ try:
108
+ parsed = datetime.fromisoformat(value.strip().replace('Z', '+00:00'))
109
+ except ValueError:
110
+ return None
111
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
112
+
113
+
114
+ def _load_json(path, label):
115
+ try:
116
+ with open(path, encoding='utf-8') as handle:
117
+ return json.load(handle)
118
+ except OSError:
119
+ raise Unusable(label + ' cannot be read.')
120
+ except ValueError:
121
+ raise Unusable(label + ' is not valid JSON.')
122
+
123
+
124
+ def _strings(value):
125
+ return isinstance(value, list) and all(isinstance(item, str) and item.strip() for item in value)
126
+
127
+
128
+ def load_config(path, sweeper_login):
129
+ raw = _load_json(path, 'Config') if path else {}
130
+ if not isinstance(raw, dict):
131
+ raise Unusable('Config must be an object.')
132
+ config = dict(DEFAULTS, **raw)
133
+ config['labels'] = dict(DEFAULTS['labels'], **(raw.get('labels') or {}))
134
+ config['sweeper_login'] = sweeper_login
135
+ if config['language'] not in LANGUAGES:
136
+ raise Unusable('Config "language" must be one of: ' + ', '.join(LANGUAGES) + '.')
137
+ for key in INT_KEYS:
138
+ if not isinstance(config[key], int) or isinstance(config[key], bool) or config[key] < 1:
139
+ raise Unusable('Config "' + key + '" must be a positive integer.')
140
+ if not all(isinstance(name, str) and name.strip() for name in config['labels'].values()):
141
+ raise Unusable('Config "labels" values must be label names.')
142
+ for key in ('exempt_labels', 'exempt_priorities'):
143
+ if not isinstance(config[key], list) or (config[key] and not _strings(config[key])):
144
+ raise Unusable('Config "' + key + '" must be an array of names.')
145
+ if not isinstance(config['report_title'], str) or not config['report_title'].strip():
146
+ raise Unusable('Config "report_title" must be a title.')
147
+ return config
148
+
149
+
150
+ def load_snapshot(path):
151
+ raw = _load_json(path, 'Snapshot')
152
+ if not isinstance(raw, dict) or not isinstance(raw.get('repo'), str) or '/' not in raw['repo']:
153
+ raise Unusable('Snapshot needs "repo" as owner/name.')
154
+ if not isinstance(raw.get('issues'), list) or not isinstance(raw.get('labels'), list):
155
+ raise Unusable('Snapshot "issues" and "labels" must be arrays.')
156
+ for item in raw['issues']:
157
+ if not isinstance(item, dict) or not isinstance(item.get('number'), int) or _time(item.get('created_at')) is None:
158
+ raise Unusable('Every snapshot issue needs a number and created_at.')
159
+ return raw
160
+
161
+
162
+ def priority_level(name):
163
+ match = PRIORITY_NAME.fullmatch(_fold(name))
164
+ if match is None:
165
+ return None
166
+ word = match.group(2) or re.split(r'[\s:/_-]+', match.group(1).strip())[0]
167
+ return LEVEL_WORDS.get(word)
168
+
169
+
170
+ def _bare(login):
171
+ folded = _fold(login)
172
+ return folded[:-5] if folded.endswith('[bot]') else folded
173
+
174
+
175
+ class Issue:
176
+ """One snapshot issue with the facts the rules need, computed once."""
177
+
178
+ def __init__(self, raw, repo, config):
179
+ self.raw = raw
180
+ self.number = raw['number']
181
+ self.author = raw.get('author') or 'ghost'
182
+ self.created = _time(raw['created_at'])
183
+ self.labels = {_fold(name) for name in raw.get('labels') or [] if isinstance(name, str)}
184
+ self.label_names = [name for name in raw.get('labels') or [] if isinstance(name, str)]
185
+ self.assignees = [login for login in raw.get('assignees') or [] if isinstance(login, str) and login]
186
+ self.incomplete = raw.get('incomplete') is True
187
+ self.prs = [pr for pr in raw.get('prs') or [] if isinstance(pr, dict) and isinstance(pr.get('number'), int)]
188
+ # The sweeper may be a person's account: only its sweep comments (by marker) and the
189
+ # labels the sweep itself sets are its own writes; anything else it does is activity.
190
+ sweeper = _bare(config['sweeper_login'])
191
+ own_labels = {_fold(config['labels']['stale']), _fold(config['labels']['close_review'])}
192
+ self.events = []
193
+ self.label_events = []
194
+ self.markers = {}
195
+ for event in raw.get('events') or []:
196
+ at = _time(event.get('at')) if isinstance(event, dict) else None
197
+ if at is None:
198
+ continue
199
+ if event.get('type') != 'comment':
200
+ self.label_events.append(dict(event, at=at))
201
+ marker = event.get('marker') if event.get('type') == 'comment' else None
202
+ if isinstance(marker, str) and marker:
203
+ self.markers[marker] = max(at, self.markers.get(marker, at))
204
+ continue
205
+ if _bare(event.get('actor')) == sweeper and _fold(event.get('label')) in own_labels:
206
+ continue
207
+ self.events.append(dict(event, at=at))
208
+ times = [self.created] + [event['at'] for event in self.events]
209
+ times += [t for t in (_time(pr.get('referenced_at')) for pr in self.prs) if t]
210
+ self.last_activity = max(times)
211
+ self.open_prs = [pr for pr in self.prs if pr.get('state') == 'OPEN']
212
+ self.merged_prs = [pr for pr in self.prs if pr.get('state') == 'MERGED' and _time(pr.get('merged_at'))]
213
+ self.repo = _fold(repo)
214
+
215
+ def has(self, label):
216
+ return _fold(label) in self.labels
217
+
218
+ def declares_closing(self, pr):
219
+ if pr.get('will_close') is True or pr.get('manual_link') is True:
220
+ return True
221
+ text = pr.get('text') if isinstance(pr.get('text'), str) else ''
222
+ same_repo = _fold(pr.get('repo')) == self.repo
223
+ for match in CLOSING.finditer(text):
224
+ target = _fold(match.group(1) or match.group(2)) or (self.repo if same_repo else '')
225
+ if target == self.repo and int(match.group(3)) == self.number:
226
+ return True
227
+ return False
228
+
229
+ def last_event(self, kind, label=None):
230
+ found = [e['at'] for e in self.label_events if e.get('type') == kind
231
+ and (label is None or _fold(e.get('label')) == _fold(label))]
232
+ return max(found) if found else None
233
+
234
+ def commented_since(self, rule):
235
+ marker = self.markers.get(rule)
236
+ return marker is not None and marker > self.last_activity
237
+
238
+
239
+ def _short(sha):
240
+ return sha[:7] if isinstance(sha, str) else '?'
241
+
242
+
243
+ def _date(value):
244
+ parsed = _time(value)
245
+ return parsed.strftime('%Y-%m-%d') if parsed else '?'
246
+
247
+
248
+ def _pr_ref(pr, repo):
249
+ number = '#' + str(pr['number'])
250
+ return number if _fold(pr.get('repo')) == _fold(repo) else str(pr.get('repo')) + number
251
+
252
+
253
+ def _who(issue):
254
+ return ' '.join('@' + login for login in (issue.assignees or [issue.author]))
255
+
256
+
257
+ def _comment(rule, language, evidence, **values):
258
+ text = TEXT[language]
259
+ body = text[rule].format(**values)
260
+ gap = GAP_LINE[language].format(text[evidence])
261
+ return {'action': 'comment', 'marker': rule, 'body': body + '\n\n' + gap + '\n\n' + MARKER.format(rule)}
262
+
263
+
264
+ class Sweep:
265
+ def __init__(self, snapshot, config, now):
266
+ self.snapshot = snapshot
267
+ self.config = config
268
+ self.now = now
269
+ self.repo = snapshot['repo']
270
+ self.lang = config['language']
271
+ self.repo_labels = {_fold(name) for name in snapshot['labels'] if isinstance(name, str)}
272
+ self.labels = config['labels']
273
+ self.exempt_labels = {_fold(name) for name in config['exempt_labels']}
274
+ self.exempt_levels = {priority_level(name) for name in config['exempt_priorities']} - {None}
275
+ self.tally = {key: 0 for key in ('stale_claims', 'duplicate_work', 'inactive')}
276
+
277
+ def days(self, since):
278
+ return (self.now - since).days
279
+
280
+ def label_step(self, action, key):
281
+ name = self.labels[key]
282
+ if _fold(name) not in self.repo_labels:
283
+ return []
284
+ return [{'action': action, 'label': name}]
285
+
286
+ def exempt(self, issue):
287
+ return bool(issue.labels & self.exempt_labels) or any(
288
+ priority_level(name) in self.exempt_levels for name in issue.label_names)
289
+
290
+ def decide(self, issue):
291
+ """(rule, steps) for one issue; steps == [] means report only; rule None means nothing to do."""
292
+ if self.exempt(issue):
293
+ return 'SW8', []
294
+ if issue.incomplete:
295
+ return None, []
296
+ decision = self.merged(issue)
297
+ if decision:
298
+ return decision
299
+ if self.needs_info_unanswered(issue):
300
+ label = self.labels['needs_info']
301
+ asked = issue.last_event('labeled', label)
302
+ comment = _comment('SW3', self.lang, 'timeline_evidence', label=label, days=self.days(asked),
303
+ author=issue.author)
304
+ return 'SW3', [comment, {'action': 'close', 'state_reason': 'not_planned'}]
305
+ if len(issue.open_prs) > 1:
306
+ self.tally['duplicate_work'] += 1
307
+ return 'SW4', []
308
+ return self.idle(issue)
309
+
310
+ def merged(self, issue):
311
+ if not issue.merged_prs:
312
+ return None
313
+ declaring = [pr for pr in issue.merged_prs if issue.declares_closing(pr)]
314
+ if declaring:
315
+ latest = max(declaring, key=lambda pr: _time(pr['merged_at']))
316
+ reopened = issue.last_event('reopened')
317
+ blocked = (reopened is not None and reopened > _time(latest['merged_at'])) or any(
318
+ issue.declares_closing(pr) for pr in issue.open_prs)
319
+ if not blocked:
320
+ comment = _comment('SW1', self.lang, 'pr_evidence', pr=_pr_ref(latest, self.repo),
321
+ date=_date(latest['merged_at']), sha=_short(latest.get('merge_commit')))
322
+ return 'SW1', [comment, {'action': 'close', 'state_reason': 'completed'}]
323
+ if issue.commented_since('SW2'):
324
+ return None, []
325
+ latest = max(issue.merged_prs, key=lambda pr: _time(pr['merged_at']))
326
+ steps = [] if issue.has(self.labels['close_review']) else self.label_step('add-label', 'close_review')
327
+ steps.append(_comment('SW2', self.lang, 'pr_evidence', who=_who(issue), pr=_pr_ref(latest, self.repo),
328
+ date=_date(latest['merged_at'])))
329
+ return 'SW2', steps
330
+
331
+ def needs_info_unanswered(self, issue):
332
+ label = self.labels['needs_info']
333
+ if not issue.has(label):
334
+ return False
335
+ asked = issue.last_event('labeled', label)
336
+ if asked is None or self.days(asked) < self.config['needs_info_days']:
337
+ return False
338
+ author = _fold(issue.author)
339
+ return not any(e['at'] > asked and e.get('type') == 'comment' and _fold(e.get('actor')) == author
340
+ for e in issue.events)
341
+
342
+ def idle(self, issue):
343
+ idle_days = self.days(issue.last_activity)
344
+ claimed = issue.has(self.labels['claim']) and bool(issue.assignees)
345
+ if claimed:
346
+ if issue.open_prs or idle_days < self.config['claim_stale_days']:
347
+ return None, []
348
+ self.tally['stale_claims'] += 1
349
+ if issue.commented_since('SW5'):
350
+ return None, []
351
+ return 'SW5', [_comment('SW5', self.lang, 'timeline_evidence', who=_who(issue), days=idle_days)]
352
+ stale = self.labels['stale']
353
+ if issue.has(stale):
354
+ marked = issue.markers.get('SW6') or issue.last_event('labeled', stale)
355
+ if marked is not None and issue.last_activity > marked and idle_days < self.config['inactive_days']:
356
+ return 'SW7', [{'action': 'remove-label', 'label': stale}]
357
+ self.tally['inactive'] += 1
358
+ return None, []
359
+ if issue.open_prs or issue.merged_prs or idle_days < self.config['inactive_days']:
360
+ return None, []
361
+ self.tally['inactive'] += 1
362
+ if issue.commented_since('SW6'):
363
+ return None, []
364
+ steps = self.label_step('add-label', 'stale')
365
+ steps.append(_comment('SW6', self.lang, 'timeline_evidence', label=stale, days=idle_days))
366
+ return 'SW6', steps
367
+
368
+ def metrics(self, issues, exempt):
369
+ ages = sorted(self.days(issue.created) for issue in issues)
370
+
371
+ def rank(share):
372
+ return ages[max(0, math.ceil(share * len(ages)) - 1)] if ages else 0
373
+
374
+ metrics = {
375
+ 'open': len(issues),
376
+ 'with_pr': sum(1 for issue in issues if issue.open_prs or issue.merged_prs),
377
+ 'assigned': sum(1 for issue in issues if issue.assignees),
378
+ 'merged_but_open': sum(1 for issue in issues if issue.merged_prs),
379
+ 'waiting_info': sum(1 for issue in issues if issue.has(self.labels['needs_info'])),
380
+ 'exempt': exempt,
381
+ 'age_days_p50': rank(0.5),
382
+ 'age_days_p90': rank(0.9),
383
+ }
384
+ metrics.update(self.tally)
385
+ return metrics
386
+
387
+ def run(self):
388
+ issues = [Issue(raw, self.repo, self.config) for raw in self.snapshot['issues']
389
+ if raw['number'] != self.snapshot.get('report_issue')]
390
+ writes, report_only, gaps = [], [], []
391
+ for name in self.labels.values():
392
+ if _fold(name) not in self.repo_labels:
393
+ gaps.append({'kind': 'missing-label', 'label': name})
394
+ for issue in issues:
395
+ if issue.incomplete:
396
+ gaps.append({'kind': 'incomplete', 'issue': issue.number})
397
+ rule, steps = self.decide(issue)
398
+ entry = {'issue': issue.number, 'rule': rule, 'url': issue.raw.get('url'), 'steps': steps}
399
+ if rule is None:
400
+ continue
401
+ (writes if steps else report_only).append(entry)
402
+ writes.sort(key=lambda entry: (WRITE_ORDER.index(entry['rule']), entry['issue']))
403
+ cap = self.config['max_writes_per_run']
404
+ chosen, deferred = writes[:cap], writes[cap:]
405
+ plan = {
406
+ 'verdict': 'ok', 'repo': self.repo, 'run_by': self.config['sweeper_login'],
407
+ 'generated_at': self.now.strftime('%Y-%m-%dT%H:%M:%SZ'),
408
+ 'report_issue': self.snapshot.get('report_issue'), 'report_title': self.config['report_title'],
409
+ 'actions': chosen,
410
+ 'deferred': [{'issue': e['issue'], 'rule': e['rule'], 'url': e['url']} for e in deferred],
411
+ 'report_only': report_only, 'gaps': gaps,
412
+ 'metrics': self.metrics(issues, sum(1 for entry in report_only if entry['rule'] == 'SW8')),
413
+ }
414
+ plan['report_markdown'] = render_report(plan, self.lang)
415
+ return plan
416
+
417
+
418
+ def _cell(value):
419
+ return str(value).replace('|', '\\|').replace('\n', ' ')
420
+
421
+
422
+ def _entries(entries, text):
423
+ if not entries:
424
+ return [text['none']]
425
+ lines = []
426
+ for entry in entries[:REPORT_ROWS]:
427
+ steps = ', '.join(step['action'] + (' `' + step['label'] + '`' if step.get('label') else '')
428
+ for step in entry.get('steps') or []) or '—'
429
+ lines.append('- #' + str(entry['issue']) + ' — `' + entry['rule'] + '` — ' + _cell(steps))
430
+ if len(entries) > REPORT_ROWS:
431
+ lines.append('- … +' + str(len(entries) - REPORT_ROWS))
432
+ return lines
433
+
434
+
435
+ def render_report(plan, language):
436
+ text = REPORT_TEXT[language]
437
+ lines = ['## ' + text['title'], '',
438
+ '- ' + text['generated'] + ': ' + plan['generated_at'],
439
+ '- ' + text['run_by'] + ': @' + _cell(plan['run_by']),
440
+ '', '| ' + text['metric'] + ' | ' + text['value'] + ' |', '|---|---|']
441
+ lines += ['| `' + key + '` | ' + str(plan['metrics'][key]) + ' |' for key in METRIC_KEYS]
442
+ for key in ('actions', 'deferred', 'report_only'):
443
+ if plan[key] or key == 'actions':
444
+ lines += ['', '### ' + text[key], ''] + _entries(plan[key], text)
445
+ lines += ['', '### ' + text['gaps'], '']
446
+ gaps = plan['gaps']
447
+ lines += [('- ' + text[gap['kind']] + ' ' + ('`' + gap['label'] + '`' if 'label' in gap else '#' + str(gap['issue'])))
448
+ for gap in gaps] or [text['none']]
449
+ lines += ['', GAP_LINE[language].format(text['evidence']), '', MARKER.format('report')]
450
+ return '\n'.join(lines)
451
+
452
+
453
+ def parse_args(argv):
454
+ if '--help' in argv or '-h' in argv:
455
+ return None
456
+ args = {}
457
+ for index in range(0, len(argv), 2):
458
+ key = argv[index]
459
+ if key not in ('--snapshot', '--config', '--now', '--sweeper-login') or index + 1 >= len(argv):
460
+ raise Unusable('Unknown or incomplete argument: ' + key)
461
+ args[key[2:]] = argv[index + 1]
462
+ for key in ('snapshot', 'sweeper-login'):
463
+ if key not in args:
464
+ raise Unusable('Missing --' + key + '.')
465
+ return args
466
+
467
+
468
+ def main(argv):
469
+ try:
470
+ args = parse_args(argv)
471
+ if args is None:
472
+ _write_out(HELP)
473
+ return 0
474
+ now = _time(args['now']) if 'now' in args else datetime.now(timezone.utc)
475
+ if now is None:
476
+ raise Unusable('--now must be ISO-8601.')
477
+ config = load_config(args.get('config'), args['sweeper-login'])
478
+ plan = Sweep(load_snapshot(args['snapshot']), config, now).run()
479
+ except Unusable as error:
480
+ _write_out(json.dumps({'verdict': 'unusable', 'reason': str(error)}, ensure_ascii=False, indent=2))
481
+ return 2
482
+ _write_out(json.dumps(plan, ensure_ascii=False, indent=2))
483
+ return 0
484
+
485
+
486
+ if __name__ == '__main__':
487
+ sys.exit(main(sys.argv[1:]))