pagetop-website/tools/doccheck/check_links.py
Manuel Cillero 1a41a456d4 ✨ Serve the PageTop guides with pagetop-mdbook
Rebuild the website on the current PageTop API, with Bootsier as its
theme and edition 2024. Add the first Spanish guide (doc/v0.6/es) as an
mdBook book, built in build.rs and served with pagetop-mdbook, and the
/doc/latest/{lang} redirect.

Add `tools/doccheck.sh` to check the links of the guides and to compile,
run and test their examples against PageTop.

Move the configuration to config/common.toml and translate the README
to English.
2026-10-17 08:06:02 +02:00

37 lines
1.3 KiB
Python

"""Checks the internal links (pages and anchors) of a book built by mdBook.
Usage: check_links.py <built book dir>. Exits with 1 if any link is broken.
"""
import pathlib
import posixpath
import re
import sys
import urllib.parse
def main():
out = pathlib.Path(sys.argv[1])
pages = {p.relative_to(out).as_posix(): p.read_text() for p in out.rglob("*.html")}
ids = {name: set(re.findall(r'id="([^"]+)"', html)) for name, html in pages.items()}
broken = 0
for name, html in pages.items():
content = html[html.find("<main>") : html.find("</main>")]
for link, anchor in re.findall(r'href="([^"#:]*\.html)(?:#([^"]*))?"', content):
page = posixpath.normpath(posixpath.join(posixpath.dirname(name), link))
if page not in ids:
print(f"{name}: missing page {page}")
broken += 1
elif anchor and urllib.parse.unquote(anchor) not in ids[page]:
print(f"{name}: missing anchor {page}#{urllib.parse.unquote(anchor)}")
broken += 1
for anchor in re.findall(r'href="#([^"]+)"', content):
if urllib.parse.unquote(anchor) not in ids[name]:
print(f"{name}: missing anchor #{anchor}")
broken += 1
print(f"{broken} broken links")
sys.exit(1 if broken else 0)
if __name__ == "__main__":
main()