#!/usr/bin/env python3 """Checks relative links (and #anchors) in the repository's Markdown files. scripts/check-docs-links.py """ import os, re, sys root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) files = [] for base in (root, os.path.join(root, "docs"), os.path.join(root, "docs", "pt-BR")): files += [os.path.join(base, f) for f in sorted(os.listdir(base)) if f.endswith(".md")] def slug(h): h = re.sub(r"`", "", h.strip().lower()) h = re.sub(r"[^\w\s-]", "", h, flags=re.UNICODE) return re.sub(r"\s", "-", h) def anchors(path): out, fence = set(), False for line in open(path, encoding="utf-8"): if line.startswith("```"): fence = not fence m = re.match(r"^#{1,6}\s+(.*)", line) if m and not fence: out.add(slug(m.group(1))) return out bad = 0 for f in files: text = open(f, encoding="utf-8").read() for m in re.finditer(r'(?:\]\(|href=")([^)"\s]+)', text): link = m.group(1) if re.match(r"^[a-z]+:", link) or link.startswith("mailto"): continue path, _, frag = link.partition("#") target = f if not path else os.path.normpath(os.path.join(os.path.dirname(f), path)) if not os.path.exists(target): print(f"{os.path.relpath(f, root)}: missing file {link}"); bad += 1; continue if frag and target.endswith(".md") and frag not in anchors(target): print(f"{os.path.relpath(f, root)}: missing anchor {link}"); bad += 1 print("links ok" if not bad else f"{bad} broken link(s)") sys.exit(1 if bad else 0)