#!/usr/bin/env python3 """Build the static site into public/.""" import shutil from datetime import date from pathlib import Path import frontmatter from jinja2 import Environment, FileSystemLoader, select_autoescape import yaml from config import NAV, SITE ROOT = Path(__file__).parent PAGES, STATIC, TEMPLATES = ROOT / "pages", ROOT / "static", ROOT / "templates" OUT, TMP, OLD = ROOT / "public", ROOT / "public.tmp", ROOT / "public.old" env = Environment( loader=FileSystemLoader(TEMPLATES), autoescape=select_autoescape(["html"]) ) common = {"site": SITE, "nav": NAV, "year": date.today().year} def write(root: Path, url: str, html: str) -> None: """'/about/' -> root/about/index.html, '/' -> root/index.html""" dest = root / url.strip("/") / "index.html" dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(html, encoding="utf-8") def build() -> None: # Build in a scratch dir; public/ is only touched at the very end, # so a failed build never breaks what's being served. shutil.rmtree(TMP, ignore_errors=True) if STATIC.exists(): shutil.copytree(STATIC, TMP) else: TMP.mkdir() page_tpl = env.get_template("base.html") for src in sorted(PAGES.glob("*.html")): post = frontmatter.load(src) url = "/" if src.stem == "index" else f"/{src.stem}/" html = page_tpl.render( **common, url=url, meta=post.metadata, content=post.content ) write(TMP, url, html) state = ( yaml.safe_load((ROOT / "data" / "state.yaml").read_text(encoding="utf-8")) or {} ) counties = [ yaml.safe_load(p.read_text(encoding="utf-8")) for p in sorted((ROOT / "data" / "counties").glob("*.yaml")) ] for c in counties: c["url"] = f"/act/{c['slug']}-county/" map_file = STATIC / "assets" / "alabama-counties.svg" map_svg = map_file.read_text(encoding="utf-8") if map_file.exists() else None write( TMP, "/act/", env.get_template("act.html").render( **common, url="/act/", state=state, counties=counties, map_svg=map_svg, meta={ "title": "Take Action", "description": "Find your representatives and county, and how to contact them.", }, ), ) county_tpl = env.get_template("county.html") for c in counties: write( TMP, c["url"], county_tpl.render( **common, url=c["url"], county=c, meta={ "title": f"{c['name']} County, Alabama", "description": f"Representatives, local groups, and ways to take action in {c['name']} County, Alabama.", }, ), ) (TMP / "404.html").write_text( env.get_template("404.html").render( **common, url="/404.html", meta={"title": "Page not found", "noindex": True} ), encoding="utf-8", ) # Swap into place if OUT.exists(): shutil.rmtree(OLD, ignore_errors=True) OUT.rename(OLD) TMP.rename(OUT) shutil.rmtree(OLD, ignore_errors=True) print(f"Built {len(list(PAGES.glob('*.html')))} pages -> {OUT}") if __name__ == "__main__": build()