python-checks 0.5.0__py3-none-any.whl → 0.6.0__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 (116) hide show
  1. py_checks/checks/__init__.py +15 -14
  2. py_checks/checks/_kind.py +34 -32
  3. py_checks/checks/_layout.py +75 -68
  4. py_checks/checks/_location.py +53 -31
  5. py_checks/checks/_names.py +25 -23
  6. py_checks/checks/api/__init__.py +4 -4
  7. py_checks/checks/api/_edge_declarations.py +80 -73
  8. py_checks/checks/api/_marker.py +1 -1
  9. py_checks/checks/calls/__init__.py +3 -3
  10. py_checks/checks/calls/_confined_functions.py +15 -14
  11. py_checks/checks/calls/_marker.py +1 -1
  12. py_checks/checks/database/__init__.py +7 -5
  13. py_checks/checks/database/_bound_checks.py +32 -31
  14. py_checks/checks/database/_confined_calls.py +23 -23
  15. py_checks/checks/database/_marker.py +1 -1
  16. py_checks/checks/database/_model_boundary.py +37 -36
  17. py_checks/checks/database/_model_columns.py +36 -36
  18. py_checks/checks/database/_raw_sql.py +40 -37
  19. py_checks/checks/database/_schema_drift.py +50 -47
  20. py_checks/checks/database/_statement_keys.py +29 -28
  21. py_checks/checks/effects/__init__.py +6 -5
  22. py_checks/checks/effects/_determinism.py +26 -23
  23. py_checks/checks/effects/_log_events.py +18 -18
  24. py_checks/checks/effects/_marker.py +1 -1
  25. py_checks/checks/errors/__init__.py +3 -3
  26. py_checks/checks/errors/_marker.py +1 -1
  27. py_checks/checks/errors/_refusals.py +39 -38
  28. py_checks/checks/hygiene/__init__.py +5 -4
  29. py_checks/checks/hygiene/_dependency_bounds.py +33 -33
  30. py_checks/checks/hygiene/_marker.py +1 -1
  31. py_checks/checks/imports/__init__.py +9 -9
  32. py_checks/checks/imports/_confined.py +15 -14
  33. py_checks/checks/imports/_marker.py +1 -1
  34. py_checks/checks/imports/_sealed.py +17 -28
  35. py_checks/checks/imports/_statements.py +5 -5
  36. py_checks/checks/placement/__init__.py +11 -11
  37. py_checks/checks/placement/_class_modules.py +17 -15
  38. py_checks/checks/placement/_class_placement.py +16 -15
  39. py_checks/checks/placement/_marker.py +1 -1
  40. py_checks/checks/placement/_operation_shape.py +56 -54
  41. py_checks/checks/placement/_required_class.py +28 -28
  42. py_checks/checks/signatures/__init__.py +6 -5
  43. py_checks/checks/signatures/_function_length.py +18 -17
  44. py_checks/checks/signatures/_functions.py +13 -12
  45. py_checks/checks/signatures/_keyword_only.py +23 -21
  46. py_checks/checks/signatures/_marker.py +1 -1
  47. py_checks/checks/signatures/_module_length.py +8 -8
  48. py_checks/checks/signatures/_nesting.py +20 -20
  49. py_checks/checks/signatures/_signature_layout.py +46 -47
  50. py_checks/checks/types/__init__.py +5 -4
  51. py_checks/checks/types/_annotation_shapes.py +20 -20
  52. py_checks/checks/types/_config_fields.py +44 -43
  53. py_checks/checks/types/_confined_types.py +26 -26
  54. py_checks/checks/types/_constant_annotations.py +18 -17
  55. py_checks/checks/types/_frozen_dataclasses.py +14 -13
  56. py_checks/checks/types/_marker.py +1 -1
  57. py_checks/cli/__init__.py +3 -3
  58. py_checks/cli/_app.py +3 -3
  59. py_checks/cli/_protocols.py +6 -5
  60. py_checks/cli/commands/__init__.py +6 -4
  61. py_checks/cli/commands/_doctor.py +81 -67
  62. py_checks/cli/commands/_explain.py +15 -14
  63. py_checks/cli/commands/_list.py +10 -10
  64. py_checks/cli/commands/_mutation.py +247 -0
  65. py_checks/cli/commands/_run.py +25 -26
  66. py_checks/cli/commands/_summary.py +3 -3
  67. py_checks/cli/commands/_sync.py +9 -9
  68. py_checks/config/__init__.py +7 -7
  69. py_checks/config/_base.py +11 -10
  70. py_checks/config/_config.py +33 -30
  71. py_checks/config/_constants.py +7 -7
  72. py_checks/config/_errors.py +5 -5
  73. py_checks/config/_loader.py +22 -21
  74. py_checks/config/_toml.py +5 -4
  75. py_checks/contracts/__init__.py +9 -9
  76. py_checks/contracts/_constants.py +4 -4
  77. py_checks/contracts/_layout.py +7 -6
  78. py_checks/contracts/_render.py +26 -25
  79. py_checks/contracts/_settings.py +11 -11
  80. py_checks/core/__init__.py +4 -4
  81. py_checks/core/_constants.py +7 -6
  82. py_checks/core/_discovery.py +6 -6
  83. py_checks/core/_edit.py +18 -15
  84. py_checks/core/_errors.py +4 -4
  85. py_checks/core/_fixer.py +5 -5
  86. py_checks/core/_format.py +7 -7
  87. py_checks/core/_markers.py +41 -37
  88. py_checks/core/_paths.py +14 -12
  89. py_checks/core/_protocols.py +33 -29
  90. py_checks/core/_registry.py +15 -13
  91. py_checks/core/_report.py +8 -7
  92. py_checks/core/_runner.py +18 -18
  93. py_checks/core/_settings.py +8 -8
  94. py_checks/core/_source.py +14 -13
  95. py_checks/core/_violation.py +15 -13
  96. py_checks/environment/__init__.py +6 -6
  97. py_checks/environment/_constants.py +1 -1
  98. py_checks/environment/_render.py +38 -37
  99. py_checks/environment/_settings.py +11 -10
  100. py_checks/mutation/__init__.py +34 -0
  101. py_checks/mutation/_baseline.py +47 -0
  102. py_checks/mutation/_constants.py +11 -0
  103. py_checks/mutation/_errors.py +12 -0
  104. py_checks/mutation/_gate.py +175 -0
  105. py_checks/mutation/_mutmut.py +162 -0
  106. py_checks/mutation/_process.py +44 -0
  107. py_checks/mutation/_scope.py +155 -0
  108. py_checks/mutation/_settings.py +54 -0
  109. py_checks/sync/__init__.py +9 -9
  110. py_checks/sync/_sync.py +11 -10
  111. {python_checks-0.5.0.dist-info → python_checks-0.6.0.dist-info}/METADATA +4 -1
  112. python_checks-0.6.0.dist-info/RECORD +117 -0
  113. {python_checks-0.5.0.dist-info → python_checks-0.6.0.dist-info}/WHEEL +1 -1
  114. python_checks-0.5.0.dist-info/RECORD +0 -107
  115. {python_checks-0.5.0.dist-info → python_checks-0.6.0.dist-info}/entry_points.txt +0 -0
  116. {python_checks-0.5.0.dist-info → python_checks-0.6.0.dist-info}/licenses/LICENSE +0 -0
@@ -1,20 +1,21 @@
1
- """Реализации правил, по пакету на группу.
1
+ """The rule implementations, one package per group.
2
2
 
3
- Внутри группы — по модулю на проверку. Правила, уехавшие в import-linter,
4
- ruff и alembic, сюда не переносятся; что и куда ушло, записано в
3
+ Inside a group, one module per check. Rules that moved to import-linter, ruff
4
+ and alembic are not carried over here; what went where is written down in
5
5
  `docs/current.md`.
6
6
 
7
- Проверка — это один класс, и всё, чем она разбирает дерево, лежит внутри него:
8
- помощники не расползаются по модулю, и видно, чьи они. Лист берёт
9
- `@staticmethod`, помощник, который зовёт другого помощника, — `@classmethod`,
10
- чтобы звать через `cls`, а не по имени класса.
7
+ A check is one class, and everything it reads the tree with lives inside it:
8
+ helpers do not spread across the module, and it is clear whose they are. A
9
+ leaf takes `@staticmethod`; a helper that calls another helper takes
10
+ `@classmethod`, so it calls through `cls` rather than by the class's name.
11
11
 
12
- Внутри класса живёт то, что правилу и принадлежит. Слово языка правилу не
13
- принадлежит: «как этот узел зовут» — это `_names.py`, «где лежит этот файл» —
14
- `_location.py`, «что тут объявлено» — `_kind.py`. Шесть одинаковых `_name` по
15
- классам — это не шесть помощников, а один, забытый в шести местах.
12
+ Inside the class lives what belongs to the rule. A word of the language does
13
+ not belong to a rule: "what is this node called" is `_names.py`, "where does
14
+ this file lie" is `_location.py`, "what is declared here" is `_kind.py`. Six
15
+ identical `_name` across classes are not six helpers but one, forgotten in six
16
+ places.
16
17
 
17
- Слово, которым правило снимают с кода, объявлено один раз на группу — в
18
- `_marker.py` пакета. Оно снимает любую проверку группы; чтобы снять ровно
19
- одну, есть `# check-ok: <код>: <причина>`.
18
+ The word that lifts a rule from the code is declared once per group, in the
19
+ package's `_marker.py`. It lifts any check of the group; to lift exactly one,
20
+ there is `# check-ok: <code>: <reason>`.
20
21
  """
py_checks/checks/_kind.py CHANGED
@@ -1,8 +1,8 @@
1
- """Что объявлено в модуле: класс, порт, dataclass, алиас.
1
+ """What a module declares: a class, a port, a dataclass, an alias.
2
2
 
3
- Правила размещения говорят о видах объявлений, а не о синтаксисе: «в `dto/`
4
- лежат dataclass-ы», «в `ports/` — протоколы». Вид узнаётся один раз здесь, и
5
- этим же знанием пользуются все правила группы.
3
+ The placement rules speak of kinds of declaration, not of syntax: "`dto/` holds
4
+ dataclasses", "`ports/` holds protocols". The kind is recognised once, here,
5
+ and every rule of the group uses the same knowledge.
6
6
  """
7
7
 
8
8
  from __future__ import annotations
@@ -27,12 +27,12 @@ ENUMS: Final[frozenset[str]] = frozenset(
27
27
 
28
28
  ERROR_BASES: Final[frozenset[str]] = frozenset({"Exception", "BaseException"})
29
29
 
30
- # Исключение проекта наследуется от своего же корня (`class NotFound(DomainError)`),
31
- # а не от `Exception`, — но имя корня кончается так же, и по нему вид узнаётся,
32
- # не читая чужой модуль.
30
+ # A project's exception inherits from its own root (`class NotFound(DomainError)`),
31
+ # not from `Exception` — but the root's name ends the same way, and the kind is
32
+ # recognised by it without reading another module.
33
33
  ERROR_SUFFIXES: Final[tuple[str, ...]] = ("Error", "Exception")
34
34
 
35
- # Присваивание, которым объявляют имя для типа, а не значение.
35
+ # An assignment that declares a name for a type, not a value.
36
36
  ALIAS_ANNOTATION: Final = "TypeAlias"
37
37
  ALIAS_FACTORIES: Final[frozenset[str]] = frozenset(
38
38
  {"TypeVar", "NewType", "ParamSpec", "TypeAliasType"},
@@ -54,7 +54,7 @@ ALIAS_CONSTRUCTORS: Final[frozenset[str]] = frozenset(
54
54
 
55
55
 
56
56
  class Kind(StrEnum):
57
- """Виды объявлений, о которых говорят правила размещения."""
57
+ """The kinds of declaration the placement rules speak of."""
58
58
 
59
59
  CLASS = "class"
60
60
  PORT = "port"
@@ -67,29 +67,29 @@ class Kind(StrEnum):
67
67
 
68
68
  @property
69
69
  def said(self) -> str:
70
- """Как вид называется в сообщении: `str.title` занят самим `str`."""
70
+ """What the kind is called in a message: `str.title` is taken by `str` itself."""
71
71
  return NAMES[self]
72
72
 
73
73
 
74
74
  NAMES: Final[dict[Kind, str]] = {
75
- Kind.CLASS: "класс",
76
- Kind.PORT: "порт",
75
+ Kind.CLASS: "class",
76
+ Kind.PORT: "port",
77
77
  Kind.DATACLASS: "dataclass",
78
- Kind.MODEL: "модель",
79
- Kind.ALIAS: "алиас",
80
- Kind.ENUM: "перечисление",
81
- Kind.ERROR: "исключение",
82
- Kind.FUNCTION: "функция",
78
+ Kind.MODEL: "model",
79
+ Kind.ALIAS: "alias",
80
+ Kind.ENUM: "enum",
81
+ Kind.ERROR: "exception",
82
+ Kind.FUNCTION: "function",
83
83
  }
84
84
 
85
85
 
86
86
  @dataclass(frozen=True, slots=True)
87
87
  class Declaration:
88
- """Объявление верхнего уровня: имя, вид и узел.
88
+ """A top-level declaration: the name, the kind and the node.
89
89
 
90
- `kind` пуст, когда вид по одному файлу не виден: класс с базой из другого
91
- модуля. Имя у такого всё равно есть, и правило, которое смотрит на суффикс,
92
- им пользуется.
90
+ `kind` is empty when one file does not show the kind: a class with a base
91
+ from another module. Such a class still has a name, and a rule that looks at
92
+ the suffix uses it.
93
93
  """
94
94
 
95
95
  name: str
@@ -98,10 +98,11 @@ class Declaration:
98
98
 
99
99
 
100
100
  def declarations(*, tree: ast.Module) -> Iterator[Declaration]:
101
- """Всё, что модуль объявляет.
101
+ """Everything a module declares.
102
102
 
103
- Импорты, константы, блоки `if TYPE_CHECKING` и докстринг сюда не попадают:
104
- они разрешены везде, и правилам размещения о них говорить нечего.
103
+ Imports, constants, `if TYPE_CHECKING` blocks and the docstring are left
104
+ out: they are allowed everywhere, and the placement rules have nothing to
105
+ say about them.
105
106
  """
106
107
  for node in tree.body:
107
108
  match node:
@@ -129,12 +130,12 @@ def declarations(*, tree: ast.Module) -> Iterator[Declaration]:
129
130
 
130
131
 
131
132
  def _class(*, node: ast.ClassDef) -> Kind | None:
132
- """Вид класса; `None`, если по одному файлу его не видно.
133
+ """The class's kind; `None` if one file does not show it.
133
134
 
134
- База, объявленная в другом модуле, — это вид, которого отсюда не видно:
135
- `class CodeMismatchResponse(ErrorResponse)` — pydantic-модель, но узнать
136
- это можно только прочитав тот модуль. Про такой класс правило молчит:
137
- заблудившийся хелпер, ради которого оно написано, базы обычно не имеет.
135
+ A base declared in another module is a kind that cannot be seen from here:
136
+ `class CodeMismatchResponse(ErrorResponse)` is a pydantic model, but that
137
+ can only be learned by reading that module. The rule is silent about such
138
+ a class: the stray helper it was written for usually has no base.
138
139
  """
139
140
  bases = frozenset(names(nodes=node.bases))
140
141
  if bases & ABSTRACT or _metaclass(node=node):
@@ -164,10 +165,11 @@ def _metaclass(*, node: ast.ClassDef) -> bool:
164
165
 
165
166
 
166
167
  def _alias(*, node: ast.AnnAssign | ast.Assign) -> bool:
167
- """Присваивание, объявляющее имя для типа.
168
+ """An assignment that declares a name for a type.
168
169
 
169
- Три вида: с аннотацией `TypeAlias`, вызов фабрики вроде `NewType`, и голое
170
- `Row = dict[str, int]` — имя для формы, а не значение.
170
+ Three kinds: annotated with `TypeAlias`, a call of a factory such as
171
+ `NewType`, and a bare `Row = dict[str, int]` — a name for a shape, not a
172
+ value.
171
173
  """
172
174
  if isinstance(node, ast.AnnAssign) and name(node=node.annotation) == ALIAS_ANNOTATION:
173
175
  return True
@@ -1,13 +1,14 @@
1
- """Раскладка проекта: один блок на директорию.
1
+ """The project's layout: one block per directory.
2
2
 
3
- Четыре правила говорят об одной и той же вещи с четырёх сторон: что здесь
4
- может лежать (`class-modules`), что живёт только здесь (`class-placement`),
5
- что модуль обязан объявить (`required-class`) и какой формы тут операция
6
- (`operation-shape`). Раньше у каждого была своя таблица, и один факт про
7
- `use_cases` приходилось писать четыре раза в четырёх синтаксисах, склеивая их
8
- глазами по строковому ключу.
3
+ Four rules speak of the same thing from four sides: what may lie here
4
+ (`class-modules`), what lives only here (`class-placement`), what a module must
5
+ declare (`required-class`) and what shape an operation has here
6
+ (`operation-shape`). Each used to have a table of its own, and one fact about
7
+ `use_cases` had to be written four times in four syntaxes, stitched together
8
+ by eye on a string key.
9
9
 
10
- Теперь блок один на директорию, а правила читают из него свои колонки:
10
+ Now there is one block per directory, and the rules read their own columns
11
+ from it:
11
12
 
12
13
  ```toml
13
14
  [layout."application/use_cases"]
@@ -17,10 +18,10 @@ required = true
17
18
  operation = { method = "execute", max-arguments = 3 }
18
19
  ```
19
20
 
20
- Правила при этом друг о друге по-прежнему не знают — они просто читают одну
21
- таблицу. Адрес в заголовке ищется подряд идущими кусками пути, поэтому
22
- `application/use_cases` находится и в модульном сервисе, где путь начинается
23
- с `modules/<имя>/`, а `*` подходит любому одному куску.
21
+ The rules still know nothing of each other — they simply read one table. The
22
+ address in the heading is looked for as consecutive path parts, so
23
+ `application/use_cases` is found in a modular service too, where the path
24
+ starts with `modules/<name>/`, and `*` matches any one part.
24
25
  """
25
26
 
26
27
  from __future__ import annotations
@@ -44,36 +45,37 @@ SECTION: Final = "layout"
44
45
 
45
46
 
46
47
  class Orm(StrEnum):
47
- """Чем директория приходится ORM-модели.
48
+ """What a directory is to an ORM model.
48
49
 
49
- Дом модели и место, где её собирают, — два конца одного соглашения, и
50
- писать их в отдельной таблице значило бы назвать те же две директории
51
- второй раз: раскладка уже знает их по имени.
50
+ The model's home and the place where it is built are two ends of one
51
+ convention, and writing them in a separate table would name the same two
52
+ directories a second time: the layout already knows them by name.
52
53
  """
53
54
 
54
- # Здесь модели объявляют: где-то ещё это таблица, которую никто не ждёт по
55
- # этому адресу, а autogenerate alembic видит только их пакет.
55
+ # Models are declared here: anywhere else it is a table nobody expects at
56
+ # that address, and alembic's autogenerate sees only their package.
56
57
  DECLARED = "declared"
57
58
 
58
- # Здесь модели собирают: собрать модель — значит записать строку.
59
+ # Models are built here: building a model means writing a row.
59
60
  BUILT = "built"
60
61
 
61
62
 
62
63
  class Operation(CheckSettings):
63
- """Форма операции, которую держат в этой директории.
64
+ """The shape of an operation kept in this directory.
64
65
 
65
- `method` — единственная публичная дверь: сценарий просят об одном деле, и
66
- второй публичный метод означает вторую операцию, поделившую с первой
67
- конструктор. Пусто — значит число дверей не ограничено: у сервиса модуля
68
- их столько, сколько переходов у его сущности.
66
+ `method` is the only public door: a use case is asked for one thing, and a
67
+ second public method means a second operation sharing a constructor with
68
+ the first. Empty means the number of doors is not limited: a module's
69
+ service has as many as its entity has transitions.
69
70
 
70
- `forbids` — имена типов, которых операция не держит: `UnitOfWork` ловится
71
- и как `IPlacementUnitOfWork`, и как `UnitOfWorkFactory`, потому что
72
- запрещено держать транзакцию, а не писать её имя одним конкретным образом.
71
+ `forbids` is the names of types an operation does not hold: `UnitOfWork` is
72
+ caught both as `IPlacementUnitOfWork` and as `UnitOfWorkFactory`, because
73
+ what is forbidden is holding the transaction, not spelling its name one
74
+ particular way.
73
75
 
74
- `max_arguments` — сколько аргументов занимает вход. Дверь несёт то, что
75
- пришло снаружи, и вход длиннее нескольких полей — вещь с именем: команда,
76
- запрос, DTO.
76
+ `max_arguments` is how many arguments the entrance takes. A door carries
77
+ what came from outside, and an entrance longer than a few fields is a thing
78
+ with a name: a command, a query, a DTO.
77
79
  """
78
80
 
79
81
  method: str | None = None
@@ -85,20 +87,21 @@ class Operation(CheckSettings):
85
87
 
86
88
 
87
89
  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` — базовый класс, по которому модель узнают в доме моделей.
90
+ """What the project keeps in this directory.
91
+
92
+ `only` — the kinds that belong here, and nothing else sits beside them.
93
+ `home` — the kinds that belong ONLY here: a port declared at the other end
94
+ of the tree is a port the reader will not find.
95
+ `area` — the part of the tree within which home and name mean anything at
96
+ all: the rule about `dto` is written about the application layer, and a
97
+ dataclass in the bootstrap or in observability is just a way to put three
98
+ fields side by side.
99
+ `suffix` — what the class this directory exists for is called; it too
100
+ lives only here.
101
+ `required` — a module must declare such a class, first and alone.
102
+ `operation` — the shape of an operation, if operations are kept here.
103
+ `orm` — what the directory is to an ORM model: its home or where it is built.
104
+ `base` — the base class by which a model is recognised in the models' home.
102
105
  """
103
106
 
104
107
  only: tuple[Kind, ...] = ()
@@ -112,44 +115,46 @@ class Directory(CheckSettings):
112
115
 
113
116
  @model_validator(mode="after")
114
117
  def _named(self) -> Self:
115
- """Обязанность и форма опираются на имя: без суффикса их не проверить."""
118
+ """Obligation and shape rest on the name: without a suffix there is no checking them."""
116
119
  if self.suffix is not None:
117
120
  return self
118
121
  if self.required:
119
- message = "`required` без `suffix`: непонятно, какой класс обязан быть"
122
+ message = "`required` without `suffix`: it is unclear which class must be there"
120
123
  raise ValueError(message)
121
124
  if self.operation is not None:
122
- message = "`operation` без `suffix`: непонятно, какой класс здесь операция"
125
+ message = (
126
+ "`operation` without `suffix`: it is unclear which class is the operation here"
127
+ )
123
128
  raise ValueError(message)
124
129
  return self
125
130
 
126
131
  @model_validator(mode="after")
127
132
  def _claims(self) -> Self:
128
- """Область сужает притязание: без дома и имени сужать нечего."""
133
+ """An area narrows a claim: without a home and a name there is nothing to narrow."""
129
134
  if self.area is not None and not self.home and self.suffix is None:
130
- message = "`area` без `home` и `suffix`: эта директория ни на что не притязает"
135
+ message = "`area` without `home` and `suffix`: this directory claims nothing"
131
136
  raise ValueError(message)
132
137
  return self
133
138
 
134
139
  @model_validator(mode="after")
135
140
  def _declares(self) -> Self:
136
- """`base` — про дом моделей: в месте сборки узнавать по базе нечего."""
141
+ """`base` is about the models' home: where they are built, there is nothing to spot."""
137
142
  if self.base is not None and self.orm is not Orm.DECLARED:
138
- message = '`base` без `orm = "declared"`: базу называет дом моделей'
143
+ message = '`base` without `orm = "declared"`: the base is named by the models\' home'
139
144
  raise ValueError(message)
140
145
  return self
141
146
 
142
147
 
143
148
  class Layout(CheckSettings):
144
- """Секция `[layout]`: адрес директории — и блок про неё.
149
+ """The `[layout]` section: a directory's address — and a block about it.
145
150
 
146
- Ключи приходят из проекта, поэтому модель принимает любые: имена
147
- директорий — это данные, а не поля. Проверяется содержимое блока.
151
+ The keys come from the project, so the model accepts any: directory names
152
+ are data, not fields. What is checked is the content of the block.
148
153
  """
149
154
 
150
155
  model_config = CheckSettings.model_config | {"extra": "allow"}
151
156
 
152
- # Типизированный `extra` pydantic: ключ — адрес, значение — блок.
157
+ # pydantic's typed `extra`: the key is an address, the value a block.
153
158
  __pydantic_extra__: dict[str, Directory] # type: ignore[assignment]
154
159
 
155
160
  @property
@@ -162,7 +167,7 @@ def addressed(
162
167
  layout: dict[str, Directory],
163
168
  orm: Orm,
164
169
  ) -> tuple[str, ...]:
165
- """Адреса, объявившие себя этим концом соглашения про ORM-модель."""
170
+ """The addresses that declared themselves this end of the ORM model convention."""
166
171
  return tuple(address for address, directory in layout.items() if directory.orm is orm)
167
172
 
168
173
 
@@ -171,11 +176,11 @@ def innermost(
171
176
  where: Place,
172
177
  among: Iterable[tuple[str, Directory]],
173
178
  ) -> tuple[str, Directory] | None:
174
- """Блок самой внутренней из совпавших директорий.
179
+ """The block of the innermost matched directory.
175
180
 
176
- Побеждает самая глубокая: `modules/betslip/application/services` важнее,
177
- чем `application`. При равной глубине — более длинный адрес: путь говорит о
178
- месте больше, чем одно имя.
181
+ The deepest wins: `modules/betslip/application/services` beats
182
+ `application`. At equal depth, the longer address: a path says more about a
183
+ place than one name.
179
184
  """
180
185
  matched = [
181
186
  (depth, len(address), address, directory)
@@ -190,7 +195,7 @@ def innermost(
190
195
 
191
196
  @dataclass(frozen=True, slots=True)
192
197
  class Claim:
193
- """Чей это дом и почему объявление в него просится."""
198
+ """Whose home this is and why the declaration asks to be in it."""
194
199
 
195
200
  address: str
196
201
  said: str
@@ -202,11 +207,11 @@ def claimants(
202
207
  layout: dict[str, Directory],
203
208
  where: Place,
204
209
  ) -> list[Claim]:
205
- """Адреса, объявившие это объявление своим: по имени или по виду.
210
+ """The addresses that claim this declaration: by name or by kind.
206
211
 
207
- Блок с `area` притязает только на то, что лежит внутри названной части
208
- дерева: соглашение про `dto` написано про слой приложения, и dataclass в
209
- загрузчике ему не подсуден.
212
+ A block with `area` claims only what lies inside the named part of the
213
+ tree: the convention about `dto` is written about the application layer,
214
+ and a dataclass in the bootstrap is not its to judge.
210
215
  """
211
216
  found: list[Claim] = []
212
217
  for address, directory in layout.items():
@@ -231,9 +236,11 @@ def _claim(
231
236
  declared: Declaration,
232
237
  directory: Directory,
233
238
  ) -> str | None:
234
- """Почему этот адрес считает объявление своим; `None` — не считает."""
239
+ """Why this address claims the declaration; `None` — it does not."""
235
240
  if directory.suffix is not None and declared.name.endswith(directory.suffix):
236
- return f"кончается на {directory.suffix}"
241
+ return f"ends with {directory.suffix}"
237
242
  if declared.kind is not None and declared.kind in directory.home:
238
- return f"— {declared.kind.said}"
243
+ said = declared.kind.said
244
+ # Every kind's name is a plain English noun, so the first letter decides.
245
+ return f"is {'an' if said[0] in 'aeiou' else 'a'} {said}"
239
246
  return None
@@ -1,9 +1,10 @@
1
- """Где файл лежит внутри своего пакета.
1
+ """Where a file lies inside its package.
2
2
 
3
- Правило про импорты говорит о месте: «sqlalchemy живёт в `infra/database`».
4
- Место считается от корня исходников, который известен ядру из настроек.
5
- Угадывать его по `__init__.py` нельзя: папка без него встречается и посреди
6
- пакета — в одном из сервисов так лежит половина репозиториев.
3
+ A rule about imports speaks of a place: "sqlalchemy lives in `infra/database`".
4
+ The place is counted from the source root, which the core knows from the
5
+ settings. It cannot be guessed from `__init__.py`: a directory without one
6
+ turns up in the middle of a package too — in one of the services half the
7
+ repositories lie that way.
7
8
  """
8
9
 
9
10
  from __future__ import annotations
@@ -12,7 +13,7 @@ from dataclasses import dataclass
12
13
  from typing import TYPE_CHECKING, Final
13
14
 
14
15
  from py_checks.config import CheckSettings
15
- from py_checks.core import depth
16
+ from py_checks.core import ANY, depth
16
17
 
17
18
  if TYPE_CHECKING:
18
19
  from collections.abc import Iterable
@@ -24,43 +25,63 @@ INIT: Final = "__init__"
24
25
 
25
26
  SEPARATOR: Final = "/"
26
27
 
27
- # Пакет и хотя бы один шаг внутри него: файл, лежащий прямо в корне исходников,
28
- # ни в каком пакете не находится, и говорить о его месте нечего.
28
+ # A package and at least one step inside it: a file lying right in the source
29
+ # root is in no package, and there is nothing to say about its place.
29
30
  INSIDE: Final = 2
30
31
 
31
32
 
32
33
  @dataclass(frozen=True, slots=True)
33
34
  class Place:
34
- """Корневой пакет файла и его адрес внутри этого пакета."""
35
+ """A file's root package, its address inside it and the directories it lies in.
36
+
37
+ The directories are kept apart from the address because a zone is a
38
+ directory: `domain` means `domain/` and what is under it, not a module
39
+ that happens to be called `domain.py` in `application/exceptions/`. The
40
+ file's own name answers only to `*`: `domain/*` still takes
41
+ `domain/exceptions.py`, since `*` is any piece and a module is one.
42
+ """
35
43
 
36
44
  package: str
37
45
  parts: tuple[str, ...]
46
+ directories: tuple[str, ...]
38
47
 
39
48
  @property
40
49
  def where(self) -> str:
41
50
  return "/".join(self.parts)
42
51
 
43
52
  def under(self, *, prefix: str) -> bool:
44
- """Лежит ли файл под этим путём; пустой путь не разрешает ничего."""
53
+ """Whether the file lies under this path; an empty path allows nothing."""
45
54
  if not prefix:
46
55
  return False
47
56
  wanted = tuple(prefix.split(SEPARATOR))
48
57
  return self.parts[: len(wanted)] == wanted
49
58
 
50
- def anywhere(self, *, zones: Iterable[str]) -> bool:
51
- """Лежит ли файл хоть в одной из этих зон.
59
+ def inside(self, *, zones: Iterable[str]) -> bool:
60
+ """Whether the file lies in at least one of these zones.
52
61
 
53
- Зоны складываются, а не спорят: правило работает там, где его о том
54
- попросили, и молчит везде остальном.
62
+ Only directories count; the file's own name matches `*` and nothing
63
+ else. Zones add up rather than argue: a rule works where it was asked
64
+ to, and is silent everywhere else.
55
65
  """
66
+ return any(
67
+ depth(
68
+ parts=self.parts if zone.split(SEPARATOR)[-1] == ANY else self.directories,
69
+ path=zone,
70
+ )
71
+ is not None
72
+ for zone in zones
73
+ )
74
+
75
+ def anywhere(self, *, zones: Iterable[str]) -> bool:
76
+ """Whether the file is at one of these addresses, a directory or a module."""
56
77
  return any(self.holds(path=zone) for zone in zones)
57
78
 
58
79
  def holds(self, *, path: str) -> bool:
59
- """Идут ли эти куски адреса подряд где угодно внутри него.
80
+ """Whether these address parts run in a row anywhere inside it.
60
81
 
61
- Адрес включает имя модуля, поэтому `exceptions` подходит и как
62
- директория, и как файл `exceptions.py`: для словаря отказов это одно и
63
- то же место.
82
+ The address includes the module's name, so `exceptions` matches both as
83
+ a directory and as the file `exceptions.py`: to the refusal vocabulary
84
+ it is one and the same place.
64
85
  """
65
86
  return (
66
87
  depth(
@@ -71,12 +92,12 @@ class Place:
71
92
  )
72
93
 
73
94
  def within(self, *, directory: str) -> int | None:
74
- """Где кончается самое глубокое вхождение этих директорий, или `None`.
95
+ """Where the deepest occurrence of these directories ends, or `None`.
75
96
 
76
- Имя файла в счёт не идёт: речь о директории, а не о модуле. Конец, а не
77
- начало, потому что сравнивать вложенность двух ключей разной длины
78
- можно только по тому, где они кончаются, — глубже тот, кто кончается
79
- позже.
97
+ The file's name does not count: this is about a directory, not a
98
+ module. The end rather than the start, because the nesting of two keys
99
+ of different length can only be compared by where they end — the one
100
+ that ends later is deeper.
80
101
  """
81
102
  return depth(
82
103
  parts=self.parts[:-1],
@@ -85,12 +106,12 @@ class Place:
85
106
 
86
107
 
87
108
  class ZonedSettings(CheckSettings):
88
- """Настройки правила, которое работает не везде.
109
+ """The settings of a rule that does not work everywhere.
89
110
 
90
- `zones` — места, где правило судит; пустой список означает, что правило
91
- молчит. Молчит, а не судит всюду: соглашение про репозитории неверно для
92
- сценариев, и правило, которому забыли назвать зону, лучше не скажет ничего,
93
- чем скажет неправду по всему дереву.
111
+ `zones` are the places where the rule judges; an empty list means the rule
112
+ is silent. Silent, not judging everywhere: a convention about repositories
113
+ is wrong for use cases, and a rule whose zone was forgotten had better say
114
+ nothing than say something untrue across the whole tree.
94
115
  """
95
116
 
96
117
  zones: tuple[str, ...] = ()
@@ -101,15 +122,15 @@ def zoned(
101
122
  file: ParsedFile,
102
123
  zones: Iterable[str],
103
124
  ) -> Place | None:
104
- """Адрес файла, если он в одной из зон; иначе `None` — правилу тут нечего сказать."""
125
+ """The file's address if it is in one of the zones; otherwise `None`: nothing to say."""
105
126
  where = place(file=file)
106
- if where is None or not where.anywhere(zones=zones):
127
+ if where is None or not where.inside(zones=zones):
107
128
  return None
108
129
  return where
109
130
 
110
131
 
111
132
  def place(*, file: ParsedFile) -> Place | None:
112
- """Адрес файла; `None`, если корень исходников неизвестен или файл вне его."""
133
+ """The file's address; `None` if the source root is unknown or the file is outside it."""
113
134
  if file.source is None:
114
135
  return None
115
136
  relative = _relative(
@@ -124,6 +145,7 @@ def place(*, file: ParsedFile) -> Place | None:
124
145
  return Place(
125
146
  package=relative[0],
126
147
  parts=parts,
148
+ directories=relative[1:-1],
127
149
  )
128
150
 
129
151