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
@@ -25,10 +25,10 @@ NULLABLE: Final = "nullable"
25
25
 
26
26
  class ModelColumnsSettings(ZonedSettings):
27
27
  factories: tuple[str, ...] = ("mapped_column", "Column")
28
- types: dict[str, str] = {}
29
- homes: dict[str, str] = {}
28
+ instead: dict[str, str] = {}
29
+ wrappers: dict[str, str] = {}
30
30
  defaults: tuple[str, ...] = ()
31
- unruled: tuple[str, ...] = ()
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
- `types` — материал, которому в колонке не место, и что писать вместо.
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
- `homes` — модуль, которому этот материал называть можно: там живёт обёртка
49
+ `wrappers` — модуль, которому этот материал называть можно: там живёт обёртка
50
50
  над ним, и правило его не касается.
51
51
 
52
52
  `defaults` — все способы, которыми колонка заполняет себя сама. Значение по
@@ -55,7 +55,7 @@ class ModelColumns:
55
55
  аргументе конструктора поймал бы проверяльщик типов, превращается в
56
56
  правдоподобную строку.
57
57
 
58
- `unruled` — встроенные типы в `Mapped[...]`. Такая колонка говорит, какой
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`, `types`, `homes`, `defaults`, `unruled`,
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.types and limits.homes.get(written) != file.path.stem:
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.types[written],
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.unruled:
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
- calls: dict[str, str] = CALLS
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
- Настройка: `calls`.
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
- calls = settings_as(
76
+ instead = settings_as(
77
77
  settings=settings,
78
78
  model=RawSqlSettings,
79
79
  code=CODE,
80
- ).calls
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 calls or not cls._sql(node=node.args[0]):
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; вместо неё — {calls[written]}",
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
- calls: tuple[str, ...] = ("from_select",)
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`, `calls`, `loops`.
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.calls and node.args:
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
- sources: dict[str, str] = {} # noqa: RUF012 — pydantic копирует значение по умолчанию
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`, `sources`.
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.sources:
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
- sources=limits.sources,
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
- sources: dict[str, str],
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 sources.items()
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
- packages: dict[str, tuple[str, ...]] = {}
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
- `[tool.py-checks.confined-imports.packages]`; пустой список значит
38
- «нигде» — так держат убранную библиотеку, чтобы она не вернулась. Пакета,
39
- которого в списке нет, правило не касается.
44
+ такого слоя нет вовсе. Имя пакета — ключ в секции, значение — места, где
45
+ ему можно быть; пустой список значит «нигде» — так держат убранную
46
+ библиотеку, чтобы она не вернулась. Пакета, которого в секции нет, правило
47
+ не касается.
40
48
 
41
- Настройка: `packages`.
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
- Таблицы проектные: имена `use_cases`, `dto`, `schemas` библиотека знать не
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.placement._class_modules import ClassModules, ClassModulesSettings
13
- from py_checks.checks.placement._class_placement import (
14
- ClassPlacement,
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
- Operation,
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
- "ClassPlacementSettings",
28
+ "Directory",
29
+ "Layout",
32
30
  "Operation",
31
+ "Orm",
33
32
  "OperationShape",
34
- "OperationShapeSettings",
35
33
  "RequiredClass",
36
- "RequiredClassSettings",
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 Kind, declarations
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.checks._location import Place
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
- Ключ политики — путь, а не имя директории, и это важно: `application/
38
- services` держит класс-оркестратор, а `domain/services` — функции, правила,
39
- сравнивающие два факта. Одно слово, два разных зверя. Директории, которой
40
- в таблице нет, правило не касается.
33
+ Адрес в заголовке блока — путь, а не имя директории, и это важно:
34
+ `application/services` держит класс-оркестратор, а `domain/services` —
35
+ функции, правила, сравнивающие два факта. Одно слово, два разных зверя.
36
+ Директории, о которой раскладка молчит, правило не касается.
41
37
 
42
- Настройка: `policies`.
38
+ Настройка: `only` в общей таблице `[layout]`.
43
39
  """
44
40
 
45
41
  code: ClassVar[str] = CODE
46
- Settings: ClassVar[type[CheckSettings]] = ClassModulesSettings
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
- policies = settings_as(
54
+ layout = settings_as(
58
55
  settings=settings,
59
- model=ClassModulesSettings,
56
+ model=Layout,
60
57
  code=CODE,
61
- ).policies
58
+ ).directories
62
59
  where = place(file=file)
63
60
  if where is None:
64
61
  return
65
- policy = cls._policy(
62
+ found = innermost(
66
63
  where=where,
67
- policies=policies,
64
+ among=[(address, directory) for address, directory in layout.items() if directory.only],
68
65
  )
69
- if policy is None:
66
+ if found is None:
70
67
  return
71
- directory, allowed = policy
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 allowed:
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}; в {directory} держат "
82
- f"{', '.join(sorted(one.said for one in allowed))}"
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,46 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, ClassVar, Final, Self
5
+ from typing import TYPE_CHECKING, ClassVar, Final
6
6
 
7
- from pydantic import model_validator
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.checks._kind import Declaration
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
- исключение — это исключение, даже если его имя кончается на `Service`.
26
+ Дом объявляется в раскладке: `home` — про вид объявления, `suffix` — про
27
+ имя. Адресов у одного вида может быть несколько, и тогда дом — любой из
28
+ них: порт репозитория и его реализация законно лежат в двух местах, а
29
+ словарь отказов — и в `errors/`, и в `exceptions.py`.
30
+
31
+ Вид, о котором раскладка не сказала ни слова, правилу не подсуден: пока
32
+ `dataclass` не назвал своего дома, он лежит где угодно. Назвал — значит
33
+ перечислены все дома, в том числе доменный: value object тоже dataclass.
70
34
 
71
- Область (`area`) — половина смысла: `dataclass` обязан лежать в `dto/`
72
- только внутри `application`, потому что доменный value object — тоже
73
- dataclass, и живёт он в домене.
35
+ `area` сужает притязание до части дерева: соглашение про `dto` написано
36
+ про слой приложения, а dataclass в загрузчике или в наблюдаемости — это
37
+ способ сложить три поля рядом, а не предмет разговора.
74
38
 
75
- Настройка: `rules`.
39
+ Настройки: `home`, `suffix` и `area` в общей таблице `[layout]`.
76
40
  """
77
41
 
78
42
  code: ClassVar[str] = CODE
79
- Settings: ClassVar[type[CheckSettings]] = ClassPlacementSettings
43
+ Settings: ClassVar[type[CheckSettings]] = Layout
44
+ section: ClassVar[str] = SECTION
80
45
  scope: ClassVar[Scope] = Scope.FILE
81
46
  marker: ClassVar[str] = MARKER
82
47
 
@@ -87,43 +52,28 @@ class ClassPlacement:
87
52
  file: ParsedFile,
88
53
  settings: CheckSettings,
89
54
  ) -> Iterator[Violation]:
90
- rules = settings_as(
55
+ layout = settings_as(
91
56
  settings=settings,
92
- model=ClassPlacementSettings,
57
+ model=Layout,
93
58
  code=CODE,
94
- ).rules
59
+ ).directories
95
60
  where = place(file=file)
96
61
  if where is None:
97
62
  return
98
63
  for declared in declarations(tree=file.tree):
99
- rule = cls._rule(
64
+ homes = claimants(
100
65
  declared=declared,
66
+ layout=layout,
101
67
  where=where,
102
- rules=rules,
103
68
  )
104
- if rule is None:
69
+ if not homes or any(where.holds(path=home.address) for home in homes):
105
70
  continue
106
71
  yield Violation.from_node(
107
72
  node=declared.node,
108
73
  path=file.path,
109
74
  code=CODE,
110
- message=(f"{declared.name} {rule.said}; ему место в {', '.join(rule.inside)}"),
75
+ message=(
76
+ f"{declared.name} {homes[0].said}; "
77
+ f"ему место в {', '.join(home.address for home in homes)}"
78
+ ),
111
79
  )
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