okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
1#!/usr/bin/env python3 2"""Local link check for the Markdown pages. 3 4python tools/check_links.py current pages: exit 1 if a local link points at a file that is not there 5python tools/check_links.py --anchors also fail on a #fragment that matches no heading or anchor in the target page 6python tools/check_links.py --baseline OUT write a report of the archived pages (history/, release notes, bench/results, ...) 7 8Local links only: http(s), mailto and other schemes are not fetched. Links inside code fences and inline code are skipped. 9Which pages are current and which are archived: tools/doc_pages.py. Standard library only. 10""" 11import argparse 12import os 13import re 14import sys 15from urllib .parse import unquote 16 17sys .path .insert (0 ,os .path .dirname (os .path .abspath (__file__ ))) 18import doc_pages # noqa: E402 19 20ROOT = doc_pages .ROOT 21FENCE = re .compile (r"^(\s*)(`{3,}|~{3,})" ) 22INLINE_CODE = re .compile (r"`+[^`\n]*`+" ) 23LINK = re .compile (r"!?\[(?:[^\[\]]|\[[^\]]*\])*\]\(\s*(<[^>]*>|[^)\s]*(?:\([^)\s]*\)[^)\s]*)*)(?:\s+(?:\"[^\"]*\"|'[^']*'))?\s*\)" ) 24REFDEF = re .compile (r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]*>|\S+)" ) 25HTML_ATTR = re .compile (r"""\b(?:href|src)\s*=\s*["']([^"']+)["']""" ,re .I ) 26SCHEME = re .compile (r"^[a-zA-Z][a-zA-Z0-9+.-]*:" ) 27 28 29def strip_code (text ,inline = True ): 30out ,fence = [],None 31for line in text .split ("\n" ): 32m = FENCE .match (line ) 33if m : 34if fence is None : 35fence = m .group (2 )[0 ] 36elif m .group (2 )[0 ]== fence : 37fence = None 38out .append ("" ) 39continue 40out .append ("" if fence else INLINE_CODE .sub (lambda x :" " * len (x .group (0 )),line )if inline else ("" if fence else line )) 41return out 42 43 44def targets (text ): 45"""(line number, raw target) for every link in a page.""" 46found = [] 47in_comment = False 48for n ,line in enumerate (strip_code (text ),1 ): 49if in_comment : 50if "-->" in line : 51in_comment ,line = False ,line .split ("-->" ,1 )[1 ] 52else : 53continue 54line = re .sub (r"<!--.*?-->" ,lambda m :" " * len (m .group (0 )),line ) 55if "<!--" in line : 56in_comment ,line = True ,line .split ("<!--" ,1 )[0 ] 57for rx in (LINK ,REFDEF ,HTML_ATTR ): 58for m in rx .finditer (line ): 59t = m .group (1 ).strip () 60if t .startswith ("<" )and t .endswith (">" ): 61t = t [1 :- 1 ] 62found .append ((n ,t )) 63return found 64 65 66def slug (heading ): 67h = re .sub (r"<[^>]+>" ,"" ,heading ).strip ().lower () 68h = re .sub (r"[`*~]" ,"" ,h ) 69h = re .sub (r"[^\w\- ]" ,"" ,h ,flags = re .U ) 70return h .replace (" " ,"-" ) 71 72 73_anchor_cache = {} 74 75 76def anchors (path ): 77if path in _anchor_cache : 78return _anchor_cache [path ] 79seen ,out = {},set () 80try : 81text = open (path ,encoding = "utf-8" ,errors = "replace" ).read () 82except OSError : 83text = "" 84for line in strip_code (text ,inline = False ): 85m = re .match (r"^\s{0,3}#{1,6}\s+(.*?)\s*#*\s*$" ,line ) 86if m : 87s = slug (m .group (1 )) 88k = seen .get (s ,0 ) 89seen [s ]= k + 1 90out .add (s if k == 0 else "%s-%d" % (s ,k )) 91for m in re .finditer (r"""<a\s+[^>]*?(?:id|name)\s*=\s*["']([^"']+)["']""" ,text ,re .I ): 92out .add (m .group (1 )) 93_anchor_cache [path ]= out 94return out 95 96 97def resolve (page ,target ): 98"""Absolute path a local target points at, or None when it is not a local file link.""" 99if not target or target .startswith ("#" )or SCHEME .match (target )or target .startswith ("//" ): 100return None 101path = unquote (target .split ("#" ,1 )[0 ].split ("?" ,1 )[0 ]) 102if not path : 103return None 104base = ROOT if path .startswith ("/" )else os .path .dirname (os .path .join (ROOT ,page )) 105return os .path .normpath (os .path .join (base ,path .lstrip ("/" )if path .startswith ("/" )else path )) 106 107 108def check_page (page ,want_anchors = False ): 109problems = [] 110with open (os .path .join (ROOT ,page ),encoding = "utf-8" ,errors = "replace" )as f : 111text = f .read () 112for n ,t in targets (text ): 113frag = unquote (t .split ("#" ,1 )[1 ])if "#" in t else "" 114dest = resolve (page ,t )if not t .startswith ("#" )else os .path .join (ROOT ,page ) 115if dest is None : 116continue 117if not os .path .exists (dest ): 118problems .append ((page ,n ,t ,"missing file" )) 119elif want_anchors and frag and dest .endswith (".md" )and os .path .isfile (dest ): 120if frag .lower ()not in {a .lower ()for a in anchors (dest )}and not re .match (r"^L\d+" ,frag ): 121problems .append ((page ,n ,t ,"no such heading or anchor" )) 122return problems 123 124 125def main (argv = None ): 126ap = argparse .ArgumentParser (description = __doc__ .split ("\n" )[0 ]) 127ap .add_argument ("--anchors" ,action = "store_true" ,help = "also check #fragments against the target page's headings" ) 128ap .add_argument ("--baseline" ,metavar = "OUT" ,help = "write a report of the archived pages to OUT and exit 0" ) 129args = ap .parse_args (argv ) 130if args .baseline : 131rows = [] 132for page ,archived in doc_pages .markdown_files (): 133if archived : 134rows += check_page (page ,False ) 135by = {} 136for page ,n ,t ,why in rows : 137by .setdefault (page , []).append ((n ,t )) 138lines = ["# Link baseline for archived pages" ,"" , 139"Local links in archived pages (history/, release notes, bench/results, phaseA-tests) whose target file is missing, as of the commit that wrote this file." , 140"Archived pages are not fixed: they keep the links they had, and evidence they pointed to that was never published stays missing." , 141"`python tools/check_links.py --baseline <file>` rebuilds this report. %d missing targets in %d pages." % (len (rows ),len (by )),"" , 142"| Page | Missing local targets |" ,"| --- | ---: |" ] 143lines += ["| %s | %d |" % (p ,len (v ))for p ,v in sorted (by .items (),key = lambda kv : (- len (kv [1 ]),kv [0 ]))] 144with open (args .baseline ,"w" ,encoding = "utf-8" ,newline = "\n" )as f : 145f .write ("\n" .join (lines )+ "\n" ) 146"baseline: %d missing targets in %d archived pages -> %s" % (len (rows ),len (by ),args .baseline )) 147return 0 148pages = doc_pages .current_pages () 149problems = [] 150for page in pages : 151problems += check_page (page ,args .anchors ) 152for page ,n ,t ,why in problems : 153"FAIL %s:%d (%s) %s" % (page ,n ,t ,why )) 154"link check: %d current pages, %s" % (len (pages ),"%d broken local link(s)" % len (problems )if problems else "all local links resolve" )) 155return 1 if problems else 0 156 157 158if __name__ == "__main__" : 159sys .exit (main ())