Skip to content

Instantly share code, notes, and snippets.

@rschuetzler
Last active April 13, 2019 12:31
Show Gist options
  • Save rschuetzler/21757aad73dbc01a11aec66cde7b3a8a to your computer and use it in GitHub Desktop.
Save rschuetzler/21757aad73dbc01a11aec66cde7b3a8a to your computer and use it in GitHub Desktop.
Takes files in format `yyyy-mm-dd-post-slug-here.markdown` and converts them to `post-slug-here/index.markdown`
import frontmatter
from pathlib import Path
import re
import os
import errno
p = Path("./posts")
for path in p.glob("*.markdown"):
with open(path, mode="r", encoding="UTF-8") as f:
lines = f.readlines()
clean_lines = [l.strip() for l in lines if l.strip()]
post = frontmatter.loads("\n".join(clean_lines))
# I don't need anything but "title" from the existing frontmatter
for key in list(post.metadata):
if key not in ("title"):
del post.metadata[key]
# Add date from the old post title to the frontmatter
match = re.match(r"([\d]{4}-[\d]{2}-[\d]{2})-{1}(.+)", path.stem)
post["date"] = match.groups()[0]
slug = match.groups()[1]
filename = f"converted_posts/{slug}/index.markdown"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, mode="w") as of:
of.write(frontmatter.dumps(post))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment