返回 CodeWhale
check-links.py
根目录 / scripts / docs / check-links.py
1 #!/usr/bin/env python3
2 """check-links.py — report Markdown links that point at nothing.
3
4 Reads every tracked Markdown file and checks each relative link, each
5 `https://github.com/codewhale-hq/Codewhale/blob/main/...` link and each
6 `#anchor` against the tracked tree and the headings of the target page.
7 External URLs are not fetched.
8
9 It is WARN-ONLY: it prints findings and exits 0. Pass --strict to exit 1 on
10 any finding, and --orphans to also list docs pages no Markdown file links.
11
12 python3 scripts/docs/check-links.py
13 python3 scripts/docs/check-links.py --strict
14 python3 scripts/docs/check-links.py --orphans
15 """
16 from __future__ import annotations
17
18 import argparse
19 import collections
20 import os
21 import re
22 import subprocess
23 import sys
24 import unicodedata
25 import urllib.parse
26 from pathlib import Path
27
28 REPO_ROOT = Path(__file__).resolve().parents[2]
29 SKIP_PREFIXES = ("node_modules/", "vendor/", "web/node_modules/", "crates/tui/CHANGELOG.md")
30 SKIP_PARTS = ("/fixtures/", "/upstream/", "/codewhale-notices/")
31 LINK = re.compile(r'(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)')
32 IMAGE = re.compile(r"!\[[^\]]*\]\(([^)\s]+)")
33 FENCE = re.compile(r"```.*?```", re.S)
34 HEADING = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$")
35 EXPLICIT_ANCHOR = re.compile(r'<a\s+(?:id|name)="([^"]+)"')
36 REPO_URL = re.compile(r"https://github\.com/codewhale-hq/[Cc]ode[Ww]hale/(?:blob|tree)/main/([^#?]+)")
37 EXTERNAL = re.compile(r"^(https?:|mailto:|<|data:)")
38
39
40 def tracked_files() -> set[str]:
41 out = subprocess.run(
42 ["git", "-C", str(REPO_ROOT), "ls-files"], capture_output=True, text=True, check=True
43 ).stdout
44 return {line for line in out.split("\n") if line}
45
46
47 def slugify(heading: str) -> str:
48 heading = heading.strip().lower().replace("`", "")
49 heading = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", heading)
50 kept = (ch for ch in heading if ch in "-_ " or unicodedata.category(ch)[0] in "LNM")
51 return "".join(kept).replace(" ", "-")
52
53
54 def anchors_of(path: str, cache: dict[str, set[str]]) -> set[str]:
55 if path in cache:
56 return cache[path]
57 found: set[str] = set()
58 counts: collections.Counter[str] = collections.Counter()
59 try:
60 text = (REPO_ROOT / path).read_text(encoding="utf8")
61 except OSError:
62 text = ""
63 in_fence = False
64 for line in text.split("\n"):
65 if line.startswith("```"):
66 in_fence = not in_fence
67 continue
68 if in_fence:
69 continue
70 match = HEADING.match(line)
71 if match:
72 slug = slugify(match.group(2))
73 seen = counts[slug]
74 counts[slug] += 1
75 found.add(slug if seen == 0 else f"{slug}-{seen}")
76 found.update(EXPLICIT_ANCHOR.findall(line))
77 cache[path] = found
78 return found
79
80
81 def main() -> int:
82 parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
83 parser.add_argument("--strict", action="store_true", help="exit 1 on any finding")
84 parser.add_argument("--orphans", action="store_true", help="list docs pages with no inbound link")
85 args = parser.parse_args()
86
87 tracked = tracked_files()
88 dirs: set[str] = set()
89 for name in tracked:
90 parent = os.path.dirname(name)
91 while parent:
92 dirs.add(parent)
93 parent = os.path.dirname(parent)
94 pages = sorted(
95 name
96 for name in tracked
97 if name.endswith(".md")
98 and not name.startswith(SKIP_PREFIXES)
99 and not any(part in name for part in SKIP_PARTS)
100 )
101
102 cache: dict[str, set[str]] = {}
103 broken: list[tuple[str, str]] = []
104 bad_anchor: list[tuple[str, str]] = []
105 inbound: dict[str, set[str]] = collections.defaultdict(set)
106
107 def has_anchor(page: str, fragment: str) -> bool:
108 known = anchors_of(page, cache)
109 fragment = urllib.parse.unquote(fragment)
110 return fragment in known or fragment.lower() in known
111
112 for page in pages:
113 text = FENCE.sub("", (REPO_ROOT / page).read_text(encoding="utf8"))
114 for match in list(LINK.finditer(text)) + list(IMAGE.finditer(text)):
115 target = match.group(1)
116 if target.startswith("#"):
117 if target[1:] and not has_anchor(page, target[1:]):
118 bad_anchor.append((page, target))
119 continue
120 if EXTERNAL.match(target):
121 repo_match = REPO_URL.match(target)
122 if repo_match:
123 path = repo_match.group(1).rstrip("/")
124 fragment = target.partition("#")[2]
125 if path in tracked:
126 inbound[path].add(page)
127 if fragment and path.endswith(".md") and not has_anchor(path, fragment):
128 bad_anchor.append((page, target))
129 elif path not in dirs:
130 broken.append((page, target))
131 continue
132 path, _, fragment = target.partition("#")
133 path = path.split("?")[0]
134 if not path:
135 continue
136 resolved = (
137 path.lstrip("/")
138 if path.startswith("/")
139 else os.path.normpath(os.path.join(os.path.dirname(page), path))
140 )
141 if resolved in tracked:
142 inbound[resolved].add(page)
143 if fragment and resolved.endswith(".md") and not has_anchor(resolved, fragment):
144 bad_anchor.append((page, target))
145 elif resolved.rstrip("/") not in dirs and resolved != ".":
146 broken.append((page, target))
147
148 for page, target in broken:
149 print(f"{page}: broken link {target}")
150 for page, target in bad_anchor:
151 print(f"{page}: missing anchor {target}")
152 orphans: list[str] = []
153 if args.orphans:
154 orphans = [
155 page
156 for page in pages
157 if page.startswith("docs/")
158 and page.count("/") == 1
159 and page != "docs/README.md"
160 and not (inbound.get(page, set()) - {page})
161 ]
162 for page in orphans:
163 print(f"{page}: no Markdown file links this page")
164
165 print(
166 f"check-links: {len(pages)} Markdown files, {len(broken)} broken links, "
167 f"{len(bad_anchor)} missing anchors"
168 + (f", {len(orphans)} unlinked docs pages" if args.orphans else "")
169 )
170 if args.strict and (broken or bad_anchor):
171 return 1
172 return 0
173
174
175 if __name__ == "__main__":
176 sys.exit(main())
177
177 lines PYTHON