1
0
Fork 0
forked from github/pelican

Modernize code base to Python 3+ syntax

Replaces syntax that was relevant in earlier Python versions but that
now has modernized equivalents.
This commit is contained in:
Justin Mayer 2020-04-26 09:55:08 +02:00
commit d43b786b30
37 changed files with 104 additions and 171 deletions

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import os import os
import sys import sys
@ -23,7 +21,7 @@ release = __version__
version = '.'.join(release.split('.')[:1]) version = '.'.join(release.split('.')[:1])
last_stable = __version__ last_stable = __version__
rst_prolog = ''' rst_prolog = '''
.. |last_stable| replace:: :pelican-doc:`{0}` .. |last_stable| replace:: :pelican-doc:`{}`
'''.format(last_stable) '''.format(last_stable)
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import argparse import argparse
import logging import logging
import multiprocessing import multiprocessing
@ -40,7 +38,7 @@ DEFAULT_CONFIG_NAME = 'pelicanconf.py'
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Pelican(object): class Pelican:
def __init__(self, settings): def __init__(self, settings):
"""Pelican initialisation """Pelican initialisation
@ -255,7 +253,7 @@ def parse_arguments(argv=None):
parser.add_argument('-s', '--settings', dest='settings', parser.add_argument('-s', '--settings', dest='settings',
help='The settings of the application, this is ' help='The settings of the application, this is '
'automatically set to {0} if a file exists with this ' 'automatically set to {} if a file exists with this '
'name.'.format(DEFAULT_CONFIG_NAME)) 'name.'.format(DEFAULT_CONFIG_NAME))
parser.add_argument('-d', '--delete-output-directory', parser.add_argument('-d', '--delete-output-directory',
@ -494,11 +492,13 @@ def main(argv=None):
pelican, settings = get_instance(args) pelican, settings = get_instance(args)
readers = Readers(settings) readers = Readers(settings)
reader_descs = sorted(set(['%s (%s)' % reader_descs = sorted(
(type(r).__name__, {
', '.join(r.file_extensions)) '%s (%s)' % (type(r).__name__, ', '.join(r.file_extensions))
for r in readers.readers.values() for r in readers.readers.values()
if r.enabled])) if r.enabled
}
)
watchers = {'content': folder_watcher(pelican.path, watchers = {'content': folder_watcher(pelican.path,
readers.extensions, readers.extensions,

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import hashlib import hashlib
import logging import logging
import os import os
@ -10,7 +8,7 @@ from pelican.utils import mkdir_p
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class FileDataCacher(object): class FileDataCacher:
"""Class that can cache data contained in files""" """Class that can cache data contained in files"""
def __init__(self, settings, cache_name, caching_policy, load_policy): def __init__(self, settings, cache_name, caching_policy, load_policy):
@ -33,7 +31,7 @@ class FileDataCacher(object):
try: try:
with self._cache_open(self._cache_path, 'rb') as fhandle: with self._cache_open(self._cache_path, 'rb') as fhandle:
self._cache = pickle.load(fhandle) self._cache = pickle.load(fhandle)
except (IOError, OSError, UnicodeDecodeError) as err: except (OSError, UnicodeDecodeError) as err:
logger.debug('Cannot load cache %s (this is normal on first ' logger.debug('Cannot load cache %s (this is normal on first '
'run). Proceeding with empty cache.\n%s', 'run). Proceeding with empty cache.\n%s',
self._cache_path, err) self._cache_path, err)
@ -67,7 +65,7 @@ class FileDataCacher(object):
mkdir_p(self.settings['CACHE_PATH']) mkdir_p(self.settings['CACHE_PATH'])
with self._cache_open(self._cache_path, 'wb') as fhandle: with self._cache_open(self._cache_path, 'wb') as fhandle:
pickle.dump(self._cache, fhandle) pickle.dump(self._cache, fhandle)
except (IOError, OSError, pickle.PicklingError) as err: except (OSError, pickle.PicklingError) as err:
logger.warning('Could not save cache %s\n ... %s', logger.warning('Could not save cache %s\n ... %s',
self._cache_path, err) self._cache_path, err)
@ -116,7 +114,7 @@ class FileStampDataCacher(FileDataCacher):
try: try:
return self._filestamp_func(filename) return self._filestamp_func(filename)
except (IOError, OSError, TypeError) as err: except (OSError, TypeError) as err:
logger.warning('Cannot get modification stamp for %s\n\t%s', logger.warning('Cannot get modification stamp for %s\n\t%s',
filename, err) filename, err)
return '' return ''

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import copy import copy
import datetime import datetime
import locale import locale
@ -22,7 +20,7 @@ from pelican.urlwrappers import (Author, Category, Tag, URLWrapper) # NOQA
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Content(object): class Content:
"""Represents a content. """Represents a content.
:param content: the string to parse, containing the original content. :param content: the string to parse, containing the original content.
@ -216,7 +214,7 @@ class Content(object):
def _expand_settings(self, key, klass=None): def _expand_settings(self, key, klass=None):
if not klass: if not klass:
klass = self.__class__.__name__ klass = self.__class__.__name__
fq_key = ('%s_%s' % (klass, key)).upper() fq_key = ('{}_{}'.format(klass, key)).upper()
return self.settings[fq_key].format(**self.url_format) return self.settings[fq_key].format(**self.url_format)
def get_url_setting(self, key): def get_url_setting(self, key):
@ -324,7 +322,7 @@ class Content(object):
(?:href|src|poster|data|cite|formaction|action)\s*=\s*) (?:href|src|poster|data|cite|formaction|action)\s*=\s*)
(?P<quote>["\']) # require value to be quoted (?P<quote>["\']) # require value to be quoted
(?P<path>{0}(?P<value>.*?)) # the url value (?P<path>{}(?P<value>.*?)) # the url value
\2""".format(intrasite_link_regex) \2""".format(intrasite_link_regex)
return re.compile(regex, re.X) return re.compile(regex, re.X)

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import calendar import calendar
import errno import errno
import fnmatch import fnmatch
@ -28,7 +26,7 @@ class PelicanTemplateNotFound(Exception):
pass pass
class Generator(object): class Generator:
"""Baseclass generator""" """Baseclass generator"""
def __init__(self, context, settings, path, theme, output_path, def __init__(self, context, settings, path, theme, output_path,
@ -262,7 +260,7 @@ class _FileLoader(BaseLoader):
if template != self.path or not os.path.exists(self.fullpath): if template != self.path or not os.path.exists(self.fullpath):
raise TemplateNotFound(template) raise TemplateNotFound(template)
mtime = os.path.getmtime(self.fullpath) mtime = os.path.getmtime(self.fullpath)
with open(self.fullpath, 'r', encoding='utf-8') as f: with open(self.fullpath, encoding='utf-8') as f:
source = f.read() source = f.read()
return (source, self.fullpath, return (source, self.fullpath,
lambda: mtime == os.path.getmtime(self.fullpath)) lambda: mtime == os.path.getmtime(self.fullpath))

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import logging import logging
import os import os
import sys import sys

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import functools import functools
import logging import logging
import os import os
@ -13,7 +11,7 @@ PaginationRule = namedtuple(
) )
class Paginator(object): class Paginator:
def __init__(self, name, url, object_list, settings, per_page=None): def __init__(self, name, url, object_list, settings, per_page=None):
self.name = name self.name = name
self.url = url self.url = url
@ -61,7 +59,7 @@ class Paginator(object):
page_range = property(_get_page_range) page_range = property(_get_page_range)
class Page(object): class Page:
def __init__(self, name, url, object_list, number, paginator, settings): def __init__(self, name, url, object_list, number, paginator, settings):
self.full_name = name self.full_name = name
self.name, self.extension = os.path.splitext(name) self.name, self.extension = os.path.splitext(name)
@ -74,7 +72,7 @@ class Page(object):
self.settings = settings self.settings = settings
def __repr__(self): def __repr__(self):
return '<Page %s of %s>' % (self.number, self.paginator.num_pages) return '<Page {} of {}>'.format(self.number, self.paginator.num_pages)
def has_next(self): def has_next(self):
return self.number < self.paginator.num_pages return self.number < self.paginator.num_pages

View file

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from blinker import signal from blinker import signal
# Run-level signals: # Run-level signals:

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import datetime import datetime
import logging import logging
import os import os
@ -101,7 +99,7 @@ def _filter_discardable_metadata(metadata):
return {name: val for name, val in metadata.items() if val is not _DISCARD} return {name: val for name, val in metadata.items() if val is not _DISCARD}
class BaseReader(object): class BaseReader:
"""Base class to read files. """Base class to read files.
This class is used to process static files, and it can be inherited for This class is used to process static files, and it can be inherited for

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import re import re
from docutils import nodes, utils from docutils import nodes, utils

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import argparse import argparse
import logging import logging
import os import os

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import copy import copy
import importlib.util import importlib.util
import inspect import inspect

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
AUTHOR = 'Alexis Métaireau' AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log" SITENAME = "Alexis' log"
SITEURL = 'http://blog.notmyidea.org' SITEURL = 'http://blog.notmyidea.org'

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale import locale
import logging import logging
import os import os
@ -134,7 +132,7 @@ def skipIfNoExecutable(executable):
res = None res = None
if res is None: if res is None:
return unittest.skip('{0} executable not found'.format(executable)) return unittest.skip('{} executable not found'.format(executable))
return lambda func: func return lambda func: func

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import os import os
from shutil import rmtree from shutil import rmtree
from tempfile import mkdtemp from tempfile import mkdtemp

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import datetime import datetime
import locale import locale
import logging import logging
@ -27,7 +25,7 @@ class TestBase(LoggedTestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
self.page_kwargs = { self.page_kwargs = {
'content': TEST_CONTENT, 'content': TEST_CONTENT,
'context': { 'context': {
@ -56,13 +54,13 @@ class TestBase(LoggedTestCase):
def _copy_page_kwargs(self): def _copy_page_kwargs(self):
# make a deep copy of page_kwargs # make a deep copy of page_kwargs
page_kwargs = dict([(key, self.page_kwargs[key]) for key in page_kwargs = {key: self.page_kwargs[key] for key in self.page_kwargs}
self.page_kwargs])
for key in page_kwargs: for key in page_kwargs:
if not isinstance(page_kwargs[key], dict): if not isinstance(page_kwargs[key], dict):
break break
page_kwargs[key] = dict([(subkey, page_kwargs[key][subkey]) page_kwargs[key] = {
for subkey in page_kwargs[key]]) subkey: page_kwargs[key][subkey] for subkey in page_kwargs[key]
}
return page_kwargs return page_kwargs

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale import locale
import os import os
from shutil import copy, rmtree from shutil import copy, rmtree
@ -27,7 +25,7 @@ CONTENT_DIR = os.path.join(CUR_DIR, 'content')
class TestGenerator(unittest.TestCase): class TestGenerator(unittest.TestCase):
def setUp(self): def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
self.settings = get_settings() self.settings = get_settings()
self.settings['READERS'] = {'asc': None} self.settings['READERS'] = {'asc': None}
self.generator = Generator(self.settings.copy(), self.settings, self.generator = Generator(self.settings.copy(), self.settings,
@ -403,7 +401,7 @@ class TestArticlesGenerator(unittest.TestCase):
'period' : a tuple of year, month, day according to the time period 'period' : a tuple of year, month, day according to the time period
""" """
old_locale = locale.setlocale(locale.LC_ALL) old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
settings = get_settings() settings = get_settings()
settings['YEAR_ARCHIVE_SAVE_AS'] = 'posts/{date:%Y}/index.html' settings['YEAR_ARCHIVE_SAVE_AS'] = 'posts/{date:%Y}/index.html'
@ -788,7 +786,7 @@ class TestTemplatePagesGenerator(unittest.TestCase):
self.temp_content = mkdtemp(prefix='pelicantests.') self.temp_content = mkdtemp(prefix='pelicantests.')
self.temp_output = mkdtemp(prefix='pelicantests.') self.temp_output = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self): def tearDown(self):
rmtree(self.temp_content) rmtree(self.temp_content)
@ -823,7 +821,7 @@ class TestTemplatePagesGenerator(unittest.TestCase):
self.assertTrue(os.path.exists(output_path)) self.assertTrue(os.path.exists(output_path))
# output content is correct # output content is correct
with open(output_path, 'r') as output_file: with open(output_path) as output_file:
self.assertEqual(output_file.read(), 'foo: bar') self.assertEqual(output_file.read(), 'foo: bar')
@ -1013,7 +1011,7 @@ class TestStaticGenerator(unittest.TestCase):
f.write("staticcontent") f.write("staticcontent")
self.generator.generate_context() self.generator.generate_context()
self.generator.generate_output(None) self.generator.generate_output(None)
with open(self.endfile, "r") as f: with open(self.endfile) as f:
self.assertEqual(f.read(), "staticcontent") self.assertEqual(f.read(), "staticcontent")
@unittest.skipUnless(MagicMock, 'Needs Mock module') @unittest.skipUnless(MagicMock, 'Needs Mock module')
@ -1162,7 +1160,7 @@ class TestJinja2Environment(unittest.TestCase):
self.temp_content = mkdtemp(prefix='pelicantests.') self.temp_content = mkdtemp(prefix='pelicantests.')
self.temp_output = mkdtemp(prefix='pelicantests.') self.temp_output = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self): def tearDown(self):
rmtree(self.temp_content) rmtree(self.temp_content)
@ -1197,7 +1195,7 @@ class TestJinja2Environment(unittest.TestCase):
self.assertTrue(os.path.exists(output_path)) self.assertTrue(os.path.exists(output_path))
# output content is correct # output content is correct
with open(output_path, 'r') as output_file: with open(output_path) as output_file:
self.assertEqual(output_file.read(), expected) self.assertEqual(output_file.read(), expected)
def test_jinja2_filter(self): def test_jinja2_filter(self):

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale import locale
import os import os
import re import re
@ -41,7 +39,7 @@ class TestBloggerXmlImporter(unittest.TestCase):
def setUp(self): def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
self.posts = blogger2fields(BLOGGER_XML_SAMPLE) self.posts = blogger2fields(BLOGGER_XML_SAMPLE)
def tearDown(self): def tearDown(self):
@ -90,7 +88,7 @@ class TestWordpressXmlImporter(unittest.TestCase):
def setUp(self): def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
self.posts = wp2fields(WORDPRESS_XML_SAMPLE) self.posts = wp2fields(WORDPRESS_XML_SAMPLE)
self.custposts = wp2fields(WORDPRESS_XML_SAMPLE, True) self.custposts = wp2fields(WORDPRESS_XML_SAMPLE, True)
@ -282,9 +280,9 @@ class TestWordpressXmlImporter(unittest.TestCase):
def test_decode_wp_content(self): def test_decode_wp_content(self):
""" Check that we can decode a wordpress content string.""" """ Check that we can decode a wordpress content string."""
with open(WORDPRESS_ENCODED_CONTENT_SAMPLE, 'r') as encoded_file: with open(WORDPRESS_ENCODED_CONTENT_SAMPLE) as encoded_file:
encoded_content = encoded_file.read() encoded_content = encoded_file.read()
with open(WORDPRESS_DECODED_CONTENT_SAMPLE, 'r') as decoded_file: with open(WORDPRESS_DECODED_CONTENT_SAMPLE) as decoded_file:
decoded_content = decoded_file.read() decoded_content = decoded_file.read()
self.assertEqual( self.assertEqual(
decode_wp_content(encoded_content, br=False), decode_wp_content(encoded_content, br=False),
@ -405,7 +403,7 @@ class TestBuildHeader(unittest.TestCase):
class TestWordpressXMLAttachements(unittest.TestCase): class TestWordpressXMLAttachements(unittest.TestCase):
def setUp(self): def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
self.attachments = get_attachments(WORDPRESS_XML_SAMPLE) self.attachments = get_attachments(WORDPRESS_XML_SAMPLE)
def tearDown(self): def tearDown(self):

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale import locale
from jinja2.utils import generate_lorem_ipsum from jinja2.utils import generate_lorem_ipsum
@ -19,7 +17,7 @@ class TestPage(unittest.TestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
self.page_kwargs = { self.page_kwargs = {
'content': TEST_CONTENT, 'content': TEST_CONTENT,
'context': { 'context': {

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale import locale
import logging import logging
import os import os
@ -47,7 +45,7 @@ class TestPelican(LoggedTestCase):
self.temp_cache = mkdtemp(prefix='pelican_cache.') self.temp_cache = mkdtemp(prefix='pelican_cache.')
self.maxDiff = None self.maxDiff = None
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self): def tearDown(self):
read_settings() # cleanup PYGMENTS_RST_OPTIONS read_settings() # cleanup PYGMENTS_RST_OPTIONS
@ -60,7 +58,7 @@ class TestPelican(LoggedTestCase):
out, err = subprocess.Popen( out, err = subprocess.Popen(
['git', 'diff', '--no-ext-diff', '--exit-code', ['git', 'diff', '--no-ext-diff', '--exit-code',
'-w', left_path, right_path], '-w', left_path, right_path],
env={str('PAGER'): str('')}, env={'PAGER': ''},
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE stderr=subprocess.PIPE
).communicate() ).communicate()
@ -131,9 +129,9 @@ class TestPelican(LoggedTestCase):
def test_custom_locale_generation_works(self): def test_custom_locale_generation_works(self):
'''Test that generation with fr_FR.UTF-8 locale works''' '''Test that generation with fr_FR.UTF-8 locale works'''
if sys.platform == 'win32': if sys.platform == 'win32':
our_locale = str('French') our_locale = 'French'
else: else:
our_locale = str('fr_FR.UTF-8') our_locale = 'fr_FR.UTF-8'
settings = read_settings(path=SAMPLE_FR_CONFIG, override={ settings = read_settings(path=SAMPLE_FR_CONFIG, override={
'PATH': INPUT_PATH, 'PATH': INPUT_PATH,

View file

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import os import os
from contextlib import contextmanager from contextlib import contextmanager
@ -84,9 +81,9 @@ class PluginTest(unittest.TestCase):
def test_load_plugins(self): def test_load_plugins(self):
def get_plugin_names(plugins): def get_plugin_names(plugins):
return set( return {
plugin.NAME if hasattr(plugin, 'NAME') else plugin.__name__ plugin.NAME if hasattr(plugin, 'NAME') else plugin.__name__
for plugin in plugins) for plugin in plugins}
# existing namespace plugins # existing namespace plugins
existing_ns_plugins = load_plugins({}) existing_ns_plugins = load_plugins({})

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import os import os
from pelican import readers from pelican import readers
@ -92,9 +90,9 @@ class DefaultReaderTest(ReaderTest):
for tag in content: for tag in content:
readers.find_empty_alt(tag, '/test/path') readers.find_empty_alt(tag, '/test/path')
log_mock.warning.assert_called_with( log_mock.warning.assert_called_with(
u'Empty alt attribute for image %s in %s', 'Empty alt attribute for image %s in %s',
u'test-image.png', 'test-image.png',
u'/test/path', '/test/path',
extra={'limit_msg': extra={'limit_msg':
'Other images have empty alt attributes'} 'Other images have empty alt attributes'}
) )

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from pelican.tests.support import unittest from pelican.tests.support import unittest
try: try:

View file

@ -7,12 +7,12 @@ from pelican.server import ComplexHTTPRequestHandler
from pelican.tests.support import unittest from pelican.tests.support import unittest
class MockRequest(object): class MockRequest:
def makefile(self, *args, **kwargs): def makefile(self, *args, **kwargs):
return BytesIO(b"") return BytesIO(b"")
class MockServer(object): class MockServer:
pass pass

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import copy import copy
import locale import locale
import os import os
@ -21,7 +19,7 @@ class TestSettingsConfiguration(unittest.TestCase):
""" """
def setUp(self): def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
self.PATH = abspath(dirname(__file__)) self.PATH = abspath(dirname(__file__))
default_conf = join(self.PATH, 'default_conf.py') default_conf = join(self.PATH, 'default_conf.py')
self.settings = read_settings(default_conf) self.settings = read_settings(default_conf)
@ -143,7 +141,7 @@ class TestSettingsConfiguration(unittest.TestCase):
# Test that the default locale is set if not specified in settings # Test that the default locale is set if not specified in settings
# Reset locale to Python's default locale # Reset locale to Python's default locale
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
self.assertEqual(self.settings['LOCALE'], DEFAULT_CONFIG['LOCALE']) self.assertEqual(self.settings['LOCALE'], DEFAULT_CONFIG['LOCALE'])
configure_settings(self.settings) configure_settings(self.settings)

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import warnings import warnings
from pelican.tests.support import unittest from pelican.tests.support import unittest

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from pelican.tests.support import unittest from pelican.tests.support import unittest
from pelican.urlwrappers import Author, Category, Tag, URLWrapper from pelican.urlwrappers import Author, Category, Tag, URLWrapper
@ -40,7 +38,7 @@ class TestURLWrapper(unittest.TestCase):
self.assertNotEqual(tag, author) self.assertNotEqual(tag, author)
# should be equal vs text representing the same name # should be equal vs text representing the same name
self.assertEqual(tag, u'test') self.assertEqual(tag, 'test')
# should not be equal vs binary # should not be equal vs binary
self.assertNotEqual(tag, b'test') self.assertNotEqual(tag, b'test')
@ -54,7 +52,7 @@ class TestURLWrapper(unittest.TestCase):
self.assertEqual(author, author_equal) self.assertEqual(author, author_equal)
cat_ascii = Category('指導書', settings={}) cat_ascii = Category('指導書', settings={})
self.assertEqual(cat_ascii, u'zhi dao shu') self.assertEqual(cat_ascii, 'zhi dao shu')
def test_slugify_with_substitutions_and_dots(self): def test_slugify_with_substitutions_and_dots(self):
tag = Tag('Tag Dot', settings={'TAG_REGEX_SUBSTITUTIONS': [ tag = Tag('Tag Dot', settings={'TAG_REGEX_SUBSTITUTIONS': [

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import locale import locale
import logging import logging
import os import os
@ -480,9 +478,9 @@ class TestUtils(LoggedTestCase):
old_locale = locale.setlocale(locale.LC_ALL) old_locale = locale.setlocale(locale.LC_ALL)
if platform == 'win32': if platform == 'win32':
locale.setlocale(locale.LC_ALL, str('Turkish')) locale.setlocale(locale.LC_ALL, 'Turkish')
else: else:
locale.setlocale(locale.LC_ALL, str('tr_TR.UTF-8')) locale.setlocale(locale.LC_ALL, 'tr_TR.UTF-8')
d = utils.SafeDatetime(2012, 8, 29) d = utils.SafeDatetime(2012, 8, 29)
@ -514,9 +512,9 @@ class TestUtils(LoggedTestCase):
old_locale = locale.setlocale(locale.LC_ALL) old_locale = locale.setlocale(locale.LC_ALL)
if platform == 'win32': if platform == 'win32':
locale.setlocale(locale.LC_ALL, str('French')) locale.setlocale(locale.LC_ALL, 'French')
else: else:
locale.setlocale(locale.LC_ALL, str('fr_FR.UTF-8')) locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
d = utils.SafeDatetime(2012, 8, 29) d = utils.SafeDatetime(2012, 8, 29)
@ -557,7 +555,7 @@ class TestCopy(unittest.TestCase):
def setUp(self): def setUp(self):
self.root_dir = mkdtemp(prefix='pelicantests.') self.root_dir = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL) self.old_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self): def tearDown(self):
shutil.rmtree(self.root_dir) shutil.rmtree(self.root_dir)
@ -666,26 +664,26 @@ class TestDateFormatter(unittest.TestCase):
# This test tries to reproduce an issue that # This test tries to reproduce an issue that
# occurred with python3.3 under macos10 only # occurred with python3.3 under macos10 only
if platform == 'win32': if platform == 'win32':
locale.setlocale(locale.LC_ALL, str('French')) locale.setlocale(locale.LC_ALL, 'French')
else: else:
locale.setlocale(locale.LC_ALL, str('fr_FR.UTF-8')) locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
date = utils.SafeDatetime(2014, 8, 14) date = utils.SafeDatetime(2014, 8, 14)
# we compare the lower() dates since macos10 returns # we compare the lower() dates since macos10 returns
# "Jeudi" for %A whereas linux reports "jeudi" # "Jeudi" for %A whereas linux reports "jeudi"
self.assertEqual( self.assertEqual(
u'jeudi, 14 août 2014', 'jeudi, 14 août 2014',
utils.strftime(date, date_format="%A, %d %B %Y").lower()) utils.strftime(date, date_format="%A, %d %B %Y").lower())
df = utils.DateFormatter() df = utils.DateFormatter()
self.assertEqual( self.assertEqual(
u'jeudi, 14 août 2014', 'jeudi, 14 août 2014',
df(date, date_format="%A, %d %B %Y").lower()) df(date, date_format="%A, %d %B %Y").lower())
# Let us now set the global locale to C: # Let us now set the global locale to C:
locale.setlocale(locale.LC_ALL, str('C')) locale.setlocale(locale.LC_ALL, 'C')
# DateFormatter should still work as expected # DateFormatter should still work as expected
# since it is the whole point of DateFormatter # since it is the whole point of DateFormatter
# (This is where pre-2014/4/15 code fails on macos10) # (This is where pre-2014/4/15 code fails on macos10)
df_date = df(date, date_format="%A, %d %B %Y").lower() df_date = df(date, date_format="%A, %d %B %Y").lower()
self.assertEqual(u'jeudi, 14 août 2014', df_date) self.assertEqual('jeudi, 14 août 2014', df_date)
@unittest.skipUnless(locale_available('fr_FR.UTF-8') or @unittest.skipUnless(locale_available('fr_FR.UTF-8') or
locale_available('French'), locale_available('French'),

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse import argparse
import logging import logging
@ -40,7 +39,7 @@ def decode_wp_content(content, br=True):
if start == -1: if start == -1:
content = content + pre_part content = content + pre_part
continue continue
name = "<pre wp-pre-tag-{0}></pre>".format(pre_index) name = "<pre wp-pre-tag-{}></pre>".format(pre_index)
pre_tags[name] = pre_part[start:] + "</pre>" pre_tags[name] = pre_part[start:] + "</pre>"
content = content + pre_part[0:start] + name content = content + pre_part[0:start] + name
pre_index += 1 pre_index += 1
@ -154,7 +153,7 @@ def wp2fields(xml, wp_custpost=False):
content = item.find('encoded').string content = item.find('encoded').string
raw_date = item.find('post_date').string raw_date = item.find('post_date').string
if raw_date == u'0000-00-00 00:00:00': if raw_date == '0000-00-00 00:00:00':
date = None date = None
else: else:
date_object = SafeDatetime.strptime( date_object = SafeDatetime.strptime(
@ -258,7 +257,7 @@ def dc2fields(file):
category_list = {} category_list = {}
posts = [] posts = []
with open(file, 'r', encoding='utf-8') as f: with open(file, encoding='utf-8') as f:
for line in f: for line in f:
# remove final \n # remove final \n
@ -394,7 +393,7 @@ def posterous2fields(api_token, email, password):
def get_posterous_posts(api_token, email, password, page=1): def get_posterous_posts(api_token, email, password, page=1):
base64string = base64.encodestring( base64string = base64.encodestring(
("%s:%s" % (email, password)).encode('utf-8')).replace('\n', '') ("{}:{}".format(email, password)).encode('utf-8')).replace('\n', '')
url = ("http://posterous.com/api/v2/users/me/sites/primary/" url = ("http://posterous.com/api/v2/users/me/sites/primary/"
"posts?api_token=%s&page=%d") % (api_token, page) "posts?api_token=%s&page=%d") % (api_token, page)
request = urllib_request.Request(url) request = urllib_request.Request(url)
@ -553,7 +552,7 @@ def build_header(title, date, author, categories, tags, slug,
from docutils.utils import column_width from docutils.utils import column_width
header = '%s\n%s\n' % (title, '#' * column_width(title)) header = '{}\n{}\n'.format(title, '#' * column_width(title))
if date: if date:
header += ':date: %s\n' % date header += ':date: %s\n' % date
if author: if author:
@ -738,7 +737,7 @@ def download_attachments(output_path, urls):
try: try:
urlretrieve(url, os.path.join(full_path, filename)) urlretrieve(url, os.path.join(full_path, filename))
locations[url] = os.path.join(localpath, filename) locations[url] = os.path.join(localpath, filename)
except (URLError, IOError) as e: except (URLError, OSError) as e:
# Python 2.7 throws an IOError rather Than URLError # Python 2.7 throws an IOError rather Than URLError
logger.warning("No file could be downloaded from %s\n%s", url, e) logger.warning("No file could be downloaded from %s\n%s", url, e)
return locations return locations
@ -828,7 +827,7 @@ def fields2pelican(
new_content = decode_wp_content(content) new_content = decode_wp_content(content)
else: else:
paragraphs = content.splitlines() paragraphs = content.splitlines()
paragraphs = ['<p>{0}</p>'.format(p) for p in paragraphs] paragraphs = ['<p>{}</p>'.format(p) for p in paragraphs]
new_content = ''.join(paragraphs) new_content = ''.join(paragraphs)
fp.write(new_content) fp.write(new_content)
@ -862,7 +861,7 @@ def fields2pelican(
os.remove(html_filename) os.remove(html_filename)
with open(out_filename, 'r', encoding='utf-8') as fs: with open(out_filename, encoding='utf-8') as fs:
content = fs.read() content = fs.read()
if out_markup == 'markdown': if out_markup == 'markdown':
# In markdown, to insert a <br />, end a line with two # In markdown, to insert a <br />, end a line with two

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse import argparse
import locale import locale
@ -87,9 +86,9 @@ def ask(question, answer=str, default=None, length=None):
r = '' r = ''
while True: while True:
if default: if default:
r = input('> {0} [{1}] '.format(question, default)) r = input('> {} [{}] '.format(question, default))
else: else:
r = input('> {0} '.format(question, default)) r = input('> {} '.format(question, default))
r = r.strip() r = r.strip()
@ -101,7 +100,7 @@ def ask(question, answer=str, default=None, length=None):
print('You must enter something') print('You must enter something')
else: else:
if length and len(r) != length: if length and len(r) != length:
print('Entry must be {0} characters long'.format(length)) print('Entry must be {} characters long'.format(length))
else: else:
break break
@ -111,11 +110,11 @@ def ask(question, answer=str, default=None, length=None):
r = None r = None
while True: while True:
if default is True: if default is True:
r = input('> {0} (Y/n) '.format(question)) r = input('> {} (Y/n) '.format(question))
elif default is False: elif default is False:
r = input('> {0} (y/N) '.format(question)) r = input('> {} (y/N) '.format(question))
else: else:
r = input('> {0} (y/n) '.format(question)) r = input('> {} (y/n) '.format(question))
r = r.strip().lower() r = r.strip().lower()
@ -135,9 +134,9 @@ def ask(question, answer=str, default=None, length=None):
r = None r = None
while True: while True:
if default: if default:
r = input('> {0} [{1}] '.format(question, default)) r = input('> {} [{}] '.format(question, default))
else: else:
r = input('> {0} '.format(question)) r = input('> {} '.format(question))
r = r.strip() r = r.strip()
@ -167,7 +166,7 @@ def ask_timezone(question, default, tzurl):
break break
else: else:
print('Please enter a valid time zone:\n' print('Please enter a valid time zone:\n'
' (check [{0}])'.format(tzurl)) ' (check [{}])'.format(tzurl))
return r return r
@ -199,7 +198,7 @@ needed by Pelican.
os.environ.get('VIRTUAL_ENV', os.curdir), '.project') os.environ.get('VIRTUAL_ENV', os.curdir), '.project')
no_path_was_specified = hasattr(args.path, 'is_default_path') no_path_was_specified = hasattr(args.path, 'is_default_path')
if os.path.isfile(project) and no_path_was_specified: if os.path.isfile(project) and no_path_was_specified:
CONF['basedir'] = open(project, 'r').read().rstrip("\n") CONF['basedir'] = open(project).read().rstrip("\n")
print('Using project associated with current virtual environment. ' print('Using project associated with current virtual environment. '
'Will save to:\n%s\n' % CONF['basedir']) 'Will save to:\n%s\n' % CONF['basedir'])
else: else:
@ -300,12 +299,12 @@ needed by Pelican.
try: try:
os.makedirs(os.path.join(CONF['basedir'], 'content')) os.makedirs(os.path.join(CONF['basedir'], 'content'))
except OSError as e: except OSError as e:
print('Error: {0}'.format(e)) print('Error: {}'.format(e))
try: try:
os.makedirs(os.path.join(CONF['basedir'], 'output')) os.makedirs(os.path.join(CONF['basedir'], 'output'))
except OSError as e: except OSError as e:
print('Error: {0}'.format(e)) print('Error: {}'.format(e))
try: try:
with open(os.path.join(CONF['basedir'], 'pelicanconf.py'), with open(os.path.join(CONF['basedir'], 'pelicanconf.py'),
@ -318,7 +317,7 @@ needed by Pelican.
fd.write(_template.render(**conf_python)) fd.write(_template.render(**conf_python))
fd.close() fd.close()
except OSError as e: except OSError as e:
print('Error: {0}'.format(e)) print('Error: {}'.format(e))
try: try:
with open(os.path.join(CONF['basedir'], 'publishconf.py'), with open(os.path.join(CONF['basedir'], 'publishconf.py'),
@ -327,7 +326,7 @@ needed by Pelican.
fd.write(_template.render(**CONF)) fd.write(_template.render(**CONF))
fd.close() fd.close()
except OSError as e: except OSError as e:
print('Error: {0}'.format(e)) print('Error: {}'.format(e))
if automation: if automation:
try: try:
@ -337,7 +336,7 @@ needed by Pelican.
fd.write(_template.render(**CONF)) fd.write(_template.render(**CONF))
fd.close() fd.close()
except OSError as e: except OSError as e:
print('Error: {0}'.format(e)) print('Error: {}'.format(e))
try: try:
with open(os.path.join(CONF['basedir'], 'Makefile'), with open(os.path.join(CONF['basedir'], 'Makefile'),
'w', encoding='utf-8') as fd: 'w', encoding='utf-8') as fd:
@ -346,7 +345,7 @@ needed by Pelican.
fd.write(_template.render(py_v=py_v, **CONF)) fd.write(_template.render(py_v=py_v, **CONF))
fd.close() fd.close()
except OSError as e: except OSError as e:
print('Error: {0}'.format(e)) print('Error: {}'.format(e))
print('Done. Your new project is available at %s' % CONF['basedir']) print('Done. Your new project is available at %s' % CONF['basedir'])

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse import argparse
import os import os
@ -11,7 +10,7 @@ def err(msg, die=None):
"""Print an error message and exits if an exit code is given""" """Print an error message and exits if an exit code is given"""
sys.stderr.write(msg + '\n') sys.stderr.write(msg + '\n')
if die: if die:
sys.exit((die if type(die) is int else 1)) sys.exit(die if type(die) is int else 1)
try: try:
@ -49,7 +48,7 @@ def main():
help="Show the themes path and exit") help="Show the themes path and exit")
excl.add_argument( excl.add_argument(
'-V', '--version', action='version', '-V', '--version', action='version',
version='pelican-themes v{0}'.format(__version__), version='pelican-themes v{}'.format(__version__),
help='Print the version of this script') help='Print the version of this script')
parser.add_argument( parser.add_argument(
@ -249,12 +248,12 @@ def clean(v=False):
if os.path.islink(path): if os.path.islink(path):
if is_broken_link(path): if is_broken_link(path):
if v: if v:
print('Removing {0}'.format(path)) print('Removing {}'.format(path))
try: try:
os.remove(path) os.remove(path)
except OSError: except OSError:
print('Error: cannot remove {0}'.format(path)) print('Error: cannot remove {}'.format(path))
else: else:
c += 1 c += 1
print("\nRemoved {0} broken links".format(c)) print("\nRemoved {} broken links".format(c))

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import functools import functools
import logging import logging
import os import os
@ -10,7 +8,7 @@ logger = logging.getLogger(__name__)
@functools.total_ordering @functools.total_ordering
class URLWrapper(object): class URLWrapper:
def __init__(self, name, settings): def __init__(self, name, settings):
self.settings = settings self.settings = settings
self._name = name self._name = name
@ -110,7 +108,7 @@ class URLWrapper(object):
"cat/{slug}" Useful for pagination. "cat/{slug}" Useful for pagination.
""" """
setting = "%s_%s" % (self.__class__.__name__.upper(), key) setting = "{}_{}".format(self.__class__.__name__.upper(), key)
value = self.settings[setting] value = self.settings[setting]
if not isinstance(value, str): if not isinstance(value, str):
logger.warning('%s is set to %s', setting, value) logger.warning('%s is set to %s', setting, value)

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import datetime import datetime
import fnmatch import fnmatch
import locale import locale
@ -99,7 +97,7 @@ class SafeDatetime(datetime.datetime):
return super().strftime(fmt) return super().strftime(fmt)
class DateFormatter(object): class DateFormatter:
'''A date formatter object used as a jinja filter '''A date formatter object used as a jinja filter
Uses the `strftime` implementation and makes sure jinja uses the locale Uses the `strftime` implementation and makes sure jinja uses the locale
@ -125,7 +123,7 @@ class DateFormatter(object):
return formatted return formatted
class memoized(object): class memoized:
"""Function decorator to cache return values. """Function decorator to cache return values.
If called later with the same arguments, the cached value is returned If called later with the same arguments, the cached value is returned
@ -209,7 +207,7 @@ def get_date(string):
try: try:
return dateutil.parser.parse(string, default=default) return dateutil.parser.parse(string, default=default)
except (TypeError, ValueError): except (TypeError, ValueError):
raise ValueError('{0!r} is not a valid date'.format(string)) raise ValueError('{!r} is not a valid date'.format(string))
@contextmanager @contextmanager
@ -646,7 +644,7 @@ def get_original_items(items, with_str):
def _warn_source_paths(msg, items, *extra): def _warn_source_paths(msg, items, *extra):
args = [len(items)] args = [len(items)]
args.extend(extra) args.extend(extra)
args.extend((x.source_path for x in items)) args.extend(x.source_path for x in items)
logger.warning('{}: {}'.format(msg, '\n%s' * len(items)), *args) logger.warning('{}: {}'.format(msg, '\n%s' * len(items)), *args)
# warn if several items have the same lang # warn if several items have the same lang

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import logging import logging
import os import os
from urllib.parse import urljoin from urllib.parse import urljoin
@ -16,7 +14,7 @@ from pelican.utils import (get_relative_path, is_selected_for_writing,
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Writer(object): class Writer:
def __init__(self, output_path, settings=None): def __init__(self, output_path, settings=None):
self.output_path = output_path self.output_path = output_path

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
AUTHOR = 'Alexis Métaireau' AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log" SITENAME = "Alexis' log"
SITESUBTITLE = 'A personal blog.' SITESUBTITLE = 'A personal blog.'

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
AUTHOR = 'Alexis Métaireau' AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log" SITENAME = "Alexis' log"
SITEURL = 'http://blog.notmyidea.org' SITEURL = 'http://blog.notmyidea.org'

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
from io import open
from os import walk from os import walk
from os.path import join, relpath from os.path import join, relpath