|
| 1 | +# |
| 2 | +# SPDX-FileCopyrightText: 2026 John Samuel <johnsamuelwrites@gmail.com> |
| 3 | +# |
| 4 | +# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 | +# |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import json |
| 10 | +import re |
| 11 | +import sys |
| 12 | +from html.parser import HTMLParser |
| 13 | +from pathlib import Path |
| 14 | +from urllib.parse import urlsplit |
| 15 | + |
| 16 | + |
| 17 | +ROOT = Path(__file__).resolve().parents[1] |
| 18 | +MARKDOWN_PATHS = sorted(ROOT.glob("*.md")) |
| 19 | +HTML_PATHS = [ROOT / "index.html"] |
| 20 | +MANIFEST_PATH = ROOT / "site.webmanifest" |
| 21 | +MARKDOWN_LINK_RE = re.compile(r"\[[^\]]+\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)") |
| 22 | + |
| 23 | + |
| 24 | +def is_external(target: str) -> bool: |
| 25 | + return target.startswith(("http://", "https://", "mailto:", "tel:", "javascript:")) or target == "" |
| 26 | + |
| 27 | + |
| 28 | +def normalize_manifest_path(target: str) -> str: |
| 29 | + if target.startswith("/playground/"): |
| 30 | + return target.removeprefix("/playground/") |
| 31 | + if target.startswith("/"): |
| 32 | + return target.lstrip("/") |
| 33 | + return target |
| 34 | + |
| 35 | + |
| 36 | +def resolve_local_target(target: str, source_path: Path) -> tuple[Path | None, str | None]: |
| 37 | + parsed = urlsplit(target) |
| 38 | + raw_path = parsed.path |
| 39 | + fragment = parsed.fragment or None |
| 40 | + |
| 41 | + if not raw_path: |
| 42 | + return source_path, fragment |
| 43 | + |
| 44 | + if source_path == MANIFEST_PATH: |
| 45 | + raw_path = normalize_manifest_path(raw_path) |
| 46 | + |
| 47 | + if raw_path.startswith("/"): |
| 48 | + candidate = ROOT / raw_path.lstrip("/") |
| 49 | + else: |
| 50 | + candidate = source_path.parent / raw_path |
| 51 | + |
| 52 | + return candidate.resolve(), fragment |
| 53 | + |
| 54 | + |
| 55 | +def path_exists(candidate: Path) -> bool: |
| 56 | + return candidate.exists() or candidate.is_dir() |
| 57 | + |
| 58 | + |
| 59 | +def heading_slug(text: str) -> str: |
| 60 | + slug = text.strip().lower() |
| 61 | + slug = re.sub(r"[`*_]+", "", slug) |
| 62 | + slug = re.sub(r"[^\w\s-]", "", slug, flags=re.UNICODE) |
| 63 | + slug = re.sub(r"\s+", "-", slug, flags=re.UNICODE) |
| 64 | + slug = re.sub(r"-{2,}", "-", slug).strip("-") |
| 65 | + return slug |
| 66 | + |
| 67 | + |
| 68 | +def collect_markdown_anchors(path: Path) -> set[str]: |
| 69 | + anchors: set[str] = set() |
| 70 | + for line in path.read_text(encoding="utf-8").splitlines(): |
| 71 | + match = re.match(r"^(#{1,6})\s+(.*)$", line.strip()) |
| 72 | + if not match: |
| 73 | + continue |
| 74 | + slug = heading_slug(match.group(2)) |
| 75 | + if slug: |
| 76 | + anchors.add(slug) |
| 77 | + return anchors |
| 78 | + |
| 79 | + |
| 80 | +class LinkHTMLParser(HTMLParser): |
| 81 | + def __init__(self) -> None: |
| 82 | + super().__init__() |
| 83 | + self.links: list[str] = [] |
| 84 | + self.anchors: set[str] = set() |
| 85 | + |
| 86 | + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: |
| 87 | + attr_map = dict(attrs) |
| 88 | + |
| 89 | + if tag == "a" and attr_map.get("href"): |
| 90 | + self.links.append(attr_map["href"]) |
| 91 | + if tag == "link" and attr_map.get("href"): |
| 92 | + self.links.append(attr_map["href"]) |
| 93 | + if tag in {"script", "img"} and attr_map.get("src"): |
| 94 | + self.links.append(attr_map["src"]) |
| 95 | + |
| 96 | + for key in ("id", "name"): |
| 97 | + value = attr_map.get(key) |
| 98 | + if value: |
| 99 | + self.anchors.add(value) |
| 100 | + |
| 101 | + |
| 102 | +def collect_html_anchors(path: Path) -> set[str]: |
| 103 | + parser = LinkHTMLParser() |
| 104 | + parser.feed(path.read_text(encoding="utf-8")) |
| 105 | + return parser.anchors |
| 106 | + |
| 107 | + |
| 108 | +def collect_html_links(path: Path) -> list[str]: |
| 109 | + parser = LinkHTMLParser() |
| 110 | + parser.feed(path.read_text(encoding="utf-8")) |
| 111 | + return parser.links |
| 112 | + |
| 113 | + |
| 114 | +def extract_markdown_links(path: Path) -> list[str]: |
| 115 | + return [match.group(1) for match in MARKDOWN_LINK_RE.finditer(path.read_text(encoding="utf-8"))] |
| 116 | + |
| 117 | + |
| 118 | +def validate_target(target: str, source_path: Path, errors: list[str]) -> None: |
| 119 | + if is_external(target): |
| 120 | + return |
| 121 | + |
| 122 | + if target.startswith("#"): |
| 123 | + fragment = target[1:] |
| 124 | + anchors = collect_markdown_anchors(source_path) if source_path.suffix == ".md" else collect_html_anchors(source_path) |
| 125 | + if fragment not in anchors: |
| 126 | + errors.append(f"{source_path.relative_to(ROOT)} -> missing local anchor #{fragment}") |
| 127 | + return |
| 128 | + |
| 129 | + candidate, fragment = resolve_local_target(target, source_path) |
| 130 | + if candidate is None or not path_exists(candidate): |
| 131 | + errors.append(f"{source_path.relative_to(ROOT)} -> missing target {target}") |
| 132 | + return |
| 133 | + |
| 134 | + if fragment: |
| 135 | + if candidate.suffix == ".md": |
| 136 | + anchors = collect_markdown_anchors(candidate) |
| 137 | + elif candidate.suffix in {".html", ".htm"}: |
| 138 | + anchors = collect_html_anchors(candidate) |
| 139 | + else: |
| 140 | + anchors = set() |
| 141 | + |
| 142 | + if anchors and fragment not in anchors: |
| 143 | + errors.append(f"{source_path.relative_to(ROOT)} -> missing anchor #{fragment} in {candidate.relative_to(ROOT)}") |
| 144 | + |
| 145 | + |
| 146 | +def main() -> int: |
| 147 | + if hasattr(sys.stdout, "reconfigure"): |
| 148 | + sys.stdout.reconfigure(encoding="utf-8") |
| 149 | + if hasattr(sys.stderr, "reconfigure"): |
| 150 | + sys.stderr.reconfigure(encoding="utf-8") |
| 151 | + |
| 152 | + errors: list[str] = [] |
| 153 | + |
| 154 | + for path in MARKDOWN_PATHS: |
| 155 | + for target in extract_markdown_links(path): |
| 156 | + validate_target(target, path, errors) |
| 157 | + |
| 158 | + for path in HTML_PATHS: |
| 159 | + for target in collect_html_links(path): |
| 160 | + validate_target(target, path, errors) |
| 161 | + |
| 162 | + manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8")) |
| 163 | + for icon in manifest.get("icons", []): |
| 164 | + src = icon.get("src", "") |
| 165 | + if src: |
| 166 | + validate_target(src, MANIFEST_PATH, errors) |
| 167 | + |
| 168 | + if errors: |
| 169 | + for error in errors: |
| 170 | + print(f"ERROR: {error}") |
| 171 | + return 1 |
| 172 | + |
| 173 | + print("Link checks passed.") |
| 174 | + print(f"Markdown files checked: {len(MARKDOWN_PATHS)}") |
| 175 | + print(f"HTML files checked: {len(HTML_PATHS)}") |
| 176 | + print(f"Manifest icons checked: {len(manifest.get('icons', []))}") |
| 177 | + return 0 |
| 178 | + |
| 179 | + |
| 180 | +if __name__ == "__main__": |
| 181 | + raise SystemExit(main()) |
0 commit comments