project now creates a static site using python
This commit is contained in:
1 parent
65f63b05d3
commit
aa7ef06858
15 files changed
+1155
-1
No files matched your search
@@ -0,0 +1,65 @@
|
||||
#!/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
|
||||
|
||||
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)
|
||||
|
||||
(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()
|
||||
Reference in new issue
Block a user