pizzawednes.day/publish.py

84 lines
1.9 KiB
Python

import datetime
import jinja2
import markdown
import os
import strip_markdown
import typing
class Post(typing.NamedTuple):
title: str
path: str
pub_date: datetime.datetime
base_url = "https://pizzawednes.day/"
cwd_path = os.getcwd()
output_path = os.path.join(cwd_path, "output")
if not os.path.exists(output_path):
os.mkdir(output_path)
feed_path = os.path.join(output_path, "feed")
if not os.path.exists(feed_path):
os.mkdir(feed_path)
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(cwd_path, "templates")))
posts_path = os.path.join(cwd_path, "posts")
post_template = jinja_env.get_template("site_post.html")
datetime_format_len = 10
markdown_extension = ".md"
posts: list[Post] = []
for filename in os.listdir(posts_path):
if not filename.endswith(markdown_extension):
continue
if len(filename) < datetime_format_len:
continue
pub_date = datetime.datetime.min
try:
pub_date = datetime.datetime.strptime(filename[0:datetime_format_len], "%Y-%m-%d").replace(
hour=0,
minute=0,
second=0,
microsecond=0,
)
except ValueError:
pass
with open(os.path.join(posts_path, filename)) as source_file:
content = source_file.read()
title = ""
try:
first_newline_index = content.index('\n')
title = strip_markdown.strip_markdown(content[0:first_newline_index])
except ValueError:
pass
slug = filename[:-len(markdown_extension)]
posts.append(Post(
title=title,
path=os.path.join("feed", slug),
pub_date=pub_date,
))
with open(f"{os.path.join(feed_path, slug)}.html", "w") as output_file:
output_file.write(post_template.render(
title = title,
content = markdown.markdown(content),
))
with open(f"{feed_path}.rss", "w") as file:
file.write(jinja_env.get_template("rss_feed.rss").render(
base_url = base_url,
posts = posts,
))
with open(f"{feed_path}.html", "w") as file:
file.write(jinja_env.get_template("site_feed.html").render(
posts = posts,
))