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.
@ -90,7 +91,7 @@ class Page(object):
if isinstance(self.date_format, tuple): if isinstance(self.date_format, tuple):
locale.setlocale(locale.LC_ALL, self.date_format[0]) locale.setlocale(locale.LC_ALL, self.date_format[0])
self.date_format = self.date_format[1] self.date_format = self.date_format[1]
if hasattr(self, 'date'): if hasattr(self, 'date'):
if platform == 'win32': if platform == 'win32':
self.locale_date = self.date.strftime(self.date_format.encode('ascii','xmlcharrefreplace')).decode(stdin.encoding) self.locale_date = self.date.strftime(self.date_format.encode('ascii','xmlcharrefreplace')).decode(stdin.encoding)
@ -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,20 +62,18 @@ 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):
if os.isatty(sys.stdout.fileno())\ if os.isatty(sys.stdout.fileno())\
and not sys.platform.startswith('win'): and not sys.platform.startswith('win'):
return ANSIFormatter(*args, **kwargs) return ANSIFormatter(*args, **kwargs)
else: else:
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)
@ -94,15 +92,15 @@ if __name__ == '__main__':
__all__ = [ __all__ = [
"debug", "debug",
"info", "info",
"warn", "warn",
"warning", "warning",
"error", "error",
"critical", "critical",
"DEBUG", "DEBUG",
"INFO", "INFO",
"WARN", "WARN",
"ERROR", "ERROR",
"CRITICAL" "CRITICAL"
] ]

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
@ -16,10 +17,10 @@ def get_date(string):
If no format matches the given date, raise a ValuEerror If no format matches the given date, raise a ValuEerror
""" """
string = re.sub(' +', ' ', string) string = re.sub(' +', ' ', string)
formats = ['%Y-%m-%d %H:%M', '%Y/%m/%d %H:%M', formats = ['%Y-%m-%d %H:%M', '%Y/%m/%d %H:%M',
'%Y-%m-%d', '%Y/%m/%d', '%Y-%m-%d', '%Y/%m/%d',
'%d-%m-%Y', '%Y-%d-%m', # Weird ones '%d-%m-%Y', '%Y-%d-%m', # Weird ones
'%d/%m/%Y', '%d.%m.%Y', '%d/%m/%Y', '%d.%m.%Y',
'%d.%m.%Y %H:%M', '%Y-%m-%d %H:%M:%S'] '%d.%m.%Y %H:%M', '%Y-%m-%d %H:%M:%S']
for date_format in formats: for date_format in formats:
try: try:
@ -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):
@ -38,8 +38,8 @@ class Writer(object):
description=item.content, description=item.content,
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,11 +185,11 @@ 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)
if context is None: if context is None:
return return
if hasattr(context, 'values'): if hasattr(context, 'values'):
@ -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):
@ -132,7 +133,7 @@ def dc2fields(file):
j=j+2 j=j+2
""" """
dotclear2 does not use markdown by default unless you use the markdown plugin dotclear2 does not use markdown by default unless you use the markdown plugin
Ref: http://plugins.dotaddict.org/dc2/details/formatting-markdown Ref: http://plugins.dotaddict.org/dc2/details/formatting-markdown
""" """
if post_format == "markdown": if post_format == "markdown":
@ -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
@ -129,7 +129,7 @@ def ask(question, answer=str, default=None, l=None):
r = raw_input('> {0} '.format(question, default)) r = raw_input('> {0} '.format(question, default))
r = r.strip() r = r.strip()
if len(r) <= 0: if len(r) <= 0:
if default: if default:
r = default r = default
@ -194,17 +194,16 @@ def ask(question, answer=str, default=None, l=None):
def main(): def main():
parser = argparse.ArgumentParser(description="A kickstarter for pelican") parser = argparse.ArgumentParser(description="A kickstarter for pelican")
parser.add_argument('-p', '--path', default=".", parser.add_argument('-p', '--path', default=".",
help="The path to generate the blog into") help="The path to generate the blog into")
parser.add_argument('-t', '--title', default=None, metavar="title", parser.add_argument('-t', '--title', default=None, metavar="title",
help='Set the title of the website') help='Set the title of the website')
parser.add_argument('-a', '--author', default=None, metavar="author", parser.add_argument('-a', '--author', default=None, metavar="author",
help='Set the author name of the website') help='Set the author name of the website')
parser.add_argument('-l', '--lang', default=None, metavar="lang", parser.add_argument('-l', '--lang', default=None, metavar="lang",
help='Set the default lang of the website') help='Set the default lang of the website')
args = parser.parse_args() args = parser.parse_args()
print('''Welcome to pelican-quickstart v{v}. print('''Welcome to pelican-quickstart v{v}.
@ -213,7 +212,7 @@ This script will help you creating a new Pelican based website.
Please answer the following questions so this script can generate the files needed by Pelican. Please answer the following questions so this script can generate the files needed by Pelican.
'''.format(v=__version__)) '''.format(v=__version__))
CONF['basedir'] = os.path.abspath(ask('Where do you want to create your new Web site ?', answer=str, default=args.path)) CONF['basedir'] = os.path.abspath(ask('Where do you want to create your new Web site ?', answer=str, default=args.path))
CONF['sitename'] = ask('How will you call your Web site ?', answer=str, default=args.title) CONF['sitename'] = ask('How will you call your Web site ?', answer=str, default=args.title)
CONF['author'] = ask('Who will be the author of this Web site ?', answer=str, default=args.author) CONF['author'] = ask('Who will be the author of this Web site ?', answer=str, default=args.author)
@ -227,7 +226,7 @@ Please answer the following questions so this script can generate the files need
CONF['default_pagination'] = False CONF['default_pagination'] = False
mkfile = ask('Do you want to generate a Makefile to easily manage your website ?', bool, True) mkfile = ask('Do you want to generate a Makefile to easily manage your website ?', bool, True)
if mkfile: if mkfile:
if ask('Do you want to upload your website using FTP ?', answer=bool, default=False): if ask('Do you want to upload your website using FTP ?', answer=bool, default=False):
CONF['ftp_host'] = ask('What is the hostname of your FTP server ?', str, CONF['ftp_host']) CONF['ftp_host'] = ask('What is the hostname of your FTP server ?', str, CONF['ftp_host'])

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,16 +54,16 @@ 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()
if args.action: if args.action:
if args.action is 'list': if args.action is 'list':
list_themes(args.verbose) list_themes(args.verbose)
@ -93,7 +95,7 @@ def main():
if args.clean: if args.clean:
if args.verbose: if args.verbose:
print('Cleaning the themes directory...') print('Cleaning the themes directory...')
clean(v=args.verbose) clean(v=args.verbose)
else: else:
print('No argument given... exiting.') print('No argument given... exiting.')
@ -142,7 +144,7 @@ def remove(theme_name, v=False):
print('Removing directory `' + target + "'") print('Removing directory `' + target + "'")
shutil.rmtree(target) shutil.rmtree(target)
elif os.path.exists(target): elif os.path.exists(target):
err(target + ' : not a valid theme') err(target + ' : not a valid theme')
else: else:
err(target + ' : no such file or directory') err(target + ' : no such file or directory')
@ -210,6 +212,6 @@ def clean(v=False):
c+=1 c+=1
print("\nRemoved {0} broken links".format(c)) print("\nRemoved {0} broken links".format(c))
if __name__ == '__main__': if __name__ == '__main__':
main() main()