#!/usr/bin/env python3 """Fail if the generated site links to local paths that were not built. Only internal hrefs/srcs that start with "/" are checked and only files under the given public/ directory are considered. External URLs are ignored. """ import html.parser import os import sys import urllib.parse class LinkParser(html.parser.HTMLParser): def __init__(self): super().__init__() self.links = [] def handle_starttag(self, tag, attrs): for name, value in attrs: if name in ("href", "src") and value: self.links.append(value) def resolves(root, path): def exists(p): return os.path.exists(os.path.join(root, p)) if exists(path): return True if exists(os.path.join(path, "index.html")): return True if not path.endswith("/") and exists(path + ".html"): return True return False def main(): if len(sys.argv) != 2: print("usage: check-links.py ", file=sys.stderr) return 2 root = sys.argv[1] failures = [] for dirpath, _, filenames in os.walk(root): for filename in filenames: if not filename.endswith(".html"): continue page = os.path.join(dirpath, filename) rel_page = os.path.relpath(page, root) with open(page, encoding="utf-8", errors="replace") as handle: parser = LinkParser() parser.feed(handle.read()) for link in parser.links: if not link.startswith("/") or link.startswith("//"): continue path = urllib.parse.unquote(urllib.parse.urlsplit(link).path) if not resolves(root, path.lstrip("/")): failures.append(f"{rel_page}: {link}") if failures: print("broken internal links:", file=sys.stderr) for failure in sorted(set(failures)): print(" " + failure, file=sys.stderr) return 1 print(f"ok: internal links resolve ({len(os.listdir(root))} top-level entries)") return 0 if __name__ == "__main__": sys.exit(main())