aboutsummaryrefslogtreecommitdiffstats
path: root/nikola/plugins/command_import_blogger.py
diff options
context:
space:
mode:
Diffstat (limited to 'nikola/plugins/command_import_blogger.py')
-rw-r--r--nikola/plugins/command_import_blogger.py139
1 files changed, 70 insertions, 69 deletions
diff --git a/nikola/plugins/command_import_blogger.py b/nikola/plugins/command_import_blogger.py
index aea210a..35a702e 100644
--- a/nikola/plugins/command_import_blogger.py
+++ b/nikola/plugins/command_import_blogger.py
@@ -27,7 +27,6 @@ import codecs
import csv
import datetime
import os
-from optparse import OptionParser
import time
try:
@@ -52,9 +51,63 @@ class CommandImportBlogger(Command):
"""Import a blogger dump."""
name = "import_blogger"
+ needs_config = False
+ doc_usage = "[options] blogger_export_file"
+ doc_purpose = "Import a blogger dump."
+ cmd_options = [
+ {
+ 'name': 'output_folder',
+ 'long': 'output-folder',
+ 'short': 'o',
+ 'default': 'new_site',
+ 'help': 'Location to write imported content.'
+ },
+ {
+ 'name': 'exclude_drafts',
+ 'long': 'no-drafts',
+ 'short': 'd',
+ 'default': False,
+ 'type': bool,
+ 'help': "Don't import drafts",
+ },
+ ]
+
+ def _execute(self, options, args):
+ """Import a Wordpress blog from an export file into a Nikola site."""
+
+ # Parse the data
+ if feedparser is None:
+ print('To use the import_blogger command,'
+ ' you have to install the "feedparser" package.')
+ return
+
+ if not args:
+ print(self.help())
+ return
+
+ options['filename'] = args[0]
+ self.blogger_export_file = options['filename']
+ self.output_folder = options['output_folder']
+ self.import_into_existing_site = False
+ self.exclude_drafts = options['exclude_drafts']
+ self.url_map = {}
+ channel = self.get_channel_from_file(self.blogger_export_file)
+ self.context = self.populate_context(channel)
+ conf_template = self.generate_base_site()
+ self.context['REDIRECTIONS'] = self.configure_redirections(
+ self.url_map)
+
+ self.import_posts(channel)
+ self.write_urlmap_csv(
+ os.path.join(self.output_folder, 'url_map.csv'), self.url_map)
+
+ self.write_configuration(self.get_configuration_output_path(
+ ), conf_template.render(**self.context))
@classmethod
def get_channel_from_file(cls, filename):
+ if not os.path.isfile(filename):
+ raise Exception("Missing file: %s" % filename)
return feedparser.parse(filename)
@staticmethod
@@ -65,7 +118,7 @@ class CommandImportBlogger(Command):
src = (urlparse(k).path + 'index.html')[1:]
dst = (urlparse(v).path)
if src == 'index.html':
- print("Can't do a redirect for: %r" % k)
+ print("Can't do a redirect for: {0!r}".format(k))
else:
redirections.append((src, dst))
@@ -73,11 +126,11 @@ class CommandImportBlogger(Command):
def generate_base_site(self):
if not os.path.exists(self.output_folder):
- os.system('nikola init --empty %s' % (self.output_folder, ))
+ os.system('nikola init --empty ' + self.output_folder)
else:
self.import_into_existing_site = True
- print('The folder %s already exists - assuming that this is a '
- 'already existing nikola site.' % self.output_folder)
+ print('The folder {0} already exists - assuming that this is a '
+ 'already existing nikola site.'.format(self.output_folder))
conf_template = Template(filename=os.path.join(
os.path.dirname(utils.__file__), 'conf.py.in'))
@@ -92,7 +145,7 @@ class CommandImportBlogger(Command):
context['BLOG_TITLE'] = channel.feed.title
context['BLOG_DESCRIPTION'] = '' # Missing in the dump
- context['BLOG_URL'] = channel.feed.link.rstrip('/')
+ context['SITE_URL'] = channel.feed.link.rstrip('/')
context['BLOG_EMAIL'] = channel.feed.author_detail.email
context['BLOG_AUTHOR'] = channel.feed.author_detail.name
context['POST_PAGES'] = '''(
@@ -124,12 +177,8 @@ class CommandImportBlogger(Command):
@staticmethod
def write_metadata(filename, title, slug, post_date, description, tags):
with codecs.open(filename, "w+", "utf8") as fd:
- fd.write('%s\n' % title)
- fd.write('%s\n' % slug)
- fd.write('%s\n' % post_date)
- fd.write('%s\n' % ','.join(tags))
- fd.write('\n')
- fd.write('%s\n' % description)
+ fd.write('\n'.join((title, slug, post_date, ','.join(tags), '',
+ description)))
def import_item(self, item, out_folder=None):
"""Takes an item from the feed and creates a post file."""
@@ -145,8 +194,8 @@ class CommandImportBlogger(Command):
# blogger supports empty titles, which Nikola doesn't
if not title:
- print("Warning: Empty title in post with URL %s. Using NO_TITLE "
- "as placeholder, please fix." % link)
+ print("Warning: Empty title in post with URL {0}. Using NO_TITLE "
+ "as placeholder, please fix.".format(link))
title = "NO_TITLE"
if link_path.lower().endswith('.html'):
@@ -179,11 +228,11 @@ class CommandImportBlogger(Command):
else:
is_draft = False
- self.url_map[link] = self.context['BLOG_URL'] + '/' + \
+ self.url_map[link] = self.context['SITE_URL'] + '/' + \
out_folder + '/' + slug + '.html'
if is_draft and self.exclude_drafts:
- print('Draft "%s" will not be imported.' % (title, ))
+ print('Draft "{0}" will not be imported.'.format(title))
elif content.strip():
# If no content is found, no files are written.
content = self.transform_content(content)
@@ -195,8 +244,8 @@ class CommandImportBlogger(Command):
os.path.join(self.output_folder, out_folder, slug + '.html'),
content)
else:
- print('Not going to import "%s" because it seems to contain'
- ' no content.' % (title, ))
+ print('Not going to import "{0}" because it seems to contain'
+ ' no content.'.format(title))
def process_item(self, item):
post_type = item.tags[0].term
@@ -235,10 +284,10 @@ class CommandImportBlogger(Command):
if not self.import_into_existing_site:
filename = 'conf.py'
else:
- filename = 'conf.py.wordpress_import-%s' % datetime.datetime.now(
- ).strftime('%Y%m%d_%H%M%s')
+ filename = 'conf.py.wordpress_import-{0}'.format(
+ datetime.datetime.now().strftime('%Y%m%d_%H%M%s'))
config_output_path = os.path.join(self.output_folder, filename)
- print('Configuration will be written to: %s' % config_output_path)
+ print('Configuration will be written to: ' + config_output_path)
return config_output_path
@@ -247,54 +296,6 @@ class CommandImportBlogger(Command):
with codecs.open(filename, 'w+', 'utf8') as fd:
fd.write(rendered_template)
- def run(self, *arguments):
- """Import a Wordpress blog from an export file into a Nikola site."""
- # Parse the data
- if feedparser is None:
- print('To use the import_blogger command,'
- ' you have to install the "feedparser" package.')
- return
-
- parser = OptionParser(
- usage="nikola %s [options] blogger_export_file" % self.name)
- parser.add_option('-f', '--filename', dest='filename',
- help='Blogger export file from which the import is '
- 'made.')
- parser.add_option('-o', '--output-folder', dest='output_folder',
- default='new_site',
- help='The location into which the imported content '
- 'will be written')
- parser.add_option('-d', '--no-drafts', dest='exclude_drafts',
- default=False, action="store_true", help='Do not '
- 'import drafts.')
-
- (options, args) = parser.parse_args(list(arguments))
-
- if not options.filename and args:
- options.filename = args[0]
-
- if not options.filename:
- parser.print_usage()
- return
-
- self.blogger_export_file = options.filename
- self.output_folder = options.output_folder
- self.import_into_existing_site = False
- self.exclude_drafts = options.exclude_drafts
- self.url_map = {}
- channel = self.get_channel_from_file(self.blogger_export_file)
- self.context = self.populate_context(channel)
- conf_template = self.generate_base_site()
- self.context['REDIRECTIONS'] = self.configure_redirections(
- self.url_map)
-
- self.import_posts(channel)
- self.write_urlmap_csv(
- os.path.join(self.output_folder, 'url_map.csv'), self.url_map)
-
- self.write_configuration(self.get_configuration_output_path(
- ), conf_template.render(**self.context))
-
def replacer(dst):
return links.get(dst, dst)