Skip to content

Commit

Permalink
address flake8 noise
Browse files Browse the repository at this point in the history
  • Loading branch information
freddrake committed Oct 30, 2018
1 parent 345cde5 commit 24d64cd
Show file tree
Hide file tree
Showing 39 changed files with 430 additions and 270 deletions.
24 changes: 15 additions & 9 deletions ZConfig/__init__.py
@@ -1,6 +1,6 @@
##############################################################################
#
# Copyright (c) 2002, 2003 Zope Foundation and Contributors.
# Copyright (c) 2002, 2003, 2018 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
Expand Down Expand Up @@ -33,13 +33,17 @@
"""
__docformat__ = "reStructuredText"

version_info = (3, 0)
__version__ = ".".join([str(n) for n in version_info])
from ZConfig._compat import TextIO
import ZConfig.loader

from ZConfig.loader import loadConfig, loadConfigFile
from ZConfig.loader import loadSchema, loadSchemaFile
loadConfigFile = ZConfig.loader.loadConfigFile
loadSchemaFile = ZConfig.loader.loadSchemaFile
loadConfig = ZConfig.loader.loadConfig
loadSchema = ZConfig.loader.loadSchema

from ZConfig._compat import TextIO

version_info = (3, 0)
__version__ = ".".join([str(n) for n in version_info])


class ConfigurationError(Exception):
Expand All @@ -48,8 +52,8 @@ class ConfigurationError(Exception):
All instances provide a ``message`` attribute that describes
the specific error, and a ``url`` attribute that gives the URL
of the resource the error was located in, or ``None``.
"""
"""

# The 'message' attribute was deprecated for BaseException with
# Python 2.6; here we create descriptor properties to continue using it
Expand Down Expand Up @@ -214,12 +218,14 @@ def __init__(self, source, name, url=None, lineno=None):

def configureLoggers(text):
"""Configure one or more loggers from configuration text."""
schema = loadSchemaFile(TextIO("""

schema = ZConfig.loader.loadSchemaFile(TextIO("""
<schema>
<import package='ZConfig.components.logger'/>
<multisection type='logger' name='*' attribute='loggers'/>
</schema>
"""))

for factory in loadConfigFile(schema, TextIO(text))[0].loggers:
config, _ = ZConfig.loader.loadConfigFile(schema, TextIO(text))
for factory in config.loggers:
factory()
33 changes: 20 additions & 13 deletions ZConfig/_compat.py
@@ -1,6 +1,6 @@
##############################################################################
#
# Copyright (c) 2016 Zope Foundation and Contributors.
# Copyright (c) 2016, 2018 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
Expand All @@ -12,28 +12,36 @@
#
##############################################################################

from io import StringIO
from io import BytesIO
import abc
import sys


PY3 = sys.version_info[0] >= 3

# Native string object IO
if str is not bytes:
from io import StringIO as NStringIO
string_types = str
text_type = str
have_unicode = False
else:
# Python 2
from io import BytesIO as NStringIO
string_types = str, unicode
string_types = str, unicode # noqa: F821
text_type = string_types[1] # avoid direct reference!
have_unicode = True


NStringIO = NStringIO

from io import StringIO
from io import BytesIO

def TextIO(text):
"Return StringIO or BytesIO as appropriate"
return BytesIO(text) if isinstance(text, bytes) else StringIO(text)


try:
import urllib2
except ImportError:
Expand All @@ -58,24 +66,23 @@ def TextIO(text):

urlparse = urlparse

if PY3: # pragma: no cover

if PY3: # pragma: no cover
import builtins
exec_ = getattr(builtins, "exec")
text_type = str
binary_type = bytes
maxsize = sys.maxsize

def reraise(tp, value, tb=None): #pragma NO COVER
def reraise(tp, value, tb=None): # pragma NO COVER
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value

else: # pragma: no cover
text_type = unicode
else: # pragma: no cover
binary_type = bytes
maxsize = sys.maxint

def exec_(code, globs=None, locs=None): #pragma NO COVER
def exec_(code, globs=None, locs=None): # pragma NO COVER
"""Execute code in a namespace."""
if globs is None:
frame = sys._getframe(1)
Expand All @@ -93,9 +100,9 @@ def exec_(code, globs=None, locs=None): #pragma NO COVER


def raise_with_same_tb(exception):
"Raise an exception having the current traceback (if there is one)"
reraise(type(exception), exception, sys.exc_info()[2])
"Raise an exception having the current traceback (if there is one)"
reraise(type(exception), exception, sys.exc_info()[2])


import abc
# workaround the metaclass diff in Py2/Py3
AbstractBaseClass = abc.ABCMeta('AbstractBaseClass', (object,), {})
52 changes: 30 additions & 22 deletions ZConfig/_schema_utils.py
@@ -1,6 +1,6 @@
##############################################################################
#
# Copyright (c) 2017 Zope Corporation and Contributors.
# Copyright (c) 2017, 2018 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
Expand Down Expand Up @@ -39,6 +39,9 @@
from ZConfig.info import AbstractType


MARKER = object()


class _VisitorBuilder(object):

def __init__(self):
Expand All @@ -50,7 +53,6 @@ def dec(func):
return func
return dec

MARKER = object()

class AbstractSchemaFormatter(AbstractBaseClass):

Expand Down Expand Up @@ -134,35 +136,39 @@ def body(self):

class AbstractSchemaPrinter(AbstractBaseClass):


def __init__(self, schema, stream=None, allowed_names=(), excluded_names=()):
def __init__(self, schema, stream=None,
allowed_names=(), excluded_names=()):
self.schema = schema
stream = stream or sys.stdout
self._explained = set()
self._seen_typenames = set()
self.fmt = self._schema_formatter(schema, stream)


def _make_predicate(names):
names = {x.lower() for x in names}

def predicate(name_info):
name, _ = name_info
return name and name.lower() in names

return predicate

def _make_filter(names, filt):
iter_all = self._iter_schema_items
pred = _make_predicate(names)

def it():
return filt(pred, iter_all())

return it

if allowed_names:
self._iter_schema_items = _make_filter(allowed_names, ifilter)

if excluded_names:
excluded_names = {x.lower() for x in excluded_names}
self._iter_schema_items = _make_filter(excluded_names, ifilterfalse)
self._iter_schema_items = _make_filter(excluded_names,
ifilterfalse)
self._included = lambda st: st.name not in excluded_names

@abstractmethod
Expand All @@ -173,7 +179,7 @@ def _included(self, st):
return True

def _explain(self, st):
if st.name in self._explained: # pragma: no cover
if st.name in self._explained: # pragma: no cover
return

self._explained.add(st.name)
Expand All @@ -192,14 +198,14 @@ def _iter_schema_items(self):
def everything():
return itertools.chain(self.schema.itertypes(),
self.schema)
# The abstract types tend to be the most important. Since
# we only document a concrete type the first time we find it,
# and we can find extensions of abstract types beneath
# the abstract type which is itself buried under a concrete section,
# all the different permutations would be only documented once under
# that section. By exposing these first, they get documented at the top-level,
# and each concrete section that uses the abstract type gets a reference
# to it.
# The abstract types tend to be the most important. Since we
# only document a concrete type the first time we find it, and
# we can find extensions of abstract types beneath the abstract
# type which is itself buried under a concrete section, all the
# different permutations would be only documented once under
# that section. By exposing these first, they get documented at
# the top-level, and each concrete section that uses the
# abstract type gets a reference to it.

def abstract_sections(base):
for name, info in base:
Expand All @@ -219,7 +225,7 @@ def printSchema(self):
self.buildSchema()

def buildSchema(self):
seen = set() # prevent duplicates at the top-level
seen = set() # prevent duplicates at the top-level
# as we find multiple abstract types
with self.fmt.body():
with self.fmt.item_list():
Expand Down Expand Up @@ -258,14 +264,14 @@ def _visit_SectionType(self, name, info):

with self.fmt.item_list():
for sub in info:
self.visit(*sub) # pragma: no cover

self.visit(*sub) # pragma: no cover

@TypeVisitor(SectionInfo)
def _visit_SectionInfo(self, name, info):
st = info.sectiontype
if st.isabstract():
with self.fmt.describing(info.description, lambda: self._explain(st)):
with self.fmt.describing(info.description,
lambda: self._explain(st)):
self.fmt.abstract_name(st.name)
self.fmt.concrete_name(info.name)

Expand All @@ -283,7 +289,8 @@ def _visit_SectionInfo(self, name, info):

@TypeVisitor(AbstractType)
def _visit_AbstractType(self, name, info):
with self.fmt.describing(info.description, lambda: self._explain(info)):
with self.fmt.describing(info.description,
lambda: self._explain(info)):
self.fmt.abstract_name(info.name)

def _visit_default(self, name, info):
Expand All @@ -305,8 +312,9 @@ def load_schema(schema, package, package_file):
if not package:
schema_reader = argparse.FileType('r')(schema)
else:
schema_template = "<schema><import package='%s' file='%s' /></schema>" % (
schema, package_file or 'component.xml')
schema_template = (
"<schema><import package='%s' file='%s' /></schema>"
% (schema, package_file or 'component.xml'))
from ZConfig._compat import TextIO
schema_reader = TextIO(schema_template)

Expand Down
30 changes: 15 additions & 15 deletions ZConfig/cfgparser.py
@@ -1,6 +1,6 @@
##############################################################################
#
# Copyright (c) 2002, 2003 Zope Foundation and Contributors.
# Copyright (c) 2002, 2003, 2018 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
Expand All @@ -13,12 +13,26 @@
##############################################################################
"""Configuration parser."""

import re

import ZConfig
import ZConfig.url

from ZConfig.substitution import isname, substitute
from ZConfig._compat import raise_with_same_tb


# _name_re does not allow "(" or ")" for historical reasons. Though
# the restriction could be lifted, there seems no need to do so.
_name_re = r"[^\s()]+"
_keyvalue_rx = re.compile(r"(?P<key>%s)\s*(?P<value>[^\s].*)?$"
% _name_re)
_section_start_rx = re.compile(r"(?P<type>%s)"
r"(?:\s+(?P<name>%s))?"
r"$"
% (_name_re, _name_re))


class ZConfigParser(object):

__slots__ = ('resource', 'context', 'lineno',
Expand Down Expand Up @@ -172,21 +186,7 @@ def error(self, message):
ZConfig.ConfigurationSyntaxError(
message, self.url, self.lineno))


def _normalize_case(self, string):
# This method is factored out solely to allow subclasses to modify
# the behavior of the parser.
return string.lower()


import re
# _name_re does not allow "(" or ")" for historical reasons. Though
# the restriction could be lifted, there seems no need to do so.
_name_re = r"[^\s()]+"
_keyvalue_rx = re.compile(r"(?P<key>%s)\s*(?P<value>[^\s].*)?$"
% _name_re)
_section_start_rx = re.compile(r"(?P<type>%s)"
r"(?:\s+(?P<name>%s))?"
r"$"
% (_name_re, _name_re))
del re
7 changes: 5 additions & 2 deletions ZConfig/cmdline.py
@@ -1,6 +1,6 @@
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# Copyright (c) 2003, 2018 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
Expand All @@ -22,6 +22,7 @@ class from the :mod:`ZConfig.loader` module. This provides support for
Each setting is given by a value specifier string, as described by
:meth:`ExtendedConfigLoader.addOption`.
"""

import ZConfig
Expand All @@ -30,6 +31,7 @@ class from the :mod:`ZConfig.loader` module. This provides support for

from ZConfig._compat import raise_with_same_tb


class ExtendedConfigLoader(ZConfig.loader.ConfigLoader):
"""A :class:`~.ConfigLoader` subclass that adds support for
command-line overrides.
Expand Down Expand Up @@ -153,7 +155,7 @@ def get_section_info(self, type_, name):
bk = self.basic_key(s, pos)
if name and self._normalize_case(s) == name:
L.append((optpath[1:], val, pos))
elif bk == type_: # pragma: no cover
elif bk == type_: # pragma: no cover
L.append((optpath[1:], val, pos))
else:
R.append(item)
Expand Down Expand Up @@ -206,6 +208,7 @@ def finish(self):
self.finish_optionbag()
return ZConfig.matcher.SectionMatcher.finish(self)


class ExtendedSchemaMatcher(MatcherMixin, ZConfig.matcher.SchemaMatcher):
def finish(self):
self.finish_optionbag()
Expand Down

0 comments on commit 24d64cd

Please sign in to comment.