Skip to content

Commit

Permalink
Apply linting config
Browse files Browse the repository at this point in the history
  • Loading branch information
linuxdaemon committed Apr 3, 2024
1 parent 79e9f3c commit 2253e2b
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 40 deletions.
4 changes: 2 additions & 2 deletions polymatch/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from .base import PolymorphicMatcher, CaseAction
from . import error
from .base import CaseAction, PolymorphicMatcher
from .error import *
from .registry import pattern_registry

__version__ = "0.2.0"

__all__ = ("PolymorphicMatcher","CaseAction", "pattern_registry")
__all__ = ("PolymorphicMatcher", "CaseAction", "pattern_registry")
__all__ += error.__all__
54 changes: 41 additions & 13 deletions polymatch/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@
from enum import Enum

import polymatch
from polymatch.error import PatternCompileError, PatternNotCompiledError, PatternTextTypeMismatchError
from polymatch.error import (
PatternCompileError,
PatternNotCompiledError,
PatternTextTypeMismatchError,
)


class CaseAction(Enum):
NONE = 'none', '' # Use whatever the pattern's default is
CASESENSITIVE = 'case-sensitive', 'cs' # Fore case sensitivity
CASEINSENSITIVE = 'case-insensitive', 'ci' # Force case insensitivity
CASEFOLD = 'casefold', 'cf' # Force case-folded comparison
NONE = "none", "" # Use whatever the pattern's default is
CASESENSITIVE = "case-sensitive", "cs" # Fore case sensitivity
CASEINSENSITIVE = "case-insensitive", "ci" # Force case insensitivity
CASEFOLD = "casefold", "cf" # Force case-folded comparison


class PolymorphicMatcher(metaclass=ABCMeta):
Expand Down Expand Up @@ -39,7 +43,9 @@ def compile(self):
try:
self._compiled_pattern = self._compile_func(self._raw_pattern)
except Exception as e:
raise PatternCompileError("Failed to compile pattern {!r}".format(self._raw_pattern)) from e
raise PatternCompileError(
f"Failed to compile pattern {self._raw_pattern!r}"
) from e

def __eq__(self, other):
if isinstance(other, self._str_type):
Expand Down Expand Up @@ -107,9 +113,11 @@ def _get_case_functions(self):
suffix = self._case_action.value[1]

if suffix:
suffix = '_' + suffix
suffix = "_" + suffix

return getattr(self, "compile_pattern" + suffix), getattr(self, "match_text" + suffix)
return getattr(self, "compile_pattern" + suffix), getattr(
self, "match_text" + suffix
)

@classmethod
@abstractmethod
Expand All @@ -130,25 +138,45 @@ def inverted(self):

def __str__(self):
return "{}{}:{}:{}".format(
'~' if self._invert else '', self.get_type(), self._case_action.value[1], self._raw_pattern
"~" if self._invert else "",
self.get_type(),
self._case_action.value[1],
self._raw_pattern,
)

def __repr__(self):
return "{}(pattern={!r}, case_action={!r}, invert={!r})".format(
type(self).__name__, self._raw_pattern, self._case_action, self._invert
type(self).__name__,
self._raw_pattern,
self._case_action,
self._invert,
)

def __getstate__(self):
return polymatch.__version__, self._raw_pattern, self._case_action, self._invert, self._compiled_pattern, \
self._str_type, self._empty
return (
polymatch.__version__,
self._raw_pattern,
self._case_action,
self._invert,
self._compiled_pattern,
self._str_type,
self._empty,
)

def __setstate__(self, state):
if len(state) > 6:
version, *state = state
else:
version = "0.0.0"

self._raw_pattern, self._case_action, self._invert, self._compiled_pattern, self._str_type, self._empty = state
(
self._raw_pattern,
self._case_action,
self._invert,
self._compiled_pattern,
self._str_type,
self._empty,
) = state
self._compile_func, self._match_func = self._get_case_functions()

if version != polymatch.__version__ and self.is_compiled():
Expand Down
17 changes: 14 additions & 3 deletions polymatch/error.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
__all__ = ("PatternCompileError","PatternNotCompiledError", "PatternTextTypeMismatchError", "DuplicateMatcherRegistrationError", "NoSuchMatcherError", "NoMatchersAvailable")
__all__ = (
"PatternCompileError",
"PatternNotCompiledError",
"PatternTextTypeMismatchError",
"DuplicateMatcherRegistrationError",
"NoSuchMatcherError",
"NoMatchersAvailable",
)


class PatternCompileError(ValueError):
pass

Expand All @@ -10,13 +19,15 @@ class PatternNotCompiledError(ValueError):
class PatternTextTypeMismatchError(TypeError):
def __init__(self, pattern_type, text_type):
super().__init__(
"Pattern of type {!r} can not match text of type {!r}".format(pattern_type.__name__, text_type.__name__)
"Pattern of type {!r} can not match text of type {!r}".format(
pattern_type.__name__, text_type.__name__
)
)


class DuplicateMatcherRegistrationError(ValueError):
def __init__(self, name):
super().__init__("Attempted o register a duplicate matcher {!r}".format(name))
super().__init__(f"Attempted o register a duplicate matcher {name!r}")


class NoSuchMatcherError(LookupError):
Expand Down
4 changes: 2 additions & 2 deletions polymatch/matchers/glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ class GlobMatcher(RegexMatcher):
def compile_pattern(self, raw_pattern, flags=0):
if isinstance(raw_pattern, bytes):
# Mimic how fnmatch handles bytes patterns
pat_str = str(raw_pattern, 'ISO-8859-1')
pat_str = str(raw_pattern, "ISO-8859-1")
res_str = translate(pat_str)
res = bytes(res_str, 'ISO-8859-1')
res = bytes(res_str, "ISO-8859-1")
else:
res = translate(raw_pattern)

Expand Down
4 changes: 2 additions & 2 deletions polymatch/matchers/regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
import regex
except ImportError as e:
try:
_exc = globals()['ModuleNotFoundError']
_exc = globals()["ModuleNotFoundError"]
except LookupError:
pass
else:
if not isinstance(e, _exc):
raise

if e.name != 'regex':
if e.name != "regex":
raise

regex = None
Expand Down
28 changes: 19 additions & 9 deletions polymatch/registry.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
from collections import OrderedDict

from polymatch.base import PolymorphicMatcher, CaseAction
from polymatch.error import DuplicateMatcherRegistrationError, NoSuchMatcherError, NoMatchersAvailable
from polymatch.base import CaseAction, PolymorphicMatcher
from polymatch.error import (
DuplicateMatcherRegistrationError,
NoMatchersAvailable,
NoSuchMatcherError,
)
from polymatch.matchers.glob import GlobMatcher
from polymatch.matchers.regex import RegexMatcher
from polymatch.matchers.standard import ExactMatcher, ContainsMatcher
from polymatch.matchers.standard import ContainsMatcher, ExactMatcher


def _opt_split(text, delim=':', empty="", invchar='~'):
def _opt_split(text, delim=":", empty="", invchar="~"):
if text.startswith(invchar):
invert = True
text = text[len(invchar):]
text = text[len(invchar) :]
else:
invert = False

Expand All @@ -34,10 +38,12 @@ def _parse_pattern_string(text):

return invert, name, opts, pattern
elif isinstance(text, bytes):
invert, name, opts, pattern = _opt_split(text, b':', b'', b'~')
invert, name, opts, pattern = _opt_split(text, b":", b"", b"~")
return invert, name.decode(), opts.decode(), pattern
else:
raise TypeError("Unable to parse pattern string of type {!r}".format(type(text).__name__))
raise TypeError(
f"Unable to parse pattern string of type {type(text).__name__!r}"
)


class PatternMatcherRegistry:
Expand All @@ -51,7 +57,9 @@ def register(self, cls):

if not issubclass(cls, PolymorphicMatcher):
raise TypeError(
"Pattern matcher must be of type {!r} not {!r}".format(PolymorphicMatcher.__name__, cls.__name__)
"Pattern matcher must be of type {!r} not {!r}".format(
PolymorphicMatcher.__name__, cls.__name__
)
)

self._matchers[name] = cls
Expand Down Expand Up @@ -88,7 +96,9 @@ def pattern_from_string(self, text):
break

if case_action is None:
raise LookupError("Unable to find CaseAction for options: {!r}".format(opts))
raise LookupError(
f"Unable to find CaseAction for options: {opts!r}"
)

return match_cls(pattern, case_action, invert)

Expand Down
2 changes: 2 additions & 0 deletions tests/test_glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

def test_patterns():
from polymatch import pattern_registry

for pattern, text, result in data:
matcher = pattern_registry.pattern_from_string(pattern)
matcher.compile()
Expand All @@ -16,6 +17,7 @@ def test_patterns():

def test_invert():
from polymatch import pattern_registry

pattern = pattern_registry.pattern_from_string("~glob::beep")
pattern.compile()
assert pattern.inverted
25 changes: 16 additions & 9 deletions tests/test_pickling.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ def __init__(self, pat):


def pytest_generate_tests(metafunc):
if 'pattern' in metafunc.fixturenames:
metafunc.parametrize('pattern', patterns)
if "pattern" in metafunc.fixturenames:
metafunc.parametrize("pattern", patterns)

if 'pickle_proto' in metafunc.fixturenames:
metafunc.parametrize('pickle_proto', list(range(pickle.HIGHEST_PROTOCOL + 1)))
if "pickle_proto" in metafunc.fixturenames:
metafunc.parametrize(
"pickle_proto", list(range(pickle.HIGHEST_PROTOCOL + 1))
)


def cycle_pickle(obj, proto):
Expand All @@ -27,6 +29,7 @@ def cycle_pickle(obj, proto):

def test_compile_state(pattern, pickle_proto):
from polymatch import pattern_registry

compiled_pattern = pattern_registry.pattern_from_string(pattern)
compiled_pattern.compile()

Expand All @@ -36,7 +39,9 @@ def test_compile_state(pattern, pickle_proto):

assert not uncompiled_pattern.is_compiled()

pat1, pat2 = cycle_pickle((compiled_pattern, uncompiled_pattern), pickle_proto)
pat1, pat2 = cycle_pickle(
(compiled_pattern, uncompiled_pattern), pickle_proto
)

assert pat1.is_compiled() is compiled_pattern.is_compiled()

Expand All @@ -45,10 +50,11 @@ def test_compile_state(pattern, pickle_proto):

def test_properties(pattern, pickle_proto):
from polymatch import pattern_registry

pat = pattern_registry.pattern_from_string(pattern)
pat.compile()

inv_pat = pattern_registry.pattern_from_string('~' + pattern)
inv_pat = pattern_registry.pattern_from_string("~" + pattern)
inv_pat.compile()

assert not pat.inverted
Expand All @@ -68,8 +74,9 @@ def test_properties(pattern, pickle_proto):


def test_version_checks(pattern, pickle_proto):
from polymatch import pattern_registry
import polymatch
from polymatch import pattern_registry

pat = pattern_registry.pattern_from_string(pattern)
pat.compile()

Expand All @@ -78,9 +85,9 @@ def test_version_checks(pattern, pickle_proto):
data = pickle.dumps(pat, pickle_proto)

# Change version
v = polymatch.__version__.split('.')
v = polymatch.__version__.split(".")
v[-1] = str(int(v[-1]) + 1)
polymatch.__version__ = '.'.join(v)
polymatch.__version__ = ".".join(v)

new_pat = pickle.loads(data)

Expand Down
2 changes: 2 additions & 0 deletions tests/test_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

def test_patterns():
from polymatch import pattern_registry

for pattern, text, result in data:
matcher = pattern_registry.pattern_from_string(pattern)
matcher.compile()
Expand All @@ -16,6 +17,7 @@ def test_patterns():

def test_invert():
from polymatch import pattern_registry

pattern = pattern_registry.pattern_from_string("~regex::beep")
pattern.compile()
assert pattern.inverted
2 changes: 2 additions & 0 deletions tests/test_standard.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

def test_patterns():
from polymatch import pattern_registry

for pattern, text, result in data:
matcher = pattern_registry.pattern_from_string(pattern)
matcher.compile()
Expand All @@ -17,6 +18,7 @@ def test_patterns():

def test_invert():
from polymatch import pattern_registry

pattern = pattern_registry.pattern_from_string("~exact::beep")
pattern.compile()
assert pattern.inverted

0 comments on commit 2253e2b

Please sign in to comment.