#!/usr/bin/env python3 """Local link check for the Markdown pages. python tools/check_links.py current pages: exit 1 if a local link points at a file that is not there python tools/check_links.py --anchors also fail on a #fragment that matches no heading or anchor in the target page python tools/check_links.py --baseline OUT write a report of the archived pages (history/, release notes, bench/results, ...) Local links only: http(s), mailto and other schemes are not fetched. Links inside code fences and inline code are skipped. Which pages are current and which are archived: tools/doc_pages.py. Standard library only. """ import argparse import os import re import sys from urllib.parse import unquote sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import doc_pages # noqa: E402 ROOT = doc_pages.ROOT FENCE = re.compile(r"^(\s*)(`{3,}|~{3,})") INLINE_CODE = re.compile(r"`+[^`\n]*`+") LINK = re.compile(r"!?\[(?:[^\[\]]|\[[^\]]*\])*\]\(\s*(<[^>]*>|[^)\s]*(?:\([^)\s]*\)[^)\s]*)*)(?:\s+(?:\"[^\"]*\"|'[^']*'))?\s*\)") REFDEF = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]*>|\S+)") HTML_ATTR = re.compile(r"""\b(?:href|src)\s*=\s*["']([^"']+)["']""", re.I) SCHEME = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:") def strip_code(text, inline=True): out, fence = [], None for line in text.split("\n"): m = FENCE.match(line) if m: if fence is None: fence = m.group(2)[0] elif m.group(2)[0] == fence: fence = None out.append("") continue out.append("" if fence else INLINE_CODE.sub(lambda x: " " * len(x.group(0)), line) if inline else ("" if fence else line)) return out def targets(text): """(line number, raw target) for every link in a page.""" found = [] in_comment = False for n, line in enumerate(strip_code(text), 1): if in_comment: if "-->" in line: in_comment, line = False, line.split("-->", 1)[1] else: continue line = re.sub(r"", lambda m: " " * len(m.group(0)), line) if "