Skip to content

Instantly share code, notes, and snippets.

@fwaggle fwaggle/pelican-to-hugo.py Secret
Created Nov 2, 2019

Embed
What would you like to do?
#!/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
You can’t perform that action at this time.