|
| 1 | +#!/usr/bin/env python |
| 2 | +# copied from https://github.com/tonybaloney/tonybaloney.github.io/blob/master/blog-gen.py |
| 3 | +import markdown |
| 4 | +import jinja2 |
| 5 | +import glob |
| 6 | +from datetime import date, datetime |
| 7 | +from email.utils import formatdate, format_datetime # for RFC2822 formatting |
| 8 | + |
| 9 | +TEMPLATE_FILE = "templates/blog_post_template.html" |
| 10 | +FEED_TEMPLATE_FILE = "templates/rss_feed_template.xml" |
| 11 | +BASE_URL = "https://tonybaloney.github.io/" |
| 12 | + |
| 13 | +def main(): |
| 14 | + posts = glob.glob("blog/*.md") |
| 15 | + extensions = ['extra', 'smarty', 'meta'] |
| 16 | + _md = markdown.Markdown(extensions=extensions, output_format='html5') |
| 17 | + |
| 18 | + loader = jinja2.FileSystemLoader(searchpath="./") |
| 19 | + env = jinja2.Environment(loader=loader) |
| 20 | + |
| 21 | + all_posts = [] |
| 22 | + for post in posts: |
| 23 | + print("rendering {0}".format(post)) |
| 24 | + post_date = date.fromisoformat(post[5:15]) |
| 25 | + url = post.replace(".md", ".html").replace("blog/", "posts/") |
| 26 | + with open(post) as post_f: |
| 27 | + html = _md.convert(post_f.read()) |
| 28 | + context = { |
| 29 | + 'blog_publish_date': post_date, |
| 30 | + **_md.Meta |
| 31 | + } |
| 32 | + doc = env.get_template(TEMPLATE_FILE).render(content=html, baseurl=BASE_URL, url=url, **context) |
| 33 | + |
| 34 | + post_html = url |
| 35 | + with open(post_html, "w") as post_html_f: |
| 36 | + post_html_f.write(doc) |
| 37 | + # all_posts.append(dict(**_md.Meta, date=post_date, rfc2822_date=format_datetime(post_date), link="{0}{1}".format(BASE_URL, url))) |
| 38 | + all_posts.append(dict(**_md.Meta, date=post_date, rfc2822_date='', link="{0}{1}".format(BASE_URL, url))) |
| 39 | + |
| 40 | + # Order blog posts by date published |
| 41 | + all_posts.sort(key=lambda item: item['date'], reverse=True) |
| 42 | + # Make the RSS feed |
| 43 | + with open("rss.xml", "w") as rss_f: |
| 44 | + rss_f.write(env.get_template(FEED_TEMPLATE_FILE).render(posts=all_posts, date=formatdate())) |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + main() |
0 commit comments