SPB Git

Repository Public

check-docs.py 3.9 KB 101 lines python

1#!/usr/bin/env python32"""Validates the relative links and image paths of the documentation.34Checks every Markdown file under docs/ and README.md (if present):5  * [text](relative/path) and ![alt](relative/path) targets must exist;6  * a '#fragment' on a Markdown target must match a heading of that file7    (GitHub anchor rules: lower case, punctuation removed, spaces -> '-');8  * every Mermaid block must be preceded by '<!-- diagram: name -->' and the9    SVG fallback docs/assets/diagrams/name.svg must exist.10External links (http, https, mailto) are not fetched.1112Usage: python3 Scripts/check-docs.py        exit status 1 if anything is broken13"""14from __future__ import annotations1516import re17import sys18import unicodedata19from pathlib import Path2021ROOT = Path(__file__).resolve().parent.parent22LINK_RE = re.compile(r"(!?)\[((?:[^\]\\]|\\.)*)\]\(\s*<?([^)\s>]+)>?(?:\s+\"[^\"]*\")?\s*\)")23FENCE_RE = re.compile(r"^(```|~~~)")24DIAGRAM_RE = re.compile(r"<!--\s*diagram:\s*([a-z0-9][a-z0-9-]*)\s*-->\s*\n```mermaid")252627def strip_code(text: str) -> str:28    """Removes fenced blocks and inline code so that sample code is not parsed as links."""29    out, inside = [], False30    for line in text.splitlines():31        if FENCE_RE.match(line.strip()):32            inside = not inside33            out.append("")34            continue35        out.append("" if inside else re.sub(r"`[^`\n]*`", "", line))36    return "\n".join(out)373839def anchors(path: Path) -> set[str]:40    found: set[str] = set()41    counts: dict[str, int] = {}42    inside = False43    for line in path.read_text(encoding="utf-8").splitlines():44        if FENCE_RE.match(line.strip()):45            inside = not inside46            continue47        if inside:48            continue49        match = re.match(r"^#{1,6}\s+(.*?)\s*#*\s*$", line)50        if not match:51            continue52        title = re.sub(r"`", "", match.group(1))53        title = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", title)54        slug = "".join(55            ch for ch in unicodedata.normalize("NFC", title.lower())56            if ch.isalnum() or ch in " -_"57        ).replace(" ", "-")58        number = counts.get(slug, 0)59        counts[slug] = number + 160        found.add(slug if number == 0 else f"{slug}-{number}")61    return found626364def main() -> int:65    files = sorted((ROOT / "docs").rglob("*.md"))66    readme = ROOT / "README.md"67    if readme.exists():68        files.append(readme)69    problems: list[str] = []70    links = images = 071    for path in files:72        raw = path.read_text(encoding="utf-8")73        relative = path.relative_to(ROOT)74        for name in DIAGRAM_RE.findall(raw):75            if not (ROOT / "docs/assets/diagrams" / f"{name}.svg").exists():76                problems.append(f"{relative}: diagram '{name}' has no SVG fallback")77        if raw.count("```mermaid") != len(DIAGRAM_RE.findall(raw)):78            problems.append(f"{relative}: Mermaid block without '<!-- diagram: name -->'")79        for bang, _, target in LINK_RE.findall(strip_code(raw)):80            if re.match(r"^[a-z][a-z0-9+.-]*:", target, re.I):81                continue  # external82            if bang:83                images += 184            else:85                links += 186            file_part, _, fragment = target.partition("#")87            destination = path if not file_part else (path.parent / file_part.replace("%20", " ")).resolve()88            if not destination.exists():89                problems.append(f"{relative}: missing target {target}")90                continue91            if fragment and destination.suffix == ".md" and fragment.lower() not in anchors(destination):92                problems.append(f"{relative}: no heading for anchor {target}")93    for problem in problems:94        print(problem)95    print(f"{len(files)} file(s), {links} relative link(s), {images} image(s), {len(problems)} problem(s)")96    return 1 if problems else 0979899if __name__ == "__main__":100    sys.exit(main())101
Files main
Menu

Theme