check_active_markdown_links.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/usr/bin/env python3
  2. """Lightweight relative-link check for active Markdown (not historical docs).
  3. Understands review-compact layout: links are resolved from the file's package
  4. path. Historical trees (docs/historical/, reference/historical/) are ignored.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import json
  9. import re
  10. import sys
  11. import zipfile
  12. from pathlib import Path
  13. from typing import Any, Iterable
  14. ROOT = Path(__file__).resolve().parents[1]
  15. TOOLS = Path(__file__).resolve().parent
  16. if str(TOOLS) not in sys.path:
  17. sys.path.insert(0, str(TOOLS))
  18. MD_LINK_RE = re.compile(r"(?<!!)\[[^\]]*\]\(([^)]+)\)")
  19. HISTORICAL_MARKERS = (
  20. "/docs/historical/",
  21. "/reference/historical/",
  22. "docs/historical/",
  23. "reference/historical/",
  24. )
  25. # Minimum regression set reproduced by remote audit.
  26. REQUIRED_ACTIVE_TARGETS = (
  27. ("README.zh-CN.md", "docs/IO_EVIDENCE_MATRIX.zh-CN.md"),
  28. (
  29. "docs/HARDWARE_TEST_ORDER_WAVEFORMS.zh-CN.md",
  30. "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
  31. ),
  32. )
  33. def _normalize(path: str) -> str:
  34. text = path.replace("\\", "/")
  35. while text.startswith("./"):
  36. text = text[2:]
  37. return text
  38. def _is_historical(path: str) -> bool:
  39. lower = f"/{_normalize(path).casefold()}/"
  40. return any(marker in lower for marker in ("/docs/historical/", "/reference/historical/"))
  41. def _strip_layout_prefix(path: str) -> str:
  42. logical = _normalize(path)
  43. if logical.casefold().startswith("cpld/"):
  44. logical = logical[len("CPLD/") :] if logical.startswith("CPLD/") else logical[5:]
  45. if logical.casefold().startswith("source/"):
  46. return logical[len("source/") :]
  47. return logical
  48. def _resolve_link(source_path: str, href: str) -> str | None:
  49. href = href.strip()
  50. if not href or href.startswith(("#", "http://", "https://", "mailto:")):
  51. return None
  52. href = href.split("#", 1)[0].split("?", 1)[0].strip()
  53. if not href:
  54. return None
  55. if href.startswith("/"):
  56. return href.lstrip("/")
  57. source_dir = Path(_strip_layout_prefix(source_path)).parent
  58. resolved = (source_dir / href).as_posix()
  59. # Normalize .. segments without escaping package root.
  60. parts: list[str] = []
  61. for part in resolved.split("/"):
  62. if part in ("", "."):
  63. continue
  64. if part == "..":
  65. if parts:
  66. parts.pop()
  67. continue
  68. parts.append(part)
  69. return "/".join(parts)
  70. def iter_markdown_members(names: Iterable[str]) -> list[str]:
  71. out: list[str] = []
  72. for name in names:
  73. logical = _normalize(name)
  74. if not logical.casefold().endswith((".md", ".markdown")):
  75. continue
  76. if _is_historical(logical):
  77. continue
  78. # Only check active software docs under source/ (or bare repo paths).
  79. stripped = _strip_layout_prefix(logical)
  80. if logical.casefold().startswith("cpld/") and not logical.casefold().startswith(
  81. "cpld/source/"
  82. ):
  83. # evidence/ copies are review entry points; links live in source/.
  84. continue
  85. if stripped.casefold().startswith(("docs/historical/", "reference/historical/")):
  86. continue
  87. out.append(logical)
  88. return sorted(out)
  89. def check_members(
  90. *,
  91. members: set[str],
  92. texts: dict[str, str],
  93. ) -> dict[str, Any]:
  94. """Check relative links among package/repo members.
  95. ``members`` keys are layout-normalized (may include CPLD/source/...).
  96. ``texts`` maps the same keys to markdown body.
  97. """
  98. present_repo = {_strip_layout_prefix(m) for m in members}
  99. present_full = {_normalize(m) for m in members}
  100. failures: list[str] = []
  101. present_dirs = {
  102. str(Path(p).parent.as_posix())
  103. for p in present_repo
  104. if Path(p).parent.as_posix() not in {"", "."}
  105. }
  106. present_dirs.update(
  107. {
  108. p.rstrip("/")
  109. for p in present_repo
  110. if p.endswith("/")
  111. }
  112. )
  113. for source, text in sorted(texts.items()):
  114. if _is_historical(source):
  115. continue
  116. for match in MD_LINK_RE.finditer(text):
  117. href = match.group(1)
  118. target = _resolve_link(source, href)
  119. if target is None:
  120. continue
  121. # Active docs may point at historical archives; those are not a release gate.
  122. if _is_historical(target) or target.casefold().rstrip("/").endswith(
  123. ("/historical", "docs/historical", "reference/historical")
  124. ):
  125. continue
  126. # Allow either repo-relative or full package path hits.
  127. ok = (
  128. target in present_repo
  129. or target.rstrip("/") in present_dirs
  130. or target in present_full
  131. or f"source/{target}" in present_full
  132. or f"CPLD/source/{target}" in present_full
  133. or f"cpld/source/{target}".casefold()
  134. in {p.casefold() for p in present_full}
  135. )
  136. if not ok:
  137. failures.append(
  138. f"broken_relative_link:{_strip_layout_prefix(source)}->{href}"
  139. )
  140. # Explicit regression targets (remote audit reproductions).
  141. for source_rel, target_rel in REQUIRED_ACTIVE_TARGETS:
  142. source_keys = [
  143. key
  144. for key in texts
  145. if _strip_layout_prefix(key).casefold() == source_rel.casefold()
  146. ]
  147. if not source_keys:
  148. failures.append(f"missing_active_doc:{source_rel}")
  149. continue
  150. if target_rel not in present_repo and f"source/{target_rel}" not in {
  151. _normalize(m) for m in members
  152. } and not any(
  153. _strip_layout_prefix(m).casefold() == target_rel.casefold() for m in members
  154. ):
  155. failures.append(f"missing_link_target:{source_rel}->{target_rel}")
  156. status = "pass" if not failures else "fail"
  157. return {
  158. "schema": "cpld-active-markdown-link-check-v1",
  159. "status": status,
  160. "failures": sorted(set(failures)),
  161. "checked_files": sorted(_strip_layout_prefix(k) for k in texts),
  162. "hardware_validation": "not_run",
  163. }
  164. def check_repo_root(root: Path) -> dict[str, Any]:
  165. root = root.resolve(strict=True)
  166. members: set[str] = set()
  167. texts: dict[str, str] = {}
  168. for path in root.rglob("*"):
  169. if path.is_symlink():
  170. continue
  171. if not path.is_file() and not path.is_dir():
  172. continue
  173. rel = path.relative_to(root).as_posix()
  174. # Keep historical paths in the member set so active docs may link to them,
  175. # but never treat historical markdown as sources under check.
  176. members.add(rel)
  177. if not path.is_file():
  178. continue
  179. if rel.casefold().endswith((".md", ".markdown")) and not _is_historical(rel):
  180. # Skip non-active trees already filtered; also skip deep vendor.
  181. if any(
  182. part.startswith(".")
  183. for part in Path(rel).parts
  184. if part not in {".", ".."}
  185. ):
  186. continue
  187. if rel.casefold().startswith(("node_modules/", "reference/original/")):
  188. continue
  189. try:
  190. texts[rel] = path.read_text(encoding="utf-8")
  191. except (OSError, UnicodeError):
  192. failures_note = f"unreadable_markdown:{rel}"
  193. return {
  194. "schema": "cpld-active-markdown-link-check-v1",
  195. "status": "fail",
  196. "failures": [failures_note],
  197. "checked_files": [],
  198. "hardware_validation": "not_run",
  199. }
  200. # Restrict texts to active docs of interest + README/docs/*.md
  201. active_texts = {
  202. key: value
  203. for key, value in texts.items()
  204. if key in {"README.zh-CN.md", "README.md"}
  205. or key.casefold().startswith("docs/")
  206. or key.casefold().endswith("readme.zh-cn.md")
  207. }
  208. return check_members(members=members, texts=active_texts)
  209. def check_review_zip(zip_path: Path) -> dict[str, Any]:
  210. zip_path = zip_path.resolve(strict=True)
  211. members: set[str] = set()
  212. texts: dict[str, str] = {}
  213. with zipfile.ZipFile(zip_path, "r", allowZip64=True) as archive:
  214. names = list(archive.namelist())
  215. members = {_normalize(name) for name in names if not name.endswith("/")}
  216. for name in iter_markdown_members(names):
  217. try:
  218. texts[name] = archive.read(name).decode("utf-8")
  219. except (KeyError, UnicodeDecodeError):
  220. return {
  221. "schema": "cpld-active-markdown-link-check-v1",
  222. "status": "fail",
  223. "failures": [f"unreadable_markdown:{name}"],
  224. "checked_files": [],
  225. "hardware_validation": "not_run",
  226. }
  227. return check_members(members=members, texts=texts)
  228. def check_extracted_review(root: Path) -> dict[str, Any]:
  229. """Fresh extraction root containing CPLD/source or source/."""
  230. root = root.resolve(strict=True)
  231. source_root = root / "CPLD" / "source"
  232. if not source_root.is_dir():
  233. source_root = root / "source"
  234. if not source_root.is_dir():
  235. return {
  236. "schema": "cpld-active-markdown-link-check-v1",
  237. "status": "fail",
  238. "failures": ["missing_source_tree"],
  239. "checked_files": [],
  240. "hardware_validation": "not_run",
  241. }
  242. # Include evidence paths as present members so duplicated review entry
  243. # targets also count, but only validate links from source/.
  244. members: set[str] = set()
  245. for path in root.rglob("*"):
  246. if path.is_file() and not path.is_symlink():
  247. members.add(path.relative_to(root).as_posix())
  248. texts: dict[str, str] = {}
  249. for path in source_root.rglob("*.md"):
  250. if path.is_symlink():
  251. continue
  252. rel = path.relative_to(root).as_posix()
  253. if _is_historical(rel):
  254. continue
  255. texts[rel] = path.read_text(encoding="utf-8")
  256. return check_members(members=members, texts=texts)
  257. def build_parser() -> argparse.ArgumentParser:
  258. parser = argparse.ArgumentParser(description=__doc__)
  259. parser.add_argument("--repo-root", type=Path, default=None)
  260. parser.add_argument("--zip", type=Path, default=None)
  261. parser.add_argument("--extract-root", type=Path, default=None)
  262. parser.add_argument("--json-out", type=Path, default=None)
  263. return parser
  264. def main(argv: list[str] | None = None) -> int:
  265. args = build_parser().parse_args(argv)
  266. if args.zip is not None:
  267. report = check_review_zip(args.zip)
  268. elif args.extract_root is not None:
  269. report = check_extracted_review(args.extract_root)
  270. else:
  271. report = check_repo_root(args.repo_root or ROOT)
  272. text = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
  273. if args.json_out is not None:
  274. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  275. args.json_out.write_text(text, encoding="utf-8")
  276. sys.stdout.write(text)
  277. return 0 if report.get("status") == "pass" else 1
  278. if __name__ == "__main__":
  279. raise SystemExit(main())