Something went wrong. Try again.
Just a personal website, like we used to make. onlocalhost.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135#!/usr/bin/env python3"""Build public/ from the Markdown in content/.
Posts are content/posts/YYYY-MM-DD-slug.md, pages are content/pages/slug.md.The first line of a file is its title; the rest is the body."""
import htmlimport reimport shutilfrom datetime import datetime, timezonefrom pathlib import Path
import markdown
SITE_TITLE = "onlocalhost.dev"SITE_URL = "https://onlocalhost.dev"SITE_DESCRIPTION = "Just a personal website, like we used to make."
ROOT = Path(__file__).resolve().parentCONTENT = ROOT / "content"TEMPLATES = ROOT / "templates"STATIC = ROOT / "static"OUT = ROOT / "public"
FILENAME = re.compile(r"^(\d{4}-\d{2}-\d{2})-(.+)\.md$")EXTERNAL_LINK = re.compile(r'<a href="(https?://(?!(?:www\.)?onlocalhost\.dev[/"])[^"]+)"')PLACEHOLDER = re.compile(r"\{\{\s*(\w+)\s*\}\}")TAGS = re.compile(r"<[^>]+>")SENTENCE = re.compile(r"(?<=[.!?])\s")
def render(template, **values): text = (TEMPLATES / template).read_text(encoding="utf-8") return PLACEHOLDER.sub(lambda m: str(values.get(m.group(1), "")), text)
def read(path): heading, _, body = path.read_text(encoding="utf-8").strip().partition("\n") title = heading.lstrip("#").strip() converted = markdown.markdown(body.strip(), extensions=["smarty"]) converted = EXTERNAL_LINK.sub(r'<a href="\1" target="_blank" rel="noopener"', converted) return title, converted
def write(url_path, page): target = OUT / url_path.strip("/") / "index.html" if url_path != "/" else OUT / "index.html" target.parent.mkdir(parents=True, exist_ok=True) target.write_text(page, encoding="utf-8")
def summarise(body): text = html.unescape(TAGS.sub("", body)).strip() first = SENTENCE.split(" ".join(text.split()), 1)[0] return first if len(first) <= 200 else first[:197].rstrip() + "..."
def page(head_title, content, body_class="", description=SITE_DESCRIPTION): return render("base.html", head_title=html.escape(head_title), tagline=SITE_DESCRIPTION, description=html.escape(description), content=content, body_attrs=f' class="{body_class}"' if body_class else "")
def build_posts(): posts = [] for path in sorted(CONTENT.glob("posts/*.md"), reverse=True): match = FILENAME.match(path.name) if not match: raise SystemExit(f"{path.name}: expected a YYYY-MM-DD-slug.md filename") date, slug = match.groups() title, body = read(path) url = f"/{date.replace('-', '/')}/{slug}/" write(url, page(f"{title} — {SITE_TITLE}", render("post.html", title=html.escape(title), date=date, body=body), description=summarise(body))) posts.append({"title": title, "date": date, "url": url, "body": body}) return posts
def build_pages(): for path in sorted(CONTENT.glob("pages/*.md")): title, body = read(path) rendered = page(f"{title} — {SITE_TITLE}", render("page.html", title=html.escape(title), body=body), body_class="notfound" if path.stem == "404" else "") if path.stem == "404": (OUT / "404.html").write_text(rendered, encoding="utf-8") else: write(f"/{path.stem}/", rendered)
def build_index(posts): items = "\n".join( f'<li><time datetime="{p["date"]}">{p["date"]}</time>' f'<a href="{p["url"]}">{html.escape(p["title"])}</a></li>' for p in posts ) write("/", page(SITE_TITLE, render("index.html", posts=items)))
def build_feed(posts): items = [] for p in posts: published = datetime.strptime(p["date"], "%Y-%m-%d").replace(tzinfo=timezone.utc) link = SITE_URL + p["url"] items.append( "<item>\n" f"<title>{html.escape(p['title'])}</title>\n" f"<link>{link}</link>\n" f"<guid isPermaLink=\"true\">{link}</guid>\n" f"<pubDate>{published.strftime('%a, %d %b %Y %H:%M:%S +0000')}</pubDate>\n" f"<description><![CDATA[{p['body']}]]></description>\n" "</item>" ) feed = render("feed.xml", site_title=SITE_TITLE, site_url=SITE_URL, site_description=SITE_DESCRIPTION, items="\n".join(items)) (OUT / "feed.xml").write_text(feed, encoding="utf-8")
def main(): if OUT.exists(): shutil.rmtree(OUT) OUT.mkdir() posts = build_posts() build_pages() build_index(posts) build_feed(posts) shutil.copytree(STATIC, OUT, dirs_exist_ok=True) print(f"{len(posts)} posts, written to {OUT.relative_to(ROOT)}/")
if __name__ == "__main__": main()