Skip to content

Commit

Permalink
Flake8 the code.
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Howitz committed Feb 21, 2019
1 parent 235ed72 commit 443a907
Show file tree
Hide file tree
Showing 10 changed files with 116 additions and 100 deletions.
9 changes: 8 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@ python:
- 2.7
- 3.5
- 3.6
- pypy-5.4.1
- pypy
matrix:
include:
- python: 3.6
name: "Flake8"
install: pip install -U flake8
script: flake8 --doctests src setup.py
after_success:
script:
- coverage run -m zope.testrunner --test-path=src --auto-color --auto-progress

Expand Down
2 changes: 1 addition & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ CHANGES
4.1 (unreleased)
----------------

- Nothing changed yet.
- Flake8 the code.


4.0.1 (2018-06-29)
Expand Down
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,4 @@ def read(*rnames):
entry_points="""
[console_scripts]
i18nextract=zope.app.locales.extract:main [extract]
"""
)
""")
2 changes: 1 addition & 1 deletion src/zope/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
2 changes: 1 addition & 1 deletion src/zope/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
73 changes: 41 additions & 32 deletions src/zope/app/locales/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
"""
from __future__ import print_function
__docformat__ = 'restructuredtext'

from collections import defaultdict
import os
import sys
Expand Down Expand Up @@ -47,7 +45,7 @@

DEFAULT_CHARSET = 'UTF-8'
DEFAULT_ENCODING = '8bit'
_import_chickens = {}, {}, ("*",) # dead chickens needed by __import__
_import_chickens = {}, {}, ("*",) # dead chickens needed by __import__

pot_header = u'''\
##############################################################################
Expand Down Expand Up @@ -173,7 +171,7 @@ def write(self, file):
file.write(b'#: %s:%d\n' % (filename.encode(DEFAULT_CHARSET),
line))
if (isinstance(self.msgid, Message) and
self.msgid.default is not None):
self.msgid.default is not None):
default = self.msgid.default.strip()

if not isinstance(default, bytes):
Expand All @@ -193,13 +191,14 @@ def __eq__(self, other):
try:
return (self.locations == other.locations
and self.msgid == other.msgid)
except AttributeError: # pragma: no cover
except AttributeError: # pragma: no cover
return NotImplemented

def __lt__(self, other):
try:
return (self.locations, self.msgid) < (other.locations, other.msgid)
except AttributeError: # pragma: no cover
return (
(self.locations, self.msgid) < (other.locations, other.msgid))
except AttributeError: # pragma: no cover
return NotImplemented

def __repr__(self):
Expand All @@ -211,7 +210,7 @@ class POTMaker(object):
"""This class inserts sets of strings into a POT file.
"""

def __init__ (self, output_fn, path):
def __init__(self, output_fn, path):
self._output_filename = output_fn
self.path = path
self.catalog = {}
Expand All @@ -238,10 +237,11 @@ def _getProductVersion(self):

def write(self):
with open(self._output_filename, 'wb') as file:
file.write((pot_header % {'time': time.ctime(),
'version': self._getProductVersion(),
'charset': DEFAULT_CHARSET,
'encoding': DEFAULT_ENCODING}).encode(DEFAULT_CHARSET))
file.write((pot_header % {
'time': time.ctime(),
'version': self._getProductVersion(),
'charset': DEFAULT_CHARSET,
'encoding': DEFAULT_ENCODING}).encode(DEFAULT_CHARSET))

# Sort the catalog entries by filename
catalog = self.catalog.values()
Expand All @@ -262,7 +262,6 @@ class TokenEater(object):
TokenEater eats tokens generated by the standard python module
`tokenize`.
>>> import tokenize
>>> from io import StringIO
We feed it a (fake) file:
Expand Down Expand Up @@ -406,6 +405,7 @@ def getCatalog(self):

return catalog


def find_files(dir, pattern, exclude=()):
files = []

Expand Down Expand Up @@ -469,13 +469,14 @@ def py_strings(dir, domain="zope", exclude=(), verify_domain=False):
"""
eater = TokenEater()
make_escapes(0)
for filename in find_files(dir, '*.py',
exclude=('extract.py', 'pygettext.py') + tuple(exclude)):
filenames = find_files(
dir, '*.py', exclude=('extract.py', 'pygettext.py') + tuple(exclude))
for filename in filenames:
if verify_domain:
module_name = module_from_filename(filename)
try:
module = __import__(module_name, *_import_chickens)
except ImportError as e: # pragma: no cover
except ImportError: # pragma: no cover
# XXX if we can't import it - we assume that the domain is
# the right one
print("Could not import %s, "
Expand All @@ -491,19 +492,21 @@ def py_strings(dir, domain="zope", exclude=(), verify_domain=False):
continue
elif mf:
print("Could not figure out the i18n domain"
" for module %s, assuming it is OK" % module_name, file=sys.stderr)
" for module %s, assuming it is OK" % module_name,
file=sys.stderr)

with open(filename) as fp:
eater.set_filename(filename)
try:
for t in generate_tokens(fp.readline):
eater(*t)
except tokenize.TokenError as e: # pragma: no cover
except tokenize.TokenError as e: # pragma: no cover
print('%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1]), file=sys.stderr)

return eater.getCatalog()


def zcml_strings(dir, domain="zope", site_zcml=None):
"""Retrieve all ZCML messages from `dir` that are in the `domain`.
"""
Expand All @@ -517,6 +520,7 @@ def zcml_strings(dir, domain="zope", site_zcml=None):

return context.i18n_strings.get(domain, {})


def tal_strings(dir,
domain="zope",
include_default_domain=False,
Expand Down Expand Up @@ -575,7 +579,7 @@ def tal_strings(dir,
>>> import shutil
>>> shutil.rmtree(dir)
"""
""" # noqa: E501

# We import zope.tal.talgettext here because we can't rely on the
# right sys path until app_dir has run
Expand All @@ -589,7 +593,7 @@ def write(self, s):
pass

for filename in find_files(dir, filePattern, exclude=tuple(exclude)):
with open(filename,'rb') as f:
with open(filename, 'rb') as f:
start = f.read(6)

if start.startswith(b'<?xml'):
Expand All @@ -604,7 +608,7 @@ def write(self, s):
program, macros = p.getCode()
POTALInterpreter(program, macros, engine, stream=Devnull(),
metal=False)()
except: # Hee hee, I love bare excepts! pragma: no cover
except Exception: # pragma: no cover
print('There was an error processing', filename)
traceback.print_exc()

Expand All @@ -624,6 +628,7 @@ def write(self, s):
catalog[msgid] = [(l[0], l[1][0]) for l in locations]
return catalog


USAGE = """Program to extract internationalization markup from Python Code,
Page Templates and ZCML.
Expand Down Expand Up @@ -659,24 +664,27 @@ def write(self, s):
Print this message and exit.
"""


def usage(code, msg=''):
# Python 2.1 required
print(USAGE, file=sys.stderr)
if msg:
print(msg, file=sys.stderr)
sys.exit(code)


def normalize_path(path):
"""Normalize a possibly relative path or symlink"""
if path == os.path.abspath(path):
return path

# This is for symlinks. Thanks to Fred for this trick.
cwd = os.getcwd()
if os.environ.has_key('PWD'):
if 'PWD' in os.environ:
cwd = os.environ['PWD']
return os.path.normpath(os.path.join(cwd, path))


def strip_base_dir(filename, base_dir):
"""Strip base directory from filename if it starts there.
Expand All @@ -693,16 +701,17 @@ def strip_base_dir(filename, base_dir):
filename = filename[len(base_dir):]
return filename


def main(argv=None):
if argv is None: # pragma: no cover
if argv is None: # pragma: no cover
argv = sys.argv[1:]

try:
opts, args = getopt.getopt(
argv,
'hd:s:i:p:o:x:',
['help', 'domain=', 'site_zcml=', 'path=', 'python-only'])
except getopt.error as msg: # pragma: no cover
except getopt.error as msg: # pragma: no cover
usage(1, msg)

domain = 'zope'
Expand Down Expand Up @@ -754,14 +763,14 @@ def main(argv=None):
os.mkdir(output_dir)
output_file = os.path.join(output_dir, output_file)

print("base path: %r\n" \
"search path: %s\n" \
"'site.zcml' location: %s\n" \
"exclude dirs: %r\n" \
"domain: %r\n" \
"include default domain: %r\n" \
"output file: %r\n" \
"Python only: %r" \
print("base path: %r\n"
"search path: %s\n"
"'site.zcml' location: %s\n"
"exclude dirs: %r\n"
"domain: %r\n"
"include default domain: %r\n"
"output file: %r\n"
"Python only: %r"
% (base_dir, path, site_zcml, exclude_dirs, domain,
include_default_domain, output_file, python_only))

Expand Down
29 changes: 11 additions & 18 deletions src/zope/app/locales/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,42 +14,35 @@
"""Abstract objects for the i18n extraction machinery
"""
__docformat__ = 'restructuredtext'

from zope.interface import Interface


class IPOTEntry(Interface):
"""Represents a single message entry in a POT file
"""
"""Represent a single message entry in a POT file."""

def addComment(comment):
"""Add a comment to the entry
"""
"""Add a comment to the entry."""

def addLocationComment(filename, line):
"""Add a comment regarding the location where this message id
entry can be found
"""
entry can be found."""

def write(file):
"""Write the entry to the file
"""
"""Write the entry to the file."""


class IPOTMaker(Interface):
"""Writes POT entries to a POT file
"""
"""Write POT entries to a POT file."""

def add(strings, base_dir=None):
"""Add `strings` to the internal catalog.
"""
"""Add `strings` to the internal catalog."""

def write():
"""Write strings to the POT file
"""
"""Write strings to the POT file."""


class ITokenEater(Interface):
"""Eats tokens from the python tokenizer
"""
"""Eat tokens from the python tokenizer."""

def getCatalog():
"""Return the catalog of collected message ids as keys of a
Expand Down

0 comments on commit 443a907

Please sign in to comment.