python-checks 0.3.2__py3-none-any.whl → 0.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- py_checks/checks/_layout.py +219 -0
- py_checks/checks/_location.py +5 -38
- py_checks/checks/calls/_confined_functions.py +4 -4
- py_checks/checks/database/__init__.py +1 -2
- py_checks/checks/database/_bound_checks.py +23 -9
- py_checks/checks/database/_confined_calls.py +8 -5
- py_checks/checks/database/_model_boundary.py +49 -15
- py_checks/checks/database/_model_columns.py +10 -10
- py_checks/checks/database/_raw_sql.py +6 -6
- py_checks/checks/database/_statement_keys.py +3 -3
- py_checks/checks/effects/_determinism.py +6 -6
- py_checks/checks/imports/_confined.py +15 -7
- py_checks/checks/placement/__init__.py +16 -19
- py_checks/checks/placement/_class_modules.py +20 -45
- py_checks/checks/placement/_class_placement.py +24 -79
- py_checks/checks/placement/_operation_shape.py +51 -58
- py_checks/checks/placement/_required_class.py +13 -28
- py_checks/checks/signatures/_nesting.py +11 -3
- py_checks/checks/types/_confined_types.py +16 -4
- py_checks/cli/commands/__init__.py +2 -0
- py_checks/cli/commands/_doctor.py +293 -0
- py_checks/cli/commands/_explain.py +40 -4
- py_checks/config/__init__.py +2 -1
- py_checks/config/_base.py +8 -0
- py_checks/config/_config.py +34 -0
- py_checks/config/_loader.py +5 -1
- py_checks/core/__init__.py +6 -1
- py_checks/core/_paths.py +49 -0
- py_checks/core/_protocols.py +11 -0
- py_checks/core/_runner.py +3 -2
- {python_checks-0.3.2.dist-info → python_checks-0.4.1.dist-info}/METADATA +5 -3
- {python_checks-0.3.2.dist-info → python_checks-0.4.1.dist-info}/RECORD +35 -32
- {python_checks-0.3.2.dist-info → python_checks-0.4.1.dist-info}/WHEEL +0 -0
- {python_checks-0.3.2.dist-info → python_checks-0.4.1.dist-info}/entry_points.txt +0 -0
- {python_checks-0.3.2.dist-info → python_checks-0.4.1.dist-info}/licenses/LICENSE +0 -0
|
@@ -25,10 +25,10 @@ NULLABLE: Final = "nullable"
|
|
|
25
25
|
|
|
26
26
|
class ModelColumnsSettings(ZonedSettings):
|
|
27
27
|
factories: tuple[str, ...] = ("mapped_column", "Column")
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
instead: dict[str, str] = {}
|
|
29
|
+
wrappers: dict[str, str] = {}
|
|
30
30
|
defaults: tuple[str, ...] = ()
|
|
31
|
-
|
|
31
|
+
skip: tuple[str, ...] = ()
|
|
32
32
|
aware: tuple[str, ...] = ()
|
|
33
33
|
nullable: bool = True
|
|
34
34
|
|
|
@@ -38,7 +38,7 @@ class ModelColumns:
|
|
|
38
38
|
|
|
39
39
|
Пять правил на одну таблицу настроек.
|
|
40
40
|
|
|
41
|
-
`
|
|
41
|
+
`instead` — материал, которому в колонке не место, и что писать вместо.
|
|
42
42
|
Голый `Enum` — нативный тип Postgres: каждый новый член требует `ALTER
|
|
43
43
|
TYPE`, а словари здесь чужие и расти будут. `Float` не держит цену точно, а
|
|
44
44
|
колонка — это состояние, и ошибка округления копится с каждой записью.
|
|
@@ -46,7 +46,7 @@ class ModelColumns:
|
|
|
46
46
|
получит каждый читатель, а разбор, поймавший бы пропущенный ключ, случается
|
|
47
47
|
в каждом отдельно или нигде.
|
|
48
48
|
|
|
49
|
-
`
|
|
49
|
+
`wrappers` — модуль, которому этот материал называть можно: там живёт обёртка
|
|
50
50
|
над ним, и правило его не касается.
|
|
51
51
|
|
|
52
52
|
`defaults` — все способы, которыми колонка заполняет себя сама. Значение по
|
|
@@ -55,7 +55,7 @@ class ModelColumns:
|
|
|
55
55
|
аргументе конструктора поймал бы проверяльщик типов, превращается в
|
|
56
56
|
правдоподобную строку.
|
|
57
57
|
|
|
58
|
-
`
|
|
58
|
+
`skip` — встроенные типы в `Mapped[...]`. Такая колонка говорит, какой
|
|
59
59
|
у значения вид, и ничего — какие значения допустимы, так что правило
|
|
60
60
|
приходится помнить каждому писателю.
|
|
61
61
|
|
|
@@ -66,7 +66,7 @@ class ModelColumns:
|
|
|
66
66
|
разрешает им разойтись, и тогда аннотация лжёт: pyright рассуждает по ней,
|
|
67
67
|
база держит ключевое слово, и одно из двух неверно на каждой строке.
|
|
68
68
|
|
|
69
|
-
Настройки: `zones`, `factories`, `
|
|
69
|
+
Настройки: `zones`, `factories`, `instead`, `wrappers`, `defaults`, `skip`,
|
|
70
70
|
`aware`, `nullable`.
|
|
71
71
|
"""
|
|
72
72
|
|
|
@@ -117,11 +117,11 @@ class ModelColumns:
|
|
|
117
117
|
) -> Iterator[Violation]:
|
|
118
118
|
"""Материал и то, чем колонка заполняет себя сама."""
|
|
119
119
|
written = name(node=node.func)
|
|
120
|
-
if written in limits.
|
|
120
|
+
if written in limits.instead and limits.wrappers.get(written) != file.path.stem:
|
|
121
121
|
yield cls._says(
|
|
122
122
|
file=file,
|
|
123
123
|
node=node,
|
|
124
|
-
message=limits.
|
|
124
|
+
message=limits.instead[written],
|
|
125
125
|
)
|
|
126
126
|
if written in limits.aware and not cls._said(
|
|
127
127
|
node=node,
|
|
@@ -160,7 +160,7 @@ class ModelColumns:
|
|
|
160
160
|
if inner is None:
|
|
161
161
|
return
|
|
162
162
|
written, optional = inner
|
|
163
|
-
if written in limits.
|
|
163
|
+
if written in limits.skip:
|
|
164
164
|
yield Violation.from_node(
|
|
165
165
|
node=node,
|
|
166
166
|
path=file.path,
|
|
@@ -27,7 +27,7 @@ CALLS: Final[dict[str, str]] = {
|
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
class RawSqlSettings(CheckSettings):
|
|
30
|
-
|
|
30
|
+
instead: dict[str, str] = CALLS
|
|
31
31
|
|
|
32
32
|
|
|
33
33
|
class RawSql:
|
|
@@ -58,7 +58,7 @@ class RawSql:
|
|
|
58
58
|
права импортировать те самые константы, поэтому её SQL выписан словами и
|
|
59
59
|
заморожен в день рождения. Это `exclude` проекта, а не дело правила.
|
|
60
60
|
|
|
61
|
-
Настройка: `
|
|
61
|
+
Настройка: `instead`.
|
|
62
62
|
"""
|
|
63
63
|
|
|
64
64
|
code: ClassVar[str] = CODE
|
|
@@ -73,16 +73,16 @@ class RawSql:
|
|
|
73
73
|
file: ParsedFile,
|
|
74
74
|
settings: CheckSettings,
|
|
75
75
|
) -> Iterator[Violation]:
|
|
76
|
-
|
|
76
|
+
instead = settings_as(
|
|
77
77
|
settings=settings,
|
|
78
78
|
model=RawSqlSettings,
|
|
79
79
|
code=CODE,
|
|
80
|
-
).
|
|
80
|
+
).instead
|
|
81
81
|
for node in ast.walk(file.tree):
|
|
82
82
|
if not isinstance(node, ast.Call) or not node.args:
|
|
83
83
|
continue
|
|
84
84
|
written = name(node=node.func)
|
|
85
|
-
if written not in
|
|
85
|
+
if written not in instead or not cls._sql(node=node.args[0]):
|
|
86
86
|
continue
|
|
87
87
|
yield Violation.from_node(
|
|
88
88
|
node=node,
|
|
@@ -90,7 +90,7 @@ class RawSql:
|
|
|
90
90
|
code=CODE,
|
|
91
91
|
# Пометка снимается с любой строки самого вызова.
|
|
92
92
|
end_line=node.end_lineno or node.lineno,
|
|
93
|
-
message=f"{written}(...) со строкой SQL; вместо неё — {
|
|
93
|
+
message=f"{written}(...) со строкой SQL; вместо неё — {instead[written]}",
|
|
94
94
|
)
|
|
95
95
|
|
|
96
96
|
@staticmethod
|
|
@@ -24,7 +24,7 @@ SAID: Final = "называет колонку строкой; маппед-ат
|
|
|
24
24
|
class StatementKeysSettings(ZonedSettings):
|
|
25
25
|
lists: tuple[str, ...] = ("index_elements",)
|
|
26
26
|
mappings: tuple[str, ...] = ("set_",)
|
|
27
|
-
|
|
27
|
+
sub_queries: tuple[str, ...] = ("from_select",)
|
|
28
28
|
loops: tuple[str, ...] = ("execute",)
|
|
29
29
|
|
|
30
30
|
|
|
@@ -49,7 +49,7 @@ class StatementKeys:
|
|
|
49
49
|
одного запроса, говорящего то же самое, не существует, — поэтому правило
|
|
50
50
|
снимается пометкой на строке цикла или самого вызова, а не отсутствует.
|
|
51
51
|
|
|
52
|
-
Настройки: `zones`, `lists`, `mappings`, `
|
|
52
|
+
Настройки: `zones`, `lists`, `mappings`, `sub-queries`, `loops`.
|
|
53
53
|
"""
|
|
54
54
|
|
|
55
55
|
code: ClassVar[str] = CODE
|
|
@@ -110,7 +110,7 @@ class StatementKeys:
|
|
|
110
110
|
written=keyword.arg,
|
|
111
111
|
nodes=cls._keyed(node=keyword.value),
|
|
112
112
|
)
|
|
113
|
-
if name(node=node.func) in limits.
|
|
113
|
+
if name(node=node.func) in limits.sub_queries and node.args:
|
|
114
114
|
yield from cls._strings(
|
|
115
115
|
file=file,
|
|
116
116
|
written=name(node=node.func),
|
|
@@ -20,7 +20,7 @@ CODE: Final = "determinism"
|
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
class DeterminismSettings(ZonedSettings):
|
|
23
|
-
|
|
23
|
+
instead: dict[str, str] = {} # noqa: RUF012 — pydantic копирует значение по умолчанию
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
class Determinism:
|
|
@@ -42,7 +42,7 @@ class Determinism:
|
|
|
42
42
|
Имя сверяется с хвостом: `datetime.now` подходит и записи
|
|
43
43
|
`datetime.datetime.now`, а `random.*` — любому вызову модуля целиком.
|
|
44
44
|
|
|
45
|
-
Настройки: `zones`, `
|
|
45
|
+
Настройки: `zones`, `instead`.
|
|
46
46
|
"""
|
|
47
47
|
|
|
48
48
|
code: ClassVar[str] = CODE
|
|
@@ -66,7 +66,7 @@ class Determinism:
|
|
|
66
66
|
file=file,
|
|
67
67
|
zones=limits.zones,
|
|
68
68
|
)
|
|
69
|
-
if where is None or not limits.
|
|
69
|
+
if where is None or not limits.instead:
|
|
70
70
|
return
|
|
71
71
|
for node in ast.walk(file.tree):
|
|
72
72
|
if not isinstance(node, ast.Call):
|
|
@@ -74,7 +74,7 @@ class Determinism:
|
|
|
74
74
|
called = ast.unparse(node.func)
|
|
75
75
|
said = cls._source(
|
|
76
76
|
called=called,
|
|
77
|
-
|
|
77
|
+
instead=limits.instead,
|
|
78
78
|
)
|
|
79
79
|
if said is None:
|
|
80
80
|
continue
|
|
@@ -89,13 +89,13 @@ class Determinism:
|
|
|
89
89
|
def _source(
|
|
90
90
|
*,
|
|
91
91
|
called: str,
|
|
92
|
-
|
|
92
|
+
instead: dict[str, str],
|
|
93
93
|
) -> str | None:
|
|
94
94
|
"""Причина, по которой такой вызов запрещён, если он в таблице."""
|
|
95
95
|
return next(
|
|
96
96
|
(
|
|
97
97
|
said
|
|
98
|
-
for pattern, said in
|
|
98
|
+
for pattern, said in instead.items()
|
|
99
99
|
if matches(
|
|
100
100
|
called=called,
|
|
101
101
|
pattern=pattern,
|
|
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, ClassVar, Final
|
|
|
7
7
|
from py_checks.checks._location import place
|
|
8
8
|
from py_checks.checks.imports._marker import MARKER
|
|
9
9
|
from py_checks.checks.imports._statements import imports
|
|
10
|
-
from py_checks.config import CheckSettings
|
|
10
|
+
from py_checks.config import OPEN, CheckSettings
|
|
11
11
|
from py_checks.core import Scope, Violation, settings_as
|
|
12
12
|
|
|
13
13
|
if TYPE_CHECKING:
|
|
@@ -22,7 +22,15 @@ CODE: Final = "confined-imports"
|
|
|
22
22
|
|
|
23
23
|
|
|
24
24
|
class ConfinedSettings(CheckSettings):
|
|
25
|
-
|
|
25
|
+
"""Секция `[confined-imports]`: пакет — и места, где его можно звать."""
|
|
26
|
+
|
|
27
|
+
model_config = OPEN
|
|
28
|
+
|
|
29
|
+
__pydantic_extra__: dict[str, tuple[str, ...]] # type: ignore[assignment]
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def packages(self) -> dict[str, tuple[str, ...]]:
|
|
33
|
+
return self.__pydantic_extra__
|
|
26
34
|
|
|
27
35
|
|
|
28
36
|
class ConfinedImports:
|
|
@@ -33,12 +41,12 @@ class ConfinedImports:
|
|
|
33
41
|
`infra/database`, а веб-стек на краю, каждый из них меняется в одном месте.
|
|
34
42
|
|
|
35
43
|
Где чьё место, знает проект: у сервиса это `infra/database`, у утилиты
|
|
36
|
-
такого слоя нет вовсе.
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
44
|
+
такого слоя нет вовсе. Имя пакета — ключ в секции, значение — места, где
|
|
45
|
+
ему можно быть; пустой список значит «нигде» — так держат убранную
|
|
46
|
+
библиотеку, чтобы она не вернулась. Пакета, которого в секции нет, правило
|
|
47
|
+
не касается.
|
|
40
48
|
|
|
41
|
-
Настройка:
|
|
49
|
+
Настройка: имя пакета — список мест.
|
|
42
50
|
"""
|
|
43
51
|
|
|
44
52
|
code: ClassVar[str] = CODE
|
|
@@ -5,34 +5,31 @@
|
|
|
5
5
|
под них нет — семейство ArchUnit для Python занято импортами, а движки образцов
|
|
6
6
|
(Semgrep, ast-grep) умеют запрещать, но не разрешать.
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
Все четыре правила читают общую таблицу `[layout]` — блок на директорию: они
|
|
9
|
+
говорят об одном и том же с четырёх сторон, и четыре таблицы об одном
|
|
10
|
+
разъезжались бы между собой. Живёт она в `checks/_layout.py`, потому что из
|
|
11
|
+
той же таблицы читает и `model-boundary`: раскладка — слово проекта, а не
|
|
12
|
+
собственность одной группы правил. Таблица проектная: имена `use_cases`, `dto`,
|
|
13
|
+
`schemas` библиотека знать не может. Без неё правила молчат.
|
|
10
14
|
"""
|
|
11
15
|
|
|
12
|
-
from py_checks.checks.
|
|
13
|
-
from py_checks.checks.placement.
|
|
14
|
-
|
|
15
|
-
ClassPlacementSettings,
|
|
16
|
-
Rule,
|
|
17
|
-
)
|
|
16
|
+
from py_checks.checks._layout import SECTION, Directory, Layout, Operation, Orm
|
|
17
|
+
from py_checks.checks.placement._class_modules import ClassModules
|
|
18
|
+
from py_checks.checks.placement._class_placement import ClassPlacement
|
|
18
19
|
from py_checks.checks.placement._marker import MARKER
|
|
19
|
-
from py_checks.checks.placement._operation_shape import
|
|
20
|
-
|
|
21
|
-
OperationShape,
|
|
22
|
-
OperationShapeSettings,
|
|
23
|
-
)
|
|
24
|
-
from py_checks.checks.placement._required_class import RequiredClass, RequiredClassSettings
|
|
20
|
+
from py_checks.checks.placement._operation_shape import OperationShape, Shape
|
|
21
|
+
from py_checks.checks.placement._required_class import RequiredClass
|
|
25
22
|
|
|
26
23
|
__all__ = [
|
|
27
24
|
"MARKER",
|
|
25
|
+
"SECTION",
|
|
28
26
|
"ClassModules",
|
|
29
|
-
"ClassModulesSettings",
|
|
30
27
|
"ClassPlacement",
|
|
31
|
-
"
|
|
28
|
+
"Directory",
|
|
29
|
+
"Layout",
|
|
32
30
|
"Operation",
|
|
31
|
+
"Orm",
|
|
33
32
|
"OperationShape",
|
|
34
|
-
"OperationShapeSettings",
|
|
35
33
|
"RequiredClass",
|
|
36
|
-
"
|
|
37
|
-
"Rule",
|
|
34
|
+
"Shape",
|
|
38
35
|
]
|
|
@@ -4,25 +4,21 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
from typing import TYPE_CHECKING, ClassVar, Final
|
|
6
6
|
|
|
7
|
-
from py_checks.checks._kind import
|
|
7
|
+
from py_checks.checks._kind import declarations
|
|
8
|
+
from py_checks.checks._layout import SECTION, Layout, innermost
|
|
8
9
|
from py_checks.checks._location import place
|
|
9
10
|
from py_checks.checks.placement._marker import MARKER
|
|
10
|
-
from py_checks.config import CheckSettings
|
|
11
11
|
from py_checks.core import Scope, Violation, settings_as
|
|
12
12
|
|
|
13
13
|
if TYPE_CHECKING:
|
|
14
14
|
from collections.abc import Iterator
|
|
15
15
|
|
|
16
|
-
from py_checks.
|
|
16
|
+
from py_checks.config import CheckSettings
|
|
17
17
|
from py_checks.core import ParsedFile
|
|
18
18
|
|
|
19
19
|
CODE: Final = "class-modules"
|
|
20
20
|
|
|
21
21
|
|
|
22
|
-
class ClassModulesSettings(CheckSettings):
|
|
23
|
-
policies: dict[str, tuple[Kind, ...]] = {}
|
|
24
|
-
|
|
25
|
-
|
|
26
22
|
class ClassModules:
|
|
27
23
|
"""Падает, если в модуле лежит то, чего его директория не допускает.
|
|
28
24
|
|
|
@@ -34,16 +30,17 @@ class ClassModules:
|
|
|
34
30
|
Импорты, константы, блоки `if TYPE_CHECKING` и докстринг разрешены везде:
|
|
35
31
|
правило про то, что модуль объявляет, а не про то, чем он пользуется.
|
|
36
32
|
|
|
37
|
-
|
|
38
|
-
services` держит класс-оркестратор, а `domain/services` —
|
|
39
|
-
сравнивающие два факта. Одно слово, два разных зверя.
|
|
40
|
-
|
|
33
|
+
Адрес в заголовке блока — путь, а не имя директории, и это важно:
|
|
34
|
+
`application/services` держит класс-оркестратор, а `domain/services` —
|
|
35
|
+
функции, правила, сравнивающие два факта. Одно слово, два разных зверя.
|
|
36
|
+
Директории, о которой раскладка молчит, правило не касается.
|
|
41
37
|
|
|
42
|
-
Настройка: `
|
|
38
|
+
Настройка: `only` в общей таблице `[layout]`.
|
|
43
39
|
"""
|
|
44
40
|
|
|
45
41
|
code: ClassVar[str] = CODE
|
|
46
|
-
Settings: ClassVar[type[CheckSettings]] =
|
|
42
|
+
Settings: ClassVar[type[CheckSettings]] = Layout
|
|
43
|
+
section: ClassVar[str] = SECTION
|
|
47
44
|
scope: ClassVar[Scope] = Scope.FILE
|
|
48
45
|
marker: ClassVar[str] = MARKER
|
|
49
46
|
|
|
@@ -54,53 +51,31 @@ class ClassModules:
|
|
|
54
51
|
file: ParsedFile,
|
|
55
52
|
settings: CheckSettings,
|
|
56
53
|
) -> Iterator[Violation]:
|
|
57
|
-
|
|
54
|
+
layout = settings_as(
|
|
58
55
|
settings=settings,
|
|
59
|
-
model=
|
|
56
|
+
model=Layout,
|
|
60
57
|
code=CODE,
|
|
61
|
-
).
|
|
58
|
+
).directories
|
|
62
59
|
where = place(file=file)
|
|
63
60
|
if where is None:
|
|
64
61
|
return
|
|
65
|
-
|
|
62
|
+
found = innermost(
|
|
66
63
|
where=where,
|
|
67
|
-
|
|
64
|
+
among=[(address, directory) for address, directory in layout.items() if directory.only],
|
|
68
65
|
)
|
|
69
|
-
if
|
|
66
|
+
if found is None:
|
|
70
67
|
return
|
|
71
|
-
|
|
68
|
+
address, directory = found
|
|
72
69
|
for declared in declarations(tree=file.tree):
|
|
73
70
|
# Вид не виден — судить не о чем: это класс с базой из другого модуля.
|
|
74
|
-
if declared.kind is None or declared.kind in
|
|
71
|
+
if declared.kind is None or declared.kind in directory.only:
|
|
75
72
|
continue
|
|
76
73
|
yield Violation.from_node(
|
|
77
74
|
node=declared.node,
|
|
78
75
|
path=file.path,
|
|
79
76
|
code=CODE,
|
|
80
77
|
message=(
|
|
81
|
-
f"{declared.name} — {declared.kind.said}; в {
|
|
82
|
-
f"{', '.join(sorted(one.said for one in
|
|
78
|
+
f"{declared.name} — {declared.kind.said}; в {address} держат "
|
|
79
|
+
f"{', '.join(sorted(one.said for one in directory.only))}"
|
|
83
80
|
),
|
|
84
81
|
)
|
|
85
|
-
|
|
86
|
-
@staticmethod
|
|
87
|
-
def _policy(
|
|
88
|
-
*,
|
|
89
|
-
where: Place,
|
|
90
|
-
policies: dict[str, tuple[Kind, ...]],
|
|
91
|
-
) -> tuple[str, tuple[Kind, ...]] | None:
|
|
92
|
-
"""Политика самой внутренней из совпавших директорий.
|
|
93
|
-
|
|
94
|
-
Побеждает самая глубокая: `modules/betslip/application/services`
|
|
95
|
-
важнее, чем `application`. При равной глубине — более длинный ключ:
|
|
96
|
-
путь говорит о месте больше, чем одно имя.
|
|
97
|
-
"""
|
|
98
|
-
matched = [
|
|
99
|
-
(depth, directory, allowed)
|
|
100
|
-
for directory, allowed in policies.items()
|
|
101
|
-
if (depth := where.within(directory=directory)) is not None
|
|
102
|
-
]
|
|
103
|
-
if not matched:
|
|
104
|
-
return None
|
|
105
|
-
deepest = max(matched, key=lambda policy: (policy[0], len(policy[1])))
|
|
106
|
-
return deepest[1], deepest[2]
|
|
@@ -2,81 +2,42 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from typing import TYPE_CHECKING, ClassVar, Final
|
|
5
|
+
from typing import TYPE_CHECKING, ClassVar, Final
|
|
6
6
|
|
|
7
|
-
from
|
|
8
|
-
|
|
9
|
-
from py_checks.checks._kind import Kind, declarations
|
|
7
|
+
from py_checks.checks._kind import declarations
|
|
8
|
+
from py_checks.checks._layout import SECTION, Layout, claimants
|
|
10
9
|
from py_checks.checks._location import place
|
|
11
10
|
from py_checks.checks.placement._marker import MARKER
|
|
12
|
-
from py_checks.config import CheckSettings
|
|
13
11
|
from py_checks.core import Scope, Violation, settings_as
|
|
14
12
|
|
|
15
13
|
if TYPE_CHECKING:
|
|
16
14
|
from collections.abc import Iterator
|
|
17
15
|
|
|
18
|
-
from py_checks.
|
|
19
|
-
from py_checks.checks._location import Place
|
|
16
|
+
from py_checks.config import CheckSettings
|
|
20
17
|
from py_checks.core import ParsedFile
|
|
21
18
|
|
|
22
19
|
CODE: Final = "class-placement"
|
|
23
20
|
|
|
24
21
|
|
|
25
|
-
class Rule(CheckSettings):
|
|
26
|
-
"""Кому куда: вид объявления или суффикс имени — и где ему место.
|
|
27
|
-
|
|
28
|
-
`area` сужает правило до части дерева. Без него `dataclass` пришлось бы
|
|
29
|
-
держать в `dto/` по всему сервису, а доменный value object — тоже
|
|
30
|
-
dataclass, и живёт он в домене.
|
|
31
|
-
|
|
32
|
-
`inside` перечисляет равноправные адреса: `errors` и `exceptions` — это
|
|
33
|
-
директория и модуль, и словарь отказов законно лежит в любом из них.
|
|
34
|
-
"""
|
|
35
|
-
|
|
36
|
-
kind: Kind | None = None
|
|
37
|
-
suffix: str | None = None
|
|
38
|
-
inside: tuple[str, ...]
|
|
39
|
-
area: str | None = None
|
|
40
|
-
|
|
41
|
-
@model_validator(mode="after")
|
|
42
|
-
def _one_subject(self) -> Self:
|
|
43
|
-
if (self.kind is None) == (self.suffix is None):
|
|
44
|
-
message = "правилу нужен ровно один признак: `kind` или `suffix`"
|
|
45
|
-
raise ValueError(message)
|
|
46
|
-
return self
|
|
47
|
-
|
|
48
|
-
def about(self, *, declared: Declaration) -> bool:
|
|
49
|
-
if self.suffix is not None:
|
|
50
|
-
return declared.name.endswith(self.suffix)
|
|
51
|
-
return declared.kind is self.kind
|
|
52
|
-
|
|
53
|
-
@property
|
|
54
|
-
def said(self) -> str:
|
|
55
|
-
if self.suffix is not None:
|
|
56
|
-
return f"кончается на {self.suffix}"
|
|
57
|
-
return f"— {self.kind.said}" if self.kind is not None else ""
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
class ClassPlacementSettings(CheckSettings):
|
|
61
|
-
rules: tuple[Rule, ...] = ()
|
|
62
|
-
|
|
63
|
-
|
|
64
22
|
class ClassPlacement:
|
|
65
23
|
"""Падает, если класс лежит не там, где лежат классы его вида.
|
|
66
24
|
|
|
67
25
|
Директория называет вид, и читатель находит порт, не открывая файла.
|
|
68
|
-
|
|
69
|
-
|
|
26
|
+
Дом объявляется в раскладке: `home` — про вид объявления, `suffix` — про
|
|
27
|
+
имя. Адресов у одного вида может быть несколько, и тогда дом — любой из
|
|
28
|
+
них: порт репозитория и его реализация законно лежат в двух местах, а
|
|
29
|
+
словарь отказов — и в `errors/`, и в `exceptions.py`.
|
|
70
30
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
31
|
+
Вид, о котором раскладка не сказала ни слова, правилу не подсуден: пока
|
|
32
|
+
`dataclass` не назвал своего дома, он лежит где угодно. Назвал — значит
|
|
33
|
+
перечислены все дома, в том числе доменный: value object тоже dataclass.
|
|
74
34
|
|
|
75
|
-
|
|
35
|
+
Настройки: `home` и `suffix` в общей таблице `[layout]`.
|
|
76
36
|
"""
|
|
77
37
|
|
|
78
38
|
code: ClassVar[str] = CODE
|
|
79
|
-
Settings: ClassVar[type[CheckSettings]] =
|
|
39
|
+
Settings: ClassVar[type[CheckSettings]] = Layout
|
|
40
|
+
section: ClassVar[str] = SECTION
|
|
80
41
|
scope: ClassVar[Scope] = Scope.FILE
|
|
81
42
|
marker: ClassVar[str] = MARKER
|
|
82
43
|
|
|
@@ -87,43 +48,27 @@ class ClassPlacement:
|
|
|
87
48
|
file: ParsedFile,
|
|
88
49
|
settings: CheckSettings,
|
|
89
50
|
) -> Iterator[Violation]:
|
|
90
|
-
|
|
51
|
+
layout = settings_as(
|
|
91
52
|
settings=settings,
|
|
92
|
-
model=
|
|
53
|
+
model=Layout,
|
|
93
54
|
code=CODE,
|
|
94
|
-
).
|
|
55
|
+
).directories
|
|
95
56
|
where = place(file=file)
|
|
96
57
|
if where is None:
|
|
97
58
|
return
|
|
98
59
|
for declared in declarations(tree=file.tree):
|
|
99
|
-
|
|
60
|
+
homes = claimants(
|
|
100
61
|
declared=declared,
|
|
101
|
-
|
|
102
|
-
rules=rules,
|
|
62
|
+
layout=layout,
|
|
103
63
|
)
|
|
104
|
-
if
|
|
64
|
+
if not homes or any(where.holds(path=home.address) for home in homes):
|
|
105
65
|
continue
|
|
106
66
|
yield Violation.from_node(
|
|
107
67
|
node=declared.node,
|
|
108
68
|
path=file.path,
|
|
109
69
|
code=CODE,
|
|
110
|
-
message=(
|
|
70
|
+
message=(
|
|
71
|
+
f"{declared.name} {homes[0].said}; "
|
|
72
|
+
f"ему место в {', '.join(home.address for home in homes)}"
|
|
73
|
+
),
|
|
111
74
|
)
|
|
112
|
-
|
|
113
|
-
@staticmethod
|
|
114
|
-
def _rule(
|
|
115
|
-
*,
|
|
116
|
-
declared: Declaration,
|
|
117
|
-
where: Place,
|
|
118
|
-
rules: tuple[Rule, ...],
|
|
119
|
-
) -> Rule | None:
|
|
120
|
-
"""Первое правило, которое про это объявление и которое нарушено."""
|
|
121
|
-
for rule in rules:
|
|
122
|
-
if not rule.about(declared=declared):
|
|
123
|
-
continue
|
|
124
|
-
if rule.area is not None and not where.holds(path=rule.area):
|
|
125
|
-
continue
|
|
126
|
-
if any(where.holds(path=address) for address in rule.inside):
|
|
127
|
-
return None
|
|
128
|
-
return rule
|
|
129
|
-
return None
|