#!/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,})(.*)$") INLINE_CODE = re.compile(r"(`+)(?:(?!\1).)+?\1", re.S) INLINE_LINK = re.compile(r"!?\[(?:[^\[\]]|\[[^\[\]]*\])*\]\(\s*(<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+)") REFERENCE = re.compile(r"^[ \t]{0,3}\[[^\]]+\]:\s*(<[^>]*>|\S+)", re.M) SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:") def paragraph_targets(first, lines): # A link label may wrap, so links are matched per paragraph. text = INLINE_CODE.sub(lambda m: "\n" * m.group().count("\n"), "\n".join(lines)) found = [(m.start(), m.group(1)) for regex in (INLINE_LINK, REFERENCE) for m in regex.finditer(text)] 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))