Skip to content

Instantly share code, notes, and snippets.

@zevaverbach
Created September 15, 2016 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zevaverbach/81956a97974d32e031aa99a6c821f90d to your computer and use it in GitHub Desktop.
Save zevaverbach/81956a97974d32e031aa99a6c821f90d to your computer and use it in GitHub Desktop.
Convert Ghost blog markdown files to Lektor markdown files
# coding: utf-8
import os
class Converter:
"""Converts Ghost markdown files to Lektor markdown."""
def __init__(self, from_dir, to_dir, author):
self.from_dir = from_dir
self.to_dir = to_dir
self.author = author
@property
def to_convert(self):
"""All markdown files in to_dir."""
return [GhostFile(item, self.to_dir, self.author)
for item in os.listdir(self.from_dir)
if os.path.isfile(item)
and os.path.splitext(item)[-1] in ['.md', '.markdown']
and not item.startswith('.')]
def convert_all(self):
"""Invoke the convert method on each GhostFile object."""
for file in self.to_convert:
file.convert()
class GhostFile:
"""Parses Ghost markdown file and converts it."""
def __init__(self, path, to_dir, author):
"""
Args:
path (str): Markdown file path.
to_dir (str): Output path.
author (str): The author's full name.
"""
self.path = path
self.to_dir = to_dir
self.author = 'author: ' + author
with open(self.path) as fin:
self.contents = fin.read()
self.body = self.contents.split('---')[-1]
self.date_line = 'pub_date: ' + self.date
self.title_line = "title: " + self.title
self.new_dir = os.path.join(to_dir, self.new_filename.split('.lr')[0])
@property
def date(self):
skip = len("date: ") + 1
date_ends = self.contents.find("date: '") + skip
date_slice = slice(date_ends, date_ends + 10)
return self.contents[date_slice]
@property
def title(self):
for line in self.contents.split('\n'):
print(line)
if "title: " in line:
title = line.split('title: ')[1]
if title[0] in ['"', "'"]:
title = title[1:]
if title[-1] in ['"', "'"]:
title = title[:-1]
return title
@property
def new_filename(self):
current_filename = os.path.split(self.path)[1]
new_filename_with_ext = current_filename.split(self.date + '-')[1]
return new_filename_with_ext.split('.')[0] + '.lr'
def convert(self):
self.make_new_dir()
with open(os.path.join(self.new_dir, 'contents.lr'), 'w') as fout:
fout.write(self.assemble())
def make_new_dir(self):
if os.path.split(self.new_dir)[1] not in os.listdir(to_dir):
os.mkdir(self.new_dir)
def assemble(self):
header = '\n---\n'.join([self.title_line,
self.date_line,
self.author,
'body:'])
return header + self.body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment