from __future__ import annotations
import json
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
AFDATA = ROOT / "target" / "debug" / "afdata"
SECTION_KEYS = tuple(f"h{level}" for level in range(1, 7))
def code_blocks(path: Path) -> list[dict]:
run = subprocess.run(
[str(AFDATA), "get", str(path), "--input-format", "markdown", "--output", "json"],
capture_output=True,
encoding="utf-8",
check=False,
)
if run.returncode != 0:
raise RuntimeError(f"afdata could not read {path}: {run.stderr.strip()[:300]}")
tree = json.loads(run.stdout)["result"]["value"]
found: list[dict] = []
_collect(tree["preamble"], found)
_collect(tree, found)
return sorted(found, key=lambda block: block["source_start_line"])
def _collect(container: dict, found: list[dict]) -> None:
for block in container.get("blocks", []):
if block["type"] == "code":
found.append(block)
_collect(block, found)
for key in SECTION_KEYS:
for section in container.get(key, []):
_collect(section, found)