check.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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/A5): the six remaining detail pages land in wave 3; strip these
  24. # entries as each wave merges. The five Invercargill-family pages (A3) have
  25. # landed and are enforced.
  26. UPCOMING_PAGES = {
  27. "developer/astralis/",
  28. "developer/statum/",
  29. "developer/spry/",
  30. "developer/locksmith/",
  31. "developer/vallama/",
  32. "developer/usm/",
  33. }
  34. def check() -> int:
  35. errors: list[str] = []
  36. pages = sorted(p for p in ROOT.rglob("*.html")
  37. if not (set(p.relative_to(ROOT).parts[:-1]) & EXCLUDE_DIRS))
  38. if not pages:
  39. errors.append("no .html files found under root")
  40. ids_by_page: dict[Path, set[str]] = {}
  41. refs: list[tuple[Path, str, str]] = [] # page, attr value, kind
  42. linked_pages: set[Path] = set()
  43. for page in pages:
  44. text = page.read_text(encoding="utf-8")
  45. ids_by_page[page] = set(re.findall(r'id="([^"]+)"', text))
  46. # strip comments so commented-out template rows are not treated as live refs
  47. body = re.sub(r"<!--.*?-->", "", text, flags=re.S)
  48. for attr, val in re.findall(r'\b(src|href)="([^"]+)"', body):
  49. refs.append((page, val, attr))
  50. # naive tag-balance check for the elements we actually use
  51. for tag in ("html", "head", "body", "header", "nav", "main", "footer",
  52. "section", "article", "figure", "table", "ul", "ol", "div", "a", "p"):
  53. opens = len(re.findall(rf"<{tag}[\s>]", body))
  54. closes = len(re.findall(rf"</{tag}>", body))
  55. if opens != closes:
  56. errors.append(f"{page.name}: <{tag}> open/close mismatch ({opens}/{closes})")
  57. for page, val, _attr in refs:
  58. parsed = urlparse(val)
  59. if parsed.scheme or val.startswith("//"):
  60. if not (val.startswith("data:")):
  61. errors.append(f"{page.name}: EXTERNAL reference '{val}'")
  62. continue
  63. if parsed.fragment and not parsed.path:
  64. # same-page anchor
  65. if parsed.fragment not in ids_by_page[page]:
  66. errors.append(f"{page.name}: broken in-page anchor '#{parsed.fragment}'")
  67. continue
  68. target = (page.parent / unquote(parsed.path)).resolve()
  69. if parsed.path.startswith("/"):
  70. # site-root-relative: resolve against the site root, not /
  71. target = (ROOT / unquote(parsed.path).lstrip("/")).resolve()
  72. if not target.exists():
  73. # allowlist upcoming pages no matter whether they are linked
  74. # root-relative (/developer/spry/) or relatively (spry/)
  75. try:
  76. rel = target.relative_to(ROOT).as_posix().strip("/") + "/"
  77. except ValueError:
  78. rel = None
  79. if rel is not None and rel in UPCOMING_PAGES:
  80. continue
  81. errors.append(f"{page.name}: missing asset '{val}'")
  82. continue
  83. if target.suffix == ".html" or target.is_dir():
  84. # a page link; check its fragment if present
  85. linked_pages.add(target / "index.html" if target.is_dir() else target)
  86. if parsed.fragment:
  87. tp = target if target.suffix == ".html" else target / "index.html"
  88. if tp.is_file():
  89. if parsed.fragment not in ids_by_page.get(tp, set()):
  90. errors.append(f"{page.name}: broken anchor in {val}")
  91. # orphan check
  92. for page in pages:
  93. if page not in linked_pages and page != ROOT / "index.html":
  94. errors.append(f"orphan page (nothing links to it): {page.relative_to(ROOT)}")
  95. if errors:
  96. print(f"FAIL ({len(errors)} problems)")
  97. for e in errors:
  98. print(" -", e)
  99. return 1
  100. print(f"OK: {len(pages)} page(s), {len(refs)} reference(s), all local, all resolve")
  101. return 0
  102. if __name__ == "__main__":
  103. sys.exit(check())