Skip to content

Commit

Permalink
Black (#29)
Browse files Browse the repository at this point in the history
Reformat code base with black - resolve #26
  • Loading branch information
Um9i authored and hackebrot committed Jul 25, 2019
1 parent 6a7eb1d commit 1a0983d
Show file tree
Hide file tree
Showing 8 changed files with 147 additions and 149 deletions.
54 changes: 27 additions & 27 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,42 +9,42 @@

def read(fname):
file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read()
return codecs.open(file_path, encoding="utf-8").read()


setuptools.setup(
name='poyo',
version='0.5.0',
author='Raphael Pierzina',
author_email='raphael@hackebrot.de',
maintainer='Raphael Pierzina',
maintainer_email='raphael@hackebrot.de',
license='MIT',
url='https://github.com/hackebrot/poyo',
description='A lightweight YAML Parser for Python',
long_description=read('README.md'),
name="poyo",
version="0.5.0",
author="Raphael Pierzina",
author_email="raphael@hackebrot.de",
maintainer="Raphael Pierzina",
maintainer_email="raphael@hackebrot.de",
license="MIT",
url="https://github.com/hackebrot/poyo",
description="A lightweight YAML Parser for Python",
long_description=read("README.md"),
long_description_content_type="text/markdown",
packages=setuptools.find_packages("src"),
package_dir={"": "src"},
include_package_data=True,
zip_safe=False,
install_requires=[],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Programming Language :: Python',
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Programming Language :: Python",
],
keywords=['YAML', 'parser'],
keywords=["YAML", "parser"],
)
8 changes: 4 additions & 4 deletions src/poyo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
from .exceptions import PoyoException
from .parser import parse_string

__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.5.0'
__author__ = "Raphael Pierzina"
__email__ = "raphael@hackebrot.de"
__version__ = "0.5.0"

logging.getLogger(__name__).addHandler(logging.NullHandler())

__all__ = ['parse_string', 'PoyoException']
__all__ = ["parse_string", "PoyoException"]
22 changes: 12 additions & 10 deletions src/poyo/_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

class TreeElement(object):
"""Helper class to identify internal classes."""

def __init__(self, **kwargs):
pass

Expand All @@ -12,6 +13,7 @@ class ContainerMixin(object):
Containers can be called to return a dict representation.
"""

def __init__(self, **kwargs):
self._children = []
super(ContainerMixin, self).__init__(**kwargs)
Expand All @@ -29,48 +31,49 @@ def add_child(self, child):
"""
if not isinstance(child, ChildMixin):
raise TypeError(
'Requires instance of TreeElement. '
'Got {}'.format(type(child))
"Requires instance of TreeElement. " "Got {}".format(type(child))
)
child.parent = self
self._children.append(child)


class ChildMixin(object):
"""Mixin that can be attached to Container object."""

def __init__(self, **kwargs):
parent = kwargs['parent']
parent = kwargs["parent"]

if not isinstance(parent, ContainerMixin):
raise ValueError(
'Parent of ChildMixin instance needs to be a Container.'
)
raise ValueError("Parent of ChildMixin instance needs to be a Container.")
parent.add_child(self)
super(ChildMixin, self).__init__(**kwargs)


class Root(ContainerMixin, TreeElement):
"""Pure Container class to represent the root of a YAML config."""

def __init__(self, **kwargs):
super(Root, self).__init__(**kwargs)
self.level = -1


class Section(ContainerMixin, ChildMixin, TreeElement):
"""Class that can act as a Child, but also as a Container."""

def __init__(self, name, level, **kwargs):
super(Section, self).__init__(**kwargs)
self.name = name
self.level = level

def __repr__(self):
return u'<Section name: {name}>'.format(name=self.name)
return u"<Section name: {name}>".format(name=self.name)


class Simple(ChildMixin, TreeElement):
"""Class that can solely be used as a Child, f.i. simple key value pairs
in a config.
"""

def __init__(self, name, level, value, **kwargs):
super(Simple, self).__init__(**kwargs)
self.name = name
Expand All @@ -81,7 +84,6 @@ def __call__(self):
return self.value

def __repr__(self):
return u'<Simple name: {name}, value: {value}>'.format(
name=self.name,
value=self.value
return u"<Simple name: {name}, value: {value}>".format(
name=self.name, value=self.value
)
91 changes: 46 additions & 45 deletions src/poyo/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,27 @@
from ._nodes import Root, Section, Simple

from .exceptions import (
NoMatchException, NoParentException, NoTypeException, IgnoredMatchException
NoMatchException,
NoParentException,
NoTypeException,
IgnoredMatchException,
)

from .patterns import (
COMMENT, BLANK_LINE, DASHES, LIST, SIMPLE, SECTION,
LIST_ITEM, NULL, TRUE, FALSE, FLOAT, INT, STR, MULTILINE_STR
COMMENT,
BLANK_LINE,
DASHES,
LIST,
SIMPLE,
SECTION,
LIST_ITEM,
NULL,
TRUE,
FALSE,
FLOAT,
INT,
STR,
MULTILINE_STR,
)

logger = logging.getLogger(__name__)
Expand All @@ -36,29 +51,28 @@ def log_callback(wrapped_function):

def debug_log(message):
"""Helper to log an escaped version of the given message to DEBUG"""
logger.debug(message.encode('unicode_escape').decode())
logger.debug(message.encode("unicode_escape").decode())

@functools.wraps(wrapped_function)
def _wrapper(parser, match, **kwargs):
func_name = wrapped_function.__name__

debug_log(u'{func_name} <- {matched_string}'.format(
func_name=func_name,
matched_string=match.group(),
))
debug_log(
u"{func_name} <- {matched_string}".format(
func_name=func_name, matched_string=match.group()
)
)

try:
result = wrapped_function(parser, match, **kwargs)
except IgnoredMatchException:
debug_log(u'{func_name} -> IGNORED'.format(func_name=func_name))
debug_log(u"{func_name} -> IGNORED".format(func_name=func_name))
raise

debug_log(u'{func_name} -> {result}'.format(
func_name=func_name,
result=result,
))
debug_log(u"{func_name} -> {result}".format(func_name=func_name, result=result))

return result

return _wrapper


Expand Down Expand Up @@ -94,9 +108,7 @@ def find_at_level(self, level):
for candidate in reversed(self.seen):
if candidate.level < level:
return candidate
raise NoParentException(
'Unable to find element at level {}'.format(level)
)
raise NoParentException("Unable to find element at level {}".format(level))

def read_from_tag(self, string):
for pattern, callback in self.tag_rules:
Expand Down Expand Up @@ -133,43 +145,36 @@ def parse_dashes(self, match):
@log_callback
def parse_list(self, match):
groups = match.groupdict()
level = len(groups['indent'])
level = len(groups["indent"])
parent = self.find_at_level(level)

item_matches = LIST_ITEM.findall(groups['items'])
item_matches = LIST_ITEM.findall(groups["items"])

list_items = [
self.read_from_tag(value)
for value in item_matches
]
list_items = [self.read_from_tag(value) for value in item_matches]

variable = self.read_from_tag(groups['variable'])
variable = self.read_from_tag(groups["variable"])
return Simple(variable, level, list_items, parent=parent)

@log_callback
def parse_simple(self, match):
groups = match.groupdict()

level = len(groups['indent'])
level = len(groups["indent"])
parent = self.find_at_level(level)

variable = self.read_from_tag(groups['variable'])
value = self.read_from_tag(groups['value'])
variable = self.read_from_tag(groups["variable"])
value = self.read_from_tag(groups["value"])

return Simple(variable, level, value, parent=parent)

@log_callback
def parse_section(self, match):
groups = match.groupdict()

level = len(groups['indent'])
level = len(groups["indent"])
parent = self.find_at_level(level)

return Section(
self.read_from_tag(groups['variable']),
level,
parent=parent
)
return Section(self.read_from_tag(groups["variable"]), level, parent=parent)

@log_callback
def parse_null(self, match):
Expand All @@ -193,7 +198,7 @@ def parse_float(self, match):

@log_callback
def parse_str(self, match):
quotes = match.group('quotes')
quotes = match.group("quotes")
return match.group().strip(quotes)

def join_lines(self, lines, keep_newlines=False):
Expand All @@ -209,24 +214,21 @@ def join_lines(self, lines, keep_newlines=False):
@log_callback
def parse_multiline_str(self, match):
groups = match.groupdict()
keep_newlines = groups['blockstyle'] == "|"
chomp = groups['chomping']
level = len(groups['indent'])
keep_newlines = groups["blockstyle"] == "|"
chomp = groups["chomping"]
level = len(groups["indent"])
parent = self.find_at_level(level)
variable = self.read_from_tag(groups['variable'])
lines = groups['lines'].splitlines()
variable = self.read_from_tag(groups["variable"])
lines = groups["lines"].splitlines()
if not lines:
return Simple(variable, level, "", parent=parent)

first_indent = groups['forceindent']
first_indent = groups["forceindent"]
if first_indent:
first_indent = int(first_indent)
else:
first_indent = len(lines[0]) - len(lines[0].lstrip())
value = self.join_lines(
[l[first_indent:] for l in lines],
keep_newlines
)
value = self.join_lines([l[first_indent:] for l in lines], keep_newlines)
if not chomp:
value = value.rstrip("\n") + "\n"
elif chomp == "-":
Expand Down Expand Up @@ -258,8 +260,7 @@ def find_match(self):
return match

raise NoMatchException(
'None of the known patterns match for {}'
''.format(self.source[self.pos:])
"None of the known patterns match for {}" "".format(self.source[self.pos :])
)

def __call__(self):
Expand Down
26 changes: 14 additions & 12 deletions src/poyo/patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,23 @@
_SIMPLE = _INDENT + _VAR + _BLANK + _VALUE + _INLINE_COMMENT + _OPT_NEWLINE

_MULTILINE = (
_INDENT + _VAR + _BLANK +
r"(?P<blockstyle>[>|])(?P<chomping>[+-]?)(?P<forceindent>\d*) *" +
_INLINE_COMMENT + _NEWLINE
)
_MULTILINE_STR = (
_INDENT_MATCH + _BLANK + _STR_VALUE + _NEWLINE + r"|" + _BLANK_LINE
)
_MULTILINE_SECTION = (
_MULTILINE + r"(?P<lines>(?:" + _MULTILINE_STR + r")*" + r")"
_INDENT
+ _VAR
+ _BLANK
+ r"(?P<blockstyle>[>|])(?P<chomping>[+-]?)(?P<forceindent>\d*) *"
+ _INLINE_COMMENT
+ _NEWLINE
)
_MULTILINE_STR = _INDENT_MATCH + _BLANK + _STR_VALUE + _NEWLINE + r"|" + _BLANK_LINE
_MULTILINE_SECTION = _MULTILINE + r"(?P<lines>(?:" + _MULTILINE_STR + r")*" + r")"

_LIST_VALUE = (
_BLANK + r"-" + _BLANK +
r"('.*?'|\".*?\"|[^#\n]+?)" +
_INLINE_COMMENT + _OPT_NEWLINE
_BLANK
+ r"-"
+ _BLANK
+ r"('.*?'|\".*?\"|[^#\n]+?)"
+ _INLINE_COMMENT
+ _OPT_NEWLINE
)
_LIST_ITEM = _BLANK_LINE + r"|" + _COMMENT + r"|" + _LIST_VALUE

Expand Down
2 changes: 1 addition & 1 deletion src/poyo/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@


def read_unicode_file(file_path):
with codecs.open(file_path, encoding='utf-8') as f:
with codecs.open(file_path, encoding="utf-8") as f:
return f.read()
Loading

0 comments on commit 1a0983d

Please sign in to comment.