|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Check that every relative markdown link resolves. |
| 3 | +
|
| 4 | +For each *.md in the repo: |
| 5 | + - [text](./other.md) -> other.md must exist |
| 6 | + - [text](./other.md#section) -> other.md must exist AND contain a heading |
| 7 | + whose GitHub-style slug is `section` |
| 8 | + - [text](#section) -> this file must contain that heading |
| 9 | +
|
| 10 | +External URLs (http/https/mailto/tel), pure images, and links inside fenced |
| 11 | +code blocks are skipped. Slugs follow GitHub's algorithm: lowercase, strip |
| 12 | +everything but word chars/spaces/hyphens, spaces -> hyphens, duplicates get |
| 13 | +-1/-2/... suffixes. Explicit <a name="..."> / id="..." anchors also count. |
| 14 | +
|
| 15 | +Run via: python .github/scripts/check_anchors.py |
| 16 | +Exit code 0 = all links resolve; 1 = violations (each printed as ::error). |
| 17 | +""" |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import pathlib |
| 21 | +import re |
| 22 | +import sys |
| 23 | +import unicodedata |
| 24 | +from urllib.parse import unquote |
| 25 | + |
| 26 | +REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] |
| 27 | + |
| 28 | +SKIP_DIRS = {".git", "node_modules", ".venv", "__pycache__"} |
| 29 | +EXTERNAL_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:") # any URI scheme |
| 30 | +LINK_RE = re.compile(r"(!?)\[(?:[^\[\]]|\[[^\]]*\])*\]\(\s*<?([^)<>\s]+)>?(?:\s+[\"'][^\"']*[\"'])?\s*\)") |
| 31 | +HEADING_RE = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$") |
| 32 | +FENCE_RE = re.compile(r"^\s*(```|~~~)") |
| 33 | +EXPLICIT_ANCHOR_RE = re.compile(r"<a\s+(?:name|id)\s*=\s*[\"']([^\"']+)[\"']|\bid\s*=\s*[\"']([^\"']+)[\"']") |
| 34 | + |
| 35 | +# strip inline markdown from heading text before slugging |
| 36 | +INLINE_MD_RE = re.compile(r"`([^`]*)`|\*\*([^*]*)\*\*|\*([^*]*)\*|__([^_]*)__|_([^_]*)_") |
| 37 | +HEADING_LINK_RE = re.compile(r"\[([^\]]*)\]\([^)]*\)") |
| 38 | + |
| 39 | + |
| 40 | +def github_slug(text: str) -> str: |
| 41 | + """GitHub heading slug: strip markdown, lowercase, keep word chars/hyphens, |
| 42 | + spaces -> hyphens.""" |
| 43 | + text = HEADING_LINK_RE.sub(r"\1", text) |
| 44 | + text = INLINE_MD_RE.sub(lambda m: next(g for g in m.groups() if g is not None), text) |
| 45 | + text = unicodedata.normalize("NFC", text) |
| 46 | + out = [] |
| 47 | + for ch in text: |
| 48 | + if ch.isalnum() or ch == "_": |
| 49 | + out.append(ch.lower()) |
| 50 | + elif ch == " ": |
| 51 | + out.append("-") # every space becomes a hyphen (GitHub does NOT collapse) |
| 52 | + elif ch == "-": |
| 53 | + out.append("-") |
| 54 | + # other punctuation dropped |
| 55 | + return "".join(out) |
| 56 | + |
| 57 | + |
| 58 | +def iter_md_files() -> list[pathlib.Path]: |
| 59 | + files = [] |
| 60 | + for p in sorted(REPO_ROOT.rglob("*.md")): |
| 61 | + if any(part in SKIP_DIRS for part in p.relative_to(REPO_ROOT).parts): |
| 62 | + continue |
| 63 | + files.append(p) |
| 64 | + return files |
| 65 | + |
| 66 | + |
| 67 | +def strip_fences(lines: list[str]) -> list[str]: |
| 68 | + """Blank out lines inside fenced code blocks (keep line count stable).""" |
| 69 | + out = [] |
| 70 | + fence = None |
| 71 | + for line in lines: |
| 72 | + m = FENCE_RE.match(line) |
| 73 | + if m: |
| 74 | + if fence is None: |
| 75 | + fence = m.group(1) |
| 76 | + elif m.group(1) == fence: |
| 77 | + fence = None |
| 78 | + out.append("") |
| 79 | + continue |
| 80 | + out.append("" if fence is not None else line) |
| 81 | + return out |
| 82 | + |
| 83 | + |
| 84 | +def collect_anchors(p: pathlib.Path, cache: dict[pathlib.Path, set[str]]) -> set[str]: |
| 85 | + if p in cache: |
| 86 | + return cache[p] |
| 87 | + anchors: set[str] = set() |
| 88 | + text = p.read_text(encoding="utf-8-sig", errors="replace").replace("\r\n", "\n") |
| 89 | + lines = strip_fences(text.split("\n")) |
| 90 | + seen: dict[str, int] = {} |
| 91 | + for line in lines: |
| 92 | + m = HEADING_RE.match(line) |
| 93 | + if m: |
| 94 | + base = github_slug(m.group(2)) |
| 95 | + n = seen.get(base, 0) |
| 96 | + seen[base] = n + 1 |
| 97 | + anchors.add(base if n == 0 else f"{base}-{n}") |
| 98 | + for am in EXPLICIT_ANCHOR_RE.finditer(line): |
| 99 | + anchors.add(am.group(1) or am.group(2)) |
| 100 | + cache[p] = anchors |
| 101 | + return anchors |
| 102 | + |
| 103 | + |
| 104 | +def main() -> int: |
| 105 | + anchor_cache: dict[pathlib.Path, set[str]] = {} |
| 106 | + violations = 0 |
| 107 | + |
| 108 | + for md in iter_md_files(): |
| 109 | + rel = md.relative_to(REPO_ROOT) |
| 110 | + text = md.read_text(encoding="utf-8-sig", errors="replace").replace("\r\n", "\n") |
| 111 | + lines = strip_fences(text.split("\n")) |
| 112 | + for lineno, line in enumerate(lines, 1): |
| 113 | + line = re.sub(r"`[^`]*`", "``", line) # links inside inline code aren't links |
| 114 | + for m in LINK_RE.finditer(line): |
| 115 | + is_image, target = m.group(1) == "!", m.group(2) |
| 116 | + target = unquote(target) |
| 117 | + if EXTERNAL_RE.match(target) or target.startswith("//"): |
| 118 | + continue # external URL or protocol-relative |
| 119 | + path_part, _, frag = target.partition("#") |
| 120 | + if path_part: |
| 121 | + dest = (md.parent / path_part).resolve() |
| 122 | + if not dest.exists(): |
| 123 | + violations += 1 |
| 124 | + print(f"::error file={rel},line={lineno}::broken link '{target}' — file not found") |
| 125 | + continue |
| 126 | + else: |
| 127 | + dest = md |
| 128 | + if is_image or not frag: |
| 129 | + continue |
| 130 | + if dest.suffix.lower() != ".md" or dest.is_dir(): |
| 131 | + continue # can't check anchors in non-markdown targets |
| 132 | + if frag not in collect_anchors(dest, anchor_cache): |
| 133 | + violations += 1 |
| 134 | + where = "" if dest == md else f" in {dest.relative_to(REPO_ROOT)}" |
| 135 | + print(f"::error file={rel},line={lineno}::broken anchor '#{frag}'{where} ('{target}')") |
| 136 | + |
| 137 | + if violations: |
| 138 | + print(f"\n{violations} broken relative link(s)/anchor(s)", file=sys.stderr) |
| 139 | + return 1 |
| 140 | + print("All relative links and anchors resolve.") |
| 141 | + return 0 |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == "__main__": |
| 145 | + sys.exit(main()) |
0 commit comments