python-checks 0.6.0__py3-none-any.whl → 0.8.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.
@@ -76,6 +76,11 @@ class Operation(CheckSettings):
76
76
  `max_arguments` is how many arguments the entrance takes. A door carries
77
77
  what came from outside, and an entrance longer than a few fields is a thing
78
78
  with a name: a command, a query, a DTO.
79
+
80
+ `takes` is the suffix of what the entrance takes: `Query` in
81
+ `use_cases/queries` means every argument of the door is a `...Query`. The
82
+ split into commands and queries holds only while each side is handed its
83
+ own kind of input.
79
84
  """
80
85
 
81
86
  method: str | None = None
@@ -84,12 +89,15 @@ class Operation(CheckSettings):
84
89
  default=None,
85
90
  gt=0,
86
91
  )
92
+ takes: str | None = None
87
93
 
88
94
 
89
95
  class Directory(CheckSettings):
90
96
  """What the project keeps in this directory.
91
97
 
92
98
  `only` — the kinds that belong here, and nothing else sits beside them.
99
+ Written out empty, `only = []`, it means constants and nothing else;
100
+ left unset, it restricts nothing.
93
101
  `home` — the kinds that belong ONLY here: a port declared at the other end
94
102
  of the tree is a port the reader will not find.
95
103
  `area` — the part of the tree within which home and name mean anything at
@@ -99,6 +107,10 @@ class Directory(CheckSettings):
99
107
  `suffix` — what the class this directory exists for is called; it too
100
108
  lives only here.
101
109
  `required` — a module must declare such a class, first and alone.
110
+ `named` — every class of the `only` kinds here ends with `suffix`, as many
111
+ per module as the idea needs: `domain/value_objects` keeps `PriceValue`
112
+ and `CurrencyValue` side by side, and a bare `Price` beside them is the
113
+ one the reader will not recognise.
102
114
  `operation` — the shape of an operation, if operations are kept here.
103
115
  `orm` — what the directory is to an ORM model: its home or where it is built.
104
116
  `base` — the base class by which a model is recognised in the models' home.
@@ -109,10 +121,16 @@ class Directory(CheckSettings):
109
121
  area: str | None = None
110
122
  suffix: str | None = None
111
123
  required: bool = False
124
+ named: bool = False
112
125
  operation: Operation | None = None
113
126
  orm: Orm | None = None
114
127
  base: str | None = None
115
128
 
129
+ @property
130
+ def restricted(self) -> bool:
131
+ """Whether `only` was written: an empty list written out allows constants alone."""
132
+ return bool(self.only) or "only" in self.model_fields_set
133
+
116
134
  @model_validator(mode="after")
117
135
  def _named(self) -> Self:
118
136
  """Obligation and shape rest on the name: without a suffix there is no checking them."""
@@ -121,6 +139,9 @@ class Directory(CheckSettings):
121
139
  if self.required:
122
140
  message = "`required` without `suffix`: it is unclear which class must be there"
123
141
  raise ValueError(message)
142
+ if self.named:
143
+ message = "`named` without `suffix`: it is unclear what the classes are called"
144
+ raise ValueError(message)
124
145
  if self.operation is not None:
125
146
  message = (
126
147
  "`operation` without `suffix`: it is unclear which class is the operation here"
@@ -185,7 +206,7 @@ def innermost(
185
206
  matched = [
186
207
  (depth, len(address), address, directory)
187
208
  for address, directory in among
188
- if (depth := where.within(directory=address)) is not None
209
+ if (depth := where.reach(address=address)) is not None
189
210
  ]
190
211
  if not matched:
191
212
  return None
@@ -25,6 +25,9 @@ INIT: Final = "__init__"
25
25
 
26
26
  SEPARATOR: Final = "/"
27
27
 
28
+ # A layout address that ends like this names a module rather than a directory.
29
+ MODULE: Final = ".py"
30
+
28
31
  # A package and at least one step inside it: a file lying right in the source
29
32
  # root is in no package, and there is nothing to say about its place.
30
33
  INSIDE: Final = 2
@@ -91,6 +94,23 @@ class Place:
91
94
  is not None
92
95
  )
93
96
 
97
+ def reach(self, *, address: str) -> int | None:
98
+ """How deep a layout address reaches into this file, or `None`.
99
+
100
+ A directory address is matched by `within`. An address ending in `.py`
101
+ names a module: its pieces end at this very file, wherever the path
102
+ before them lies, and a package's `__init__.py` is not that module.
103
+ """
104
+ if not address.endswith(MODULE):
105
+ return self.within(directory=address)
106
+ if self.directories == self.parts:
107
+ return None
108
+ end = depth(
109
+ parts=self.parts,
110
+ path=address.removesuffix(MODULE),
111
+ )
112
+ return end if end == len(self.parts) else None
113
+
94
114
  def within(self, *, directory: str) -> int | None:
95
115
  """Where the deepest occurrence of these directories ends, or `None`.
96
116
 
@@ -47,14 +47,14 @@ class Shape:
47
47
  # spelling.
48
48
  methods: tuple[str, ...]
49
49
 
50
- # Only as a decorator. For a route this is a must: its `methods` are `get`,
51
- # `post`, `delete`, the same names an HTTP client goes by, and a rule
52
- # reading every `.post(...)` would find a route in the first adapter that
53
- # talks to a neighbouring service. A subscription cannot be mistaken for
54
- # anything like that, and it is written both as a decorator and as a call:
55
- # it is kept in a variable and applied to the handler separately, because
56
- # its client is taken before the start.
57
- decorated: bool
50
+ # Recognised only as a decorator. For a route this is a must: its `methods`
51
+ # are `get`, `post`, `delete`, the same names an HTTP client goes by, and a
52
+ # rule reading every `.post(...)` would find a route in the first adapter
53
+ # that talks to a neighbouring service. A subscription cannot be mistaken
54
+ # for anything like that, so `False` takes it in both forms: as a decorator,
55
+ # `@router.subscriber(...)`, and as a call kept in a variable and applied to
56
+ # the handler separately, because its client is taken before the start.
57
+ decorator_only: bool
58
58
 
59
59
  # The word a message uses for the first argument.
60
60
  subject: str
@@ -73,7 +73,7 @@ class Shape:
73
73
  KNOWN: Final[dict[str, Shape]] = {
74
74
  Framework.FASTAPI: Shape(
75
75
  methods=("get", "post", "put", "patch", "delete", "head", "options", "trace"),
76
- decorated=True,
76
+ decorator_only=True,
77
77
  subject="path",
78
78
  named="path",
79
79
  body="response_model",
@@ -86,7 +86,7 @@ KNOWN: Final[dict[str, Shape]] = {
86
86
  ),
87
87
  Framework.FASTSTREAM: Shape(
88
88
  methods=("subscriber",),
89
- decorated=False,
89
+ decorator_only=False,
90
90
  subject="topic",
91
91
  named=None,
92
92
  ),
@@ -167,6 +167,13 @@ class EdgeDeclarations:
167
167
  An entrance taken out of the schema (`include_in_schema=False`) the rule
168
168
  leaves alone: the schema is what it protects, and such a route is not in it.
169
169
 
170
+ A keyword decided once for a whole router or broker counts for every
171
+ entrance on it: `router = KafkaRouter(parser=...)` declares the parser of
172
+ each `router.subscriber(...)`. Only when the object is built in the same
173
+ module, by a call the file shows; built elsewhere, it has nothing to read,
174
+ and the entrance answers for itself. A name assigned twice counts only
175
+ what both constructors passed.
176
+
170
177
  Settings: one block per framework, with `required` in it.
171
178
  """
172
179
 
@@ -188,6 +195,7 @@ class EdgeDeclarations:
188
195
  code=CODE,
189
196
  ).frameworks
190
197
  decorators = cls._decorators(tree=file.tree)
198
+ built = cls._built(tree=file.tree)
191
199
  for node in ast.walk(file.tree):
192
200
  if not isinstance(node, ast.Call):
193
201
  continue
@@ -198,13 +206,17 @@ class EdgeDeclarations:
198
206
  if found is None:
199
207
  continue
200
208
  shape, edge = found
201
- if shape.decorated and node not in decorators:
209
+ if shape.decorator_only and node not in decorators:
202
210
  continue
203
211
  yield from cls._judged(
204
212
  call=node,
205
213
  file=file,
206
214
  shape=shape,
207
215
  edge=edge,
216
+ inherited=cls._inherited(
217
+ call=node,
218
+ built=built,
219
+ ),
208
220
  )
209
221
 
210
222
  @staticmethod
@@ -218,6 +230,39 @@ class EdgeDeclarations:
218
230
  if isinstance(decorator, ast.Call)
219
231
  }
220
232
 
233
+ @staticmethod
234
+ def _built(*, tree: ast.Module) -> dict[str, frozenset[str]]:
235
+ """The keywords each name was built with in this module: `router = KafkaRouter(...)`.
236
+
237
+ A name assigned more than once keeps only what every constructor
238
+ passed: which of them the entrance hangs on, the file does not say.
239
+ """
240
+ found: dict[str, frozenset[str]] = {}
241
+ for node in ast.walk(tree):
242
+ match node:
243
+ case (
244
+ ast.Assign(targets=[ast.Name(id=name)], value=ast.Call() as call)
245
+ | ast.AnnAssign(target=ast.Name(id=name), value=ast.Call() as call)
246
+ ):
247
+ passed = frozenset(keyword.arg for keyword in call.keywords if keyword.arg)
248
+ found[name] = found[name] & passed if name in found else passed
249
+ case _:
250
+ continue
251
+ return found
252
+
253
+ @staticmethod
254
+ def _inherited(
255
+ *,
256
+ call: ast.Call,
257
+ built: dict[str, frozenset[str]],
258
+ ) -> frozenset[str]:
259
+ """What the router or broker the entrance hangs on already declared."""
260
+ match call.func:
261
+ case ast.Attribute(value=ast.Name(id=name)):
262
+ return built.get(name, frozenset())
263
+ case _:
264
+ return frozenset()
265
+
221
266
  @staticmethod
222
267
  def _matched(
223
268
  *,
@@ -241,6 +286,7 @@ class EdgeDeclarations:
241
286
  file: ParsedFile,
242
287
  shape: Shape,
243
288
  edge: Edge,
289
+ inherited: frozenset[str],
244
290
  ) -> Iterator[Violation]:
245
291
  if cls._unpublished(
246
292
  call=call,
@@ -251,7 +297,7 @@ class EdgeDeclarations:
251
297
  call=call,
252
298
  shape=shape,
253
299
  )
254
- declared = {keyword.arg for keyword in call.keywords}
300
+ declared = {keyword.arg for keyword in call.keywords} | inherited
255
301
  yield from cls._first(
256
302
  call=call,
257
303
  file=file,
@@ -37,6 +37,10 @@ class ClassModules:
37
37
  two different animals. A directory the layout says nothing about is not
38
38
  the rule's business.
39
39
 
40
+ A block may address one module rather than a directory:
41
+ `[layout."domain/constraints.py"]`. Written with `only = []`, it says the
42
+ module holds constants and nothing else — no function, class or alias.
43
+
40
44
  Settings: `only` in the shared `[layout]` table.
41
45
  """
42
46
 
@@ -63,21 +67,27 @@ class ClassModules:
63
67
  return
64
68
  found = innermost(
65
69
  where=where,
66
- among=[(address, directory) for address, directory in layout.items() if directory.only],
70
+ among=[
71
+ (address, directory)
72
+ for address, directory in layout.items()
73
+ if directory.restricted
74
+ ],
67
75
  )
68
76
  if found is None:
69
77
  return
70
78
  address, directory = found
79
+ allowed = ", ".join(sorted(one.said for one in directory.only)) or "constants"
71
80
  for declared in declarations(tree=file.tree):
72
- # No kind to see, nothing to judge: a class with a base from another module.
73
- if declared.kind is None or declared.kind in directory.only:
81
+ if declared.kind in directory.only:
82
+ continue
83
+ # No kind to see, nothing to judge: a class with a base from another
84
+ # module. Unless nothing but constants is allowed: then any class is wrong.
85
+ if declared.kind is None and directory.only:
74
86
  continue
87
+ said = "class" if declared.kind is None else declared.kind.said
75
88
  yield Violation.from_node(
76
89
  node=declared.node,
77
90
  path=file.path,
78
91
  code=CODE,
79
- message=(
80
- f"{declared.name}: {declared.kind.said}; {address} holds only "
81
- f"{', '.join(sorted(one.said for one in directory.only))}"
82
- ),
92
+ message=f"{declared.name}: {said}; {address} holds only {allowed}",
83
93
  )
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, ClassVar, Final
6
6
 
7
7
  from py_checks.checks._kind import declarations
8
8
  from py_checks.checks._layout import SECTION, Layout, claimants
9
- from py_checks.checks._location import place
9
+ from py_checks.checks._location import MODULE, place
10
10
  from py_checks.checks.placement._marker import MARKER
11
11
  from py_checks.core import Scope, Violation, settings_as
12
12
 
@@ -67,7 +67,8 @@ class ClassPlacement:
67
67
  layout=layout,
68
68
  where=where,
69
69
  )
70
- if not homes or any(where.holds(path=home.address) for home in homes):
70
+ home_here = any(where.holds(path=home.address.removesuffix(MODULE)) for home in homes)
71
+ if not homes or home_here:
71
72
  continue
72
73
  yield Violation.from_node(
73
74
  node=declared.node,
@@ -37,6 +37,7 @@ class Shape:
37
37
  method: str | None
38
38
  forbids: tuple[str, ...]
39
39
  max_arguments: int | None
40
+ takes: str | None
40
41
 
41
42
 
42
43
  class OperationShape:
@@ -52,6 +53,11 @@ class OperationShape:
52
53
  operation needs it, it becomes a private method; if two need it, it moves
53
54
  to where the shared code lives.
54
55
 
56
+ With `takes`, every argument of the door is a class of that suffix: a
57
+ query use case handed a `...Command`, or a bare `name: str`, is a split
58
+ into commands and queries that holds only on the reviewer's eye. The
59
+ annotation is read by name, a forward reference included.
60
+
55
61
  Constants and aliases may stand there: a name is read where it is used.
56
62
  An enum may not, unlike in other directories: a vocabulary is a class, and
57
63
  an operation that needed one is naming something its module does not own.
@@ -105,28 +111,51 @@ class OperationShape:
105
111
  )
106
112
  )
107
113
  if subject is not None and isinstance(subject.node, ast.ClassDef):
108
- found += [
109
- *cls._door(
110
- file=file,
111
- subject=subject,
112
- node=subject.node,
113
- rule=rule,
114
- ),
115
- *cls._input(
116
- file=file,
117
- subject=subject,
118
- node=subject.node,
119
- rule=rule,
120
- ),
121
- *cls._held(
122
- file=file,
123
- subject=subject,
124
- node=subject.node,
125
- rule=rule,
126
- ),
127
- ]
114
+ found += cls._shaped(
115
+ file=file,
116
+ subject=subject,
117
+ node=subject.node,
118
+ rule=rule,
119
+ )
128
120
  yield from sorted(found, key=lambda violation: (violation.line, violation.column))
129
121
 
122
+ @classmethod
123
+ def _shaped(
124
+ cls,
125
+ *,
126
+ file: ParsedFile,
127
+ subject: Declaration,
128
+ node: ast.ClassDef,
129
+ rule: Shape,
130
+ ) -> list[Violation]:
131
+ """What is wrong with the operation class itself: its door, input and holdings."""
132
+ return [
133
+ *cls._door(
134
+ file=file,
135
+ subject=subject,
136
+ node=node,
137
+ rule=rule,
138
+ ),
139
+ *cls._input(
140
+ file=file,
141
+ subject=subject,
142
+ node=node,
143
+ rule=rule,
144
+ ),
145
+ *cls._held(
146
+ file=file,
147
+ subject=subject,
148
+ node=node,
149
+ rule=rule,
150
+ ),
151
+ *cls._taken(
152
+ file=file,
153
+ subject=subject,
154
+ node=node,
155
+ rule=rule,
156
+ ),
157
+ ]
158
+
130
159
  @staticmethod
131
160
  def _rule(
132
161
  *,
@@ -160,6 +189,7 @@ class OperationShape:
160
189
  method=operation.method,
161
190
  forbids=operation.forbids,
162
191
  max_arguments=operation.max_arguments,
192
+ takes=operation.takes,
163
193
  )
164
194
 
165
195
  @staticmethod
@@ -261,7 +291,7 @@ class OperationShape:
261
291
  if rule.max_arguments is None:
262
292
  return
263
293
  for method in cls._public(node=node):
264
- count = cls._arguments(node=method)
294
+ count = len(cls._filled(node=method))
265
295
  if count <= rule.max_arguments:
266
296
  continue
267
297
  yield Violation.from_node(
@@ -277,7 +307,38 @@ class OperationShape:
277
307
  )
278
308
 
279
309
  @classmethod
280
- def _arguments(cls, *, node: ast.FunctionDef | ast.AsyncFunctionDef) -> int:
310
+ def _taken(
311
+ cls,
312
+ *,
313
+ file: ParsedFile,
314
+ subject: Declaration,
315
+ node: ast.ClassDef,
316
+ rule: Shape,
317
+ ) -> Iterator[Violation]:
318
+ """An argument of the door that is not the directory's kind of input."""
319
+ if rule.takes is None:
320
+ return
321
+ takes = rule.takes
322
+ for method in cls._public(node=node):
323
+ for argument in cls._filled(node=method):
324
+ annotation = argument.annotation
325
+ if annotation is not None and any(
326
+ name.endswith(takes) for name in cls._typed(node=annotation)
327
+ ):
328
+ continue
329
+ said = "nothing" if annotation is None else ast.unparse(annotation)
330
+ yield Violation.from_node(
331
+ node=argument,
332
+ path=file.path,
333
+ code=CODE,
334
+ message=(
335
+ f"{subject.name}.{method.name} takes {argument.arg}: {said}; "
336
+ f"in {rule.address} an operation takes a ...{takes}"
337
+ ),
338
+ )
339
+
340
+ @classmethod
341
+ def _filled(cls, *, node: ast.FunctionDef | ast.AsyncFunctionDef) -> list[ast.arg]:
281
342
  """Everything the caller fills; the first argument of a method does not count.
282
343
 
283
344
  By position, not by name: `self` in a `@staticmethod` is an ordinary argument.
@@ -285,7 +346,7 @@ class OperationShape:
285
346
  receiver = 0 if cls._static(node=node) else 1
286
347
  named = [*node.args.posonlyargs, *node.args.args][receiver:]
287
348
  collectors = [one for one in (node.args.vararg, node.args.kwarg) if one is not None]
288
- return len(named) + len(node.args.kwonlyargs) + len(collectors)
349
+ return [*named, *node.args.kwonlyargs, *collectors]
289
350
 
290
351
  @staticmethod
291
352
  def _static(*, node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import ast
5
6
  from typing import TYPE_CHECKING, ClassVar, Final
6
7
 
7
8
  from py_checks.checks._kind import Kind, declarations
@@ -14,6 +15,7 @@ if TYPE_CHECKING:
14
15
  from collections.abc import Iterator
15
16
 
16
17
  from py_checks.checks._kind import Declaration
18
+ from py_checks.checks._layout import Directory
17
19
  from py_checks.config import CheckSettings
18
20
  from py_checks.core import ParsedFile
19
21
 
@@ -42,12 +44,18 @@ class RequiredClass:
42
44
  Constants, aliases and enums are allowed above the required class: a name
43
45
  is read where it is used, and a value does not become a second subject.
44
46
 
47
+ With `named`, the directory keeps many classes of one kind rather than
48
+ one per module, and each of them carries the suffix: a `Price` among the
49
+ `...Value` classes is the one nobody will look for under that name. A
50
+ class with a leading underscore is the module's machinery and is left
51
+ alone.
52
+
45
53
  `__init__.py` re-exports rather than declares; an empty module has not
46
54
  promised anything yet; a module with a leading underscore (`_base.py`)
47
55
  holds its directory's machinery, not one of its classes. The rule leaves
48
56
  these three alone.
49
57
 
50
- Settings: `required` and `suffix` in the shared `[layout]` table.
58
+ Settings: `required`, `named` and `suffix` in the shared `[layout]` table.
51
59
  """
52
60
 
53
61
  code: ClassVar[str] = CODE
@@ -74,19 +82,30 @@ class RequiredClass:
74
82
  found = innermost(
75
83
  where=where,
76
84
  among=[
77
- (address, directory) for address, directory in layout.items() if directory.required
85
+ (address, directory)
86
+ for address, directory in layout.items()
87
+ if directory.required or directory.named
78
88
  ],
79
89
  )
80
90
  if found is None or (suffix := found[1].suffix) is None:
81
91
  return
92
+ address, directory = found
82
93
  declared = list(declarations(tree=file.tree))
83
94
  if not declared:
84
95
  return
85
- yield from cls._violations(
86
- file=file,
87
- declared=declared,
88
- suffix=suffix,
89
- )
96
+ if directory.required:
97
+ yield from cls._violations(
98
+ file=file,
99
+ declared=declared,
100
+ suffix=suffix,
101
+ )
102
+ if directory.named:
103
+ yield from cls._unnamed(
104
+ file=file,
105
+ declared=declared,
106
+ address=address,
107
+ directory=directory,
108
+ )
90
109
 
91
110
  @classmethod
92
111
  def _violations(
@@ -131,6 +150,30 @@ class RequiredClass:
131
150
  ),
132
151
  )
133
152
 
153
+ @classmethod
154
+ def _unnamed(
155
+ cls,
156
+ *,
157
+ file: ParsedFile,
158
+ declared: list[Declaration],
159
+ address: str,
160
+ directory: Directory,
161
+ ) -> Iterator[Violation]:
162
+ """A class of this directory's kinds that does not carry its suffix."""
163
+ suffix = directory.suffix or ""
164
+ for one in declared:
165
+ if not isinstance(one.node, ast.ClassDef) or one.name.startswith("_"):
166
+ continue
167
+ if directory.only and one.kind not in directory.only:
168
+ continue
169
+ if one.name.endswith(suffix):
170
+ continue
171
+ yield cls._says(
172
+ file=file,
173
+ node=one,
174
+ message=f"{one.name} does not end with {suffix}; in {address} every class does",
175
+ )
176
+
134
177
  @staticmethod
135
178
  def _ahead(
136
179
  *,
@@ -224,15 +224,18 @@ def _nowhere(*, config: Config) -> Iterator[Complaint]:
224
224
  return
225
225
  named = prefix(source=config.origin)
226
226
  for section, address, zone in sorted(_addressed(config=config)):
227
- modules = not zone or address.split(SEPARATOR)[-1] == ANY
228
227
  if any(
229
228
  depth(
230
229
  parts=parts,
231
- path=address,
230
+ path=address.removesuffix(SUFFIX),
232
231
  )
233
232
  is not None
234
233
  for parts, directory in places
235
- if directory or modules
234
+ if _answers(
235
+ address=address,
236
+ zone=zone,
237
+ directory=directory,
238
+ )
236
239
  ):
237
240
  continue
238
241
  yield Complaint(
@@ -244,6 +247,25 @@ def _nowhere(*, config: Config) -> Iterator[Complaint]:
244
247
  )
245
248
 
246
249
 
250
+ def _answers(
251
+ *,
252
+ address: str,
253
+ zone: bool,
254
+ directory: bool,
255
+ ) -> bool:
256
+ """Whether a place of this sort can answer the address.
257
+
258
+ An address ending in `.py` names a module and only a module answers it. A
259
+ zone is answered by a directory, and by a module only through a trailing
260
+ `*`. Any other address — a layout block — by either.
261
+ """
262
+ if address.endswith(SUFFIX):
263
+ return not directory
264
+ if zone:
265
+ return directory or address.split(SEPARATOR)[-1] == ANY
266
+ return True
267
+
268
+
247
269
  def _addressed(*, config: Config) -> Iterator[tuple[str, str, bool]]:
248
270
  """The addresses written in the settings, and whether each is a zone.
249
271
 
@@ -16,3 +16,6 @@ MIGRATIONS: Final = "migrations"
16
16
  VERSIONS: Final = "versions"
17
17
 
18
18
  SECTION: Final = "contracts"
19
+
20
+ # A table entry with this in it names part of a layer: `domain/enums`.
21
+ PART: Final = "/"
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  from typing import TYPE_CHECKING, Final
6
6
 
7
7
  from py_checks.config import prefix
8
- from py_checks.contracts._constants import MIGRATIONS, MODULES, SECTION, VERSIONS
8
+ from py_checks.contracts._constants import MIGRATIONS, MODULES, PART, SECTION, VERSIONS
9
9
  from py_checks.contracts._layout import expressions, migrations, modules, package
10
10
  from py_checks.contracts._settings import contracts
11
11
 
@@ -95,6 +95,7 @@ def _contracts(
95
95
  package=package,
96
96
  layer=layer,
97
97
  forbidden=known - frozenset(table[layer]),
98
+ parts=[one for one in table[layer] if PART in one],
98
99
  )
99
100
  )
100
101
  ]
@@ -121,8 +122,14 @@ def _layer(
121
122
  package: str,
122
123
  layer: str,
123
124
  forbidden: Iterable[str],
125
+ parts: Iterable[str],
124
126
  ) -> str | None:
125
- """The contract "this layer may not import that"."""
127
+ """The contract "this layer may not import that".
128
+
129
+ A part of a forbidden layer the table lets in (`domain/enums`) stays in the
130
+ forbidden layer — listing the rest would leave `domain/__init__` open — and
131
+ is let through by `ignore_imports`; an exception nobody uses is no error.
132
+ """
126
133
  sources = expressions(
127
134
  root=root,
128
135
  src=config.src,
@@ -141,21 +148,62 @@ def _layer(
141
148
  ]
142
149
  if not sources or not targets:
143
150
  return None
151
+ ignored = _let_through(
152
+ root=root,
153
+ config=config,
154
+ package=package,
155
+ sources=sources,
156
+ parts=[part for part in parts if part.split(PART)[0] in forbidden],
157
+ )
158
+ scalars = {
159
+ "name": f"{layer} imports only what it may",
160
+ "type": "forbidden",
161
+ # Direct imports only. There is no indirect chain to check here:
162
+ # `presentation` calls `application`, and `application` knows
163
+ # `domain` — by the table that is exactly the intended work, and
164
+ # forbidding indirect links would forbid it too.
165
+ "allow_indirect_imports": "True",
166
+ }
167
+ lists = {"source_modules": list(sources), "forbidden_modules": targets}
168
+ if ignored:
169
+ scalars["unmatched_ignore_imports_alerting"] = "none"
170
+ lists["ignore_imports"] = ignored
144
171
  return _block(
145
172
  head=f"[importlinter:contract:layer-{layer}]",
146
- scalars={
147
- "name": f"{layer} imports only what it may",
148
- "type": "forbidden",
149
- # Direct imports only. There is no indirect chain to check here:
150
- # `presentation` calls `application`, and `application` knows
151
- # `domain` — by the table that is exactly the intended work, and
152
- # forbidding indirect links would forbid it too.
153
- "allow_indirect_imports": "True",
154
- },
155
- lists={"source_modules": list(sources), "forbidden_modules": targets},
173
+ scalars=scalars,
174
+ lists=lists,
156
175
  )
157
176
 
158
177
 
178
+ def _let_through(
179
+ *,
180
+ root: Path,
181
+ config: Config,
182
+ package: str,
183
+ sources: Iterable[str],
184
+ parts: Iterable[str],
185
+ ) -> list[str]:
186
+ """The imports from the layer into the parts it may see, module and descendants alike."""
187
+ targets = [
188
+ f"{expression}.{rest.replace(PART, '.')}"
189
+ for part in parts
190
+ for layer, _, rest in [part.partition(PART)]
191
+ for expression in expressions(
192
+ root=root,
193
+ src=config.src,
194
+ package=package,
195
+ layer=layer,
196
+ )
197
+ ]
198
+ return [
199
+ f"{importer} -> {imported}"
200
+ for source in sources
201
+ for importer in (source, f"{source}.**")
202
+ for target in targets
203
+ for imported in (target, f"{target}.**")
204
+ ]
205
+
206
+
159
207
  def _independence(
160
208
  *,
161
209
  root: Path,
@@ -18,7 +18,9 @@ class Contracts(CheckSettings):
18
18
 
19
19
  `layers` — a layer and what it may import. Anything missing from the table
20
20
  has no restrictions: the library does not know what the layers are called
21
- in this project and does not guess on its behalf.
21
+ in this project and does not guess on its behalf. An entry with a slash
22
+ names part of another layer: `domain/enums` lets the layer import the
23
+ domain's enums while the rest of `domain` stays forbidden.
22
24
 
23
25
  `composition-root` — layers that may import anything: they tie the rest
24
26
  together, and that is the whole of their work. They are listed separately
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-checks
3
- Version: 0.6.0
3
+ Version: 0.8.0
4
4
  Summary: Проверки архитектурных соглашений проекта
5
5
  Author: Armontex
6
6
  Author-email: Armontex <windle1337@gmail.com>
@@ -1,11 +1,11 @@
1
1
  py_checks/__init__.py,sha256=xR8QJ9loLxCkxktQedfgoesRfCP8eQMAeijGbZVDE70,55
2
2
  py_checks/checks/__init__.py,sha256=BuStA0L0APy1ceCyjmVmo2qj4yRSmJTn_VrXFKkYGcc,1040
3
3
  py_checks/checks/_kind.py,sha256=9URjekgDY85ya9Z-3e5_LUTwAd1ROBLSyFluVvNaGSg,5748
4
- py_checks/checks/_layout.py,sha256=MhKpwOCA5rNDcBAUtNsxrFyf-g743t97mXHhybpYMws,8692
5
- py_checks/checks/_location.py,sha256=DlucPBVL-IT-cG6L1lXW5cuLQFKCZ6E-gZ-ge6uYI-U,5121
4
+ py_checks/checks/_layout.py,sha256=ICpSL-akEMBzxHRdk71aWT92F6Gt8GGy-Aubnuh-kaQ,9729
5
+ py_checks/checks/_location.py,sha256=2Hzbsve6oO0ExTx03iraSOKu7aqM5R5uNXTZexrjhZM,5913
6
6
  py_checks/checks/_names.py,sha256=LrwKwl2g1Z7eZmNOSx-hQhpOjFL-L-TUqpWOFzjRC9A,3047
7
7
  py_checks/checks/api/__init__.py,sha256=NBgeG3O4Ctiy74AFvLOFitmHUOq7jsrUG0-eLKpvlkY,527
8
- py_checks/checks/api/_edge_declarations.py,sha256=zOYr-d8Ps_NSRMsuU11M4Fz-H5bLFDboqatUn5KMUak,13005
8
+ py_checks/checks/api/_edge_declarations.py,sha256=x7Vm_0RJWFd6mLDR8WPsnwvI5Y30jxvn96PNznSffC4,15029
9
9
  py_checks/checks/api/_marker.py,sha256=F64S2mLvWkJV6Lqoj8Hq2oyx61ENvWO6gat_3yaFZrQ,118
10
10
  py_checks/checks/calls/__init__.py,sha256=S2DYJ0Bj5nQR_4SnJ3SF08w1wMQ7WGgV7x4WKljMaCs,378
11
11
  py_checks/checks/calls/_confined_functions.py,sha256=2PYXxUycnGIUrM3G3gwyi3Cr-bYdUOhZnk3k6Vj-19k,3278
@@ -35,11 +35,11 @@ py_checks/checks/imports/_marker.py,sha256=LNJ1vFrHG2C_3ybl1vJrIx2y9-m7CgTLWG95Z
35
35
  py_checks/checks/imports/_sealed.py,sha256=lndjOt6vJk1_otSw8r4ifPbHRXOz7OiKDGGiA5xZHpc,2884
36
36
  py_checks/checks/imports/_statements.py,sha256=16h5A8MBzRIjB5yDg_4hKzAqrL9g4lOvbSwQXQcZwS8,1425
37
37
  py_checks/checks/placement/__init__.py,sha256=KQ6Kch71ZJ_SBfJ6-QOzkhVSfXST25K5uVjASk1FanA,1418
38
- py_checks/checks/placement/_class_modules.py,sha256=gNckSE4tE5HxD-Reptmcn6U0QmvXQQ8lD1ffhgn0nI0,2947
39
- py_checks/checks/placement/_class_placement.py,sha256=0DBXimQfY4kI6tp9bqjDVm4m_1dlMmZBD2iMMoj6t-g,2830
38
+ py_checks/checks/placement/_class_modules.py,sha256=7hJaozA-vat05yYz5JTNS1TsmUXCJQ01feG-OsYqCco,3407
39
+ py_checks/checks/placement/_class_placement.py,sha256=liHF1E0200qt2s2SAzp9QKIGGqILCs-9Zt-hkh_36jo,2893
40
40
  py_checks/checks/placement/_marker.py,sha256=962xuJm5CWvUqtOg_R2NcG2Fnt8TFNhc7RwLVIWIeSU,146
41
- py_checks/checks/placement/_operation_shape.py,sha256=kfFsoiP1B20k0EzQwwDXsquyOm_jC7CBPE_z2ranDLw,12979
42
- py_checks/checks/placement/_required_class.py,sha256=7xWEgLuxPkGX3yJ5iDHZ__kSE8_3yTHI75wsNSUdOhg,5457
41
+ py_checks/checks/placement/_operation_shape.py,sha256=eZrtE5c0SBmC5nCzz4ei4jPIwOs6IqbKQ82EHfKyVuA,14962
42
+ py_checks/checks/placement/_required_class.py,sha256=pSB5n8AGRMt1fHb1_Jb4NlvPennv3dRuv5PT4dyjOoU,7001
43
43
  py_checks/checks/signatures/__init__.py,sha256=C1iH5IxOmwwPwu6G91lcjF16dBJmFR8dObm6uWlWhaI,1129
44
44
  py_checks/checks/signatures/_function_length.py,sha256=83mc8R4WH7RdZkHNeQGP78KCqb54zvE-Bpjx_i_IBLY,3007
45
45
  py_checks/checks/signatures/_functions.py,sha256=0ovCI5qGl315ekq7sKj-hYc2GTeZscfbxScgv7xcpyY,2857
@@ -59,7 +59,7 @@ py_checks/cli/__init__.py,sha256=bSoxcpOM-Gk0XvR-XjKuHvXPwdEeIg0hTjfUL4Ac2WA,290
59
59
  py_checks/cli/_app.py,sha256=PAXu38bJN3FJM3GU-geAnFGRrgGc_SUZ3H_CQXmx24I,413
60
60
  py_checks/cli/_protocols.py,sha256=NdWZOW5dRvXNAh4VK6hI8A9fy5j2XzxsbPZhAA_-rkw,573
61
61
  py_checks/cli/commands/__init__.py,sha256=jPmzVcERgp6xvVfvWOZyGeKGwR2pG74IEF4stlM4Mps,975
62
- py_checks/cli/commands/_doctor.py,sha256=qHOg8Wo8hZVH5KoNOCz3e0Q0hhPfI15t97l_J7rdHyc,10732
62
+ py_checks/cli/commands/_doctor.py,sha256=9Vr18eM1Jw8OfLVCSNCyvBOF_wnkyNAYqTGXg4mAvoc,11316
63
63
  py_checks/cli/commands/_explain.py,sha256=gT7WR0AIe4BzhmH8BVXUL2ENSvMejh9KT3pctyy-ueQ,2443
64
64
  py_checks/cli/commands/_list.py,sha256=PTRpUn_1E6iug_rfoHo6rA6eHtm0-Y6bvjmtVg_6bLY,1516
65
65
  py_checks/cli/commands/_mutation.py,sha256=IjMKW7BWa1qDG2Vm2KnhbG-1fF07HRQN8NdKUtKBDd8,6638
@@ -74,10 +74,10 @@ py_checks/config/_errors.py,sha256=wpSK_mmjndMBzKuluJrjtSAuIuoKuNXdp0C11M6sA0s,3
74
74
  py_checks/config/_loader.py,sha256=n1D_XTkz-a8b-P7L8fZCYLiB7V8A0OQSwDcDnm6mE5I,4445
75
75
  py_checks/config/_toml.py,sha256=83bhkb66olUuCx6tveDMiKwqPxwo1VSCDxBJVkrq-Jo,540
76
76
  py_checks/contracts/__init__.py,sha256=t5QVSZLfNngmJY-45t_lpHyDsVmM8a3GYe2aY9TQTXc,918
77
- py_checks/contracts/_constants.py,sha256=ftrHU4CE1OZeocifd-ULECLBGZE6TDWntwBqPI4LiRs,502
77
+ py_checks/contracts/_constants.py,sha256=Q6ELufudar9BHfAXOhhpakhm2ILl7J7AVUn8T_oXvzE,592
78
78
  py_checks/contracts/_layout.py,sha256=SQPDcH2hkicsDbF80i4osKPffTXl9V8noIIG_ZcILxs,1583
79
- py_checks/contracts/_render.py,sha256=Y1kxPibrj5Y5Frvbli7mw2IkiebaGjTH9hQw8fYjr5w,5923
80
- py_checks/contracts/_settings.py,sha256=tOHteNT70l-_u8AIlTfLI3hRXOI8uTg-WJPwMclz8BM,1387
79
+ py_checks/contracts/_render.py,sha256=dimhl7cVBu4T0gOgv_I0m8vBmsY6U5gKNZM4IGGhsJo,7364
80
+ py_checks/contracts/_settings.py,sha256=hrG6T2ejatBs23ACX4UdVYsvUBbNU21Re4suvIp39sQ,1546
81
81
  py_checks/core/__init__.py,sha256=xtV-oFMsNtFQCjGKC58lMK56ivPAQri76lBGilsedh8,1695
82
82
  py_checks/core/_constants.py,sha256=mzd4LnnB1likzBSuV5kroJXwyTOXOGDIhVgFduaZFes,563
83
83
  py_checks/core/_discovery.py,sha256=CeTOdSgMGKQWu2mL4eASR2AxDrF_xNx106DcSF3orck,1505
@@ -110,8 +110,8 @@ py_checks/mutation/_settings.py,sha256=HF9-6ICtsHAV8-1MRHDe1wEfj5dbCKux05_YHxl_X
110
110
  py_checks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
111
111
  py_checks/sync/__init__.py,sha256=l5yy0yACEYTnFzR7EXyF7GJ2eX6KZ_dyudxTdKrIUGs,696
112
112
  py_checks/sync/_sync.py,sha256=GF1BGkWR_1sP0Lq_XZJ6Lfe59Bm_ABbaWPoeuEWnNrM,1878
113
- python_checks-0.6.0.dist-info/licenses/LICENSE,sha256=omcAXq_cAQNMI5X3fRdH7UC6W2Zc8AC-G9xIZ2U1xF0,1065
114
- python_checks-0.6.0.dist-info/WHEEL,sha256=7hzKWg-J8I3Buqyw5tBii5z_MmAVsDYXXijd_QAtNZ8,81
115
- python_checks-0.6.0.dist-info/entry_points.txt,sha256=TtWmUfXcevBejdpwhas4_nNHwVEOW4Qleq2OgafxwbE,1715
116
- python_checks-0.6.0.dist-info/METADATA,sha256=IA7lAF7lFsg_sm9QFSakslAxFIUsI4Si6C52Ov4nKaI,15647
117
- python_checks-0.6.0.dist-info/RECORD,,
113
+ python_checks-0.8.0.dist-info/licenses/LICENSE,sha256=omcAXq_cAQNMI5X3fRdH7UC6W2Zc8AC-G9xIZ2U1xF0,1065
114
+ python_checks-0.8.0.dist-info/WHEEL,sha256=e4_1dyBeezi8ZjfxrZ3bnVOxFDa3ksqVqH0jTHkUZ3k,81
115
+ python_checks-0.8.0.dist-info/entry_points.txt,sha256=TtWmUfXcevBejdpwhas4_nNHwVEOW4Qleq2OgafxwbE,1715
116
+ python_checks-0.8.0.dist-info/METADATA,sha256=ZGvVPQeQbyVCIjH-g4J-cqTVjn7vZ_6VC3-JG5vBjcU,15647
117
+ python_checks-0.8.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: uv 0.12.18
2
+ Generator: uv 0.12.19
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any