# -*- coding: utf-8 -*- """Rewrite each section's Discharges line from the ledger itself. An audit found 48 claim ids cited in these lines that did not exist, because the lines were typed by hand and the ledger grew. Generating them removes the whole class of error: the citation cannot disagree with the ledger because it is read from it. Run after make_ledger.py and before build_paper.py. """ import collections import csv import io import os import re B = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LEDGER = os.path.join(B, 'claims', 'claim-ledger.csv') DRAFT = os.path.join(B, 'draft') rows = list(csv.DictReader(io.open(LEDGER, encoding='utf-8'))) by_sec = collections.defaultdict(list) for r in rows: by_sec[r['section'].zfill(2)].append(r['claim_id']) LINE = re.compile(r'^\*(?:Discharges claims[^*]*|This section argues[^*]*)\*$', re.M) def contiguous(ids): """Describe a set of ids as ranges, so a gap cannot hide in a dash.""" nums = sorted(int(i[1:]) for i in ids) out, start, prev = [], nums[0], nums[0] for n in nums[1:]: if n == prev + 1: prev = n continue out.append((start, prev)) start = prev = n out.append((start, prev)) return ', '.join('K%03d' % a if a == b else 'K%03d to K%03d' % (a, b) for a, b in out) changed = 0 for name in sorted(os.listdir(DRAFT)): m = re.match(r's(\d\d)-', name) if not m: continue sec = m.group(1) path = os.path.join(DRAFT, name) t = io.open(path, encoding='utf-8').read() ids = by_sec.get(sec) new = ('*Discharges claims %s.*' % contiguous(ids) if ids else '*This section argues from claims discharged elsewhere and introduces ' 'none of its own.*') if not LINE.search(t): print(' %s: no discharge line found' % name) continue old = LINE.search(t).group(0) if old != new: t = LINE.sub(new.replace('\\', '\\\\'), t, count=1) io.open(path, 'w', encoding='utf-8', newline='').write(t) changed += 1 print(' %-34s %s' % (name, new.strip('*'))) total = sum(len(v) for v in by_sec.values()) assert total == len(rows), 'claims lost: %d of %d' % (total, len(rows)) print('\n%d section(s) rewritten, %d ledger claims all attributed' % (changed, len(rows)))