render_diagrams.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. #!/usr/bin/env python3
  2. """Render every Mermaid diagram in the README and the wiki pages to a dark-mode PNG.
  3. GitHub's mobile app and some viewers show a Mermaid block as raw code, so every
  4. diagram is a picture first, with its Mermaid source kept underneath in a
  5. collapsed section. The pictures are dark (docs/diagrams-theme.json) so they read
  6. the same in light and dark mode. The page is the source of truth; the PNG is
  7. generated from it.
  8. Each diagram in a page looks like this (the script wraps a bare block for you):
  9. ![alt text](images/NAME.png)
  10. <details>
  11. <summary>Diagram source (Mermaid)</summary>
  12. ```mermaid
  13. ...
  14. ```
  15. </details>
  16. docs/diagrams.json records the SHA-256 of each diagram's source next to the
  17. picture made from it, so --check fails when a diagram was edited and its picture
  18. was not re-rendered.
  19. Usage, from anywhere inside a clone:
  20. scripts/render_diagrams.py --check offline; exit 1 on a bare block, a missing picture or a stale hash
  21. scripts/render_diagrams.py --write wrap bare blocks, render what changed, update the manifest
  22. --write needs Mermaid CLI (`mmdc`) on PATH and a Chromium; set PUPPETEER_EXECUTABLE_PATH to the browser if
  23. Puppeteer does not find one.
  24. Pillow shrinks the pictures (at most 2400 px wide, a 128-color palette).
  25. """
  26. from __future__ import annotations
  27. import hashlib
  28. import json
  29. import os
  30. import re
  31. import shutil
  32. import subprocess
  33. import sys
  34. import tempfile
  35. from pathlib import Path
  36. ROOT = Path(__file__).resolve().parent.parent
  37. MANIFEST = ROOT / "docs" / "diagrams.json"
  38. THEME = ROOT / "docs" / "diagrams-theme.json"
  39. MAX_WIDTH = 2400
  40. SUMMARY = "<summary>Diagram source (Mermaid)</summary>"
  41. WRAPPED = re.compile(
  42. r"!\[(?P<alt>[^\]\n]*)\]\((?P<path>[^)\n]+)\)\n\n<details>\n" + re.escape(SUMMARY) + r"\n\n```mermaid\n(?P<src>.*?)\n```\n\n</details>",
  43. re.DOTALL,
  44. )
  45. BARE = re.compile(r"```mermaid\n(?P<src>.*?)\n```", re.DOTALL)
  46. def pages() -> list[Path]:
  47. return [ROOT / "README.md", *sorted((ROOT / "docs" / "wiki").glob("*.md"))]
  48. def digest(src: str) -> str:
  49. return hashlib.sha256(src.encode()).hexdigest()
  50. def slug(page: Path) -> str:
  51. return re.sub(r"[^a-z0-9]+", "-", page.stem.lower()).strip("-")
  52. def picture_dir(page: Path) -> str:
  53. return "docs/images" if page.name == "README.md" else "images"
  54. MAX_ALT = 150 # wiki accessibility rule (tests/test_wiki_accessibility.py): alt text is read aloud, so keep it short
  55. MORE = "; and more in the source below"
  56. def alt_for(src: str, heading: str) -> str:
  57. labels = re.findall(r'\["([^"\n]+)"\]|\["?([^\]"\n]+)"?\]|participant \w+ as ([^\n]+)', src)
  58. names = []
  59. for group in labels:
  60. text = next(g for g in group if g)
  61. text = re.sub(r"<br\s*/?>", " ", text).strip()
  62. text = re.sub(r"\s+", " ", text)
  63. if text and text not in names:
  64. names.append(text)
  65. kind = "Sequence diagram" if src.lstrip().startswith("sequenceDiagram") else "Diagram"
  66. head = re.sub(r"\s+", " ", f"{kind}, {heading}".replace("`", "")).strip()
  67. chosen = []
  68. for i, name in enumerate(names[:8]):
  69. trial = head + ": " + "; ".join(chosen + [name])
  70. # Leave room for the "and more" note unless this is the last label there is.
  71. room = MAX_ALT if i == len(names) - 1 else MAX_ALT - len(MORE)
  72. if len(trial) > room:
  73. break
  74. chosen.append(name)
  75. alt = head
  76. if chosen:
  77. alt += ": " + "; ".join(chosen)
  78. if len(chosen) < len(names):
  79. alt += MORE
  80. return alt[:MAX_ALT].replace("]", ")").replace("[", "(")
  81. def key_for(page: Path) -> str:
  82. return page.relative_to(ROOT).as_posix()
  83. def blocks(page: Path):
  84. """Yield (alt, relative path, source) for each wrapped diagram, and the count of bare ones."""
  85. text = page.read_text()
  86. wrapped = list(WRAPPED.finditer(text))
  87. stripped = WRAPPED.sub("", text)
  88. return wrapped, len(BARE.findall(stripped))
  89. def check() -> list[str]:
  90. problems = []
  91. manifest = json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {}
  92. seen = set()
  93. for page in pages():
  94. wrapped, bare = blocks(page)
  95. if bare:
  96. problems.append(f"{key_for(page)}: {bare} Mermaid block(s) with no picture above them; run scripts/render_diagrams.py --write")
  97. for m in wrapped:
  98. png = (page.parent / m["path"]).resolve()
  99. rel = png.relative_to(ROOT).as_posix() if ROOT in png.parents else m["path"]
  100. seen.add(rel)
  101. if not png.is_file():
  102. problems.append(f"{key_for(page)}: {m['path']} is missing")
  103. entry = manifest.get(rel)
  104. if not entry:
  105. problems.append(f"{key_for(page)}: {rel} is not in docs/diagrams.json")
  106. elif entry.get("sha256") != digest(m["src"]):
  107. problems.append(f"{key_for(page)}: the source of {rel} changed; re-render with --write")
  108. for rel in sorted(set(manifest) - seen):
  109. problems.append(f"docs/diagrams.json lists {rel}, which no page uses")
  110. return problems
  111. def render(src: str, out: Path) -> None:
  112. from PIL import Image # imported here: --check needs only the standard library
  113. if not shutil.which("mmdc"):
  114. raise SystemExit("render_diagrams: Mermaid CLI (mmdc) not found on PATH")
  115. os.nice(19) # headless Chromium at the lowest priority, as the platform rules ask
  116. with tempfile.TemporaryDirectory() as tmp:
  117. mmd, raw = Path(tmp) / "d.mmd", Path(tmp) / "d.png"
  118. mmd.write_text(src + "\n")
  119. # A fixed command: nothing from the environment goes into it. Mermaid CLI's browser is chosen by
  120. # PUPPETEER_EXECUTABLE_PATH, which Puppeteer reads itself.
  121. subprocess.run(
  122. ["mmdc", "-c", str(THEME), "-t", "dark", "-b", "#0d1117", "-w", "1400", "-s", "2", "-i", str(mmd), "-o", str(raw)],
  123. check=True,
  124. capture_output=True,
  125. )
  126. img = Image.open(raw).convert("RGB")
  127. if img.width > MAX_WIDTH:
  128. img = img.resize((MAX_WIDTH, round(img.height * MAX_WIDTH / img.width)), Image.LANCZOS)
  129. img = img.quantize(colors=128, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
  130. out.parent.mkdir(parents=True, exist_ok=True)
  131. img.save(out, optimize=True)
  132. subprocess.run([sys.executable, "-I", str(ROOT / "scripts" / "strip_png_metadata.py"), str(out)], check=True, capture_output=True)
  133. ANY = re.compile("(?P<w>" + WRAPPED.pattern + ")|```mermaid\\n(?P<bsrc>.*?)\\n```", re.DOTALL)
  134. def wrap_bare(page: Path, text: str) -> str:
  135. """Put a picture above every bare Mermaid block; leave wrapped blocks as they are."""
  136. position = 0
  137. def one(m: re.Match) -> str:
  138. nonlocal position
  139. position += 1
  140. if m["w"]:
  141. return m["w"]
  142. heads = re.findall(r"^#{1,4} (.+)$", text[: m.start()], re.MULTILINE)
  143. heading = heads[-1] if heads else page.stem.replace("-", " ")
  144. name = f"{slug(page)}-diagram-{position}.png"
  145. alt = alt_for(m["bsrc"], heading)
  146. return f"![{alt}]({picture_dir(page)}/{name})\n\n<details>\n{SUMMARY}\n\n```mermaid\n{m['bsrc']}\n```\n\n</details>"
  147. return ANY.sub(one, text)
  148. def write() -> None:
  149. manifest = json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {}
  150. live = {}
  151. for page in pages():
  152. text = page.read_text()
  153. new = wrap_bare(page, text)
  154. if new != text:
  155. page.write_text(new)
  156. for m in WRAPPED.finditer(new):
  157. png = (page.parent / m["path"]).resolve()
  158. rel = png.relative_to(ROOT).as_posix()
  159. live[rel] = digest(m["src"])
  160. if not png.is_file() or manifest.get(rel, {}).get("sha256") != live[rel]:
  161. print(f"render {rel}")
  162. render(m["src"], png)
  163. MANIFEST.write_text(json.dumps({k: {"sha256": v} for k, v in sorted(live.items())}, indent=2) + "\n")
  164. def main(argv: list[str]) -> int:
  165. if argv == ["--check"]:
  166. problems = check()
  167. for p in problems:
  168. print(p)
  169. return 1 if problems else 0
  170. if argv == ["--write"]:
  171. write()
  172. return 0
  173. print(__doc__)
  174. return 2
  175. if __name__ == "__main__":
  176. sys.exit(main(sys.argv[1:]))