test_markdown_anchors.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """Every Markdown link with a #fragment must point at a heading that exists.
  2. GitHub builds the fragment from the heading text: lower case, markup and punctuation
  3. dropped, spaces to hyphens, repeats get -1, -2. Links inside code are ignored.
  4. """
  5. import posixpath
  6. import re
  7. import subprocess
  8. from pathlib import Path
  9. ROOT = Path(__file__).resolve().parent.parent
  10. FENCE_LINE = re.compile(r"^\s*(```|~~~)")
  11. LINK = re.compile(r"(?<!!)\[[^\]\n]*\]\(([^)\s]*)(?:\s+\"[^\"]*\")?\)")
  12. HEADING = re.compile(r"^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$")
  13. INLINE_CODE = re.compile(r"`[^`\n]*`")
  14. def slug(heading: str) -> str:
  15. text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", heading) # link text only
  16. text = text.replace("`", "")
  17. text = re.sub(r"[^\w\- ]", "", text.lower())
  18. return text.replace(" ", "-")
  19. def strip_fences(text: str) -> list[tuple[int, str]]:
  20. out, in_fence = [], False
  21. for n, line in enumerate(text.split("\n"), start=1):
  22. if FENCE_LINE.match(line):
  23. in_fence = not in_fence
  24. elif not in_fence:
  25. out.append((n, line))
  26. return out
  27. def anchors(text: str) -> set[str]:
  28. seen: dict[str, int] = {}
  29. found = set()
  30. for _, line in strip_fences(text):
  31. m = HEADING.match(line)
  32. if not m:
  33. continue
  34. base = slug(m.group(2))
  35. count = seen.get(base, 0)
  36. seen[base] = count + 1
  37. found.add(base if count == 0 else f"{base}-{count}")
  38. return found
  39. def broken_links(files: dict[str, str]) -> list[str]:
  40. """files maps repo-relative path to text; returns 'path:line: target' for each bad fragment."""
  41. table = {path: anchors(text) for path, text in files.items()}
  42. problems = []
  43. for path, text in files.items():
  44. for n, line in strip_fences(text):
  45. for m in LINK.finditer(INLINE_CODE.sub("", line)):
  46. target = m.group(1)
  47. if "#" not in target or re.match(r"[a-z][a-z0-9+.-]*:", target):
  48. continue
  49. file_part, _, frag = target.partition("#")
  50. dest = path if not file_part else posixpath.normpath(posixpath.join(posixpath.dirname(path), file_part))
  51. if dest not in table or not frag:
  52. continue
  53. if frag.lower() not in table[dest]:
  54. problems.append(f"{path}:{n}: {target}")
  55. return problems
  56. def repo_markdown() -> dict[str, str]:
  57. names = subprocess.run(["git", "-C", str(ROOT), "ls-files", "*.md"], capture_output=True, text=True, check=True).stdout.split()
  58. return {n: (ROOT / n).read_text(encoding="utf-8") for n in names}
  59. def test_every_fragment_points_at_a_heading():
  60. files = repo_markdown()
  61. assert len(files) > 50
  62. assert not broken_links(files), "\n".join(broken_links(files))
  63. def test_checker_catches_a_broken_fragment_and_accepts_a_good_one():
  64. files = {"a.md": "# Top\n\n## Security and threat modeling\n\n[x](#security-and-threat-modelling)\n[y](b.md#some-heading)\n",
  65. "b.md": "# Some heading\n"}
  66. assert broken_links(files) == ["a.md:5: #security-and-threat-modelling"]
  67. files["a.md"] = "## Security and threat modeling\n[x](#security-and-threat-modeling)\n[y](b.md#some-heading)\n"
  68. assert broken_links(files) == []
  69. def test_checker_ignores_fences_and_handles_repeated_headings():
  70. files = {"a.md": "# A\n# A\n```\n# Fake\n```\n[1](#a) [2](#a-1) [3](#fake)\n"}
  71. assert broken_links(files) == ["a.md:6: #fake"]