Phase 7 (part 1): assemble the archived site and apply the seed layer
prepare_site.py rebuilds web/site/ from site-src/: rebuilt home page, repaired images, Wayback links resolved to local files or neutralised, hit counter removed, crawler metadata dropped, home page breadcrumb. Link check fails the build on dangling references. Seed layer adds public/IT-inventaire.txt and robots.txt.
This commit is contained in:
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Assemble the lab's web root from the archived 2002 site.
|
||||
|
||||
Input : site-src/norbourg-2002/ (Wayback mirror, 46 pages)
|
||||
site-src/norbourg-static/ (rebuilt home page + repaired images)
|
||||
Output : web/site/ (served by IIS on FS01)
|
||||
|
||||
The mirror was captured for offline reading, not for hosting: it keeps absolute
|
||||
links to web.archive.org, points at a dead hit counter, and ships crawler
|
||||
metadata that would tell students they are looking at an archive. This script
|
||||
removes all of that and fails if a local reference is left dangling.
|
||||
|
||||
Usage:
|
||||
python3 scripts/prepare_site.py [--warn-only] [--quiet]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
SRC_MIRROR = REPO / "site-src" / "norbourg-2002"
|
||||
SRC_HOME = REPO / "site-src" / "norbourg-static"
|
||||
OUT = REPO / "web" / "site"
|
||||
|
||||
# Files that exist only for the archivist.
|
||||
DROP_FILES = {"MIRROR.txt", "_index.json"}
|
||||
|
||||
# https://web.archive.org/web/20020929201450/http://norbourg.com/pdfs/s0102.pdf
|
||||
WAYBACK = re.compile(
|
||||
r"""https?://web\.archive\.org/web/\d+/ # capture timestamp
|
||||
(?:https?://)?(?:www\.)?norbourg\.com # original host
|
||||
(/[^"'\s>]*)""",
|
||||
re.VERBOSE | re.IGNORECASE,
|
||||
)
|
||||
|
||||
# The 2002 hit counter (/webstat/webstat.exe) was not archived: 42 pages point
|
||||
# at it and would render a broken-image icon.
|
||||
HITCOUNTER_TAG = re.compile(r"<img[^>]*webstat[^>]*>", re.IGNORECASE)
|
||||
HITCOUNTER_ANY = re.compile(r"""["']/webstat/webstat\.exe["']""", re.IGNORECASE)
|
||||
|
||||
# In-universe breadcrumb for the SMB pivot; injected into the home page only.
|
||||
HOME_HINT = (
|
||||
"\n<!-- TI: penser a migrer \\\\FS01\\Public vers le nouveau serveur "
|
||||
"avant la fermeture du site -->\n"
|
||||
)
|
||||
|
||||
LINK_ATTR = re.compile(r"""(?:href|src)\s*=\s*["']([^"']+)["']""", re.IGNORECASE)
|
||||
HREF_ATTR = re.compile(r"""href\s*=\s*["']([^"']+)["']""", re.IGNORECASE)
|
||||
SKIP_PREFIX = ("http://", "https://", "mailto:", "javascript:", "data:", "#", "ftp://")
|
||||
|
||||
|
||||
def decode(raw: bytes) -> str:
|
||||
# The mirror is ISO-8859-1 with CRLF; round-trip through latin-1 so nothing
|
||||
# gets mangled and the served bytes stay identical to the original.
|
||||
return raw.decode("latin-1")
|
||||
|
||||
|
||||
def encode(text: str) -> bytes:
|
||||
return text.encode("latin-1", errors="replace")
|
||||
|
||||
|
||||
def rewrite_links(text: str, out_root: Path, page_dir: Path) -> tuple[str, int]:
|
||||
"""Point archive links back at local files, or neutralise them."""
|
||||
changed = 0
|
||||
|
||||
def replace(match: re.Match[str]) -> str:
|
||||
nonlocal changed
|
||||
path = match.group(1).split("?")[0].split("#")[0]
|
||||
candidate = out_root / path.lstrip("/")
|
||||
if candidate.is_file():
|
||||
changed += 1
|
||||
return path
|
||||
changed += 1
|
||||
return "#"
|
||||
|
||||
text = WAYBACK.sub(replace, text)
|
||||
text = HITCOUNTER_TAG.sub("", text)
|
||||
text = HITCOUNTER_ANY.sub('"#"', text)
|
||||
return text, changed
|
||||
|
||||
|
||||
def local_links(text: str, page: Path, out_root: Path) -> list[str]:
|
||||
"""Return local references that do not resolve to a file."""
|
||||
missing: list[str] = []
|
||||
for ref in LINK_ATTR.findall(text):
|
||||
if ref.lower().startswith(SKIP_PREFIX):
|
||||
continue
|
||||
target = ref.split("?")[0].split("#")[0]
|
||||
if not target:
|
||||
continue
|
||||
if target.startswith("/"):
|
||||
resolved = out_root / target.lstrip("/")
|
||||
else:
|
||||
resolved = (page.parent / target).resolve()
|
||||
if not resolved.exists():
|
||||
missing.append(ref)
|
||||
return missing
|
||||
|
||||
|
||||
def neutralize_missing(text: str, page: Path, out_root: Path) -> tuple[str, int]:
|
||||
"""Turn hrefs that resolve to nothing into anchors.
|
||||
|
||||
The mirror never captured a few ASP pages and PDFs. A dead link is better
|
||||
than a 404 in a lab where students click everything, and it matches how the
|
||||
archive links were already rewritten to '#'.
|
||||
"""
|
||||
changed = 0
|
||||
|
||||
def replace(match: re.Match[str]) -> str:
|
||||
nonlocal changed
|
||||
ref = match.group(1)
|
||||
if ref.lower().startswith(SKIP_PREFIX):
|
||||
return match.group(0)
|
||||
target = ref.split("?")[0].split("#")[0]
|
||||
if not target:
|
||||
return match.group(0)
|
||||
resolved = (out_root / target.lstrip("/")) if target.startswith("/") \
|
||||
else (page.parent / target).resolve()
|
||||
if resolved.exists():
|
||||
return match.group(0)
|
||||
changed += 1
|
||||
return 'href="#"'
|
||||
|
||||
return HREF_ATTR.sub(replace, text), changed
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--warn-only", action="store_true",
|
||||
help="report dangling references but exit 0")
|
||||
parser.add_argument("--quiet", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not SRC_MIRROR.is_dir():
|
||||
print(f"error: mirror not found: {SRC_MIRROR}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
if OUT.exists():
|
||||
shutil.rmtree(OUT)
|
||||
shutil.copytree(SRC_MIRROR, OUT)
|
||||
|
||||
# Rebuilt home page and repaired images replace the mirror's versions.
|
||||
home = SRC_HOME / "index.html"
|
||||
if home.is_file():
|
||||
shutil.copy2(home, OUT / "index.html")
|
||||
if (SRC_HOME / "images").is_dir():
|
||||
shutil.copytree(SRC_HOME / "images", OUT / "images", dirs_exist_ok=True)
|
||||
|
||||
for name in DROP_FILES:
|
||||
target = OUT / name
|
||||
if target.exists():
|
||||
target.unlink()
|
||||
|
||||
pages = sorted(OUT.rglob("*.html"))
|
||||
rewritten = 0
|
||||
neutralized = 0
|
||||
for page in pages:
|
||||
text = decode(page.read_bytes())
|
||||
text, changed = rewrite_links(text, OUT, page.parent)
|
||||
rewritten += changed
|
||||
text, dead = neutralize_missing(text, page, OUT)
|
||||
neutralized += dead
|
||||
page.write_bytes(encode(text))
|
||||
|
||||
# Home-page breadcrumb: the only thing this script adds to the site itself.
|
||||
index = OUT / "index.html"
|
||||
if index.is_file():
|
||||
text = decode(index.read_bytes())
|
||||
if "FS01" not in text:
|
||||
marker = re.search(r"<body[^>]*>", text, re.IGNORECASE)
|
||||
if marker:
|
||||
text = text[: marker.end()] + HOME_HINT + text[marker.end():]
|
||||
else:
|
||||
text = HOME_HINT + text
|
||||
index.write_bytes(encode(text))
|
||||
|
||||
dangling: dict[str, list[str]] = {}
|
||||
for page in pages:
|
||||
missing = local_links(decode(page.read_bytes()), page, OUT)
|
||||
if missing:
|
||||
dangling[str(page.relative_to(OUT))] = sorted(set(missing))
|
||||
|
||||
if not args.quiet:
|
||||
total = sum(1 for _ in OUT.rglob("*") if _.is_file())
|
||||
print(f"assembled {OUT.relative_to(REPO)} ({total} files, {len(pages)} pages)")
|
||||
print(f"rewrote {rewritten} archive references")
|
||||
print(f"neutered {neutralized} link(s) with no archived target")
|
||||
if dangling:
|
||||
print(f"dangling {len(dangling)} page(s):")
|
||||
for name, refs in list(dangling.items())[:15]:
|
||||
print(f" {name}: {', '.join(refs[:4])}"
|
||||
+ (" ..." if len(refs) > 4 else ""))
|
||||
if len(dangling) > 15:
|
||||
print(f" ... and {len(dangling) - 15} more")
|
||||
|
||||
if dangling and not args.warn_only:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user