erick.is/_generate.py

89 lines
2.5 KiB
Python

import glob
import os
import subprocess
from datetime import datetime
import frontmatter
if not os.path.exists("_capsule"):
os.makedirs("_capsule")
with open("_layouts/home.gmi", mode="r", encoding="utf8") as file:
home_body = file.read()
with open("_layouts/article.gmi", mode="r", encoding="utf8") as file:
article_body = file.read()
with open("_includes/header.gmi", mode="r", encoding="utf8") as file:
header_body = file.read()
with open("_includes/footer.gmi", mode="r", encoding="utf8") as file:
footer_body = file.read()
with open("_includes/links.gmi", mode="r", encoding="utf8") as file:
links_body = file.read()
articles = glob.glob("_posts/*.md")
articles.sort()
if os.getenv("GEMINI_ENV") != "production":
articles += glob.glob("_drafts/*.md")
today = datetime.today().strftime("%F")
year = datetime.today().strftime("%Y")
articles_list = []
for article in articles:
gmi = article.replace("_posts/", "").replace("_drafts/", "").replace(".md", ".gmi")
fm = frontmatter.load(article)
article_title = fm.get("title")
article_date = fm.get("date")
links = fm.get("links", "end")
result = subprocess.run(
["lowdown", "-tgemini", f"--gemini-link-{links}", "--out-no-smarty", article],
capture_output=True,
check=True,
text=True,
)
article_content = result.stdout
if article_date is None:
article_date = today
gmi = f"{article_date}-{gmi}"
elif isinstance(article_date, str):
article_date = datetime.fromisoformat(article_date).strftime("%Y-%m-%d")
body = (
article_body.replace("%%header%%", header_body)
.replace("%%links%%", links_body)
.replace("%%title%%", f"{article_title}\n{article_date}\n")
.replace("%%body%%", article_content)
.replace("%%footer%%", footer_body)
.replace("%%year%%", year)
)
articles_list.append(f"=> {gmi} {article_date} {article_title}")
with open(f"_capsule/{gmi}", mode="w", encoding="utf8") as file:
file.write(body)
articles_list.sort(reverse=True)
result = subprocess.run(
["lowdown", "-tgemini", "index.md"],
capture_output=True,
check=True,
text=True,
)
home_content = result.stdout
body = (
home_body.replace("%%header%%", header_body)
.replace("%%links%%", links_body)
.replace("%%body%%", home_content)
.replace("%%articles%%", "\n".join(articles_list))
.replace("%%footer%%", footer_body)
.replace("%%year%%", year)
)
with open("_capsule/index.gmi", mode="w", encoding="utf8") as file:
file.write(body)