Add update_categories.py script

parent 74ba8d9b
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import yaml
TAGPAGE_TPL = """---
layout: tagpage
title: "POuL » Tag: {item}"
pagetitle: "Tag: {item}"
tag: {item}
---
"""
CATPAGE_TPL = """---
layout: categorypage
title: "POuL » Topic: {item}"
pagetitle: "Topic: {item}"
category: {item}
---
"""
CATEGORIES_DIR = "topic"
TAGS_DIR = "tag"
def get_post_yaml(file):
with open(file) as f:
text = f.read()
meta = text.split("---", 2)[1]
return yaml.load(meta, Loader=yaml.SafeLoader)
def yaml_get_categories(meta):
return meta.get("categories", list())
def yaml_get_tags(meta):
return meta.get("tags", list())
def walk_posts(root="_posts"):
for dirpath, dirnames, filenames in os.walk(root):
for name in filenames:
yield os.path.join(dirpath, name)
def make_templates(root_dir: str, items: list, template: str):
for i in items:
tpl_path = os.path.join(root_dir, i + ".md")
if os.path.exists(tpl_path):
continue
with open(tpl_path, "w") as f:
f.write(template.format(item=i))
def main():
tags = []
categories = []
for post in walk_posts():
# noinspection PyBroadException
try:
meta = get_post_yaml(post)
except Exception:
print("Unable to retrieve meta for post: '{0}'".format(post), file=sys.stderr)
continue
tags.extend(yaml_get_tags(meta))
categories.extend(yaml_get_categories(meta))
os.makedirs(CATEGORIES_DIR, exist_ok=True)
os.makedirs(TAGS_DIR, exist_ok=True)
make_templates(CATEGORIES_DIR, categories, CATPAGE_TPL)
make_templates(TAGS_DIR, tags, TAGPAGE_TPL)
if __name__ == "__main__":
main()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment