Skip to content

Commit

Permalink
Make pretty and add ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Dec 7, 2023
1 parent 7663531 commit 9724541
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 40 deletions.
12 changes: 9 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ test:
test-cov:
${PYTEST} --cov sanic_routing

.PHONY: fix
fix:
ruff check sanic_routing --fix

.PHONY: format
format:
ruff format sanic_routing

.PHONY: pretty
pretty:
black --line-length 79 sanic_routing tests
isort --line-length 79 sanic_routing tests --profile=black
pretty: fix format
29 changes: 29 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[tool.ruff]
target-version = "py38"
line-length = 79

[tool.ruff.lint]
select = [
"E", # pycodestyle
"F", # pyflakes
"I", # isort
"W", # pycodestyle warnings
]
ignore = [
"E203",
]

[tool.ruff.lint.pydocstyle]
convention = "google"

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
line-ending = "auto"

[tool.ruff.isort]
known-first-party = ["sanic_routing"]
known-third-party = ["pytest"]
lines-after-imports = 2
lines-between-types = 1
1 change: 1 addition & 0 deletions sanic_routing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
from .route import Route
from .router import BaseRouter


__version__ = "23.6.0"
__all__ = ("BaseRouter", "Route", "RouteGroup")
32 changes: 25 additions & 7 deletions sanic_routing/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ def __init__(self, *routes) -> None:
self.pattern_idx = 0

def __str__(self):
display = f"path={self.path or self.router.delimiter} len={len(self.routes)}"
display = (
f"path={self.path or self.router.delimiter} len={len(self.routes)}"
)
return f"<{self.__class__.__name__}: {display}>"

def __repr__(self) -> str:
Expand All @@ -95,15 +97,21 @@ def __getattr__(self, key):

def finalize(self):
self.methods_index = Immutable(
{method: route for route in self._routes for method in route.methods}
{
method: route
for route in self._routes
for method in route.methods
}
)

def prioritize_routes(self) -> None:
"""
Sorts the routes in the group by priority
"""
self._routes = tuple(
sorted(self._routes, key=lambda route: route.priority, reverse=True)
sorted(
self._routes, key=lambda route: route.priority, reverse=True
)
)

def reset(self):
Expand Down Expand Up @@ -149,8 +157,14 @@ def handler2(...):
for current_route in self:
if (
current_route == other_route
or (current_route.requirements and not other_route.requirements)
or (not current_route.requirements and other_route.requirements)
or (
current_route.requirements
and not other_route.requirements
)
or (
not current_route.requirements
and other_route.requirements
)
) and not append:
if not overwrite:
raise RouteExists(
Expand All @@ -159,7 +173,9 @@ def handler2(...):
)
else:
_routes.append(other_route)
_routes.sort(key=lambda route: route.priority, reverse=True)
_routes.sort(
key=lambda route: route.priority, reverse=True
)
self._routes = tuple(_routes)

@property
Expand All @@ -179,7 +195,9 @@ def dynamic_path(self) -> bool:
@property
def methods(self) -> FrozenSet[str]:
""""""
return frozenset([method for route in self for method in route.methods])
return frozenset(
[method for route in self for method in route.methods]
)

@property
def routes(self) -> Sequence[Route]:
Expand Down
8 changes: 6 additions & 2 deletions sanic_routing/patterns.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import re
import typing as t
import uuid

from datetime import date, datetime
from types import SimpleNamespace
from typing import Any, Callable, Dict, Pattern, Tuple, Type
Expand Down Expand Up @@ -86,7 +87,8 @@ def __init__(self, **kwargs):
)
if match.group(2) == "path":
raise InvalidUsage(
"Extension parameter matching does not support the " "`path` type."
"Extension parameter matching does not support the "
"`path` type."
)
ext_type = match.group(3)
regex_type = REGEX_TYPES.get(match.group(2))
Expand Down Expand Up @@ -132,7 +134,9 @@ def process(self, params, value):


EXTENSION = r"[a-z0-9](?:[a-z0-9\.]*[a-z0-9])?"
PARAM_EXT = r"<([a-zA-Z_][a-zA-Z0-9_]*)(?:=([a-z]+))?(?::ext(?:=([a-z0-9|\.]+))?)>"
PARAM_EXT = (
r"<([a-zA-Z_][a-zA-Z0-9_]*)(?:=([a-z]+))?(?::ext(?:=([a-z0-9|\.]+))?)>"
)
REGEX_PARAM_NAME = re.compile(r"^<([a-zA-Z_][a-zA-Z0-9_]*)(?::(.*))?>$")
REGEX_PARAM_EXT_PATH = re.compile(PARAM_EXT)
REGEX_PARAM_NAME_EXT = re.compile(r"^" + PARAM_EXT + r"$")
Expand Down
25 changes: 19 additions & 6 deletions sanic_routing/route.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
import typing as t

from types import SimpleNamespace
from warnings import warn

Expand Down Expand Up @@ -204,7 +205,11 @@ def add_parameter(
pattern = re.compile(pattern)

is_regex = label not in self.router.regex_types
priority = 0 if is_regex else list(self.router.regex_types.keys()).index(label)
priority = (
0
if is_regex
else list(self.router.regex_types.keys()).index(label)
)
self._params[idx] = param_info_class(
name=name,
raw_path=raw_path,
Expand All @@ -229,8 +234,12 @@ def _finalize_params(self):
sorted(params.items(), key=lambda param: self._sorting(param[1]))
)

if not self.regex and any(":" in param.label for param in self.params.values()):
raise InvalidUsage(f"Invalid parameter declaration: {self.raw_path}")
if not self.regex and any(
":" in param.label for param in self.params.values()
):
raise InvalidUsage(
f"Invalid parameter declaration: {self.raw_path}"
)

def _compile_regex(self):
components = []
Expand Down Expand Up @@ -266,7 +275,9 @@ def _compile_regex(self):
else:
components.append(part)

self.pattern = self.router.delimiter + self.router.delimiter.join(components)
self.pattern = self.router.delimiter + self.router.delimiter.join(
components
)

def finalize(self):
self._finalize_params()
Expand Down Expand Up @@ -329,7 +340,7 @@ def parse_parameter_string(self, parameter_string: str):
:param parameter_string: String to parse
:return: tuple containing
(parameter_name, parameter_type, parameter_pattern)
"""
""" # noqa: E501
# We could receive NAME or NAME:PATTERN
parameter_string = parameter_string.strip("<>")
name = parameter_string
Expand All @@ -343,7 +354,9 @@ def parse_parameter_string(self, parameter_string: str):
name, _ = name.split("=", 1)

if not name:
raise ValueError(f"Invalid parameter syntax: {parameter_string}")
raise ValueError(
f"Invalid parameter syntax: {parameter_string}"
)
if label == "string":
warn(
"Use of 'string' as a path parameter type is deprected, "
Expand Down
43 changes: 33 additions & 10 deletions sanic_routing/router.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ast
import sys
import typing as t

from abc import ABC, abstractmethod
from types import SimpleNamespace
from warnings import warn
Expand All @@ -21,6 +22,7 @@
from .tree import Node, Tree
from .utils import parts_to_path, path_to_parts


# The below functions might be called by the compiled source code, and
# therefore should be made available here by import
import re # noqa isort:skip
Expand Down Expand Up @@ -125,7 +127,9 @@ def resolve(
# Apply if tuple (from ext) or if it is not a regex matcher
if isinstance(value, tuple):
param.process(params, value)
elif not route.regex or (route.regex and param.cast is not str):
elif not route.regex or (
route.regex and param.cast is not str
):
params[param.name] = value

# Double check that if we made a match it is not a false positive
Expand All @@ -146,7 +150,9 @@ def add(
self,
path: str,
handler: t.Callable,
methods: t.Optional[t.Union[t.Sequence[str], t.FrozenSet[str], str]] = None,
methods: t.Optional[
t.Union[t.Sequence[str], t.FrozenSet[str], str]
] = None,
name: t.Optional[str] = None,
requirements: t.Optional[t.Dict[str, t.Any]] = None,
strict: bool = False,
Expand All @@ -161,7 +167,8 @@ def add(
# - append: if matching path exists, append handler to it
if overwrite and append:
raise FinalizationError(
"Cannot add a route with both overwrite and append equal " "to True"
"Cannot add a route with both overwrite and append equal "
"to True"
)
if priority and not append:
raise FinalizationError(
Expand All @@ -178,7 +185,11 @@ def add(
if self.ALLOWED_METHODS and any(
method not in self.ALLOWED_METHODS for method in methods
):
bad = [method for method in methods if method not in self.ALLOWED_METHODS]
bad = [
method
for method in methods
if method not in self.ALLOWED_METHODS
]
raise BadMethod(
f"Bad method: {bad}. Must be one of: {self.ALLOWED_METHODS}"
)
Expand All @@ -201,7 +212,9 @@ def add(
routes = self.dynamic_routes

# Only URL encode the static parts of the path
path = parts_to_path(path_to_parts(path, self.delimiter), self.delimiter)
path = parts_to_path(
path_to_parts(path, self.delimiter), self.delimiter
)

# We need to clean off the delimiters are the beginning, and maybe the
# end, depending upon whether we are in strict mode
Expand Down Expand Up @@ -376,7 +389,9 @@ def _generate_tree(self) -> None:
self.tree.generate(self._get_non_static_non_path_groups(False))
self.tree.finalize()

def _render(self, do_compile: bool = True, do_optimize: bool = False) -> None:
def _render(
self, do_compile: bool = True, do_optimize: bool = False
) -> None:
# Initial boilerplate for the function source
src = [
Line("def find_route(path, method, router, basket, extra):", 0),
Expand Down Expand Up @@ -435,7 +450,9 @@ def _render(self, do_compile: bool = True, do_optimize: bool = False) -> None:

# Inject regex matching that could not be in the tree
for group in self._get_non_static_non_path_groups(True):
route_container = "regex_routes" if group.regex else "dynamic_routes"
route_container = (
"regex_routes" if group.regex else "dynamic_routes"
)
route_idx: t.Union[str, int] = 0
holder: t.List[Line] = []

Expand Down Expand Up @@ -472,7 +489,9 @@ def _render(self, do_compile: bool = True, do_optimize: bool = False) -> None:
src.append(Line("raise NotFound", 1))
src.extend(delayed)

self.find_route_src = "".join(map(str, filter(lambda x: x.render, src)))
self.find_route_src = "".join(
map(str, filter(lambda x: x.render, src))
)
if do_compile:
try:
syntax_tree = ast.parse(self.find_route_src)
Expand Down Expand Up @@ -532,7 +551,9 @@ def groups(self):

@property
def routes(self):
return tuple([route for group in self.groups.values() for route in group])
return tuple(
[route for group in self.groups.values() for route in group]
)

def _optimize(self, node) -> None:
warn(
Expand All @@ -559,7 +580,9 @@ def _optimize(self, node) -> None:
for test in [current.test, nested.test]:
if isinstance(test, ast.Compare):
values.append(test)
elif isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And):
elif isinstance(test, ast.BoolOp) and isinstance(
test.op, ast.And
):
values.extend(test.values)
else:
...
Expand Down
Loading

0 comments on commit 9724541

Please sign in to comment.