#!/usr/bin/env python3 """Check local Markdown file and anchor links without network access.""" from __future__ import annotations import argparse from dataclasses import dataclass import html import os from pathlib import Path import re import sys import unicodedata from urllib.parse import unquote, urlsplit @dataclass(frozen=True) class MarkdownLink: source: Path line: int target: str @dataclass(frozen=True) class Diagnostic: source: Path line: int target: str reason: str _FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})") _REFERENCE_DEFINITION = re.compile(r"^ {0,3}\[([^]]+)\]:[ \t]*(.*)$") _ATX_HEADING = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*)|[ \t]*)$") _SETEXT_HEADING = re.compile(r"^ {0,3}(?:=+|-+)[ \t]*$") _HTML_ID = re.compile( r"<[^>]+\s(?:id|name)\s*=\s*(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))[^>]*>", re.IGNORECASE, ) _TITLE_TEXT = r'(?:"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|\((?:[^)\\]|\\.)*\))' _TITLE = re.compile(rf'^(.*?)(?:[ \t]+{_TITLE_TEXT})?$', re.DOTALL) _TITLE_ONLY = re.compile(rf'^{_TITLE_TEXT}$', re.DOTALL) _BACKSLASH_ESCAPE = re.compile(r"\\([!\"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~])") def _is_escaped(text: str, index: int) -> bool: backslashes = 0 index -= 1 while index >= 0 and text[index] == "\\": backslashes += 1 index -= 1 return backslashes % 2 == 1 def _without_code_spans(line: str) -> str: result = list(line) index = 0 while index < len(line): if line[index] != "`" or _is_escaped(line, index): index += 1 continue end = index while end < len(line) and line[end] == "`": end += 1 delimiter = line[index:end] closing = line.find(delimiter, end) if closing < 0: index = end continue for position in range(index, closing + len(delimiter)): if result[position] != "\n": result[position] = " " index = closing + len(delimiter) return "".join(result) def _matching_delimiter( text: str, start: int, opening: str, closing: str ) -> int | None: depth = 0 in_angle_destination = False for index in range(start, len(text)): char = text[index] if _is_escaped(text, index): continue if opening == "(" and char == "<" and depth == 1: in_angle_destination = True elif in_angle_destination and char == ">": in_angle_destination = False elif not in_angle_destination and char == opening: depth += 1 elif not in_angle_destination and char == closing: depth -= 1 if depth == 0: return index return None def _unescape(target: str) -> str: return _BACKSLASH_ESCAPE.sub(r"\1", target) def _destination(contents: str) -> str | None: contents = contents.strip() if contents.startswith("<"): index = 1 while index < len(contents): if contents[index] == ">" and not _is_escaped(contents, index): rest = contents[index + 1 :].strip() if rest and not _TITLE_ONLY.fullmatch(rest): return None return _unescape(contents[1:index]) if contents[index] == "\n": return None index += 1 return None match = _TITLE.fullmatch(contents) if match is None: return None destination = match.group(1).strip() if any(char in destination for char in "\r\n"): return None return _unescape(destination) def _normalise_label(label: str) -> str: return " ".join(label.split()).casefold() def _links_in_file(path: Path) -> list[MarkdownLink]: text = path.read_text(encoding="utf-8", errors="replace") lines = text.splitlines() definitions: dict[str, str] = {} references: list[tuple[int, str, str]] = [] links: list[MarkdownLink] = [] fence: str | None = None for line_number, original in enumerate(lines, start=1): fence_match = _FENCE.match(original) if fence is not None: if fence_match and fence_match.group(1)[0] == fence[0]: fence = None continue if fence_match: fence = fence_match.group(1) continue line = _without_code_spans(original) definition = _REFERENCE_DEFINITION.match(line) if definition: target = _destination(definition.group(2)) if target is not None: definitions[_normalise_label(definition.group(1))] = target continue index = 0 while index < len(line): if line[index] != "[" or _is_escaped(line, index): index += 1 continue label_end = _matching_delimiter(line, index, "[", "]") if label_end is None: index += 1 continue label = original[index + 1 : label_end] following = label_end + 1 if following < len(line) and line[following] == "(": target_end = _matching_delimiter(line, following, "(", ")") if target_end is None: index = label_end + 1 continue target = _destination(original[following + 1 : target_end]) if target is not None: links.append(MarkdownLink(path, line_number, target)) index = target_end + 1 continue if following < len(line) and line[following] == "[": reference_end = _matching_delimiter(line, following, "[", "]") if reference_end is None: index = label_end + 1 continue reference_label = original[following + 1 : reference_end] or label references.append((line_number, label, reference_label)) index = reference_end + 1 continue references.append((line_number, label, label)) index = label_end + 1 for line_number, _label, reference_label in references: target = definitions.get(_normalise_label(reference_label)) if target is not None: links.append(MarkdownLink(path, line_number, target)) return links def _heading_text(text: str) -> str: previous = None while previous != text: previous = text text = re.sub(r"!?\[([^]]*)\]\([^)]*\)", r"\1", text) text = re.sub(r"!?\[([^]]*)\]\[[^]]*\]", r"\1", text) text = re.sub(r"<[^>]*>", "", text) return html.unescape(_unescape(text)) def _slug(text: str) -> str: text = _heading_text(text).lower() kept = [] for char in text: category = unicodedata.category(char) if char.isalnum() or char in "_-" or char.isspace() or category.startswith("M"): kept.append(char) return re.sub(r"\s", "-", "".join(kept)) def _anchors(path: Path) -> set[str]: text = path.read_text(encoding="utf-8", errors="replace") lines = text.splitlines() anchors: set[str] = set() occurrences: dict[str, int] = {} fence: str | None = None def add_heading(heading: str) -> None: base = _slug(heading.strip()) count = occurrences.get(base, 0) occurrences[base] = count + 1 anchors.add(base if count == 0 else f"{base}-{count}") for index, original in enumerate(lines): fence_match = _FENCE.match(original) if fence is not None: if fence_match and fence_match.group(1)[0] == fence[0]: fence = None continue if fence_match: fence = fence_match.group(1) continue for match in _HTML_ID.finditer(original): anchors.add(next(group for group in match.groups() if group is not None)) heading = _ATX_HEADING.match(original) if heading: title = re.sub(r"[ \t]+#+[ \t]*$", "", heading.group(2) or "") add_heading(title) elif ( index > 0 and _SETEXT_HEADING.match(original) and lines[index - 1].strip() and not _FENCE.match(lines[index - 1]) ): add_heading(lines[index - 1]) return anchors def _relative_source(root: Path, source: Path) -> str: return source.resolve().relative_to(root).as_posix() def _check_link( root: Path, link: MarkdownLink, anchor_cache: dict[Path, set[str]] ) -> Diagnostic | None: target = link.target if re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", target): return None try: parsed = urlsplit(target) except ValueError as error: return Diagnostic(link.source, link.line, target, f"malformed target: {error}") try: decoded_path = unquote(parsed.path) fragment = unquote(parsed.fragment) except (UnicodeError, ValueError) as error: return Diagnostic(link.source, link.line, target, f"invalid URL encoding: {error}") if decoded_path.startswith("/"): return None try: if decoded_path: destination = (link.source.parent / decoded_path).resolve() destination.relative_to(root) else: destination = link.source.resolve() except (OSError, RuntimeError, ValueError): return Diagnostic(link.source, link.line, target, "target is outside root or invalid") if not destination.exists(): return Diagnostic(link.source, link.line, target, "target does not exist") if not destination.is_file() and not destination.is_dir(): return Diagnostic(link.source, link.line, target, "target is not a file or directory") if not fragment: return None if not destination.is_file() or destination.suffix.lower() not in {".md", ".markdown"}: return None try: if destination not in anchor_cache: anchor_cache[destination] = _anchors(destination) except OSError as error: return Diagnostic(link.source, link.line, target, f"cannot read target: {error}") if fragment not in anchor_cache[destination]: return Diagnostic(link.source, link.line, target, "anchor does not exist") return None def _markdown_files(root: Path, paths: list[Path]) -> list[Path]: selected = paths or [Path()] files: set[Path] = set() for selected_path in selected: path = (root / selected_path).resolve() path.relative_to(root) if path.is_file(): if path.suffix.lower() in {".md", ".markdown"}: files.add(path) continue if not path.is_dir(): raise ValueError(f"input path does not exist: {selected_path}") for directory, directory_names, file_names in os.walk(path): directory_names[:] = [ name for name in directory_names if name not in {".git", ".claude", "node_modules", "target"} ] for name in file_names: candidate = Path(directory) / name if candidate.suffix.lower() in {".md", ".markdown"}: files.add(candidate.resolve()) return sorted(files, key=lambda path: path.relative_to(root).as_posix()) def _parse_allowlist(values: list[str]) -> set[tuple[str, str]]: allowlist: set[tuple[str, str]] = set() for value in values: source, separator, target = value.partition("=") if not separator or not source or not target: raise ValueError(f"allowlist entry must be SOURCE=TARGET: {value!r}") source_path = Path(source) if source_path.is_absolute() or ".." in source_path.parts: raise ValueError(f"allowlist source must be a root-relative file: {source!r}") normalised_source = source_path.as_posix() if normalised_source.startswith("./"): normalised_source = normalised_source[2:] allowlist.add((normalised_source, target)) return allowlist def check( root: Path, paths: list[Path] | None = None, allowlist: set[tuple[str, str]] | None = None ) -> tuple[list[Diagnostic], int, int]: root = root.resolve() allowed = allowlist or set() diagnostics: list[Diagnostic] = [] anchor_cache: dict[Path, set[str]] = {} files = _markdown_files(root, paths or []) link_count = 0 for source in files: try: links = _links_in_file(source) except OSError as error: diagnostics.append(Diagnostic(source, 1, source.name, f"cannot read source: {error}")) continue for link in links: source_name = _relative_source(root, source) if (source_name, link.target) in allowed: continue link_count += 1 diagnostic = _check_link(root, link, anchor_cache) if diagnostic is not None: diagnostics.append(diagnostic) return diagnostics, len(files), link_count def _argument_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Check local Markdown file and anchor links; never accesses the network." ) parser.add_argument("--root", type=Path, required=True, help="repository or public-tree root") parser.add_argument( "paths", nargs="*", type=Path, help="root-relative Markdown files or directories (default: the whole root)", ) parser.add_argument( "--allow", action="append", default=[], metavar="SOURCE=TARGET", help="allow one exact root-relative source and raw target pair (repeatable)", ) parser.add_argument( "--public", action="store_true", help="public-tree mode: historical allowlist entries are forbidden", ) return parser def main(argv: list[str] | None = None) -> int: parser = _argument_parser() arguments = parser.parse_args(argv) if arguments.public and arguments.allow: parser.error("--public does not permit --allow exceptions") root = arguments.root.resolve() if not root.is_dir(): parser.error(f"root is not a directory: {arguments.root}") try: allowlist = _parse_allowlist(arguments.allow) diagnostics, file_count, link_count = check(root, arguments.paths, allowlist) except (OSError, ValueError) as error: parser.error(str(error)) for diagnostic in diagnostics: source = _relative_source(root, diagnostic.source) print(f"{source}:{diagnostic.line} → {diagnostic.target} ({diagnostic.reason})") print( f"Checked {file_count} Markdown files, examined {link_count} non-allowlisted links; " f"{len(diagnostics)} broken links." ) return 1 if diagnostics else 0 if __name__ == "__main__": sys.exit(main())