1
0
flewkey.com/scripts/template.py
2020-07-13 02:35:49 +00:00

91 lines
2.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import markdown
from datetime import datetime
from email import utils
def get_path(path, ext_in, ext_out):
path = path[len("pages"):]
if path[-len("index"+ext_in):] == "index"+ext_in:
return path[:-len("index"+ext_in)]
return path[:-len(ext_in)] + ext_out
def get_dir(path):
return "/".join(path.split("/")[1:-1])+"/"
def get_root(path):
root = ""
for i in range(len(path.split("/"))-2):
root += "../"
return root
licenses = {
"CC-BY": ["cc-by", "CC BY 4.0", "https://creativecommons.org/licenses/by/4.0/"]
}
def get_badge(license, root):
if license not in licenses:
return ""
data = licenses[license]
return "<a class=\"badge\" title=\""+data[1]+"\" href=\""+data[2]+"\"><img src=\""+root+"badges/"+data[0]+".png\" alt=\""+data[1]+"\"/></a>"
def read_template(template, meta_in):
if template[:10] != "meta: yes\n":
return [template, {"meta": "no"}]
data = template[:-1].split("\n\n") # Strip trailing newline
md = markdown.Markdown(extensions = ["meta"])
md.convert(data[0])
content = "\n\n".join(data[1:])
content = content.replace("{", "{{").replace("}", "}}")
meta = meta_in.copy()
meta.update(md.Meta)
return [content, MetaDict(meta)]
defaults = {
"base": "https://flewkey.com/",
"title": "Untitled",
"author": "flewkey",
"ext": ".html",
"head": ""
}
class MetaDict(dict):
def __missing__(self, key):
return defaults[key] if key in defaults else ""
def __getitem__(self, key):
value = dict.__getitem__(self, key)
if isinstance(value, list):
return "\n".join(value)
else:
return value
def template(content, path, ext, meta):
global base
meta = MetaDict(meta)
if meta["template"] == None:
return content.format_map(meta)
with open("templates/"+meta["template"]+ext, "r", encoding="utf-8") as file:
t_content = file.read()
t_info = read_template(t_content, meta)
if t_info[1]["meta"] != "no" and "template" in t_info[1]:
t_content = template(t_info[0], path, ext, t_info[1])
if "root" not in meta:
meta["root"] = get_root(path)
if "home" not in meta:
meta["home"] = "." if meta["root"] == "" else meta["root"]
if "full_path" not in meta:
meta["full_path"] = get_path(path, ext, meta["ext"])
if "full_dir" not in meta:
meta["full_dir"] = get_dir(path)
if "badge" not in meta and ext == ".html":
meta["badge"] = get_badge(meta["license"], meta["root"])
if "date" not in meta and "timestamp" in meta:
meta["date"] = datetime.fromtimestamp(int(meta["timestamp"])).isoformat().split("T")[0]
if "pub_date" not in meta and "timestamp" in meta:
meta["pub_date"] = utils.format_datetime(datetime.fromtimestamp(int(meta["timestamp"])))
meta["head"] += "\n<link rel=\"canonical\" href=\""+meta["base"]+meta["full_path"]+"\"/>"
meta["content"] = content.format_map(meta)
if "description" not in meta and ext == ".html":
meta["description"] = meta["content"].split("</p>")[0]+"</p>" # Disgusting!
return t_content.format_map(meta)