Coverage for scripts/mermaid_fences.py: 100%
19 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"""What counts as a Mermaid diagram, and as code, in the docs (ADR 0014).
3One definition for check_diagrams.py (CI) and replace_readme_diagrams.py
4(publish): if they disagreed, CI would pass a README that the publish then
5refuses on release day, or that reaches PyPI with diagram source in it.
6"""
8from __future__ import annotations
10import re
11from collections.abc import Iterator
13# The one form both scripts extract: a ``` fence at the start of a line. The
14# closing fence may be indented up to three spaces and followed by spaces, and
15# may end the file (CommonMark); anything stricter would let the lazy match run
16# on to a later fence and take the text in between with it.
17DIAGRAM = re.compile(
18 r"^```mermaid[ \t]*\n(.*?)^ {0,3}`{3,}[ \t]*(?:\n|\Z)", re.MULTILINE | re.DOTALL
19)
20# Every form GitHub or Material would still render as a diagram: a tilde or a
21# longer fence, or one indented inside an admonition or a tab. `[ \t]`, not
22# `\s`: a match must not run on to "mermaid" at the start of a later line.
23ANY_FENCE = re.compile(r"^[ \t]*(?:`{3,}|~{3,})[ \t]*mermaid\b", re.MULTILINE)
24# Any line that opens or closes a fenced code block.
25FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
28def code_flags(lines: list[str]) -> Iterator[bool]:
29 """For each line, whether it belongs to a fenced code block, fences included.
31 A block closes only on a fence of its own character, at least as long and
32 with nothing after it, so a ``` example inside a ```` block stays code.
33 """
34 opener: str | None = None
35 for line in lines:
36 fence = FENCE.match(line)
37 if opener is None:
38 if fence:
39 opener = fence.group(1)
40 yield fence is not None
41 continue
42 closes = (
43 fence is not None
44 and fence.group(1)[0] == opener[0]
45 and len(fence.group(1)) >= len(opener)
46 and not fence.group(2).strip()
47 )
48 yield True
49 if closes:
50 opener = None