Skip to content

Commit

Permalink
chore(ruff): Enable and fix all ruff rules that we can (#3742)
Browse files Browse the repository at this point in the history
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
  • Loading branch information
bellini666 and sourcery-ai[bot] authored Jan 4, 2025
1 parent 15044cd commit 6bc7332
Show file tree
Hide file tree
Showing 148 changed files with 592 additions and 669 deletions.
4 changes: 2 additions & 2 deletions .github/release-check-action/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ def get_release_info(file_path: Path) -> ReleaseInfo:
match = RELEASE_TYPE_REGEX.match(line)

if not match:
raise InvalidReleaseFileError()
raise InvalidReleaseFileError

change_type_key = match.group(1)
change_type = ChangeType[change_type_key.upper()]
changelog = "".join([line for line in f.readlines()]).strip()
changelog = "".join(f.readlines()).strip()

return ReleaseInfo(change_type, changelog)
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.4
rev: v0.8.5
hooks:
- id: ruff-format
exclude: ^tests/\w+/snapshots/
Expand Down
2 changes: 1 addition & 1 deletion federation-compatibility/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ def resolve_reference(cls, **data: Any) -> Optional["Product"]:
return get_product_by_sku_and_variation(
sku=data["sku"], variation=data["variation"]
)
elif "package" in data:
if "package" in data:
return get_product_by_sku_and_package(
sku=data["sku"], package=data["package"]
)
Expand Down
175 changes: 81 additions & 94 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -228,125 +228,69 @@ src = ["strawberry", "tests"]
select = ["ALL"]
ignore = [
# https://github.com/astral-sh/ruff/pull/4427
# equivalent to keep-runtime-typing
# equivalent to keep-runtime-typing. We might want to enable those
# after we drop support for Python 3.9
"UP006",
"UP007",

"TID252",
# we use asserts in tests and to hint mypy
"S101",
"S102",
"S104",
"S324",
# definitely enable these, maybe not in tests

# Allow "Any" for annotations. We have too many Any annotations and some
# are legit. Maybe reconsider in the future, except for tests?
"ANN401",
"PGH003",
"PGH004",
"RET504",
"RET505",
"RET506",
"RET507",
"RET503",
"BLE001",
"B008",
"N811",
"N804",

# Allow our exceptions to have names that don't end in "Error". Maybe refactor
# in the future? But that would be a breaking change.
"N818",

# Allow "type: ignore" without rule code. Because we support both mypy and
# pyright, and they have different codes for the same error, we can't properly
# fix those issues.
"PGH003",

# Variable `T` in function should be lowercase
# this seems a potential bug or opportunity for improvement in ruff
"N806",

# first argument should named self (found in tests)
"N805",

"N815",

# shadowing builtins
"A001",
"A002",
"A003",

# Unused arguments
"ARG001",
"ARG002",
"ARG003",
"ARG004",
"ARG005",

# Boolean positional arguments
"FBT001",
"FBT002",
"FBT003",

"PT001",
"PT023",

# this is pretty much handled by black
"E501",

# enable these, we have some in tests
"B006",
"PT007",
"PT011",
"PT012",
"PT015",
"PT017",
"C414",
"N802",

"SIM117",
"SIM102",

"F841",
"B027",
"B905",
"ISC001",

# same?
"S105",
"S106",
# Too many arguments/branches/return statements
"PLR0913",
"PLR0912",
"PLR0911",

"DTZ003",
"DTZ005",
# Do not force adding _co to covariant typevars
"PLC0105",

"RSE102",
# Allow private access to attributes
"SLF001",

# in tests
"DTZ001",

"EM101",
"EM102",
"EM103",

"B904",
"B019",

"N801",
"N807",

# pandas
"PD",

"RUF012",
"PLC0105",
"FA102",

# code complexity
"C",
"C901",

# trailing commas
"COM812",

"PLR",
"INP",
"TRY",
"SIM300",
"SIM114",

"DJ008",
# Allow todo/fixme/etc comments
"TD002",
"TD003",
"FIX001",
"FIX002",

# We don't want to add "from __future__ mport annotations" everywhere
"FA100",

# Docstrings, maybe to enable later
Expand All @@ -359,29 +303,72 @@ ignore = [
"D106",
"D107",
"D412",

# Allow to define exceptions text in the exception body
"TRY003",
"EM101",
"EM102",
"EM103",

# Allow comparisons with magic numbers
"PLR2004",

# Allow methods to use lru_cache
"B019",

# Don't force if branches to be converted to "or"
"SIM114",

# ruff formatter recommends to disable those, as they conflict with it
# we don't need to ever enable those.
"COM812",
"COM819",
"D206",
"E111",
"E114",
"E117",
"E501",
"ISC001",
"Q000",
"Q001",
"Q002",
"Q003",
"W191",
]

[tool.ruff.lint.per-file-ignores]
"strawberry/schema/types/concrete_type.py" = ["TCH002"]
".github/*" = ["INP001"]
"federation-compatibility/*" = ["INP001"]
"strawberry/cli/*" = ["B008"]
"strawberry/extensions/tracing/__init__.py" = ["TCH004"]
"strawberry/fastapi/*" = ["B008"]
"strawberry/annotation.py" = ["RET505"]
"tests/*" = [
"RSE102",
"SLF001",
"TCH001",
"TCH002",
"TCH003",
"ANN001",
"ANN201",
"ANN202",
"ANN204",
"PLW0603",
"B008",
"B018",
"D",
"DTZ001",
"DTZ005",
"FA102",
"N805",
"PLC1901",
"PLR2004",
"PLW0603",
"PT011",
"RUF012",
"S105",
"S106",
"S603",
"S607",
"B018",
"D",
"TCH001",
"TCH002",
"TCH003",
"TRY002",
]
"strawberry/extensions/tracing/__init__.py" = ["TCH004"]
"tests/http/clients/__init__.py" = ["F401"]

[tool.ruff.lint.isort]
known-first-party = ["strawberry"]
Expand Down
4 changes: 1 addition & 3 deletions strawberry/aiohttp/test/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,11 @@ async def request(
headers: Optional[dict[str, object]] = None,
files: Optional[dict[str, object]] = None,
) -> Any:
response = await self._client.post(
return await self._client.post(
self.url,
json=body if not files else None,
data=body if files else None,
)

return response


__all__ = ["GraphQLTestClient"]
6 changes: 3 additions & 3 deletions strawberry/aiohttp/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,12 @@ async def iter_json(
if ws_message.type == http.WSMsgType.TEXT:
try:
yield self.view.decode_json(ws_message.data)
except JSONDecodeError:
except JSONDecodeError as e:
if not ignore_parsing_errors:
raise NonJsonMessageReceived()
raise NonJsonMessageReceived from e

elif ws_message.type == http.WSMsgType.BINARY:
raise NonTextMessageReceived()
raise NonTextMessageReceived

async def send_json(self, message: Mapping[str, object]) -> None:
try:
Expand Down
12 changes: 5 additions & 7 deletions strawberry/annotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,7 @@ def evaluate(self) -> type:
if isinstance(annotation, str):
annotation = ForwardRef(annotation)

evaled_type = eval_type(annotation, self.namespace, None)

return evaled_type
return eval_type(annotation, self.namespace, None)

def _get_type_with_args(
self, evaled_type: type[Any]
Expand Down Expand Up @@ -155,13 +153,13 @@ def _resolve(self) -> Union[StrawberryType, type]:
# a StrawberryType
if self._is_enum(evaled_type):
return self.create_enum(evaled_type)
elif self._is_optional(evaled_type, args):
if self._is_optional(evaled_type, args):
return self.create_optional(evaled_type)
elif self._is_union(evaled_type, args):
if self._is_union(evaled_type, args):
return self.create_union(evaled_type, args)
elif is_type_var(evaled_type) or evaled_type is Self:
if is_type_var(evaled_type) or evaled_type is Self:
return self.create_type_var(cast(TypeVar, evaled_type))
elif self._is_strawberry_type(evaled_type):
if self._is_strawberry_type(evaled_type):
# Simply return objects that are already StrawberryTypes
return evaled_type

Expand Down
8 changes: 4 additions & 4 deletions strawberry/asgi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@ async def iter_json(
try:
text = await self.ws.receive_text()
yield self.view.decode_json(text)
except JSONDecodeError: # noqa: PERF203
except JSONDecodeError as e: # noqa: PERF203
if not ignore_parsing_errors:
raise NonJsonMessageReceived()
except KeyError:
raise NonTextMessageReceived()
raise NonJsonMessageReceived from e
except KeyError as e:
raise NonTextMessageReceived from e
except WebSocketDisconnect: # pragma: no cover
pass

Expand Down
6 changes: 3 additions & 3 deletions strawberry/channels/handlers/ws_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ async def iter_json(
break

if message["message"] is None:
raise NonTextMessageReceived()
raise NonTextMessageReceived

try:
yield self.view.decode_json(message["message"])
except json.JSONDecodeError:
except json.JSONDecodeError as e:
if not ignore_parsing_errors:
raise NonJsonMessageReceived()
raise NonJsonMessageReceived from e

async def send_json(self, message: Mapping[str, object]) -> None:
serialized_message = self.view.encode_json(message)
Expand Down
4 changes: 3 additions & 1 deletion strawberry/channels/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __init__(
path: str,
headers: Optional[list[tuple[bytes, bytes]]] = None,
protocol: str = GRAPHQL_TRANSPORT_WS_PROTOCOL,
connection_params: dict = {},
connection_params: dict | None = None,
**kwargs: Any,
) -> None:
"""Create a new communicator.
Expand All @@ -69,6 +69,8 @@ def __init__(
subprotocols: an ordered list of preferred subprotocols to be sent to the server.
**kwargs: additional arguments to be passed to the `WebsocketCommunicator` constructor.
"""
if connection_params is None:
connection_params = {}
self.protocol = protocol
subprotocols = kwargs.get("subprotocols", [])
subprotocols.append(protocol)
Expand Down
12 changes: 7 additions & 5 deletions strawberry/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
try:
from .app import app
from .commands.codegen import codegen as codegen # noqa
from .commands.export_schema import export_schema as export_schema # noqa
from .commands.schema_codegen import schema_codegen as schema_codegen # noqa
from .commands.server import server as server # noqa
from .commands.upgrade import upgrade as upgrade # noqa
from .commands.codegen import codegen as codegen # noqa: PLC0414
from .commands.export_schema import export_schema as export_schema # noqa: PLC0414
from .commands.schema_codegen import (
schema_codegen as schema_codegen, # noqa: PLC0414
)
from .commands.server import server as server # noqa: PLC0414
from .commands.upgrade import upgrade as upgrade # noqa: PLC0414

def run() -> None:
app()
Expand Down
Loading

0 comments on commit 6bc7332

Please sign in to comment.