1 #!/usr/bin/env python32 """Generate or check the capability shapes from their published pages.3 4 The page is the source. This script reads only the four tables that define a5 shape: input parts, parameters, output channels, and terminal metadata. It6 writes one JSON file per capability under `goldens/capabilities/`.7 8 `--check` is what CI runs. Without it the script writes the files, which is the9 same operation a person uses after changing a page on purpose.10 """11 12 import json13 import pathlib14 import sys15 16 ROOT = pathlib.Path(__file__).resolve().parents[2]17 PAGES = ROOT / ".f0rge" / "wiki" / "docs" / "capabilities"18 OUT = ROOT / "goldens" / "capabilities"19 20 SECTIONS = {21 "Parts in": "parts",22 "Parameters": "parameters",23 "Channels out": "channels",24 "Terminal metadata": "meta",25 }26 27 28 def cells(line):29 """The cells of one markdown table row, with an escaped pipe kept whole."""30 line = line.replace(r"\|", "\x00")31 return [cell.strip().replace("\x00", "|").replace("`", "") for cell in line.strip().strip("|").split("|")]32 33 34 def table(lines):35 """Rows of the first table after a section heading."""36 rows = []37 started = False38 for line in lines:39 if not line.startswith("|"):40 if started and rows:41 break42 continue43 started = True44 row = cells(line)45 if all(set(cell) <= {"-", ":"} for cell in row if cell):46 continue47 rows.append(row)48 return rows49 50 51 def shape(page):52 text = page.read_text().splitlines()53 capability = None54 for line in text:55 if line.startswith("**Capability key:**"):56 capability = line.split("`")[1]57 break58 if not capability:59 raise SystemExit(f"{page}: no capability key")60 61 result = {"capability": capability, "version": 1}62 for heading, key in SECTIONS.items():63 try:64 start = next(index for index, line in enumerate(text) if line.strip() == f"## {heading}")65 except StopIteration:66 raise SystemExit(f"{page}: no {heading} section")67 rows = table(text[start + 1 :])68 if not rows:69 raise SystemExit(f"{page}: {heading} has no table")70 header, body = rows[0], rows[1:]71 fields = []72 for row in body:73 if len(row) != len(header):74 raise SystemExit(f"{page}: a row in {heading} has the wrong width")75 fields.append(dict(zip((name.lower() for name in header), row)))76 result[key] = fields77 return result78 79 80 def encoded(shape):81 return json.dumps(shape, indent=2, sort_keys=True) + "\n"82 83 84 def main():85 check = "--check" in sys.argv[1:]86 OUT.mkdir(parents=True, exist_ok=True)87 failures = 088 expected = {page.stem + ".json" for page in PAGES.glob("*.v1.md")}89 if check:90 actual = {path.name for path in OUT.glob("*.json")}91 for name in sorted(actual - expected):92 print(f"shape: {name} has no page", file=sys.stderr)93 failures += 194 for page in sorted(PAGES.glob("*.v1.md")):95 document = shape(page)96 path = OUT / f"{page.stem}.json"97 text = encoded(document)98 if check:99 if not path.exists():100 print(f"shape: {path.relative_to(ROOT)} is missing", file=sys.stderr)101 failures += 1102 elif path.read_text() != text:103 print(f"shape: {path.relative_to(ROOT)} differs from {page.name}", file=sys.stderr)104 failures += 1105 else:106 path.write_text(text)107 print(f"shape: wrote {path.relative_to(ROOT)}")108 if check and failures:109 raise SystemExit(1)110 if check:111 print("shape: capability goldens ok")112 113 114 if __name__ == "__main__":115 main()