okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
6.7 KiB159 linesraw
1#!/usr/bin/env python3
2"""Local link check for the Markdown pages.
3
4    python tools/check_links.py                  current pages: exit 1 if a local link points at a file that is not there
5    python tools/check_links.py --anchors        also fail on a #fragment that matches no heading or anchor in the target page
6    python 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):
30    out, fence = [], None
31    for line in text.split("\n"):
32        m = FENCE.match(line)
33        if m:
34            if fence is None:
35                fence = m.group(2)[0]
36            elif m.group(2)[0] == fence:
37                fence = None
38            out.append("")
39            continue
40        out.append("" if fence else INLINE_CODE.sub(lambda x: " " * len(x.group(0)), line) if inline else ("" if fence else line))
41    return out
42
43
44def targets(text):
45    """(line number, raw target) for every link in a page."""
46    found = []
47    in_comment = False
48    for n, line in enumerate(strip_code(text), 1):
49        if in_comment:
50            if "-->" in line:
51                in_comment, line = False, line.split("-->", 1)[1]
52            else:
53                continue
54        line = re.sub(r"<!--.*?-->", lambda m: " " * len(m.group(0)), line)
55        if "<!--" in line:
56            in_comment, line = True, line.split("<!--", 1)[0]
57        for rx in (LINK, REFDEF, HTML_ATTR):
58            for m in rx.finditer(line):
59                t = m.group(1).strip()
60                if t.startswith("<") and t.endswith(">"):
61                    t = t[1:-1]
62                found.append((n, t))
63    return found
64
65
66def slug(heading):
67    h = re.sub(r"<[^>]+>", "", heading).strip().lower()
68    h = re.sub(r"[`*~]", "", h)
69    h = re.sub(r"[^\w\- ]", "", h, flags=re.U)
70    return h.replace(" ", "-")
71
72
73_anchor_cache = {}
74
75
76def anchors(path):
77    if path in _anchor_cache:
78        return _anchor_cache[path]
79    seen, out = {}, set()
80    try:
81        text = open(path, encoding="utf-8", errors="replace").read()
82    except OSError:
83        text = ""
84    for line in strip_code(text, inline=False):
85        m = re.match(r"^\s{0,3}#{1,6}\s+(.*?)\s*#*\s*$", line)
86        if m:
87            s = slug(m.group(1))
88            k = seen.get(s, 0)
89            seen[s] = k + 1
90            out.add(s if k == 0 else "%s-%d" % (s, k))
91    for m in re.finditer(r"""<a\s+[^>]*?(?:id|name)\s*=\s*["']([^"']+)["']""", text, re.I):
92        out.add(m.group(1))
93    _anchor_cache[path] = out
94    return 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."""
99    if not target or target.startswith("#") or SCHEME.match(target) or target.startswith("//"):
100        return None
101    path = unquote(target.split("#", 1)[0].split("?", 1)[0])
102    if not path:
103        return None
104    base = ROOT if path.startswith("/") else os.path.dirname(os.path.join(ROOT, page))
105    return os.path.normpath(os.path.join(base, path.lstrip("/") if path.startswith("/") else path))
106
107
108def check_page(page, want_anchors=False):
109    problems = []
110    with open(os.path.join(ROOT, page), encoding="utf-8", errors="replace") as f:
111        text = f.read()
112    for n, t in targets(text):
113        frag = unquote(t.split("#", 1)[1]) if "#" in t else ""
114        dest = resolve(page, t) if not t.startswith("#") else os.path.join(ROOT, page)
115        if dest is None:
116            continue
117        if not os.path.exists(dest):
118            problems.append((page, n, t, "missing file"))
119        elif want_anchors and frag and dest.endswith(".md") and os.path.isfile(dest):
120            if frag.lower() not in {a.lower() for a in anchors(dest)} and not re.match(r"^L\d+", frag):
121                problems.append((page, n, t, "no such heading or anchor"))
122    return problems
123
124
125def main(argv=None):
126    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
127    ap.add_argument("--anchors", action="store_true", help="also check #fragments against the target page's headings")
128    ap.add_argument("--baseline", metavar="OUT", help="write a report of the archived pages to OUT and exit 0")
129    args = ap.parse_args(argv)
130    if args.baseline:
131        rows = []
132        for page, archived in doc_pages.markdown_files():
133            if archived:
134                rows += check_page(page, False)
135        by = {}
136        for page, n, t, why in rows:
137            by.setdefault(page, []).append((n, t))
138        lines = ["# 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 |", "| --- | ---: |"]
143        lines += ["| %s | %d |" % (p, len(v)) for p, v in sorted(by.items(), key=lambda kv: (-len(kv[1]), kv[0]))]
144        with open(args.baseline, "w", encoding="utf-8", newline="\n") as f:
145            f.write("\n".join(lines) + "\n")
146        print("baseline: %d missing targets in %d archived pages -> %s" % (len(rows), len(by), args.baseline))
147        return 0
148    pages = doc_pages.current_pages()
149    problems = []
150    for page in pages:
151        problems += check_page(page, args.anchors)
152    for page, n, t, why in problems:
153        print("FAIL %s:%d  (%s)  %s" % (page, n, t, why))
154    print("link check: %d current pages, %s" % (len(pages), "%d broken local link(s)" % len(problems) if problems else "all local links resolve"))
155    return 1 if problems else 0
156
157
158if __name__ == "__main__":
159    sys.exit(main())