Repository Public MIT Research preview
1#!/usr/bin/env python32"""Check the source registry and (optionally) that URLs resolve.34Offline (default, used in CI quality gates): every bibliography entry of every implemented session must be5listed in docs/source-verification.md with an access date and a volatility class; URLs must be well formed.6Online (--online): fetch each URL once and record the HTTP status in reports/links.json. Publishers that7block automated clients (HTTP 403 from a DOI landing page) are reported as "restricted", not as failures.8Network-dependent results are never fabricated: without --online, statuses are reported as "not checked".9"""10from __future__ import annotations1112import argparse13import datetime as dt14import re15import sys16import urllib.error17import urllib.request1819from atlaslib import ROOT, Report, load_course, select_sessions, session_dir2021VOLATILITY = {"stable", "version-sensitive", "rapidly-changing"}22URL_RE = re.compile(r"https?://[^\s<>\"'{}|\\^`]+")232425def fetch(url: str) -> tuple[str, int | None]:26 req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (link-check)"})27 try:28 with urllib.request.urlopen(req, timeout=25) as r:29 return "ok", r.status30 except urllib.error.HTTPError as e:31 return ("restricted" if e.code in (401, 403, 429) else "broken"), e.code32 except Exception: # noqa: BLE00133 return "unreachable", None343536def main() -> int:37 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)38 ap.add_argument("--online", action="store_true")39 ap.add_argument("--session")40 args = ap.parse_args()41 rep = Report("links")42 # Registry rows live in docs/source-verification.md (policy + S01) and, per session, in43 # sessions/SXX/slides/source-registry.md (same table format). Keys are scoped to their session:44 # two sessions may use the same BibTeX key for different URLs.45 def parse(path) -> dict:46 out = {}47 if path.exists():48 for line in path.read_text(encoding="utf-8").splitlines():49 cells = [c.strip() for c in line.strip().strip("|").split("|")]50 if len(cells) >= 7 and re.fullmatch(r"`[A-Za-z0-9_-]+`", cells[0]):51 out[cells[0].strip("`")] = cells52 return out5354 shared_rows = parse(ROOT / "docs" / "source-verification.md")55 urls: dict[str, str] = {}56 for s in select_sessions(load_course(), args.session):57 bib = session_dir(s) / "slides" / "references.bib"58 if not bib.exists():59 continue60 rows = {**shared_rows, **parse(session_dir(s) / "slides" / "source-registry.md")}61 for key, body in re.findall(r"@\w+\{([^,]+),(.*?)\n\}", bib.read_text(encoding="utf-8"), flags=re.S):62 m = re.search(r"url\s*=\s*\{([^}]*)\}", body)63 if not m or not URL_RE.fullmatch(m.group(1)):64 rep.error(f"{s['id']}: {key} has no well-formed URL")65 continue66 urls[f"{s['id']}:{key}"] = m.group(1)67 row = rows.get(key)68 if not row:69 rep.error(f"{s['id']}: {key} is not listed in a source registry (slides/source-registry.md)")70 continue71 if m.group(1) not in row[2]:72 rep.error(f"{key}: URL in the registry differs from references.bib")73 if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", row[3]):74 rep.error(f"{key}: registry lacks an ISO access date")75 if row[4] not in VOLATILITY:76 rep.error(f"{key}: volatility must be one of {sorted(VOLATILITY)}")77 if len(row[6]) < 15:78 rep.error(f"{key}: registry must state the claim supported")79 results = {}80 for key, url in urls.items():81 if args.online:82 state, code = fetch(url)83 results[key] = {"url": url, "state": state, "http": code}84 (rep.error if state in ("broken", "unreachable") else rep.note)(f"{key}: {state} ({code}) {url}")85 else:86 results[key] = {"url": url, "state": "not checked"}87 rep.data["checked_online"] = args.online88 rep.data["date"] = dt.date.today().isoformat()89 rep.data["urls"] = results90 rep.note(f"{len(urls)} source URLs; online check: {'yes' if args.online else 'no (run with --online)'}")91 return rep.finish()929394if __name__ == "__main__":95 sys.exit(main())96