Last active
April 13, 2019 12:31
-
-
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`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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