-
-
Save fwaggle/1db66dbd0cb69a7dfce7c07941829a84 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
import datetime | |
import os | |
import re | |
import sys | |
def handle_one(input_path): | |
global path_to, path_from | |
output_file = os.path.join(path_to, input_path[(len(path_from)):]) | |
print("Found file: %s" % input_path[(len(path_from)):]) | |
try: | |
os.makedirs(os.path.dirname(output_file)) | |
except FileExistsError: | |
pass | |
with open(input_path, 'r') as fi, open(output_file, 'w') as fo: | |
frontmatter_start = True | |
frontmatter_end = False | |
for line in fi: | |
if frontmatter_start: | |
frontmatter_start = False | |
fo.write("---\n") | |
if line == "\n" and not frontmatter_end: | |
frontmatter_end = True | |
fo.write("---\n") | |
if ':' in line and not frontmatter_end: | |
k,v = line.split(':', 1) | |
if k == 'Title': | |
fo.write('title: "%s"\n' % v.strip().replace('"','\\"')) | |
continue | |
if k == 'Date': | |
try: | |
date = datetime.datetime.strptime(v.strip(), '%Y-%m-%d %X %z') | |
except ValueError: | |
date = datetime.datetime.strptime(v.strip(), '%Y-%m-%d %H:%M %z') | |
fo.write('date: %s\n' % date.strftime('%Y-%m-%dT%X%z')) | |
continue | |
if k == 'Modified': | |
try: | |
date = datetime.datetime.strptime(v.strip(), '%Y-%m-%d %X %z') | |
except ValueError: | |
date = datetime.datetime.strptime(v.strip(), '%Y-%m-%d %H:%M %z') | |
fo.write('lastmod: %s\n' % date.strftime('%Y-%m-%dT%X%z')) | |
continue | |
if k == 'Location': | |
fo.write('location:%s' % v) | |
continue | |
if k == 'Slug': | |
fo.write('url:%s' % v) | |
continue | |
if k == 'Status' and v == ' hidden\n': | |
fo.write('noblog: true\n') | |
continue | |
if k == 'Authors': | |
fo.write('author:%s' % v) | |
continue | |
if k == 'Tags': | |
fo.write('tags:\n') | |
for t in v.strip().split(','): | |
tag = t.strip() | |
fo.write(' - %s\n' % tag) | |
continue | |
fo.write(line) | |
def handle_many(input_path): | |
for path, subdirs, files in os.walk(input_path): | |
for f in files: | |
if os.path.splitext(f)[1] != '.md': | |
continue | |
handle_one(os.path.join(path, f)) | |
def main(): | |
global path_to, path_from | |
if len(sys.argv) < 3: | |
print("Usage: %s <fromdir> <todir>" % sys.argv[0]) | |
sys.exit(-1) | |
path_from = sys.argv[1] | |
path_to = sys.argv[2] | |
print("Converting from %s into %s" % (path_from, path_to)) | |
handle_many(path_from) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment