website/page.py
Midgard 455f26baf9
Fix or_none() to or_else(None) and catch edge case
Apparently there's no or_none() in pymaybe.

Catch the case when no date is found
2022-01-09 20:28:39 +01:00

90 lines
2 KiB
Python
Executable file

#!/usr/bin/env python3
import sys
import re
from markdown import markdown
from strictyaml import load as load_yaml
from pymaybe import maybe as maybe
from functools import partial as p
from ipo import read, write, dictmap, starstarmap, ipo, all_before, all_after
LIST_ITEM_TEMPLATE = """
<li><a href="{path}">
<div class="title">{title}</div>
<div class="summary">{summary}</div>
</a></li>"""
def blog_page_template():
with open("templates/blog.html") as fh:
return fh.read()
def date_from_filename(filename):
return maybe(
re.search(r"(?:^|/)([0-9]{4}-[0-9]{2}-[0-9]{2})[^/]+$", filename)
).group(1).or_else(None)
def blog_page_metadata(filename):
with open(filename) as file:
metadata_from_file = (
read(file=file) | p(all_before, p(re.fullmatch, "---+")) | "\n".join |
load_yaml | (lambda x: x.data)
).data
return {
**metadata_from_file,
"path": re.sub(r".md$", "", filename),
"published": date_from_filename(filename)
}
def blog_page_body(filename):
with open(filename) as file:
return (
read(file=file) | p(all_after, p(re.fullmatch, "---+")) | "\n".join |
p(markdown, extensions=["abbr", "toc", "smarty", "fenced_code", "codehilite"])
).data
def safe_metadata(metadata):
return {
k: (
v
if k in ("published", "path")
else markdown(v, extensions=["smarty"]).replace("<p>", "").replace("</p>", "")
)
for k, v in metadata.items()
}
def main():
if sys.argv[1] == "--index":
blog_post_list = (
ipo(sys.argv[3:]) |
p(map, blog_page_metadata) |
p(sorted, key=lambda x: x["published"]) |
p(map, safe_metadata) |
p(map, lambda metadata: LIST_ITEM_TEMPLATE.format(**metadata)) |
"".join
).data
with open(sys.argv[2]) as file_in:
print(
file_in.read().format(blog_posts=blog_post_list),
end=""
)
else:
metadata = safe_metadata(blog_page_metadata(sys.argv[1]))
body = blog_page_body(sys.argv[1])
print(
blog_page_template().format(**metadata, body=body),
end=""
)
if __name__ == '__main__':
main()