python-checks 0.3.2__py3-none-any.whl → 0.4.2__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.
Files changed (35) hide show
  1. py_checks/checks/_layout.py +239 -0
  2. py_checks/checks/_location.py +5 -38
  3. py_checks/checks/calls/_confined_functions.py +4 -4
  4. py_checks/checks/database/__init__.py +1 -2
  5. py_checks/checks/database/_bound_checks.py +23 -9
  6. py_checks/checks/database/_confined_calls.py +8 -5
  7. py_checks/checks/database/_model_boundary.py +49 -15
  8. py_checks/checks/database/_model_columns.py +10 -10
  9. py_checks/checks/database/_raw_sql.py +6 -6
  10. py_checks/checks/database/_statement_keys.py +3 -3
  11. py_checks/checks/effects/_determinism.py +6 -6
  12. py_checks/checks/imports/_confined.py +15 -7
  13. py_checks/checks/placement/__init__.py +16 -19
  14. py_checks/checks/placement/_class_modules.py +20 -45
  15. py_checks/checks/placement/_class_placement.py +28 -78
  16. py_checks/checks/placement/_operation_shape.py +51 -58
  17. py_checks/checks/placement/_required_class.py +13 -28
  18. py_checks/checks/signatures/_nesting.py +11 -3
  19. py_checks/checks/types/_confined_types.py +16 -4
  20. py_checks/cli/commands/__init__.py +2 -0
  21. py_checks/cli/commands/_doctor.py +293 -0
  22. py_checks/cli/commands/_explain.py +40 -4
  23. py_checks/config/__init__.py +2 -1
  24. py_checks/config/_base.py +8 -0
  25. py_checks/config/_config.py +34 -0
  26. py_checks/config/_loader.py +5 -1
  27. py_checks/core/__init__.py +6 -1
  28. py_checks/core/_paths.py +49 -0
  29. py_checks/core/_protocols.py +11 -0
  30. py_checks/core/_runner.py +3 -2
  31. {python_checks-0.3.2.dist-info → python_checks-0.4.2.dist-info}/METADATA +5 -3
  32. {python_checks-0.3.2.dist-info → python_checks-0.4.2.dist-info}/RECORD +35 -32
  33. {python_checks-0.3.2.dist-info → python_checks-0.4.2.dist-info}/WHEEL +0 -0
  34. {python_checks-0.3.2.dist-info → python_checks-0.4.2.dist-info}/entry_points.txt +0 -0
  35. {python_checks-0.3.2.dist-info → python_checks-0.4.2.dist-info}/licenses/LICENSE +0 -0
@@ -3,21 +3,22 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import ast
6
+ from dataclasses import dataclass
6
7
  from typing import TYPE_CHECKING, ClassVar, Final
7
8
 
8
- from pydantic import Field
9
-
10
9
  from py_checks.checks._kind import Kind, declarations
10
+ from py_checks.checks._layout import SECTION, Layout, innermost
11
11
  from py_checks.checks._location import place
12
12
  from py_checks.checks.placement._marker import MARKER
13
- from py_checks.config import CheckSettings
14
13
  from py_checks.core import Scope, Violation, settings_as
15
14
 
16
15
  if TYPE_CHECKING:
17
16
  from collections.abc import Iterator
18
17
 
19
18
  from py_checks.checks._kind import Declaration
19
+ from py_checks.checks._layout import Directory
20
20
  from py_checks.checks._location import Place
21
+ from py_checks.config import CheckSettings
21
22
  from py_checks.core import ParsedFile
22
23
 
23
24
  CODE: Final = "operation-shape"
@@ -27,38 +28,15 @@ PRIVATE: Final = "_"
27
28
  STATIC: Final = "staticmethod"
28
29
 
29
30
 
30
- class Operation(CheckSettings):
31
- """Директория с операциями и форма, которую там держат.
32
-
33
- `method` — единственная публичная дверь: сценарий просят об одном деле, и
34
- второй публичный метод означает вторую операцию, поделившую с первой
35
- конструктор. Пусто — значит число дверей не ограничено: у сервиса модуля
36
- их столько, сколько переходов у его сущности, и это тот же выбор, а не
37
- поблажка.
38
-
39
- `forbids` — имена типов, которых операция не держит: `UnitOfWork` ловится
40
- и как `IPlacementUnitOfWork`, и как `UnitOfWorkFactory`, потому что
41
- запрещено держать транзакцию, а не писать её имя одним конкретным образом.
31
+ @dataclass(frozen=True, slots=True)
32
+ class Shape:
33
+ """Форма операции этой директории: имя класса плюс то, что сказано в блоке."""
42
34
 
43
- `max_arguments` — сколько аргументов занимает вход. Дверь несёт то, что
44
- пришло снаружи, и вход длиннее нескольких полей — вещь с именем: команда,
45
- запрос, DTO. Считаются публичные методы: конструктор получает зависимости,
46
- а это проводка, не вход, и в счёт он не идёт уже потому, что публичным не
47
- является.
48
- """
49
-
50
- inside: str
35
+ address: str
51
36
  suffix: str
52
- method: str | None = None
53
- forbids: tuple[str, ...] = ()
54
- max_arguments: int | None = Field(
55
- default=None,
56
- gt=0,
57
- )
58
-
59
-
60
- class OperationShapeSettings(CheckSettings):
61
- operations: tuple[Operation, ...] = ()
37
+ method: str | None
38
+ forbids: tuple[str, ...]
39
+ max_arguments: int | None
62
40
 
63
41
 
64
42
  class OperationShape:
@@ -81,11 +59,12 @@ class OperationShape:
81
59
  Модуль, не объявивший операции вовсе, — тоже: об этом говорит
82
60
  `required-class`, и второе мнение сообщило бы одну ошибку дважды.
83
61
 
84
- Настройка: `operations`.
62
+ Настройка: `operation` в общей таблице `[layout]`, рядом с `suffix`.
85
63
  """
86
64
 
87
65
  code: ClassVar[str] = CODE
88
- Settings: ClassVar[type[CheckSettings]] = OperationShapeSettings
66
+ Settings: ClassVar[type[CheckSettings]] = Layout
67
+ section: ClassVar[str] = SECTION
89
68
  scope: ClassVar[Scope] = Scope.FILE
90
69
  marker: ClassVar[str] = MARKER
91
70
 
@@ -96,17 +75,17 @@ class OperationShape:
96
75
  file: ParsedFile,
97
76
  settings: CheckSettings,
98
77
  ) -> Iterator[Violation]:
99
- listed = settings_as(
78
+ layout = settings_as(
100
79
  settings=settings,
101
- model=OperationShapeSettings,
80
+ model=Layout,
102
81
  code=CODE,
103
- ).operations
82
+ ).directories
104
83
  where = place(file=file)
105
84
  if where is None or file.path.stem.startswith(PRIVATE):
106
85
  return
107
86
  rule = cls._rule(
108
87
  where=where,
109
- listed=listed,
88
+ layout=layout,
110
89
  )
111
90
  if rule is None:
112
91
  return
@@ -150,28 +129,42 @@ class OperationShape:
150
129
  def _rule(
151
130
  *,
152
131
  where: Place,
153
- listed: tuple[Operation, ...],
154
- ) -> Operation | None:
155
- """Правило этой директории: самое глубокое, а при равенстве — точное.
132
+ layout: dict[str, Directory],
133
+ ) -> Shape | None:
134
+ """Форма самой внутренней из совпавших директорий.
156
135
 
157
- Директорий в `inside` у правила может быть несколько, и файл попадает
158
- под оба: `use_cases` внутри `application/services` судит то, что
159
- названо длиннее и лежит ближе.
136
+ Блоков, под которые попадает файл, может быть несколько:
137
+ `application/services` внутри `application` судит то, что названо
138
+ длиннее и лежит ближе.
160
139
  """
161
- matched = [
162
- (depth, len(one.inside), one)
163
- for one in listed
164
- if (depth := where.within(directory=one.inside)) is not None
165
- ]
166
- if not matched:
140
+ found = innermost(
141
+ where=where,
142
+ among=[
143
+ (address, directory)
144
+ for address, directory in layout.items()
145
+ if directory.operation is not None and directory.suffix is not None
146
+ ],
147
+ )
148
+ if found is None:
149
+ return None
150
+ address, directory = found
151
+ # Оба поля проверены при отборе выше: блок без них сюда не попадает.
152
+ operation = directory.operation
153
+ if operation is None or directory.suffix is None:
167
154
  return None
168
- return max(matched, key=lambda found: found[:2])[2]
155
+ return Shape(
156
+ address=address,
157
+ suffix=directory.suffix,
158
+ method=operation.method,
159
+ forbids=operation.forbids,
160
+ max_arguments=operation.max_arguments,
161
+ )
169
162
 
170
163
  @staticmethod
171
164
  def _subject(
172
165
  *,
173
166
  declared: list[Declaration],
174
- rule: Operation,
167
+ rule: Shape,
175
168
  ) -> Declaration | None:
176
169
  """Операция, ради которой существует модуль, — по имени, а не по месту.
177
170
 
@@ -191,7 +184,7 @@ class OperationShape:
191
184
  file: ParsedFile,
192
185
  declared: list[Declaration],
193
186
  subject: Declaration | None,
194
- rule: Operation,
187
+ rule: Shape,
195
188
  ) -> Iterator[Violation]:
196
189
  """Всё, что встало рядом с операцией: второй класс или функция."""
197
190
  for one in declared:
@@ -211,7 +204,7 @@ class OperationShape:
211
204
  file=file,
212
205
  declared=one,
213
206
  message=(
214
- f"{one.name} стоит рядом с операцией; в {rule.inside} модуль "
207
+ f"{one.name} стоит рядом с операцией; в {rule.address} модуль "
215
208
  f"объявляет один класс и больше ничего"
216
209
  ),
217
210
  )
@@ -223,7 +216,7 @@ class OperationShape:
223
216
  file: ParsedFile,
224
217
  subject: Declaration,
225
218
  node: ast.ClassDef,
226
- rule: Operation,
219
+ rule: Shape,
227
220
  ) -> Iterator[Violation]:
228
221
  """Единственная публичная дверь операции."""
229
222
  if rule.method is None:
@@ -260,7 +253,7 @@ class OperationShape:
260
253
  file: ParsedFile,
261
254
  subject: Declaration,
262
255
  node: ast.ClassDef,
263
- rule: Operation,
256
+ rule: Shape,
264
257
  ) -> Iterator[Violation]:
265
258
  """Сколько аргументов занимает вход."""
266
259
  if rule.max_arguments is None:
@@ -307,7 +300,7 @@ class OperationShape:
307
300
  file: ParsedFile,
308
301
  subject: Declaration,
309
302
  node: ast.ClassDef,
310
- rule: Operation,
303
+ rule: Shape,
311
304
  ) -> Iterator[Violation]:
312
305
  """Тип, которого операция не держит, — в поле или в параметре."""
313
306
  for annotation in cls._annotations(node=node):
@@ -5,16 +5,16 @@ from __future__ import annotations
5
5
  from typing import TYPE_CHECKING, ClassVar, Final
6
6
 
7
7
  from py_checks.checks._kind import Kind, 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
16
  from py_checks.checks._kind import Declaration
17
- from py_checks.checks._location import Place
17
+ from py_checks.config import CheckSettings
18
18
  from py_checks.core import ParsedFile
19
19
 
20
20
  CODE: Final = "required-class"
@@ -26,10 +26,6 @@ CODE: Final = "required-class"
26
26
  VOCABULARY: Final[frozenset[Kind]] = frozenset({Kind.ALIAS, Kind.ENUM})
27
27
 
28
28
 
29
- class RequiredClassSettings(CheckSettings):
30
- suffixes: dict[str, str] = {}
31
-
32
-
33
29
  class RequiredClass:
34
30
  """Падает, если модуль не объявил класс, ради которого лежит в этой директории.
35
31
 
@@ -51,11 +47,12 @@ class RequiredClass:
51
47
  ничего не обещал; модуль с подчёркиванием (`_base.py`) держит машинерию
52
48
  своей директории, а не один из её классов. Эти трое правилу не подсудны.
53
49
 
54
- Настройка: `suffixes`.
50
+ Настройки: `required` и `suffix` в общей таблице `[layout]`.
55
51
  """
56
52
 
57
53
  code: ClassVar[str] = CODE
58
- Settings: ClassVar[type[CheckSettings]] = RequiredClassSettings
54
+ Settings: ClassVar[type[CheckSettings]] = Layout
55
+ section: ClassVar[str] = SECTION
59
56
  scope: ClassVar[Scope] = Scope.FILE
60
57
  marker: ClassVar[str] = MARKER
61
58
 
@@ -66,19 +63,21 @@ class RequiredClass:
66
63
  file: ParsedFile,
67
64
  settings: CheckSettings,
68
65
  ) -> Iterator[Violation]:
69
- suffixes = settings_as(
66
+ layout = settings_as(
70
67
  settings=settings,
71
- model=RequiredClassSettings,
68
+ model=Layout,
72
69
  code=CODE,
73
- ).suffixes
70
+ ).directories
74
71
  where = place(file=file)
75
72
  if where is None or file.path.stem.startswith("_"):
76
73
  return
77
- suffix = cls._suffix(
74
+ found = innermost(
78
75
  where=where,
79
- suffixes=suffixes,
76
+ among=[
77
+ (address, directory) for address, directory in layout.items() if directory.required
78
+ ],
80
79
  )
81
- if suffix is None:
80
+ if found is None or (suffix := found[1].suffix) is None:
82
81
  return
83
82
  declared = list(declarations(tree=file.tree))
84
83
  if not declared:
@@ -146,20 +145,6 @@ class RequiredClass:
146
145
  return one
147
146
  return None
148
147
 
149
- @staticmethod
150
- def _suffix(
151
- *,
152
- where: Place,
153
- suffixes: dict[str, str],
154
- ) -> str | None:
155
- """Суффикс самой внутренней из совпавших директорий."""
156
- matched = [
157
- (depth, len(directory), suffix)
158
- for directory, suffix in suffixes.items()
159
- if (depth := where.within(directory=directory)) is not None
160
- ]
161
- return max(matched)[2] if matched else None
162
-
163
148
  @staticmethod
164
149
  def _says(
165
150
  *,
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, ClassVar, Final, Self
8
8
  from pydantic import model_validator
9
9
 
10
10
  from py_checks.checks.signatures._marker import MARKER
11
- from py_checks.config import CheckSettings
11
+ from py_checks.config import OPEN, CheckSettings
12
12
  from py_checks.core import Scope, Violation, settings_as
13
13
 
14
14
  if TYPE_CHECKING:
@@ -35,7 +35,15 @@ BRANCHES: Final[tuple[str, ...]] = ("body", "orelse", "finalbody")
35
35
 
36
36
 
37
37
  class NestingSettings(CheckSettings):
38
- limits: dict[str, int] = {}
38
+ """Секция `[nesting]`: конструкция — и её предел вложенности."""
39
+
40
+ model_config = OPEN
41
+
42
+ __pydantic_extra__: dict[str, int] # type: ignore[assignment]
43
+
44
+ @property
45
+ def limits(self) -> dict[str, int]:
46
+ return self.__pydantic_extra__
39
47
 
40
48
  @model_validator(mode="after")
41
49
  def _known(self) -> Self:
@@ -63,7 +71,7 @@ class Nesting:
63
71
  Вложенный `with` в таблицу лучше не класть: его ловит ruff `SIM117`, с
64
72
  автофиксом и с ответом на месте.
65
73
 
66
- Настройка: `limits`.
74
+ Настройка: имя конструкции — предел: `try = 1`.
67
75
  """
68
76
 
69
77
  code: ClassVar[str] = CODE
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, ClassVar, Final
8
8
  from py_checks.checks._location import place
9
9
  from py_checks.checks._names import walked
10
10
  from py_checks.checks.types._marker import MARKER
11
- from py_checks.config import CheckSettings
11
+ from py_checks.config import OPEN, CheckSettings
12
12
  from py_checks.core import Scope, Violation, settings_as
13
13
 
14
14
  if TYPE_CHECKING:
@@ -25,7 +25,19 @@ ASIDE: Final[frozenset[str]] = frozenset({"ClassVar", "Final"})
25
25
 
26
26
 
27
27
  class ConfinedTypesSettings(CheckSettings):
28
- zones: dict[str, tuple[str, ...]] = {}
28
+ """Секция `[confined-types]`: адрес — и типы, которых там не бывает.
29
+
30
+ Ключи приносит проект, поэтому подтаблицы нет: имя директории и есть
31
+ настройка, а не значение под её именем.
32
+ """
33
+
34
+ model_config = OPEN
35
+
36
+ __pydantic_extra__: dict[str, tuple[str, ...]] # type: ignore[assignment]
37
+
38
+ @property
39
+ def forbidden(self) -> dict[str, tuple[str, ...]]:
40
+ return self.__pydantic_extra__
29
41
 
30
42
 
31
43
  class ConfinedTypes:
@@ -47,7 +59,7 @@ class ConfinedTypes:
47
59
  этажом ниже. Судятся поля класса; `ClassVar` и `Final` — не поля: они
48
60
  принадлежат классу, а не экземпляру.
49
61
 
50
- Настройка: `zones` — путь (можно с `*`: `modules/*/domain`) и список имён.
62
+ Настройка: адрес (можно с `*`: `modules/*/domain`) — и список имён.
51
63
  """
52
64
 
53
65
  code: ClassVar[str] = CODE
@@ -66,7 +78,7 @@ class ConfinedTypes:
66
78
  settings=settings,
67
79
  model=ConfinedTypesSettings,
68
80
  code=CODE,
69
- ).zones
81
+ ).forbidden
70
82
  where = place(file=file)
71
83
  if where is None:
72
84
  return
@@ -8,6 +8,7 @@
8
8
  from typing import Final
9
9
 
10
10
  from py_checks.cli._protocols import Registrar
11
+ from py_checks.cli.commands._doctor import register as register_doctor
11
12
  from py_checks.cli.commands._explain import register as register_explain
12
13
  from py_checks.cli.commands._list import register as register_list
13
14
  from py_checks.cli.commands._run import register as register_run
@@ -18,6 +19,7 @@ REGISTRARS: Final[tuple[Registrar, ...]] = (
18
19
  register_list,
19
20
  register_explain,
20
21
  register_sync,
22
+ register_doctor,
21
23
  )
22
24
 
23
25
  __all__ = ["REGISTRARS", "Registrar"]