Files
libretro/tests/mdsections.py
T
Abdessamad Derraz a58ca7bf6b refactor: one markdown section reader for tests
test_doc_surfaces, test_doc_pages, test_site_wiki and test_site_integration each cut a markdown section their own way. Two of them did not blank fenced code, so a shell comment such as '# from a checkout' in a bash block ended the section early and test_user_sections_never_send_to_verify could pass without reading the command below it. tests/mdsections.section() blanks fences and takes the stop level each caller used.
2026-11-21 06:04:40 +01:00

29 lines
1.1 KiB
Python

"""Sections of the markdown pages, for the tests that read them."""
from __future__ import annotations
import re
FENCED = re.compile(r"^```.*?^```", re.S | re.M)
def blank_fences(text: str) -> str:
"""The text with each fenced block's characters turned to spaces, lines
kept: a shell comment in a fence is no heading."""
return FENCED.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), text)
def section(text: str, heading: str, *, stop: int | None = None) -> str:
"""The body under a heading, up to the next heading of level stop or
higher (the heading's own level by default).
The heading is its text, or the full line with its hashes, which then
fix its level; a trailing ``{ #anchor }`` is optional either way."""
hashes, title = re.fullmatch(r"(#*)\s*(.*)", heading).groups()
start = re.search(rf"(?m)^({hashes or '#+'}) {re.escape(title)}(?:\s*\{{[^}}]*\}})?\n", text)
if start is None:
raise AssertionError(f"no section {heading!r}")
rest = text[start.end():]
end = re.search(rf"(?m)^#{{1,{stop or len(start.group(1))}}} ", blank_fences(rest))
return rest[: end.start()] if end else rest