check.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/usr/bin/env python3
  2. """Static-site sanity checker for the Astrologue website.
  3. Walks every .html file under the given root, then verifies:
  4. 1. every src/href asset reference resolves to a real file (site-root-
  5. relative paths such as /developer/ resolve against the site root);
  6. 2. no external URLs are referenced (the site must be self-contained);
  7. 3. internal page anchors (#id and page#id) point at real ids;
  8. 4. every local page is reachable by some link (orphan check);
  9. 5. quick HTML well-formedness signals (basic tag balance).
  10. Exit code 1 on any failure. Usage: check.py [root]
  11. """
  12. import re
  13. import sys
  14. from pathlib import Path
  15. from urllib.parse import urlparse, unquote
  16. ROOT = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
  17. EXTERNAL = re.compile(r"^(https?|ftp|wss?|//):?")
  18. # Reference designs are not part of the deployable site.
  19. EXCLUDE_DIRS = {"Original", "Proposed", ".git"}
  20. # Site-root-relative pages that are linked ahead of their existence because a
  21. # later task in this goal builds them. Remove entries here once the page lands
  22. # so the checker enforces them again.
  23. # TODO(A4): the three remaining detail pages land in wave 3; strip these
  24. # entries as each wave merges. The five Invercargill-family pages (A3) and
  25. # the security/intelligence/packaging trio (A5: locksmith, vallama, usm)
  26. # have landed and are enforced.
  27. UPCOMING_PAGES = {
  28. "developer/astralis/",
  29. "developer/statum/",
  30. "developer/spry/",
  31. }
  32. def check() -> int:
  33. errors: list[str] = []
  34. pages = sorted(p for p in ROOT.rglob("*.html")
  35. if not (set(p.relative_to(ROOT).parts[:-1]) & EXCLUDE_DIRS))
  36. if not pages:
  37. errors.append("no .html files found under root")
  38. ids_by_page: dict[Path, set[str]] = {}
  39. refs: list[tuple[Path, str, str]] = [] # page, attr value, kind
  40. linked_pages: set[Path] = set()
  41. for page in pages:
  42. text = page.read_text(encoding="utf-8")
  43. ids_by_page[page] = set(re.findall(r'id="([^"]+)"', text))
  44. # strip comments so commented-out template rows are not treated as live refs
  45. body = re.sub(r"<!--.*?-->", "", text, flags=re.S)
  46. for attr, val in re.findall(r'\b(src|href)="([^"]+)"', body):
  47. refs.append((page, val, attr))
  48. # naive tag-balance check for the elements we actually use
  49. for tag in ("html", "head", "body", "header", "nav", "main", "footer",
  50. "section", "article", "figure", "table", "ul", "ol", "div", "a", "p"):
  51. opens = len(re.findall(rf"<{tag}[\s>]", body))
  52. closes = len(re.findall(rf"</{tag}>", body))
  53. if opens != closes:
  54. errors.append(f"{page.name}: <{tag}> open/close mismatch ({opens}/{closes})")
  55. for page, val, _attr in refs:
  56. parsed = urlparse(val)
  57. if parsed.scheme or val.startswith("//"):
  58. if not (val.startswith("data:")):
  59. errors.append(f"{page.name}: EXTERNAL reference '{val}'")
  60. continue
  61. if parsed.fragment and not parsed.path:
  62. # same-page anchor
  63. if parsed.fragment not in ids_by_page[page]:
  64. errors.append(f"{page.name}: broken in-page anchor '#{parsed.fragment}'")
  65. continue
  66. target = (page.parent / unquote(parsed.path)).resolve()
  67. if parsed.path.startswith("/"):
  68. # site-root-relative: resolve against the site root, not /
  69. target = (ROOT / unquote(parsed.path).lstrip("/")).resolve()
  70. if not target.exists():
  71. # allowlist upcoming pages no matter whether they are linked
  72. # root-relative (/developer/spry/) or relatively (spry/)
  73. try:
  74. rel = target.relative_to(ROOT).as_posix().strip("/") + "/"
  75. except ValueError:
  76. rel = None
  77. if rel is not None and rel in UPCOMING_PAGES:
  78. continue
  79. errors.append(f"{page.name}: missing asset '{val}'")
  80. continue
  81. if target.suffix == ".html" or target.is_dir():
  82. # a page link; check its fragment if present
  83. linked_pages.add(target / "index.html" if target.is_dir() else target)
  84. if parsed.fragment:
  85. tp = target if target.suffix == ".html" else target / "index.html"
  86. if tp.is_file():
  87. if parsed.fragment not in ids_by_page.get(tp, set()):
  88. errors.append(f"{page.name}: broken anchor in {val}")
  89. # orphan check
  90. for page in pages:
  91. if page not in linked_pages and page != ROOT / "index.html":
  92. errors.append(f"orphan page (nothing links to it): {page.relative_to(ROOT)}")
  93. if errors:
  94. print(f"FAIL ({len(errors)} problems)")
  95. for e in errors:
  96. print(" -", e)
  97. return 1
  98. print(f"OK: {len(pages)} page(s), {len(refs)} reference(s), all local, all resolve")
  99. return 0
  100. if __name__ == "__main__":
  101. sys.exit(check())