infrastructure/pipeline/build-docs.py

88 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""Build the portal's read-only documentation index from one committed RFC revision."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import subprocess
def build(repo, revision):
def git(*args):
return subprocess.check_output(['git', '-C', str(repo), *args], text=True)
revision = git('rev-parse', '--verify', revision + '^{commit}').strip()
def source(path):
return git('show', f'{revision}:{path}')
log = source('spec/decision-log.md')
decisions = {}
# The log contains both full narrative sections and historical table entries.
headers = list(re.finditer(r'^## (D-\d{3}) [—–-] (.+?) \((Accepted|Proposed|Draft|Rejected|Superseded), (\d{4}-\d{2}-\d{2})\)\s*$', log, re.M))
for match in headers:
end = re.search(r'^## ', log[match.end():], re.M)
body = log[match.end():match.end() + end.start() if end else len(log)].strip()
ident, title, status, date = match.groups()
decisions[ident] = dict(id=ident, title=title, status=status, date=date,
date_source='Decision heading', markdown=body,
path='spec/decision-log.md', line=log[:match.start()].count('\n') + 1)
for match in re.finditer(r'^\| (D-\d{3}) \| (.+) \| (Accepted|Proposed|Draft|Rejected|Superseded) \|\s*$', log, re.M):
ident, text, status = match.groups()
if ident in decisions:
raise ValueError('Duplicate decision identity: ' + ident)
dates = sorted(set(re.findall(r'\b\d{4}-\d{2}-\d{2}\b', text)))
# Do not infer approval dates from IDs, Git timestamps or related decisions.
date = dates[0] if len(dates) == 1 else None
sentence = re.split(r'(?<=[.!?])\s+', text)[0]
title = sentence if len(sentence) <= 115 else sentence[:112].rsplit(' ', 1)[0] + '…'
decisions[ident] = dict(id=ident, title=title, status=status, date=date,
date_source='Date recorded in entry' if date else 'Date not recorded',
markdown=text, path='spec/decision-log.md',
line=log[:match.start()].count('\n') + 1)
expected = set(re.findall(r'^(?:\| |## )(D-\d{3})\b', log, re.M))
if set(decisions) != expected:
raise ValueError('Unparsed decisions: ' + ', '.join(sorted(expected - set(decisions))))
for item in decisions.values():
item['references'] = sorted(set(re.findall(r'\bD-\d{3}\b', item['markdown'])) & decisions.keys() - {item['id']})
item['later_references'] = sorted(other['id'] for other in decisions.values()
if other['id'] > item['id'] and item['id'] in re.findall(r'\bD-\d{3}\b', other['markdown']))
rfcs = []
paths = git('ls-tree', '-r', '--name-only', revision, '--', 'rfc').splitlines()
for path in sorted(paths):
if not re.fullmatch(r'rfc/RFC-\d{4}-.+\.md', path):
continue
text = source(path)
heading = re.search(r'^# (RFC-\d{4}): (.+)$', text, re.M)
fields = dict(re.findall(r'^- \*\*([^:*]+):\*\* (.+)$', text, re.M))
if not heading or 'Status' not in fields:
raise ValueError('Missing RFC metadata: ' + path)
status = fields['Status'].split(' —')[0].strip()
if status not in ('Accepted', 'Proposed', 'Draft', 'Rejected', 'Superseded'):
raise ValueError('Unknown RFC status: ' + path)
accepted_date = re.search(r'\d{4}-\d{2}-\d{2}', fields.get('Accepted', '') or fields['Status'])
ident, title = heading.groups()
rfcs.append(dict(id=ident, title=title, status=status, status_detail=fields['Status'],
date=accepted_date.group() if accepted_date else fields.get('Date'),
version=fields.get('Version', ''), scope=fields.get('Scope', ''),
path=path, markdown=text, sha256=hashlib.sha256(text.encode()).hexdigest(),
decisions=sorted(set(re.findall(r'\bD-\d{3}\b', text)) & decisions.keys())))
if not rfcs or not decisions:
raise ValueError('Empty documentation index')
return dict(version=1, source_repository='https://git.fasoley.net/Archipelago/rfc',
source_revision=revision, source_committed_at=git('show', '-s', '--format=%cI', revision).strip(),
generated_at=datetime.now(timezone.utc).isoformat(),
decisions=sorted(decisions.values(), key=lambda x: x['id'], reverse=True), rfcs=rfcs)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--rfc-repo', type=Path, required=True)
parser.add_argument('--revision', default='HEAD')
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
data = build(args.rfc_repo, args.revision)
args.output.parent.mkdir(parents=True, exist_ok=True)
temp = args.output.with_suffix('.tmp')
temp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
temp.replace(args.output)
print(f"{len(data['decisions'])} decisions, {len(data['rfcs'])} RFCs; source {data['source_revision']}")