1
0
Fork 0
forked from github/pelican

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 -*-
from pelican.utils import slugify, truncate_html_words
from pelican.log import *
from pelican.settings import _DEFAULT_CONFIG
from datetime import datetime
import datetime
from os import getenv
from sys import platform, stdin
import locale
from pelican.log import *
from pelican.settings import _DEFAULT_CONFIG
from pelican.utils import slugify, truncate_html_words
class Page(object):
"""Represents a page
Given a content, and metadata, create an adequate object.
@ -90,7 +91,7 @@ class Page(object):
if isinstance(self.date_format, tuple):
locale.setlocale(locale.LC_ALL, self.date_format[0])
self.date_format = self.date_format[1]
if hasattr(self, 'date'):
if platform == 'win32':
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'):
self.status = settings['DEFAULT_STATUS']
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'
# set summary
@ -130,11 +131,10 @@ class Page(object):
"""Dummy function"""
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")
class Article(Page):
mandatory_properties = ('title', 'date', 'category')

View file

@ -1,22 +1,23 @@
# -*- 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 datetime
import math
import random
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.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 slugify
from pelican.contents import Article, Page, is_valid_content
from pelican.readers import read_file
from pelican.log import *
class Generator(object):
@ -231,7 +232,7 @@ class ArticlesGenerator(Generator):
if 'date' not in metadata.keys()\
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,
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, info, warning, warn, debug
from logging import Formatter, getLogger, StreamHandler
import sys
import os
global ANSI
ANSI = {
@ -62,20 +62,18 @@ class TextFormatter(Formatter):
class DummyFormatter(object):
"""
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):
if os.isatty(sys.stdout.fileno())\
and not sys.platform.startswith('win'):
and not sys.platform.startswith('win'):
return ANSIFormatter(*args, **kwargs)
else:
return TextFormatter( *args, **kwargs)
def init(level=None, logger=getLogger(), handler=StreamHandler()):
fmt = DummyFormatter()
handler.setFormatter(fmt)
@ -94,15 +92,15 @@ if __name__ == '__main__':
__all__ = [
"debug",
"info",
"warn",
"debug",
"info",
"warn",
"warning",
"error",
"critical",
"DEBUG",
"INFO",
"WARN",
"ERROR",
"error",
"critical",
"DEBUG",
"INFO",
"WARN",
"ERROR",
"CRITICAL"
]
]

View file

@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
import re
import os
import shutil
import pytz
from datetime import datetime
import re
import shutil
from codecs import open as _open
from datetime import datetime
from itertools import groupby
from operator import attrgetter
from pelican.log import warning, info
@ -16,10 +17,10 @@ def get_date(string):
If no format matches the given date, raise a ValuEerror
"""
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',
'%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']
for date_format in formats:
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)))
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_):
try:
@ -80,6 +81,7 @@ def copy(path, source, destination, destination_path=None, overwrite=False):
shutil.copy(source_, destination_)
info('copying %s to %s' % (source_, destination_))
def clean_output_dir(path):
"""Remove all the files from the output directory"""
@ -228,6 +230,7 @@ def files_changed(path, extensions):
return True
return False
def set_date_tzinfo(d, tz_name=None):
""" Date without tzinfo shoudbe utc.
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 -*-
from __future__ import with_statement
import os
import re
from codecs import open
from functools import partial
import locale
import re
from feedgenerator import Atom1Feed, Rss201rev2Feed
from pelican.utils import get_relative_path, set_date_tzinfo
from pelican.paginator import Paginator
from pelican.log import *
from pelican.utils import get_relative_path, set_date_tzinfo
class Writer(object):
@ -38,8 +38,8 @@ class Writer(object):
description=item.content,
categories=item.tags if hasattr(item, 'tags') else None,
author_name=getattr(item, 'author', 'John Doe'),
pubdate=set_date_tzinfo(item.date,
self.settings.get('TIMEZONE', None)))
pubdate=set_date_tzinfo(item.date,
self.settings.get('TIMEZONE', None)))
def write_feed(self, elements, context, filename=None, feed_type='atom'):
"""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 relative_urls: use relative urls or absolutes ones
: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
"""
@ -142,14 +142,14 @@ class Writer(object):
paginator = paginators[key]
page = paginator.page(page_num+1)
paginated_localcontext.update({'%s_paginator' % key: paginator,
'%s_page' % key: page})
'%s_page' % key: page})
if page_num > 0:
ext = '.' + paginated_name.rsplit('.')[-1]
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,
paginated_name)
paginated_name)
else:
# no pagination
_write_file(template, localcontext, self.output_path, name)
@ -161,7 +161,7 @@ class Writer(object):
:param name: name of the file to output.
:param context: dict that will be passed to the templates, which need to
be updated.
be updated.
"""
def _update_content(name, input):
"""Change all the relatives paths of the input content to relatives
@ -185,11 +185,11 @@ class Writer(object):
def replacer(m):
relative_path = m.group('path')
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 hrefs.sub(replacer, content)
if context is None:
return
if hasattr(context, 'values'):
@ -208,4 +208,4 @@ class Writer(object):
if relative_path not in paths:
paths.append(relative_path)
setattr(item, "_get_content",
partial(_update_content, name, item))
partial(_update_content, name, item))

View file

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

View file

@ -1,11 +1,12 @@
#! /usr/bin/env python
from pelican.utils import slugify
import argparse
import os
import time
from codecs import open
import os
import argparse
import time
from pelican.utils import slugify
def wp2fields(xml):
@ -132,7 +133,7 @@ def dc2fields(file):
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
"""
if post_format == "markdown":
@ -151,7 +152,7 @@ def feed2fields(file):
d = feedparser.parse(file)
for entry in d.entries:
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
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__':
parser = argparse.ArgumentParser(
description="Transform feed, Wordpress or Dotclear files to rst files."
"Be sure to have pandoc installed")
description="Transform feed, Wordpress or Dotclear files to rst files."
"Be sure to have pandoc installed")
parser.add_argument(dest='input', help='The input file to read')
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',
help='Dotclear export')
help='Dotclear export')
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',
help='Output path')
help='Output path')
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',
help='Put files in directories with categories name')
help='Put files in directories with categories name')
args = parser.parse_args()
input_type = None

View file

@ -5,7 +5,7 @@ import os, sys, argparse, string
from pelican import __version__
TEMPLATES={
'Makefile' : '''
'Makefile' : '''
PELICAN=$pelican
PELICANOPTS=$pelicanopts
@ -75,10 +75,10 @@ DEFAULT_LANG='$lang'
# Blogroll
LINKS = (
('Pelican', 'http://docs.notmyidea.org/alexis/pelican/'),
('Python.org', 'http://python.org'),
('Jinja2', 'http://jinja.pocoo.org'),
('You can modify those links in your config file', '#')
('Pelican', 'http://docs.notmyidea.org/alexis/pelican/'),
('Python.org', 'http://python.org'),
('Jinja2', 'http://jinja.pocoo.org'),
('You can modify those links in your config file', '#')
)
# Social widget
@ -129,7 +129,7 @@ def ask(question, answer=str, default=None, l=None):
r = raw_input('> {0} '.format(question, default))
r = r.strip()
if len(r) <= 0:
if default:
r = default
@ -194,17 +194,16 @@ def ask(question, answer=str, default=None, l=None):
def main():
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")
parser.add_argument('-t', '--title', default=None, metavar="title",
help='Set the title of the website')
parser.add_argument('-a', '--author', default=None, metavar="author",
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')
args = parser.parse_args()
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.
'''.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['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)
@ -227,7 +226,7 @@ Please answer the following questions so this script can generate the files need
CONF['default_pagination'] = False
mkfile = ask('Do you want to generate a Makefile to easily manage your website ?', bool, True)
if mkfile:
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'])

View file

@ -1,8 +1,10 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, shutil
import argparse
import os
import shutil
import sys
try:
import pelican
@ -38,11 +40,11 @@ def main():
excl= parser.add_mutually_exclusive_group()
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',
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__),
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",
@ -52,16 +54,16 @@ def main():
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")
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",
help="Verbose output")
help="Verbose output")
args = parser.parse_args()
if args.action:
if args.action is 'list':
list_themes(args.verbose)
@ -93,7 +95,7 @@ def main():
if args.clean:
if args.verbose:
print('Cleaning the themes directory...')
clean(v=args.verbose)
else:
print('No argument given... exiting.')
@ -142,7 +144,7 @@ def remove(theme_name, v=False):
print('Removing directory `' + target + "'")
shutil.rmtree(target)
elif os.path.exists(target):
err(target + ' : not a valid theme')
err(target + ' : not a valid theme')
else:
err(target + ' : no such file or directory')
@ -210,6 +212,6 @@ def clean(v=False):
c+=1
print("\nRemoved {0} broken links".format(c))
if __name__ == '__main__':
main()