|
| 1 | +"""Referential-integrity guard for documentation citations (#653). |
| 2 | +
|
| 3 | +Docstrings and comments in this package cite docs by filename |
| 4 | +(``ARCHITECTURE.md``) and by section (``§4.5``). A doc reorg once left a |
| 5 | +trail of dangling citations to deleted files (``docs/ux/pwa.md``, |
| 6 | +``theming.md``, ``ACCEPTANCE.md``, …) — this test fails fast when a cite |
| 7 | +points at a ``*.md`` file or a ``§N`` section heading that no longer |
| 8 | +exists, so the defect class can't recur. |
| 9 | +
|
| 10 | +Scope: the package source, the test suite, and ``.pre-commit-config.yaml`` |
| 11 | +(it carries doc citations too). It is intentionally simple and fast — a |
| 12 | +regex sweep, no network, no imports of the cited docs. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import re |
| 18 | +from pathlib import Path |
| 19 | + |
| 20 | +_REPO_ROOT = Path(__file__).resolve().parent.parent |
| 21 | +_THIS_FILE = Path(__file__).resolve() |
| 22 | + |
| 23 | +# Files whose comments/docstrings we scan for citations. This guard file is |
| 24 | +# excluded from its own scan — it legitimately quotes the (historically |
| 25 | +# dangling) doc names it exists to forbid. |
| 26 | +_SCANNED_FILES: list[Path] = [ |
| 27 | + *sorted((_REPO_ROOT / "django_admin_react").rglob("*.py")), |
| 28 | + *(p for p in sorted((_REPO_ROOT / "tests").rglob("*.py")) if p.resolve() != _THIS_FILE), |
| 29 | + _REPO_ROOT / ".pre-commit-config.yaml", |
| 30 | +] |
| 31 | + |
| 32 | +# A cited Markdown doc, e.g. ``ARCHITECTURE.md`` or ``docs/ux/pwa.md``. |
| 33 | +# Captures an optional path prefix so ``docs/foo.md`` resolves relative to |
| 34 | +# the repo root, while a bare ``FOO.md`` may live anywhere in the tree. |
| 35 | +_MD_REF_RE = re.compile(r"(?<![\w./-])((?:[\w./-]+/)?[A-Za-z0-9_-]+\.md)\b") |
| 36 | + |
| 37 | +# A cited section, e.g. ``§4.5`` or ``§3``. The doc it belongs to is the |
| 38 | +# nearest preceding ``*.md`` cite on the same line (the repo's convention |
| 39 | +# is ``ARCHITECTURE.md §4.5``). |
| 40 | +_SECTION_RE = re.compile(r"§\s*([\d]+(?:\.[\dA-Za-z]+)*)") |
| 41 | + |
| 42 | + |
| 43 | +def _iter_lines() -> list[tuple[Path, int, str]]: |
| 44 | + out: list[tuple[Path, int, str]] = [] |
| 45 | + for path in _SCANNED_FILES: |
| 46 | + if not path.is_file(): |
| 47 | + continue |
| 48 | + for lineno, line in enumerate(path.read_text("utf-8").splitlines(), start=1): |
| 49 | + out.append((path, lineno, line)) |
| 50 | + return out |
| 51 | + |
| 52 | + |
| 53 | +def _resolve_md(ref: str) -> bool: |
| 54 | + """True if a cited ``*.md`` reference resolves to a real file.""" |
| 55 | + # Path-qualified (``docs/ux/pwa.md``): resolve from the repo root. |
| 56 | + if "/" in ref: |
| 57 | + return (_REPO_ROOT / ref).is_file() |
| 58 | + # Bare filename (``ARCHITECTURE.md``): match anywhere in the tree, |
| 59 | + # skipping vendored / build dirs. |
| 60 | + skip = {"node_modules", ".git", "dist", ".venv", "__pycache__"} |
| 61 | + for candidate in _REPO_ROOT.rglob(ref): |
| 62 | + if not any(part in skip for part in candidate.parts): |
| 63 | + return True |
| 64 | + return False |
| 65 | + |
| 66 | + |
| 67 | +def _section_exists(doc: Path, section: str) -> bool: |
| 68 | + """True if ``doc`` has a heading for ``§section`` (e.g. ``## 4.5``).""" |
| 69 | + text = doc.read_text("utf-8") |
| 70 | + # Headings look like ``## 4. Backend design`` or ``### 4.5 URL mounting``. |
| 71 | + pattern = re.compile(rf"^#{{1,6}}\s+{re.escape(section)}(?:[.\s]|$)", re.MULTILINE) |
| 72 | + return bool(pattern.search(text)) |
| 73 | + |
| 74 | + |
| 75 | +def test_no_dangling_md_references() -> None: |
| 76 | + """Every cited ``*.md`` file in the scanned sources exists.""" |
| 77 | + failures: list[str] = [] |
| 78 | + for path, lineno, line in _iter_lines(): |
| 79 | + for match in _MD_REF_RE.finditer(line): |
| 80 | + ref = match.group(1) |
| 81 | + if not _resolve_md(ref): |
| 82 | + rel = path.relative_to(_REPO_ROOT) |
| 83 | + failures.append(f"{rel}:{lineno} cites missing doc {ref!r}") |
| 84 | + assert not failures, "Dangling Markdown references:\n" + "\n".join(failures) |
| 85 | + |
| 86 | + |
| 87 | +def test_no_dangling_section_references() -> None: |
| 88 | + """Every ``§N`` cite resolves to a heading in the doc named on its line.""" |
| 89 | + failures: list[str] = [] |
| 90 | + for path, lineno, line in _iter_lines(): |
| 91 | + sections = _SECTION_RE.findall(line) |
| 92 | + if not sections: |
| 93 | + continue |
| 94 | + md_refs = _MD_REF_RE.findall(line) |
| 95 | + if not md_refs: |
| 96 | + # A §N with no doc named on the same line — can't verify which |
| 97 | + # doc it belongs to, so we don't guess. The repo convention |
| 98 | + # always names the doc; flag the orphan so it gets fixed. |
| 99 | + rel = path.relative_to(_REPO_ROOT) |
| 100 | + cited = "/".join("§" + s for s in sections) |
| 101 | + failures.append(f"{rel}:{lineno} cites {cited} with no doc on the line") |
| 102 | + continue |
| 103 | + # The section belongs to the last doc named before it on the line. |
| 104 | + doc_ref = md_refs[-1] |
| 105 | + doc_path = _REPO_ROOT / doc_ref |
| 106 | + if not doc_path.is_file(): |
| 107 | + # The missing-file case is already covered by the other test. |
| 108 | + continue |
| 109 | + for section in sections: |
| 110 | + if not _section_exists(doc_path, section): |
| 111 | + rel = path.relative_to(_REPO_ROOT) |
| 112 | + failures.append(f"{rel}:{lineno} cites {doc_ref} §{section} — no such heading") |
| 113 | + assert not failures, "Dangling section references:\n" + "\n".join(failures) |
0 commit comments