#!/usr/bin/env python3 """Fail when a Markdown file links to a relative path that does not exist. Usage: doc-links-check.py """ import os import re import sys import urllib.parse SKIP_DIRS = {".git", "node_modules", "vendor"} FENCE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$") BACKTICKS = re.compile(r"`+") INLINE_DESTINATION = r"<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+" REFERENCE_DESTINATION = r"<[^>]*>|\S+" INLINE_LINK = re.compile(r"!?\[(?:[^\[\]]|\[[^\[\]]*\])*\]\(\s*(" + INLINE_DESTINATION + r")") REFERENCE = re.compile(r"^[ \t]{0,3}\[[^\]]+\]:\s*(" + REFERENCE_DESTINATION + r")", re.M) SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:") def mask_code_spans(text): runs = list(BACKTICKS.finditer(text)) masked = list(text) i = 0 while i < len(runs): opening = runs[i] start = opening.start() # Only prose escapes delimiters; backslashes inside code are literal. preceding = start while preceding > 0 and text[preceding - 1] == "\\": preceding -= 1 if (start - preceding) % 2: start += 1 width = opening.end() - start if not width: i += 1 continue closing = next((j for j in range(i + 1, len(runs)) if len(runs[j].group()) == width), None) if closing is None: i += 1 continue # Keep columns and non-whitespace line context as well as line numbers. for pos in range(start, runs[closing].end()): if text[pos] != "\n": masked[pos] = "\0" i = closing + 1 return "".join(masked) def paragraph_targets(first, lines): # A link label may wrap, so links are matched per paragraph. original = "\n".join(lines) text = mask_code_spans(original) # Masked bytes are context only, never a synthetic filesystem destination. found = [] for regex, syntax in ((INLINE_LINK, INLINE_DESTINATION), (REFERENCE, REFERENCE_DESTINATION)): for match in regex.finditer(text): target = original[match.start(1):match.end(1)] if re.fullmatch(syntax, target): found.append((match.start(), target)) for pos, target in sorted(found): yield first + text.count("\n", 0, pos), target def link_targets(text): fence, block, first = None, [], 1 for lineno, line in enumerate(text.splitlines() + [""], 1): m = FENCE.match(line) if fence is not None: # Only a fence of the same character, at least as long, closes it. if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not m.group(2).strip(): fence = None continue if m or not line.strip(): yield from paragraph_targets(first, block) block = [] if m: fence = m.group(1) continue if not block: first = lineno block.append(line) def local_path(target): if target.startswith("<") and target.endswith(">"): target = target[1:-1] if not target or target.startswith(("#", "//")) or SCHEME.match(target): return None path = urllib.parse.unquote(target.split("#", 1)[0].split("?", 1)[0]) return path or None def broken_links(root): root = os.path.abspath(root) for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS) for name in sorted(filenames): if not name.endswith(".md"): continue source = os.path.join(dirpath, name) with open(source, encoding="utf-8", errors="replace") as f: text = f.read() for lineno, target in link_targets(text): path = local_path(target) if path is None: continue if path.startswith("/"): resolved = os.path.join(root, path.lstrip("/")) else: resolved = os.path.join(dirpath, path) if not os.path.exists(resolved): yield os.path.relpath(source, root), lineno, target def main(argv): if len(argv) != 2: print(__doc__.strip(), file=sys.stderr) return 2 broken = list(broken_links(argv[1])) for source, lineno, target in broken: print(f"{source}:{lineno}: broken relative link {target}") return 1 if broken else 0 if __name__ == "__main__": sys.exit(main(sys.argv))