Sort imports and remove trailing whitespaces

This commit is contained in:
Stéphane Raimbault 2012-02-21 17:53:53 +01:00
commit 9cced6be83
9 changed files with 93 additions and 88 deletions

View file

@ -1,12 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from pelican.utils import slugify, truncate_html_words import datetime
from pelican.log import *
from pelican.settings import _DEFAULT_CONFIG
from datetime import datetime
from os import getenv from os import getenv
from sys import platform, stdin from sys import platform, stdin
import locale import locale
from pelican.log import *
from pelican.settings import _DEFAULT_CONFIG
from pelican.utils import slugify, truncate_html_words
class Page(object): class Page(object):
"""Represents a page """Represents a page
Given a content, and metadata, create an adequate object. Given a content, and metadata, create an adequate object.
@ -101,7 +102,7 @@ class Page(object):
if not hasattr(self, 'status'): if not hasattr(self, 'status'):
self.status = settings['DEFAULT_STATUS'] self.status = settings['DEFAULT_STATUS']
if not settings['WITH_FUTURE_DATES']: if not settings['WITH_FUTURE_DATES']:
if hasattr(self, 'date') and self.date > datetime.now(): if hasattr(self, 'date') and self.date > datetime.datetime.now():
self.status = 'draft' self.status = 'draft'
# set summary # set summary
@ -130,11 +131,10 @@ class Page(object):
"""Dummy function""" """Dummy function"""
pass pass
summary = property(_get_summary, _set_summary, \ summary = property(_get_summary, _set_summary,
"Summary of the article. Based on the content. Can't be set") "Summary of the article. Based on the content. Can't be set")
class Article(Page): class Article(Page):
mandatory_properties = ('title', 'date', 'category') mandatory_properties = ('title', 'date', 'category')

View file

@ -1,22 +1,23 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from operator import attrgetter, itemgetter
from itertools import chain
from functools import partial
from datetime import datetime
from collections import defaultdict
import os import os
import datetime
import math import math
import random import random
import urlparse import urlparse
from collections import defaultdict
from functools import partial
from itertools import chain
from operator import attrgetter, itemgetter
from jinja2 import Environment, FileSystemLoader, PrefixLoader, ChoiceLoader from jinja2 import Environment, FileSystemLoader, PrefixLoader, ChoiceLoader
from jinja2.exceptions import TemplateNotFound from jinja2.exceptions import TemplateNotFound
from pelican.contents import Article, Page, is_valid_content
from pelican.log import *
from pelican.readers import read_file
from pelican.utils import copy, process_translations, open from pelican.utils import copy, process_translations, open
from pelican.utils import slugify from pelican.utils import slugify
from pelican.contents import Article, Page, is_valid_content
from pelican.readers import read_file
from pelican.log import *
class Generator(object): class Generator(object):
@ -231,7 +232,7 @@ class ArticlesGenerator(Generator):
if 'date' not in metadata.keys()\ if 'date' not in metadata.keys()\
and self.settings['FALLBACK_ON_FS_DATE']: and self.settings['FALLBACK_ON_FS_DATE']:
metadata['date'] = datetime.fromtimestamp(os.stat(f).st_ctime) metadata['date'] = datetime.datetime.fromtimestamp(os.stat(f).st_ctime)
article = Article(content, metadata, settings=self.settings, article = Article(content, metadata, settings=self.settings,
filename=f) filename=f)

View file

@ -1,8 +1,8 @@
import os
import sys
from logging import CRITICAL, ERROR, WARN, INFO, DEBUG from logging import CRITICAL, ERROR, WARN, INFO, DEBUG
from logging import critical, error, info, warning, warn, debug from logging import critical, error, info, warning, warn, debug
from logging import Formatter, getLogger, StreamHandler from logging import Formatter, getLogger, StreamHandler
import sys
import os
global ANSI global ANSI
ANSI = { ANSI = {
@ -62,7 +62,8 @@ class TextFormatter(Formatter):
class DummyFormatter(object): class DummyFormatter(object):
""" """
A dummy class. A dummy class.
Return an instance of the appropriate formatter (ANSIFormatter if sys.stdout.isatty() is True, else TextFormatter) Return an instance of the appropriate formatter (ANSIFormatter if
sys.stdout.isatty() is True, else TextFormatter)
""" """
def __new__(cls, *args, **kwargs): def __new__(cls, *args, **kwargs):
@ -73,9 +74,6 @@ class DummyFormatter(object):
return TextFormatter( *args, **kwargs) return TextFormatter( *args, **kwargs)
def init(level=None, logger=getLogger(), handler=StreamHandler()): def init(level=None, logger=getLogger(), handler=StreamHandler()):
fmt = DummyFormatter() fmt = DummyFormatter()
handler.setFormatter(fmt) handler.setFormatter(fmt)

View file

@ -1,10 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import re
import os import os
import shutil
import pytz import pytz
from datetime import datetime import re
import shutil
from codecs import open as _open from codecs import open as _open
from datetime import datetime
from itertools import groupby from itertools import groupby
from operator import attrgetter from operator import attrgetter
from pelican.log import warning, info from pelican.log import warning, info
@ -64,7 +65,7 @@ def copy(path, source, destination, destination_path=None, overwrite=False):
source_ = os.path.abspath(os.path.expanduser(os.path.join(source, path))) source_ = os.path.abspath(os.path.expanduser(os.path.join(source, path)))
destination_ = os.path.abspath( destination_ = os.path.abspath(
os.path.expanduser(os.path.join(destination, destination_path))) os.path.expanduser(os.path.join(destination, destination_path)))
if os.path.isdir(source_): if os.path.isdir(source_):
try: try:
@ -80,6 +81,7 @@ def copy(path, source, destination, destination_path=None, overwrite=False):
shutil.copy(source_, destination_) shutil.copy(source_, destination_)
info('copying %s to %s' % (source_, destination_)) info('copying %s to %s' % (source_, destination_))
def clean_output_dir(path): def clean_output_dir(path):
"""Remove all the files from the output directory""" """Remove all the files from the output directory"""
@ -228,6 +230,7 @@ def files_changed(path, extensions):
return True return True
return False return False
def set_date_tzinfo(d, tz_name=None): def set_date_tzinfo(d, tz_name=None):
""" Date without tzinfo shoudbe utc. """ Date without tzinfo shoudbe utc.
This function set the right tz to date that aren't utc and don't have tzinfo This function set the right tz to date that aren't utc and don't have tzinfo

View file

@ -1,15 +1,15 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import with_statement from __future__ import with_statement
import os import os
import re
from codecs import open from codecs import open
from functools import partial from functools import partial
import locale import locale
import re
from feedgenerator import Atom1Feed, Rss201rev2Feed from feedgenerator import Atom1Feed, Rss201rev2Feed
from pelican.utils import get_relative_path, set_date_tzinfo
from pelican.paginator import Paginator from pelican.paginator import Paginator
from pelican.log import * from pelican.log import *
from pelican.utils import get_relative_path, set_date_tzinfo
class Writer(object): class Writer(object):
@ -39,7 +39,7 @@ class Writer(object):
categories=item.tags if hasattr(item, 'tags') else None, categories=item.tags if hasattr(item, 'tags') else None,
author_name=getattr(item, 'author', 'John Doe'), author_name=getattr(item, 'author', 'John Doe'),
pubdate=set_date_tzinfo(item.date, pubdate=set_date_tzinfo(item.date,
self.settings.get('TIMEZONE', None))) self.settings.get('TIMEZONE', None)))
def write_feed(self, elements, context, filename=None, feed_type='atom'): def write_feed(self, elements, context, filename=None, feed_type='atom'):
"""Generate a feed with the list of articles provided """Generate a feed with the list of articles provided
@ -90,7 +90,7 @@ class Writer(object):
:param context: dict to pass to the templates. :param context: dict to pass to the templates.
:param relative_urls: use relative urls or absolutes ones :param relative_urls: use relative urls or absolutes ones
:param paginated: dict of article list to paginate - must have the :param paginated: dict of article list to paginate - must have the
same length (same list in different orders) same length (same list in different orders)
:param **kwargs: additional variables to pass to the templates :param **kwargs: additional variables to pass to the templates
""" """
@ -142,14 +142,14 @@ class Writer(object):
paginator = paginators[key] paginator = paginators[key]
page = paginator.page(page_num+1) page = paginator.page(page_num+1)
paginated_localcontext.update({'%s_paginator' % key: paginator, paginated_localcontext.update({'%s_paginator' % key: paginator,
'%s_page' % key: page}) '%s_page' % key: page})
if page_num > 0: if page_num > 0:
ext = '.' + paginated_name.rsplit('.')[-1] ext = '.' + paginated_name.rsplit('.')[-1]
paginated_name = paginated_name.replace(ext, paginated_name = paginated_name.replace(ext,
'%s%s' % (page_num + 1, ext)) '%s%s' % (page_num + 1, ext))
_write_file(template, paginated_localcontext, self.output_path, _write_file(template, paginated_localcontext, self.output_path,
paginated_name) paginated_name)
else: else:
# no pagination # no pagination
_write_file(template, localcontext, self.output_path, name) _write_file(template, localcontext, self.output_path, name)
@ -161,7 +161,7 @@ class Writer(object):
:param name: name of the file to output. :param name: name of the file to output.
:param context: dict that will be passed to the templates, which need to :param context: dict that will be passed to the templates, which need to
be updated. be updated.
""" """
def _update_content(name, input): def _update_content(name, input):
"""Change all the relatives paths of the input content to relatives """Change all the relatives paths of the input content to relatives
@ -185,7 +185,7 @@ class Writer(object):
def replacer(m): def replacer(m):
relative_path = m.group('path') relative_path = m.group('path')
dest_path = os.path.normpath( os.sep.join( (get_relative_path(name), dest_path = os.path.normpath( os.sep.join( (get_relative_path(name),
"static", relative_path) ) ) "static", relative_path) ) )
return m.group('markup') + m.group('quote') + dest_path + m.group('quote') return m.group('markup') + m.group('quote') + dest_path + m.group('quote')
return hrefs.sub(replacer, content) return hrefs.sub(replacer, content)
@ -208,4 +208,4 @@ class Writer(object):
if relative_path not in paths: if relative_path not in paths:
paths.append(relative_path) paths.append(relative_path)
setattr(item, "_get_content", setattr(item, "_get_content",
partial(_update_content, name, item)) partial(_update_content, name, item))

View file

@ -4,8 +4,9 @@ try:
except ImportError, e: except ImportError, e:
import unittest as unittest2 import unittest as unittest2
import os
import datetime import datetime
import os
from pelican import readers from pelican import readers
CUR_DIR = os.path.dirname(__file__) CUR_DIR = os.path.dirname(__file__)

View file

@ -1,11 +1,12 @@
#! /usr/bin/env python #! /usr/bin/env python
from pelican.utils import slugify import argparse
import os
import time
from codecs import open from codecs import open
import os
import argparse from pelican.utils import slugify
import time
def wp2fields(xml): def wp2fields(xml):
@ -151,7 +152,7 @@ def feed2fields(file):
d = feedparser.parse(file) d = feedparser.parse(file)
for entry in d.entries: for entry in d.entries:
date = (time.strftime("%Y-%m-%d %H:%M", entry.updated_parsed) date = (time.strftime("%Y-%m-%d %H:%M", entry.updated_parsed)
if hasattr(entry, "updated_parsed") else None) if hasattr(entry, "updated_parsed") else None)
author = entry.author if hasattr(entry, "author") else None author = entry.author if hasattr(entry, "author") else None
tags = [e['term'] for e in entry.tags] if hasattr(entry, "tags") else None tags = [e['term'] for e in entry.tags] if hasattr(entry, "tags") else None
@ -243,22 +244,22 @@ def main(input_type, input, out_markup, output_path, dircat=False):
if __name__ == '__main__': if __name__ == '__main__':
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Transform feed, Wordpress or Dotclear files to rst files." description="Transform feed, Wordpress or Dotclear files to rst files."
"Be sure to have pandoc installed") "Be sure to have pandoc installed")
parser.add_argument(dest='input', help='The input file to read') parser.add_argument(dest='input', help='The input file to read')
parser.add_argument('--wpfile', action='store_true', dest='wpfile', parser.add_argument('--wpfile', action='store_true', dest='wpfile',
help='Wordpress XML export') help='Wordpress XML export')
parser.add_argument('--dotclear', action='store_true', dest='dotclear', parser.add_argument('--dotclear', action='store_true', dest='dotclear',
help='Dotclear export') help='Dotclear export')
parser.add_argument('--feed', action='store_true', dest='feed', parser.add_argument('--feed', action='store_true', dest='feed',
help='Feed to parse') help='Feed to parse')
parser.add_argument('-o', '--output', dest='output', default='output', parser.add_argument('-o', '--output', dest='output', default='output',
help='Output path') help='Output path')
parser.add_argument('-m', '--markup', dest='markup', default='rst', parser.add_argument('-m', '--markup', dest='markup', default='rst',
help='Output markup format (supports rst & markdown)') help='Output markup format (supports rst & markdown)')
parser.add_argument('--dir-cat', action='store_true', dest='dircat', parser.add_argument('--dir-cat', action='store_true', dest='dircat',
help='Put files in directories with categories name') help='Put files in directories with categories name')
args = parser.parse_args() args = parser.parse_args()
input_type = None input_type = None

View file

@ -5,7 +5,7 @@ import os, sys, argparse, string
from pelican import __version__ from pelican import __version__
TEMPLATES={ TEMPLATES={
'Makefile' : ''' 'Makefile' : '''
PELICAN=$pelican PELICAN=$pelican
PELICANOPTS=$pelicanopts PELICANOPTS=$pelicanopts
@ -75,10 +75,10 @@ DEFAULT_LANG='$lang'
# Blogroll # Blogroll
LINKS = ( LINKS = (
('Pelican', 'http://docs.notmyidea.org/alexis/pelican/'), ('Pelican', 'http://docs.notmyidea.org/alexis/pelican/'),
('Python.org', 'http://python.org'), ('Python.org', 'http://python.org'),
('Jinja2', 'http://jinja.pocoo.org'), ('Jinja2', 'http://jinja.pocoo.org'),
('You can modify those links in your config file', '#') ('You can modify those links in your config file', '#')
) )
# Social widget # Social widget
@ -205,7 +205,6 @@ def main():
args = parser.parse_args() args = parser.parse_args()
print('''Welcome to pelican-quickstart v{v}. print('''Welcome to pelican-quickstart v{v}.
This script will help you creating a new Pelican based website. This script will help you creating a new Pelican based website.

View file

@ -1,8 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os, sys, shutil
import argparse import argparse
import os
import shutil
import sys
try: try:
import pelican import pelican
@ -38,11 +40,11 @@ def main():
excl= parser.add_mutually_exclusive_group() excl= parser.add_mutually_exclusive_group()
excl.add_argument('-l', '--list', dest='action', action="store_const", const='list', excl.add_argument('-l', '--list', dest='action', action="store_const", const='list',
help="Show the themes already installed and exit") help="Show the themes already installed and exit")
excl.add_argument('-p', '--path', dest='action', action="store_const", const='path', excl.add_argument('-p', '--path', dest='action', action="store_const", const='path',
help="Show the themes path and exit") help="Show the themes path and exit")
excl.add_argument('-V', '--version', action='version', version='pelican-themes v{0}'.format(__version__), excl.add_argument('-V', '--version', action='version', version='pelican-themes v{0}'.format(__version__),
help='Print the version of this script') help='Print the version of this script')
parser.add_argument('-i', '--install', dest='to_install', nargs='+', metavar="theme path", parser.add_argument('-i', '--install', dest='to_install', nargs='+', metavar="theme path",
@ -52,11 +54,11 @@ def main():
parser.add_argument('-s', '--symlink', dest='to_symlink', nargs='+', metavar="theme path", parser.add_argument('-s', '--symlink', dest='to_symlink', nargs='+', metavar="theme path",
help="Same as `--install', but create a symbolic link instead of copying the theme. Useful for theme development") help="Same as `--install', but create a symbolic link instead of copying the theme. Useful for theme development")
parser.add_argument('-c', '--clean', dest='clean', action="store_true", parser.add_argument('-c', '--clean', dest='clean', action="store_true",
help="Remove the broken symbolic links of the theme path") help="Remove the broken symbolic links of the theme path")
parser.add_argument('-v', '--verbose', dest='verbose', action="store_true", parser.add_argument('-v', '--verbose', dest='verbose', action="store_true",
help="Verbose output") help="Verbose output")
args = parser.parse_args() args = parser.parse_args()