#!/usr/bin/env python3 """Check local Markdown links, anchors and canonical R/D identifiers (Python 3.9+).""" from collections import defaultdict import html import os from pathlib import Path import re import sys from urllib.parse import unquote, urlsplit SKIP = {".git", "bin", "obj", ".artifacts", "node_modules"} IDENTIFIER = re.compile(r"\b[RD][0-9]+\b") LINK = re.compile(r"!?\[[^\]\n]*\]\((<[^>\n]+>|[^()\s]*(?:\([^()\s]*\)[^()\s]*)*)(?:\s+[\"'][^\n]*?[\"'])?\)") REFERENCE = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)") def markdown_files(root): """Skip build output, symlinks and nested repositories (including worktrees).""" for directory, directories, files in os.walk(root): directories[:] = sorted(name for name in directories if name not in SKIP and not os.path.islink(os.path.join(directory, name)) and not os.path.lexists(os.path.join(directory, name, ".git"))) for name in sorted(files): if name.lower().endswith(".md"): yield Path(directory) / name def prose_lines(text): """Ignore fenced code while preserving original line numbers.""" fence = None for number, line in enumerate(text.splitlines(), 1): marker = re.match(r"^\s*(`{3,}|~{3,})(.*)$", line) if fence is None and marker: fence = marker.group(1) yield number, "" elif fence is not None: if marker and marker.group(1)[0] == fence[0] and len(marker.group(1)) >= len(fence) and not marker.group(2).strip(): fence = None yield number, "" else: yield number, line def anchors(text): found, used = set(), set() previous = "" for _, line in prose_lines(text): for tag in re.findall(r"]*>", line, re.IGNORECASE): found.update(html.unescape(match[1]) for match in re.findall( r"\b(?:id|name)\s*=\s*([\"'])(.*?)\1", tag, re.IGNORECASE)) match = re.match(r"^\s{0,3}#{1,6}\s+(.+?)(?:\s+#+)?\s*$", line) heading = match.group(1) if match else None if heading is None and previous.strip() and re.fullmatch(r"\s{0,3}(?:=+|-+)\s*", line): heading = previous.strip() if heading is not None: value = re.sub(r"!?\[([^\]]+)\]\([^)]*\)", r"\1", heading) value = html.unescape(re.sub(r"<[^>]*>", "", value)).lower() value = "".join(c for c in value if c.isalnum() or c in "- ").replace(" ", "-") candidate, suffix = value, 0 while candidate in used: suffix += 1 candidate = f"{value}-{suffix}" used.add(candidate) found.add(candidate) previous = line return found def check(root): root = Path(root).resolve() errors, definitions, references, anchor_cache = [], defaultdict(list), [], {} for path in markdown_files(root): relative = path.relative_to(root).as_posix() for number, line in prose_lines(path.read_text(encoding="utf-8-sig")): where = f"{relative}:{number}" definition = None if relative == "docs/requirements.md": definition = re.match(r"^- \*\*(R[0-9]+)\*\*", line) elif relative == "docs/decisions.md": definition = re.match(r"^## (D[0-9]+) —\s+", line) if definition: definitions[definition.group(1)].append(where) references.extend((identifier, where) for identifier in IDENTIFIER.findall(line)) targets = [match.group(1) for match in LINK.finditer(line)] reference = REFERENCE.match(line) if reference: targets.append(reference.group(1)) for raw in targets: target = raw.strip("<>") try: parts = urlsplit(target) except ValueError: errors.append(f"{where}: malformed link: {target}") continue if parts.scheme or parts.netloc: continue destination = (path.parent / unquote(parts.path)).resolve() if parts.path else path if not destination.exists(): errors.append(f"{where}: broken link: {target}") elif parts.fragment: if destination not in anchor_cache: anchor_cache[destination] = (anchors(destination.read_text(encoding="utf-8-sig")) if destination.is_file() and destination.suffix.lower() == ".md" else set()) if unquote(parts.fragment) not in anchor_cache[destination]: errors.append(f"{where}: missing anchor: {target}") for identifier, places in sorted(definitions.items()): if len(places) > 1: errors.extend(f"{where}: identifier {identifier} is defined more than once ({', '.join(places)})" for where in places) for identifier, where in references: if identifier not in definitions: errors.append(f"{where}: undefined identifier {identifier}") return errors def main(): errors = check(Path(__file__).resolve().parents[2]) for error in errors: print(error) print(f"documentation check: {len(errors)} error(s)") return 1 if errors else 0 if __name__ == "__main__": sys.exit(main())