Skip to content

Commit 88a6a95

Browse files
Enable more linting rules (#801)
1 parent 22d8a9c commit 88a6a95

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

78 files changed

+634
-624
lines changed

pdm.lock

Lines changed: 145 additions & 130 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,6 @@ dipdup = "dipdup.cli:cli"
8686
dev = [
8787
"black",
8888
"docker",
89-
"isort",
9089
"mypy",
9190
"pprofile",
9291
"pytest",
@@ -104,12 +103,11 @@ dev = [
104103
]
105104

106105
[tool.pdm.scripts]
107-
_isort = "isort src tests scripts"
108106
_black = "black src tests scripts"
109107
_ruff = "ruff check --fix src tests scripts"
110108
_mypy = "mypy src tests scripts"
111109
all = { composite = ["fmt", "lint", "test"] }
112-
fmt = { composite = ["_isort", "_black"] }
110+
fmt = { composite = ["_black"] }
113111
lint = { composite = ["_ruff", "_mypy"] }
114112
test = "pytest --cov-report=term-missing --cov=dipdup --cov-report=xml -n auto -s -v tests"
115113
update = { shell = """
@@ -129,25 +127,27 @@ docs_build = "python scripts/docs.py --source docs --destination {args:../interf
129127
docs_serve = "python scripts/docs.py --source docs --destination {args:../interface}/content/docs --watch --serve"
130128
docs_watch = "python scripts/docs.py --source docs --destination {args:../interface}/content/docs --watch"
131129
docs_references = "python scripts/dump_references.py"
130+
fixme = "grep -r -e 'FIXME: ' -e 'TODO: ' -e 'type: ignore' -n src/dipdup --color"
132131

133132
[tool.pdm.build.targets.wheel]
134133
packages = ["src/dipdup"]
135134

136-
[tool.isort]
137-
line_length = 120
138-
force_single_line = true
139-
140135
[tool.black]
141136
line-length = 120
142137
target-version = ["py311"]
143138
skip-string-normalization = true
144139

145140
[tool.ruff]
146141
line-length = 120
147-
ignore = ["E402", "E501", "B905"]
142+
ignore = [
143+
"E402", # module level import not at top of file
144+
"E501", # line too long
145+
"TCH001", # breaks our runtime Pydantic magic
146+
]
148147
target-version = "py311"
149-
extend-select = ["B", "C4", "PTH", "Q"] # todo: G, RET, RUF, S, TCH
148+
extend-select = ["B", "C4", "FA", "G", "I", "PTH", "Q", "RET", "RUF", "TCH", "UP"]
150149
flake8-quotes = { inline-quotes = "single", multiline-quotes = "double" }
150+
isort = { force-single-line = true, known-first-party = ["dipdup"] }
151151

152152
[tool.mypy]
153153
python_version = "3.11"

scripts/docs.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22
import logging
33
import re
44
import time
5+
from collections.abc import Callable
6+
from collections.abc import Iterator
57
from contextlib import ExitStack
68
from contextlib import contextmanager
79
from contextlib import suppress
810
from pathlib import Path
911
from shutil import rmtree
1012
from subprocess import Popen
1113
from typing import Any
12-
from typing import Callable
13-
from typing import Iterator
1414

1515
import click
1616
from watchdog.events import EVENT_TYPE_CREATED
@@ -68,15 +68,15 @@ def on_modified(self, event: FileSystemEvent) -> None:
6868
dst_file.unlink(True)
6969
return
7070

71-
elif event.event_type not in (EVENT_TYPE_CREATED, EVENT_TYPE_MODIFIED, EVENT_TYPE_MOVED):
71+
if event.event_type not in (EVENT_TYPE_CREATED, EVENT_TYPE_MODIFIED, EVENT_TYPE_MOVED):
7272
return
7373

7474
src_file = self._source / src_file
7575
dst_file = (self._destination / src_file.relative_to(self._source)).resolve()
7676
# NOTE: Make sure the destination directory exists
7777
dst_file.parent.mkdir(parents=True, exist_ok=True)
7878

79-
_logger.info(f'`{src_file}` has been modified; copying')
79+
_logger.info('`%s` has been modified; copying', src_file)
8080

8181
try:
8282
if src_file.suffix in TEXT:
@@ -97,7 +97,7 @@ def callback(data: str) -> str:
9797
def replacer(match: re.Match[str]) -> str:
9898
# FIXME: Slices are not handled yet
9999
included_file = source / match.group(1).split(':')[0]
100-
_logger.info(f'including `{included_file.name}`')
100+
_logger.info('including `%s`', included_file.name)
101101
return included_file.read_text()
102102

103103
return re.sub(INCLUDE_REGEX, replacer, data)

src/dipdup/cli.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import atexit
44
import logging
55
import sys
6+
from collections.abc import Awaitable
7+
from collections.abc import Callable
68
from contextlib import AsyncExitStack
79
from contextlib import suppress
810
from copy import copy
@@ -11,8 +13,6 @@
1113
from pathlib import Path
1214
from typing import TYPE_CHECKING
1315
from typing import Any
14-
from typing import Awaitable
15-
from typing import Callable
1616
from typing import TypeVar
1717
from typing import cast
1818

@@ -28,14 +28,18 @@
2828
from dipdup.report import save_report
2929
from dipdup.sys import set_up_process
3030

31+
if TYPE_CHECKING:
32+
from dipdup.config import DipDupConfig
33+
34+
3135
_click_wrap_text = click.formatting.wrap_text
3236

3337

3438
def _wrap_text(text: str, *a: Any, **kw: Any) -> str:
3539
# NOTE: WELCOME_ASCII and EPILOG
36-
if text.startswith((' ')):
40+
if text.startswith(' '):
3741
return text
38-
if text.startswith(('\0\n')):
42+
if text.startswith('\0\n'):
3943
return text[2:]
4044
return _click_wrap_text(text, *a, **kw)
4145

@@ -60,8 +64,6 @@ def _wrap_text(text: str, *a: Any, **kw: Any) -> str:
6064
'wipe',
6165
}
6266

63-
if TYPE_CHECKING:
64-
from dipdup.config import DipDupConfig
6567

6668
_logger = logging.getLogger(__name__)
6769

@@ -218,7 +220,7 @@ async def cli(ctx: click.Context, config: list[str], env_file: list[str]) -> Non
218220

219221
# NOTE: Fire and forget, do not block instant commands
220222
if not any((_config.advanced.skip_version_check, env.TEST, env.CI)):
221-
asyncio.ensure_future(_check_version())
223+
_ = asyncio.ensure_future(_check_version())
222224

223225
try:
224226
# NOTE: Avoid early import errors if project package is incomplete.
@@ -242,7 +244,6 @@ async def run(ctx: click.Context) -> None:
242244
243245
Execution can be gracefully interrupted with `Ctrl+C` or `SIGINT` signal.
244246
"""
245-
from dipdup.config import DipDupConfig
246247
from dipdup.dipdup import DipDup
247248

248249
config: DipDupConfig = ctx.obj.config
@@ -388,7 +389,6 @@ async def schema(ctx: click.Context) -> None:
388389
async def schema_approve(ctx: click.Context) -> None:
389390
"""Continue to use existing schema after reindexing was triggered."""
390391

391-
from dipdup.config import DipDupConfig
392392
from dipdup.database import tortoise_wrapper
393393
from dipdup.models import Index
394394
from dipdup.models import Schema

src/dipdup/codegen/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22
import subprocess
33
from abc import ABC
44
from abc import abstractmethod
5+
from collections.abc import Awaitable
6+
from collections.abc import Callable
57
from pathlib import Path
68
from shutil import rmtree
79
from shutil import which
810
from typing import Any
9-
from typing import Awaitable
10-
from typing import Callable
1111

1212
from pydantic import BaseModel
1313

src/dipdup/codegen/evm_subsquid.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,15 +174,14 @@ async def _fetch_abi(self, index_config: SubsquidEventsIndexConfig) -> None:
174174
abi_path.write_bytes(json_dumps(abi_json))
175175

176176
def get_typeclass_name(self, schema_path: Path) -> str:
177-
module_name = schema_path.stem
177+
return schema_path.stem
178178
# FIXME: Do we need prefixes or postfixes there?
179179
# if schema_path.parent.name == 'evm_events':
180180
# class_name = f'{module_name}_event'
181181
# elif schema_path.parent.name == 'evm_functions':
182182
# class_name = f'{module_name}_function'
183183
# else:
184184
# class_name = module_name
185-
return module_name
186185

187186
async def _generate_type(self, schema_path: Path, force: bool) -> None:
188187
if 'evm_events' not in schema_path.parts:

src/dipdup/codegen/tezos_tzkt.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,20 +66,19 @@ def preprocess_storage_jsonschema(schema: dict[str, Any]) -> dict[str, Any]:
6666
prop: preprocess_storage_jsonschema(sub_schema) for prop, sub_schema in schema['properties'].items()
6767
},
6868
}
69-
elif 'items' in schema:
69+
if 'items' in schema:
7070
return {
7171
**schema,
7272
'items': preprocess_storage_jsonschema(schema['items']),
7373
}
74-
elif 'additionalProperties' in schema:
74+
if 'additionalProperties' in schema:
7575
return {
7676
**schema,
7777
'additionalProperties': preprocess_storage_jsonschema(schema['additionalProperties']),
7878
}
79-
elif schema.get('$comment') == 'big_map':
79+
if schema.get('$comment') == 'big_map':
8080
return cast(dict[str, Any], schema['oneOf'][1])
81-
else:
82-
return schema
81+
return schema
8382

8483

8584
class TzktCodeGenerator(CodeGenerator):
@@ -156,7 +155,7 @@ async def generate_handlers(self) -> None:
156155
if isinstance(index_config, IndexTemplateConfig):
157156
continue
158157
# NOTE: Always single handler
159-
if isinstance(index_config, (TzktOperationsUnfilteredIndexConfig, TzktHeadIndexConfig)):
158+
if isinstance(index_config, TzktOperationsUnfilteredIndexConfig | TzktHeadIndexConfig):
160159
await self._generate_callback(index_config.handler_config, 'handlers')
161160
continue
162161

@@ -232,7 +231,7 @@ async def _fetch_operation_pattern_schema(
232231
return
233232

234233
# NOTE: A very special case; unresolved `operation` template to spawn from factory indexes.
235-
elif isinstance(contract_config, str) and contract_config in self._config.contracts:
234+
if isinstance(contract_config, str) and contract_config in self._config.contracts:
236235
contract_config = self._config.get_tezos_contract(contract_config)
237236

238237
elif isinstance(contract_config, str):

src/dipdup/config/__init__.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,10 @@
2424
from collections import Counter
2525
from contextlib import suppress
2626
from dataclasses import field
27-
from pathlib import Path
2827
from pydoc import locate
28+
from typing import TYPE_CHECKING
2929
from typing import Any
3030
from typing import Generic
31-
from typing import Iterator
3231
from typing import Literal
3332
from typing import TypeVar
3433
from typing import cast
@@ -49,10 +48,15 @@
4948
from dipdup.models import ReindexingReason
5049
from dipdup.models import SkipHistory
5150
from dipdup.performance import MetricsLevel
52-
from dipdup.subscriptions import Subscription
5351
from dipdup.utils import pascal_to_snake
5452
from dipdup.yaml import DipDupYAMLConfig
5553

54+
if TYPE_CHECKING:
55+
from collections.abc import Iterator
56+
from pathlib import Path
57+
58+
from dipdup.subscriptions import Subscription
59+
5660
DEFAULT_POSTGRES_SCHEMA = 'public'
5761
DEFAULT_POSTGRES_DATABASE = 'postgres'
5862
DEFAULT_POSTGRES_USER = 'postgres'
@@ -196,7 +200,7 @@ def create(
196200
cls,
197201
default: HttpConfig,
198202
user: HttpConfig | None,
199-
) -> 'ResolvedHttpConfig':
203+
) -> ResolvedHttpConfig:
200204
config = cls()
201205
# NOTE: Apply datasource defaults first
202206
for merge_config in (default, user):
@@ -445,7 +449,7 @@ def __post_init_post_parse__(self) -> None:
445449
schedules_enabled = sum(int(bool(x)) for x in (self.crontab, self.interval, self.daemon))
446450
if schedules_enabled > 1:
447451
raise ConfigurationError('Only one of `crontab`, `interval` of `daemon` can be specified')
448-
elif not schedules_enabled:
452+
if not schedules_enabled:
449453
raise ConfigurationError('One of `crontab`, `interval` or `daemon` must be specified')
450454

451455
NameMixin.__post_init_post_parse__(self)

src/dipdup/config/evm_subsquid_events.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
from dataclasses import field
4-
from typing import Iterator
4+
from typing import TYPE_CHECKING
55
from typing import Literal
66

77
from pydantic.dataclasses import dataclass
@@ -13,10 +13,14 @@
1313
from dipdup.config.evm_subsquid import SubsquidDatasourceConfig
1414
from dipdup.models.evm_node import EvmNodeLogsSubscription
1515
from dipdup.models.evm_node import EvmNodeNewHeadsSubscription
16-
from dipdup.subscriptions import Subscription
1716
from dipdup.utils import pascal_to_snake
1817
from dipdup.utils import snake_to_pascal
1918

19+
if TYPE_CHECKING:
20+
from collections.abc import Iterator
21+
22+
from dipdup.subscriptions import Subscription
23+
2024

2125
@dataclass
2226
class SubsquidEventsHandlerConfig(HandlerConfig):

src/dipdup/config/evm_subsquid_operations.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from __future__ import annotations
22

33
from dataclasses import field
4+
from typing import TYPE_CHECKING
45
from typing import Any
5-
from typing import Iterator
66
from typing import Literal
77

88
from pydantic.dataclasses import dataclass
@@ -12,7 +12,11 @@
1212
from dipdup.config import IndexConfig
1313
from dipdup.config.evm import EvmContractConfig
1414
from dipdup.config.evm_subsquid import SubsquidDatasourceConfig
15-
from dipdup.subscriptions import Subscription
15+
16+
if TYPE_CHECKING:
17+
from collections.abc import Iterator
18+
19+
from dipdup.subscriptions import Subscription
1620

1721

1822
@dataclass

0 commit comments

Comments
 (0)