Coverage for scripts/replace_readme_diagrams.py: 100%
45 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-12 12:29 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-12 12:29 +0000
1"""Swap the README's Mermaid diagrams for links to them on GitHub at publish (ADR 0014).
3GitHub and the docs site render Mermaid; PyPI does not, and would show each
4diagram as its source. A fence this script cannot swap fails the publish
5instead of shipping that source, because PyPI keeps a release's README forever.
7The links say `blob/master` and point at the diagram's own section. The publish
8workflow runs this before pin_readme_links.py, which pins them to the release
9tag, so a release on PyPI links the diagrams of that release. The docs site
10follows master and could show a later one.
11"""
13from __future__ import annotations
15import re
16import sys
17from pathlib import Path
19from mermaid_fences import ANY_FENCE, DIAGRAM, FENCE, code_flags
20from pin_readme_links import REPO
22# From the pinning step, which must recognise these links to pin them.
23README = f"{REPO}/blob/master/README.md"
24HEADING = re.compile(r"#{1,6} +(.+?)$")
27def anchor(heading: str) -> str:
28 """GitHub's anchor for a heading, without the suffix of a repeated one."""
29 text = re.sub(r"[ \t]+#+[ \t]*$", "", heading.strip()) # closing hashes
30 text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text) # a link keeps its text
31 kept = re.sub(r"[^\w\- ]", "", text.lower())
32 return kept.replace(" ", "-")
35def section(text: str, end: int) -> str | None:
36 """Anchor of the last heading before `end`; a repeated one gets GitHub's `-1`."""
37 # Headings only outside code: a `# comment` in a bash or python block
38 # would give a link to a section that does not exist.
39 lines = text[:end].splitlines()
40 seen: dict[str, int] = {}
41 found = None
42 for line, in_code in zip(lines, code_flags(lines), strict=True):
43 heading = None if in_code else HEADING.match(line)
44 if heading:
45 base = anchor(heading.group(1))
46 repeat = seen.get(base, 0)
47 seen[base] = repeat + 1
48 found = f"{base}-{repeat}" if repeat else base
49 return found
52def link(text: str, match: re.Match[str]) -> str:
53 # A fence inside the diagram means the match ran past its own closing
54 # fence and took other text with it; that text would vanish from PyPI.
55 if any(FENCE.match(line) for line in match.group(1).splitlines()):
56 raise ValueError(f"a diagram swallowed a code block near: {match.group(0)[:80]!r}")
57 anchor_ = section(text, match.start())
58 target = f"{README}#{anchor_}" if anchor_ else README
59 return f"*This diagram is shown in the [README on GitHub]({target}).*\n"
62def main(argv: list[str]) -> int:
63 readme = Path("README.md")
64 # Bytes: text mode would turn LF into CRLF when run on Windows.
65 text = readme.read_bytes().decode("utf-8")
66 try:
67 replaced, count = DIAGRAM.subn(lambda match: link(text, match), text)
68 except ValueError as error:
69 print(f"README.md: {error}")
70 return 1
71 if ANY_FENCE.search(replaced):
72 print("README.md: a Mermaid fence this script cannot replace; use ```mermaid")
73 return 1
74 readme.write_bytes(replaced.encode("utf-8"))
75 print(f"README.md: {count} diagram(s) replaced with a link to GitHub")
76 return 0
79if __name__ == "__main__":
80 sys.exit(main(sys.argv[1:]))