koopa-admin-log/scripts/dossiers-ngi/inject-cascade-bar.py

56 lines
1.4 KiB
Python
Executable file

#!/usr/bin/env python3
"""Insert {% include "_cascade/bar.html" . %} after <body> in freeze HTML.
Idempotent. Skips files that already contain the include or live under
_cascade/. Usage:
python3 inject-cascade-bar.py /path/to/edition/root
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
INCLUDE = '{% include "_cascade/bar.html" . %}'
BODY_RE = re.compile(r"(<body[^>]*>)", re.IGNORECASE)
def inject(text: str) -> str | None:
if INCLUDE in text:
return None
if "_cascade/bar" in text:
return None
m = BODY_RE.search(text)
if not m:
return None
i = m.end()
return text[:i] + "\n" + INCLUDE + "\n" + text[i:]
def main() -> int:
if len(sys.argv) != 2:
print(f"usage: {sys.argv[0]} EDITION_ROOT", file=sys.stderr)
return 2
root = Path(sys.argv[1]).resolve()
if not root.is_dir():
print(f"not a dir: {root}", file=sys.stderr)
return 2
changed = 0
scanned = 0
for path in root.rglob("*.html"):
if "/_cascade/" in path.as_posix() + "/":
continue
scanned += 1
raw = path.read_text(encoding="utf-8", errors="ignore")
out = inject(raw)
if out is None:
continue
path.write_text(out, encoding="utf-8")
changed += 1
print(f"OK: scanned={scanned} injected={changed} root={root}")
return 0
if __name__ == "__main__":
raise SystemExit(main())