website/page.py

91 lines
2 KiB
Python
Raw Normal View History

2020-06-02 15:42:25 +02:00
#!/usr/bin/env python3
import sys
import re
2020-06-02 15:42:25 +02:00
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
2020-06-02 15:42:25 +02:00
LIST_ITEM_TEMPLATE = """
<li><a href="{path}">
<div class="title">{title}</div>
<div class="summary">{summary}</div>
</a></li>"""
def blog_page_template():
2020-06-13 14:46:35 +02:00
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_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()
}
2020-06-02 15:42:25 +02:00
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()