python-checks 0.3.2__tar.gz → 0.4.2__tar.gz

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 (107) hide show
  1. {python_checks-0.3.2 → python_checks-0.4.2}/PKG-INFO +5 -3
  2. {python_checks-0.3.2 → python_checks-0.4.2}/README.md +4 -2
  3. {python_checks-0.3.2 → python_checks-0.4.2}/pyproject.toml +1 -1
  4. {python_checks-0.3.2 → python_checks-0.4.2}/pyproject.toml.orig +1 -1
  5. python_checks-0.4.2/src/py_checks/checks/_layout.py +239 -0
  6. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/_location.py +5 -38
  7. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/calls/_confined_functions.py +4 -4
  8. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/__init__.py +1 -2
  9. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/_bound_checks.py +23 -9
  10. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/_confined_calls.py +8 -5
  11. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/_model_boundary.py +49 -15
  12. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/_model_columns.py +10 -10
  13. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/_raw_sql.py +6 -6
  14. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/_statement_keys.py +3 -3
  15. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/effects/_determinism.py +6 -6
  16. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/imports/_confined.py +15 -7
  17. python_checks-0.4.2/src/py_checks/checks/placement/__init__.py +35 -0
  18. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/placement/_class_modules.py +20 -45
  19. python_checks-0.4.2/src/py_checks/checks/placement/_class_placement.py +79 -0
  20. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/placement/_operation_shape.py +51 -58
  21. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/placement/_required_class.py +13 -28
  22. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/signatures/_nesting.py +11 -3
  23. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/types/_confined_types.py +16 -4
  24. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/cli/commands/__init__.py +2 -0
  25. python_checks-0.4.2/src/py_checks/cli/commands/_doctor.py +293 -0
  26. python_checks-0.4.2/src/py_checks/cli/commands/_explain.py +64 -0
  27. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/config/__init__.py +2 -1
  28. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/config/_base.py +8 -0
  29. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/config/_config.py +34 -0
  30. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/config/_loader.py +5 -1
  31. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/__init__.py +6 -1
  32. python_checks-0.4.2/src/py_checks/core/_paths.py +49 -0
  33. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_protocols.py +11 -0
  34. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_runner.py +3 -2
  35. python_checks-0.3.2/src/py_checks/checks/placement/__init__.py +0 -38
  36. python_checks-0.3.2/src/py_checks/checks/placement/_class_placement.py +0 -129
  37. python_checks-0.3.2/src/py_checks/cli/commands/_explain.py +0 -28
  38. {python_checks-0.3.2 → python_checks-0.4.2}/LICENSE +0 -0
  39. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/__init__.py +0 -0
  40. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/__init__.py +0 -0
  41. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/_kind.py +0 -0
  42. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/_names.py +0 -0
  43. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/api/__init__.py +0 -0
  44. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/api/_endpoint_declarations.py +0 -0
  45. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/api/_marker.py +0 -0
  46. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/calls/__init__.py +0 -0
  47. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/calls/_marker.py +0 -0
  48. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/_marker.py +0 -0
  49. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/database/_schema_drift.py +0 -0
  50. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/effects/__init__.py +0 -0
  51. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/effects/_log_events.py +0 -0
  52. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/effects/_marker.py +0 -0
  53. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/hygiene/__init__.py +0 -0
  54. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/hygiene/_dependency_bounds.py +0 -0
  55. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/hygiene/_marker.py +0 -0
  56. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/imports/__init__.py +0 -0
  57. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/imports/_marker.py +0 -0
  58. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/imports/_sealed.py +0 -0
  59. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/imports/_statements.py +0 -0
  60. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/placement/_marker.py +0 -0
  61. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/signatures/__init__.py +0 -0
  62. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/signatures/_function_length.py +0 -0
  63. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/signatures/_functions.py +0 -0
  64. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/signatures/_keyword_only.py +0 -0
  65. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/signatures/_marker.py +0 -0
  66. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/signatures/_module_length.py +0 -0
  67. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/signatures/_signature_layout.py +0 -0
  68. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/types/__init__.py +0 -0
  69. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/types/_annotation_shapes.py +0 -0
  70. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/types/_config_fields.py +0 -0
  71. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/types/_constant_annotations.py +0 -0
  72. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/types/_frozen_dataclasses.py +0 -0
  73. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/checks/types/_marker.py +0 -0
  74. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/cli/__init__.py +0 -0
  75. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/cli/_app.py +0 -0
  76. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/cli/_protocols.py +0 -0
  77. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/cli/commands/_list.py +0 -0
  78. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/cli/commands/_run.py +0 -0
  79. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/cli/commands/_summary.py +0 -0
  80. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/cli/commands/_sync.py +0 -0
  81. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/config/_constants.py +0 -0
  82. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/config/_errors.py +0 -0
  83. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/config/_toml.py +0 -0
  84. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/contracts/__init__.py +0 -0
  85. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/contracts/_constants.py +0 -0
  86. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/contracts/_layout.py +0 -0
  87. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/contracts/_render.py +0 -0
  88. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/contracts/_settings.py +0 -0
  89. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_constants.py +0 -0
  90. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_discovery.py +0 -0
  91. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_edit.py +0 -0
  92. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_errors.py +0 -0
  93. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_fixer.py +0 -0
  94. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_format.py +0 -0
  95. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_markers.py +0 -0
  96. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_registry.py +0 -0
  97. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_report.py +0 -0
  98. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_settings.py +0 -0
  99. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_source.py +0 -0
  100. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/core/_violation.py +0 -0
  101. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/environment/__init__.py +0 -0
  102. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/environment/_constants.py +0 -0
  103. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/environment/_render.py +0 -0
  104. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/environment/_settings.py +0 -0
  105. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/py.typed +0 -0
  106. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/sync/__init__.py +0 -0
  107. {python_checks-0.3.2 → python_checks-0.4.2}/src/py_checks/sync/_sync.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-checks
3
- Version: 0.3.2
3
+ Version: 0.4.2
4
4
  Summary: Проверки архитектурных соглашений проекта
5
5
  Author: Armontex
6
6
  Author-email: Armontex <windle1337@gmail.com>
@@ -106,11 +106,11 @@ max-lines = 300
106
106
  # Rules that depend on place only work in the zones you name.
107
107
  [model-columns]
108
108
  zones = ["infra/database/models"]
109
- types = { Numeric = "money is described by Numeric(18, 4)" }
109
+ instead = { Float = "a Float column drifts; state is exact, use Numeric" }
110
110
 
111
111
  [determinism]
112
112
  zones = ["modules/*/domain", "modules/*/application"]
113
- sources = { "datetime.now" = "take the clock as a port", "uuid4" = "hand the id out at the edge" }
113
+ instead = { "datetime.now" = "take the clock as a port", "uuid4" = "hand the id out at the edge" }
114
114
  ```
115
115
 
116
116
  and run:
@@ -120,6 +120,7 @@ py-checks run # check `src`
120
120
  py-checks run --fix # and repair what repairs itself
121
121
  py-checks list # which rules exist and which are on
122
122
  py-checks explain determinism # what a rule asks for and what it can be told
123
+ py-checks doctor # and whether the config itself holds together
123
124
  ```
124
125
 
125
126
  The settings can also live in a `[tool.py-checks]` section of
@@ -347,6 +348,7 @@ obeys `ignore`, and is lifted by a mark.
347
348
  | `py-checks list` | every rule: code, state, one line of description |
348
349
  | `py-checks explain <code>` | what a rule asks for and what it can be told |
349
350
  | `py-checks sync [--check]` | build the import contracts and `.env.example` |
351
+ | `py-checks doctor` | check the config itself: typos, dead addresses, rules that say nothing |
350
352
 
351
353
  ## Development
352
354
 
@@ -85,11 +85,11 @@ max-lines = 300
85
85
  # Rules that depend on place only work in the zones you name.
86
86
  [model-columns]
87
87
  zones = ["infra/database/models"]
88
- types = { Numeric = "money is described by Numeric(18, 4)" }
88
+ instead = { Float = "a Float column drifts; state is exact, use Numeric" }
89
89
 
90
90
  [determinism]
91
91
  zones = ["modules/*/domain", "modules/*/application"]
92
- sources = { "datetime.now" = "take the clock as a port", "uuid4" = "hand the id out at the edge" }
92
+ instead = { "datetime.now" = "take the clock as a port", "uuid4" = "hand the id out at the edge" }
93
93
  ```
94
94
 
95
95
  and run:
@@ -99,6 +99,7 @@ py-checks run # check `src`
99
99
  py-checks run --fix # and repair what repairs itself
100
100
  py-checks list # which rules exist and which are on
101
101
  py-checks explain determinism # what a rule asks for and what it can be told
102
+ py-checks doctor # and whether the config itself holds together
102
103
  ```
103
104
 
104
105
  The settings can also live in a `[tool.py-checks]` section of
@@ -326,6 +327,7 @@ obeys `ignore`, and is lifted by a mark.
326
327
  | `py-checks list` | every rule: code, state, one line of description |
327
328
  | `py-checks explain <code>` | what a rule asks for and what it can be told |
328
329
  | `py-checks sync [--check]` | build the import contracts and `.env.example` |
330
+ | `py-checks doctor` | check the config itself: typos, dead addresses, rules that say nothing |
329
331
 
330
332
  ## Development
331
333
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-checks"
3
- version = "0.3.2"
3
+ version = "0.4.2"
4
4
  description = "Проверки архитектурных соглашений проекта"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-checks"
3
- version = "0.3.2"
3
+ version = "0.4.2"
4
4
  description = "Проверки архитектурных соглашений проекта"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -0,0 +1,239 @@
1
+ """Раскладка проекта: один блок на директорию.
2
+
3
+ Четыре правила говорят об одной и той же вещи с четырёх сторон: что здесь
4
+ может лежать (`class-modules`), что живёт только здесь (`class-placement`),
5
+ что модуль обязан объявить (`required-class`) и какой формы тут операция
6
+ (`operation-shape`). Раньше у каждого была своя таблица, и один факт про
7
+ `use_cases` приходилось писать четыре раза в четырёх синтаксисах, склеивая их
8
+ глазами по строковому ключу.
9
+
10
+ Теперь блок один на директорию, а правила читают из него свои колонки:
11
+
12
+ ```toml
13
+ [layout."application/use_cases"]
14
+ only = ["class"]
15
+ suffix = "UseCase"
16
+ required = true
17
+ operation = { method = "execute", max-arguments = 3 }
18
+ ```
19
+
20
+ Правила при этом друг о друге по-прежнему не знают — они просто читают одну
21
+ таблицу. Адрес в заголовке ищется подряд идущими кусками пути, поэтому
22
+ `application/use_cases` находится и в модульном сервисе, где путь начинается
23
+ с `modules/<имя>/`, а `*` подходит любому одному куску.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from dataclasses import dataclass
29
+ from enum import StrEnum
30
+ from typing import TYPE_CHECKING, Final, Self
31
+
32
+ from pydantic import Field, model_validator
33
+
34
+ from py_checks.checks._kind import Kind
35
+ from py_checks.config import CheckSettings
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Iterable
39
+
40
+ from py_checks.checks._kind import Declaration
41
+ from py_checks.checks._location import Place
42
+
43
+ SECTION: Final = "layout"
44
+
45
+
46
+ class Orm(StrEnum):
47
+ """Чем директория приходится ORM-модели.
48
+
49
+ Дом модели и место, где её собирают, — два конца одного соглашения, и
50
+ писать их в отдельной таблице значило бы назвать те же две директории
51
+ второй раз: раскладка уже знает их по имени.
52
+ """
53
+
54
+ # Здесь модели объявляют: где-то ещё это таблица, которую никто не ждёт по
55
+ # этому адресу, а autogenerate alembic видит только их пакет.
56
+ DECLARED = "declared"
57
+
58
+ # Здесь модели собирают: собрать модель — значит записать строку.
59
+ BUILT = "built"
60
+
61
+
62
+ class Operation(CheckSettings):
63
+ """Форма операции, которую держат в этой директории.
64
+
65
+ `method` — единственная публичная дверь: сценарий просят об одном деле, и
66
+ второй публичный метод означает вторую операцию, поделившую с первой
67
+ конструктор. Пусто — значит число дверей не ограничено: у сервиса модуля
68
+ их столько, сколько переходов у его сущности.
69
+
70
+ `forbids` — имена типов, которых операция не держит: `UnitOfWork` ловится
71
+ и как `IPlacementUnitOfWork`, и как `UnitOfWorkFactory`, потому что
72
+ запрещено держать транзакцию, а не писать её имя одним конкретным образом.
73
+
74
+ `max_arguments` — сколько аргументов занимает вход. Дверь несёт то, что
75
+ пришло снаружи, и вход длиннее нескольких полей — вещь с именем: команда,
76
+ запрос, DTO.
77
+ """
78
+
79
+ method: str | None = None
80
+ forbids: tuple[str, ...] = ()
81
+ max_arguments: int | None = Field(
82
+ default=None,
83
+ gt=0,
84
+ )
85
+
86
+
87
+ class Directory(CheckSettings):
88
+ """Что проект держит в этой директории.
89
+
90
+ `only` — виды, которым здесь место, и ничего другого рядом не садится.
91
+ `home` — виды, которым место ТОЛЬКО здесь: порт, объявленный в другом
92
+ конце дерева, — это порт, которого читатель не найдёт.
93
+ `area` — часть дерева, внутри которой дом и имя вообще о чём-то говорят:
94
+ правило про `dto` написано про слой приложения, а dataclass в загрузчике
95
+ или в наблюдаемости — просто способ сложить три поля рядом.
96
+ `suffix` — как зовут класс, ради которого директория существует; он же
97
+ живёт только здесь.
98
+ `required` — модуль обязан объявить такой класс, первым и один.
99
+ `operation` — форма операции, если здесь держат операции.
100
+ `orm` — чем директория приходится ORM-модели: домом или местом сборки.
101
+ `base` — базовый класс, по которому модель узнают в доме моделей.
102
+ """
103
+
104
+ only: tuple[Kind, ...] = ()
105
+ home: tuple[Kind, ...] = ()
106
+ area: str | None = None
107
+ suffix: str | None = None
108
+ required: bool = False
109
+ operation: Operation | None = None
110
+ orm: Orm | None = None
111
+ base: str | None = None
112
+
113
+ @model_validator(mode="after")
114
+ def _named(self) -> Self:
115
+ """Обязанность и форма опираются на имя: без суффикса их не проверить."""
116
+ if self.suffix is not None:
117
+ return self
118
+ if self.required:
119
+ message = "`required` без `suffix`: непонятно, какой класс обязан быть"
120
+ raise ValueError(message)
121
+ if self.operation is not None:
122
+ message = "`operation` без `suffix`: непонятно, какой класс здесь операция"
123
+ raise ValueError(message)
124
+ return self
125
+
126
+ @model_validator(mode="after")
127
+ def _claims(self) -> Self:
128
+ """Область сужает притязание: без дома и имени сужать нечего."""
129
+ if self.area is not None and not self.home and self.suffix is None:
130
+ message = "`area` без `home` и `suffix`: эта директория ни на что не притязает"
131
+ raise ValueError(message)
132
+ return self
133
+
134
+ @model_validator(mode="after")
135
+ def _declares(self) -> Self:
136
+ """`base` — про дом моделей: в месте сборки узнавать по базе нечего."""
137
+ if self.base is not None and self.orm is not Orm.DECLARED:
138
+ message = '`base` без `orm = "declared"`: базу называет дом моделей'
139
+ raise ValueError(message)
140
+ return self
141
+
142
+
143
+ class Layout(CheckSettings):
144
+ """Секция `[layout]`: адрес директории — и блок про неё.
145
+
146
+ Ключи приходят из проекта, поэтому модель принимает любые: имена
147
+ директорий — это данные, а не поля. Проверяется содержимое блока.
148
+ """
149
+
150
+ model_config = CheckSettings.model_config | {"extra": "allow"}
151
+
152
+ # Типизированный `extra` pydantic: ключ — адрес, значение — блок.
153
+ __pydantic_extra__: dict[str, Directory] # type: ignore[assignment]
154
+
155
+ @property
156
+ def directories(self) -> dict[str, Directory]:
157
+ return self.__pydantic_extra__
158
+
159
+
160
+ def addressed(
161
+ *,
162
+ layout: dict[str, Directory],
163
+ orm: Orm,
164
+ ) -> tuple[str, ...]:
165
+ """Адреса, объявившие себя этим концом соглашения про ORM-модель."""
166
+ return tuple(address for address, directory in layout.items() if directory.orm is orm)
167
+
168
+
169
+ def innermost(
170
+ *,
171
+ where: Place,
172
+ among: Iterable[tuple[str, Directory]],
173
+ ) -> tuple[str, Directory] | None:
174
+ """Блок самой внутренней из совпавших директорий.
175
+
176
+ Побеждает самая глубокая: `modules/betslip/application/services` важнее,
177
+ чем `application`. При равной глубине — более длинный адрес: путь говорит о
178
+ месте больше, чем одно имя.
179
+ """
180
+ matched = [
181
+ (depth, len(address), address, directory)
182
+ for address, directory in among
183
+ if (depth := where.within(directory=address)) is not None
184
+ ]
185
+ if not matched:
186
+ return None
187
+ deepest = max(matched, key=lambda found: found[:2])
188
+ return deepest[2], deepest[3]
189
+
190
+
191
+ @dataclass(frozen=True, slots=True)
192
+ class Claim:
193
+ """Чей это дом и почему объявление в него просится."""
194
+
195
+ address: str
196
+ said: str
197
+
198
+
199
+ def claimants(
200
+ *,
201
+ declared: Declaration,
202
+ layout: dict[str, Directory],
203
+ where: Place,
204
+ ) -> list[Claim]:
205
+ """Адреса, объявившие это объявление своим: по имени или по виду.
206
+
207
+ Блок с `area` притязает только на то, что лежит внутри названной части
208
+ дерева: соглашение про `dto` написано про слой приложения, и dataclass в
209
+ загрузчике ему не подсуден.
210
+ """
211
+ found: list[Claim] = []
212
+ for address, directory in layout.items():
213
+ if directory.area is not None and not where.holds(path=directory.area):
214
+ continue
215
+ said = _claim(
216
+ declared=declared,
217
+ directory=directory,
218
+ )
219
+ if said is not None:
220
+ found.append(
221
+ Claim(
222
+ address=address,
223
+ said=said,
224
+ )
225
+ )
226
+ return found
227
+
228
+
229
+ def _claim(
230
+ *,
231
+ declared: Declaration,
232
+ directory: Directory,
233
+ ) -> str | None:
234
+ """Почему этот адрес считает объявление своим; `None` — не считает."""
235
+ if directory.suffix is not None and declared.name.endswith(directory.suffix):
236
+ return f"кончается на {directory.suffix}"
237
+ if declared.kind is not None and declared.kind in directory.home:
238
+ return f"— {declared.kind.said}"
239
+ return None
@@ -12,6 +12,7 @@ from dataclasses import dataclass
12
12
  from typing import TYPE_CHECKING, Final
13
13
 
14
14
  from py_checks.config import CheckSettings
15
+ from py_checks.core import depth
15
16
 
16
17
  if TYPE_CHECKING:
17
18
  from collections.abc import Iterable
@@ -23,9 +24,6 @@ INIT: Final = "__init__"
23
24
 
24
25
  SEPARATOR: Final = "/"
25
26
 
26
- # Один любой кусок пути: `modules/*/domain` — домен любого модуля.
27
- ANY: Final = "*"
28
-
29
27
  # Пакет и хотя бы один шаг внутри него: файл, лежащий прямо в корне исходников,
30
28
  # ни в каком пакете не находится, и говорить о его месте нечего.
31
29
  INSIDE: Final = 2
@@ -65,9 +63,9 @@ class Place:
65
63
  то же место.
66
64
  """
67
65
  return (
68
- _run(
66
+ depth(
69
67
  parts=self.parts,
70
- wanted=path,
68
+ path=path,
71
69
  )
72
70
  is not None
73
71
  )
@@ -80,9 +78,9 @@ class Place:
80
78
  можно только по тому, где они кончаются, — глубже тот, кто кончается
81
79
  позже.
82
80
  """
83
- return _run(
81
+ return depth(
84
82
  parts=self.parts[:-1],
85
- wanted=directory,
83
+ path=directory,
86
84
  )
87
85
 
88
86
 
@@ -139,34 +137,3 @@ def _relative(
139
137
  except ValueError:
140
138
  return None
141
139
  return inside.with_suffix("").parts
142
-
143
-
144
- def _run(
145
- *,
146
- parts: tuple[str, ...],
147
- wanted: str,
148
- ) -> int | None:
149
- """Конец последнего вхождения подряд идущих кусков пути.
150
-
151
- `*` подходит любому одному куску: `modules/*/domain` — это домен любого
152
- модуля, и перечислять модули по именам не нужно.
153
- """
154
- needle = tuple(wanted.split(SEPARATOR))
155
- span = len(needle)
156
- ends = [
157
- start + span
158
- for start in range(len(parts) - span + 1)
159
- if _same(
160
- found=parts[start : start + span],
161
- needle=needle,
162
- )
163
- ]
164
- return max(ends) if ends else None
165
-
166
-
167
- def _same(
168
- *,
169
- found: tuple[str, ...],
170
- needle: tuple[str, ...],
171
- ) -> bool:
172
- return all(wanted in (ANY, part) for part, wanted in zip(found, needle, strict=True))
@@ -21,7 +21,7 @@ CODE: Final = "confined-functions"
21
21
 
22
22
  class ConfinedFunctionsSettings(CheckSettings):
23
23
  calls: dict[str, tuple[str, ...]] = {} # noqa: RUF012 — pydantic копирует значение сам
24
- home: str | None = None
24
+ declared_in: str | None = None
25
25
 
26
26
 
27
27
  class ConfinedFunctions:
@@ -36,10 +36,10 @@ class ConfinedFunctions:
36
36
  Место — кусок пути, а не файл: край — это место в замысле, и файл, который
37
37
  разделили надвое, краем быть не перестал.
38
38
 
39
- `home` — модуль, где функция объявлена: там она написана, а не позвана, и
39
+ `declared-in` — модуль, где функция объявлена: там она написана, а не позвана, и
40
40
  правило его не трогает.
41
41
 
42
- Настройки: `calls`, `home`.
42
+ Настройки: `calls`, `declared-in`.
43
43
  """
44
44
 
45
45
  code: ClassVar[str] = CODE
@@ -62,7 +62,7 @@ class ConfinedFunctions:
62
62
  where = place(file=file)
63
63
  if where is None or not limits.calls:
64
64
  return
65
- if limits.home is not None and where.holds(path=limits.home):
65
+ if limits.declared_in is not None and where.holds(path=limits.declared_in):
66
66
  return
67
67
  for node in ast.walk(file.tree):
68
68
  if not isinstance(node, ast.Call):
@@ -13,7 +13,7 @@ from py_checks.checks.database._confined_calls import (
13
13
  ConfinedCallsSettings,
14
14
  )
15
15
  from py_checks.checks.database._marker import MARKER
16
- from py_checks.checks.database._model_boundary import ModelBoundary, ModelBoundarySettings
16
+ from py_checks.checks.database._model_boundary import ModelBoundary
17
17
  from py_checks.checks.database._model_columns import ModelColumns, ModelColumnsSettings
18
18
  from py_checks.checks.database._raw_sql import RawSql, RawSqlSettings
19
19
  from py_checks.checks.database._schema_drift import SchemaDrift, SchemaDriftSettings
@@ -27,7 +27,6 @@ __all__ = [
27
27
  "ConfinedCalls",
28
28
  "ConfinedCallsSettings",
29
29
  "ModelBoundary",
30
- "ModelBoundarySettings",
31
30
  "ModelColumns",
32
31
  "ModelColumnsSettings",
33
32
  "RawSql",
@@ -5,15 +5,17 @@ from __future__ import annotations
5
5
  import ast
6
6
  from typing import TYPE_CHECKING, ClassVar, Final
7
7
 
8
+ from pydantic import Field
9
+
8
10
  from py_checks.checks._location import ZonedSettings, zoned
9
11
  from py_checks.checks._names import name
10
12
  from py_checks.checks.database._marker import MARKER
13
+ from py_checks.config import CheckSettings
11
14
  from py_checks.core import Scope, Violation, settings_as
12
15
 
13
16
  if TYPE_CHECKING:
14
17
  from collections.abc import Iterator
15
18
 
16
- from py_checks.config import CheckSettings
17
19
  from py_checks.core import ParsedFile
18
20
 
19
21
  CODE: Final = "bound-checks"
@@ -21,13 +23,24 @@ CODE: Final = "bound-checks"
21
23
  MAPPED: Final = "Mapped"
22
24
 
23
25
 
24
- class BoundChecksSettings(ZonedSettings):
25
- primitives: tuple[str, ...] = ()
26
+ class Helper(CheckSettings):
27
+ """Как зовут хелпер проекта и два его аргумента.
28
+
29
+ Три голых слова в секции не говорили, что они об одном: `call` —
30
+ функция, `column` и `primitive` — её аргументы, и прочитать это можно было
31
+ только из документации. Блок говорит это формой.
32
+ """
33
+
26
34
  call: str = "bound_check"
27
35
  column: str = "column"
28
36
  primitive: str = "primitive"
29
37
 
30
38
 
39
+ class BoundChecksSettings(ZonedSettings):
40
+ primitives: tuple[str, ...] = ()
41
+ helper: Helper = Field(default_factory=Helper)
42
+
43
+
31
44
  class BoundChecks:
32
45
  """Падает, если ограниченная колонка не повторила своё ограничение как CHECK.
33
46
 
@@ -48,7 +61,7 @@ class BoundChecks:
48
61
  этого сервиса деньги — `PositiveDecimal`, а доля — `MarginFraction`. Без
49
62
  списка правило молчит.
50
63
 
51
- Настройки: `zones`, `primitives`, `call`, `column`, `primitive`.
64
+ Настройки: `zones`, `primitives`, `helper`.
52
65
  """
53
66
 
54
67
  code: ClassVar[str] = CODE
@@ -126,14 +139,15 @@ class BoundChecks:
126
139
  said: str | None,
127
140
  limits: BoundChecksSettings,
128
141
  ) -> str:
142
+ helper = limits.helper
129
143
  if said is None:
130
144
  return (
131
145
  f"{field} объявлено как {bounded}, но CHECK не несёт; добавь "
132
- f"{limits.call}({limits.column}={field}, {limits.primitive}={bounded}) "
146
+ f"{helper.call}({helper.column}={field}, {helper.primitive}={bounded}) "
133
147
  f"в __table_args__"
134
148
  )
135
149
  return (
136
- f"{field} объявлено как {bounded}, а его {limits.call} называет {said}; "
150
+ f"{field} объявлено как {bounded}, а его {helper.call} называет {said}; "
137
151
  f"аннотация и CHECK читают одну границу"
138
152
  )
139
153
 
@@ -147,15 +161,15 @@ class BoundChecks:
147
161
  """Колонка — тип, по каждому вызову в теле класса."""
148
162
  found: dict[str, str] = {}
149
163
  for child in ast.walk(node):
150
- if not isinstance(child, ast.Call) or name(node=child.func) != limits.call:
164
+ if not isinstance(child, ast.Call) or name(node=child.func) != limits.helper.call:
151
165
  continue
152
166
  column = cls._argument(
153
167
  node=child,
154
- named=limits.column,
168
+ named=limits.helper.column,
155
169
  )
156
170
  primitive = cls._argument(
157
171
  node=child,
158
- named=limits.primitive,
172
+ named=limits.helper.primitive,
159
173
  )
160
174
  if column is not None and primitive is not None:
161
175
  found[column] = primitive
@@ -25,15 +25,18 @@ class Confined(ZonedSettings):
25
25
  `owner` — имя модуля без расширения. Правило его не касается: там вызов и
26
26
  должен стоять, потому и владелец.
27
27
 
28
- `outside` — куски зоны, где правило молчит. Имя метода — всё, что видно по
28
+ `skip` — куски зоны, где правило молчит. Имя метода — всё, что видно по
29
29
  одному файлу, и край брокера тому пример: `commit()` у консьюмера
30
30
  подтверждает смещение, а не транзакцию базы.
31
+
32
+ `because` — причина в отказе: она объясняет, кто владеет этим вызовом, и
33
+ печатается тому, кто его написал не там.
31
34
  """
32
35
 
33
36
  methods: tuple[str, ...]
34
- outside: tuple[str, ...] = ()
37
+ skip: tuple[str, ...] = ()
35
38
  owner: str | None = None
36
- said: str = "этим владеет другой модуль"
39
+ because: str = "этим владеет другой модуль"
37
40
 
38
41
 
39
42
  class ConfinedCallsSettings(CheckSettings):
@@ -98,7 +101,7 @@ class ConfinedCalls:
98
101
  node=node,
99
102
  path=file.path,
100
103
  code=CODE,
101
- message=f"{ast.unparse(node.func)}: {rule.said}",
104
+ message=f"{ast.unparse(node.func)}: {rule.because}",
102
105
  )
103
106
 
104
107
  @staticmethod
@@ -110,6 +113,6 @@ class ConfinedCalls:
110
113
  ) -> bool:
111
114
  if rule.owner is not None and file.path.stem == rule.owner:
112
115
  return False
113
- if where.anywhere(zones=rule.outside):
116
+ if where.anywhere(zones=rule.skip):
114
117
  return False
115
118
  return where.anywhere(zones=rule.zones)