Skip to content

Commit

Permalink
Flake8 the code. (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Howitz authored May 25, 2019
1 parent 235ed72 commit 953ebf0
Show file tree
Hide file tree
Showing 10 changed files with 140 additions and 124 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
121 changes: 65 additions & 56 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 @@ -190,28 +188,24 @@ def write(self, file):
file.write(b'\n')

def __eq__(self, other):
try:
return (self.locations == other.locations
and self.msgid == other.msgid)
except AttributeError: # pragma: no cover
return NotImplemented
if not isinstance(other, POTEntry):
return NotImplemented # pragma: no cover
return self.locations == other.locations and self.msgid == other.msgid

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

def __repr__(self):
return '<POTEntry: %r>' % self.msgid


@implementer(IPOTMaker)
class POTMaker(object):
"""This class inserts sets of strings into a POT file.
"""
"""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 +232,12 @@ 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))
formatted_header = pot_header % {
'time': time.ctime(),
'version': self._getProductVersion(),
'charset': DEFAULT_CHARSET,
'encoding': DEFAULT_ENCODING}
file.write(formatted_header.encode(DEFAULT_CHARSET))

# Sort the catalog entries by filename
catalog = self.catalog.values()
Expand All @@ -262,7 +258,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 +401,7 @@ def getCatalog(self):

return catalog


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

Expand Down Expand Up @@ -469,13 +465,15 @@ 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,22 +489,23 @@ 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`.
"""
"""Retrieve all ZCML messages from `dir` that are in the `domain`."""
from zope.configuration import xmlconfig, config

# Load server-independent site config
Expand All @@ -517,6 +516,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 All @@ -530,15 +530,19 @@ def tal_strings(dir,
Let's create a page template in the i18n domain ``test``:
>>> with open(os.path.join(dir, 'test.pt'), 'w') as testpt:
... _ = testpt.write('<tal:block i18n:domain="test" i18n:translate="">test</tal:block>')
... _ = testpt.write(
... '<tal:block i18n:domain="test"'
... ' i18n:translate="">test</tal:block>')
And now one in no domain:
>>> with open(os.path.join(dir, 'no.pt'), 'w') as nopt:
... _ = nopt.write('<tal:block i18n:translate="">no domain</tal:block>')
... _ = nopt.write(
... '<tal:block i18n:translate="">no domain</tal:block>')
Now let's find the strings for the domain ``test``:
>>> strs = extract.tal_strings(dir, domain='test', include_default_domain=True)
>>> strs = extract.tal_strings(
... dir, domain='test', include_default_domain=True)
>>> len(strs)
2
>>> strs[u'test']
Expand All @@ -565,7 +569,9 @@ def tal_strings(dir,
We also provide a file with a different file ending:
>>> with open(os.path.join(dir, 'test.html'), 'w') as testpt:
... _ = testpt.write('<tal:block i18n:domain="html" i18n:translate="">html</tal:block>')
... _ = testpt.write(
... '<tal:block i18n:domain="html"'
... ' i18n:translate="">html</tal:block>')
>>> extract.tal_strings(dir, domain='html', include_default_domain=True,
... filePattern='*.html')
Expand All @@ -576,7 +582,6 @@ def tal_strings(dir,
>>> import shutil
>>> shutil.rmtree(dir)
"""

# We import zope.tal.talgettext here because we can't rely on the
# right sys path until app_dir has run
from zope.tal.talgettext import POEngine, POTALInterpreter
Expand All @@ -589,7 +594,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 +609,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 +629,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,50 +665,53 @@ 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)
if not msg:
msg = USAGE
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.
>>> strip_base_dir('/path/to/base/relpath/to/file',
... '/path/to/base/')
'relpath/to/file'
>>> strip_base_dir('/path/to/base/relpath/to/file',
... '/path/to/base/')
'relpath/to/file'
>>> strip_base_dir('/path/to/somewhere/else/relpath/to/file',
... '/path/to/base/')
'/path/to/somewhere/else/relpath/to/file'
>>> strip_base_dir('/path/to/somewhere/else/relpath/to/file',
... '/path/to/base/')
'/path/to/somewhere/else/relpath/to/file'
"""
if filename.startswith(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
Loading

0 comments on commit 953ebf0

Please sign in to comment.