Skip to content

Instantly share code, notes, and snippets.

@punchagan
Last active December 25, 2015 11:39
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 punchagan/6970578 to your computer and use it in GitHub Desktop.
Save punchagan/6970578 to your computer and use it in GitHub Desktop.
Scripts to import blog from o-blog to Nikola.
import codecs
import os
from os.path import exists, join
from orgparse import load
from nikola.utils import slugify
DATE_FORMAT = '%Y/%m/%d %H:%M:%S'
def to_text(node):
""" Get the writable format of a node.
For level 3 nodes, just write the body, after stripping off 4 spaces.
For other nodes, write the heading and the body (after stripping of 4
spaces from the left)
"""
if node.level > 3:
stars = '*' * ((node.level - 1)/2)
heading = '%s %s' % (stars, node.heading)
else:
heading = ''
lines = ['', heading]
for line in node.body.splitlines():
if line[:4].strip() == '':
lines.append(line[4:])
else:
lines.append(line)
lines.append('')
text = '\n'.join(lines)
return text
def nikola_write(post):
post_slug = slugify(post.heading)
post_file = join('posts', '%s.org' % post_slug)
with codecs.open(post_file, 'w') as f:
f.write('#+BEGIN_COMMENT\n')
f.write('.. title: %s\n' % post.heading.encode('utf8'))
f.write('.. date: %s\n' % post.closed.start.strftime(DATE_FORMAT))
f.write('.. tags: %s\n' % ', '.join(sorted(post.tags)))
f.write('.. slug: %s\n' % post_slug)
f.write('#+END_COMMENT\n')
f.write('\n') # blank line
f.write(to_text(post).encode('utf8'))
def write_children(root, fp):
for node in root.children:
fp.write(to_text(node).encode('utf8'))
write_children(node, fp)
write_children(post, f)
def import_blog(infile):
root = load(infile)
blog = root.children[0]
for post in blog.children:
nikola_write(post)
if __name__ == '__main__':
import sys
infile = sys.argv[1]
if not exists('posts'):
os.mkdir('posts')
import_blog(infile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment