check-links.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env python3
  2. """Check every internal link, image, script and #anchor of the built site (website/**/index.html).
  3. python3 website/_src/check-links.py exit 1 if something points nowhere
  4. """
  5. import json
  6. import re
  7. import sys
  8. from pathlib import Path
  9. OUT = Path(__file__).resolve().parent.parent
  10. pages = {("/" + str(p.parent.relative_to(OUT)).replace(".", "") + "/").replace("//", "/"): p.read_text(encoding="utf-8")
  11. for p in sorted(OUT.glob("**/index.html")) if "_src" not in p.parts}
  12. ids = {u: set(re.findall(r'\bid="([^"]+)"', t)) for u, t in pages.items()}
  13. # the tutorial videos live on the `media` branch (scripts/site-media.sh puts them in place for a deploy): listed in media.json
  14. MEDIA = set(json.loads((OUT / "_src/learn/media.json").read_text(encoding="utf-8"))) if (OUT / "_src/learn/media.json").exists() else set()
  15. bad, n = [], 0
  16. for url, text in pages.items():
  17. for ref in set(re.findall(r'(?:href|src|poster)="([^"]+)"', text)):
  18. if re.match(r"(https?:|mailto:|data:)", ref):
  19. continue
  20. n += 1
  21. path, _, frag = ref.partition("#")
  22. path = path.split("?")[0] or url
  23. if not path.startswith("/"):
  24. bad.append(f"{url}: relative link {ref}")
  25. elif path in pages:
  26. if frag and frag not in ids[path]:
  27. bad.append(f"{url}: no #{frag} in {path}")
  28. elif not (OUT / path.lstrip("/")).is_file() and path.lstrip("/") not in MEDIA:
  29. bad.append(f"{url}: {ref} not found")
  30. for b in bad:
  31. print("error:", b)
  32. print(f"check-links: {len(pages)} pages, {n} internal links, {len(bad)} broken")
  33. sys.exit(1 if bad else 0)