python-checks 0.3.1__py3-none-any.whl → 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,370 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-checks
3
+ Version: 0.3.2
4
+ Summary: Проверки архитектурных соглашений проекта
5
+ Author: Armontex
6
+ Author-email: Armontex <windle1337@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: libcst>=1.9,<2
10
+ Requires-Dist: pydantic>=2.13.5,<3
11
+ Requires-Dist: pydantic-settings>=2.15.0,<3
12
+ Requires-Dist: rich>=14.0.0,<16.0.0
13
+ Requires-Dist: typer>=0.27.2,<0.28
14
+ Requires-Python: >=3.14
15
+ Project-URL: Homepage, https://github.com/Armontex/py-checks
16
+ Project-URL: Source, https://github.com/Armontex/py-checks
17
+ Project-URL: Issues, https://github.com/Armontex/py-checks/issues
18
+ Project-URL: Changelog, https://github.com/Armontex/py-checks/blob/main/CHANGELOG.md
19
+ Project-URL: Documentation, https://github.com/Armontex/py-checks/blob/main/docs/service.md
20
+ Description-Content-Type: text/markdown
21
+
22
+ <div align="center">
23
+
24
+ <img src="docs/logo.svg" width="112" alt="py-checks">
25
+
26
+ # py-checks
27
+
28
+ **Your project's architecture, checked like code.**
29
+
30
+ English · [Русский](docs/readmes/README.ru.md)
31
+
32
+ [![ci](https://github.com/Armontex/py-checks/actions/workflows/ci.yml/badge.svg)](https://github.com/Armontex/py-checks/actions/workflows/ci.yml)
33
+ [![python](https://img.shields.io/badge/python-3.14%2B-3776AB)](https://www.python.org/)
34
+ [![checks](https://img.shields.io/badge/checks-28-2ea043)](#what-is-checked)
35
+ [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-FAB040)](#pre-commit)
36
+ [![ruff](https://img.shields.io/badge/linted%20with-ruff-261230)](https://docs.astral.sh/ruff/)
37
+ [![pyright](https://img.shields.io/badge/types-pyright%20strict-1f6feb)](https://microsoft.github.io/pyright/)
38
+ [![license](https://img.shields.io/badge/license-MIT-750014)](https://github.com/Armontex/py-checks/blob/main/LICENSE)
39
+
40
+ </div>
41
+
42
+ ---
43
+
44
+ A linter knows the language; it does not know your project. It will not tell
45
+ you that an ORM model has wandered into a use case, that a `Numeric` column
46
+ was left without a CHECK, that `datetime.now()` is called in the domain rather
47
+ than behind a port. These are not language errors — they are broken
48
+ conventions, and until now review caught them: by eye, differently for each
49
+ reviewer, from scratch every time.
50
+
51
+ `py-checks` is an engine for conventions like these. The library brings the
52
+ rules, the project brings its architecture: the names of the layers, the list
53
+ of sealed zones, where the ORM lives, what bounds a column. Without the
54
+ project's tables the rules stay silent — the library does not guess what your
55
+ domain is called.
56
+
57
+ ```
58
+ src/app/modules/cashout/application/offer.py:34:9: determinism: uuid4() is not deterministic;
59
+ the identifier is handed out at the edge and passed inwards
60
+ src/app/infra/database/models/bet.py:51:5: model-columns: stake is a Numeric with no bound;
61
+ money is described by Numeric(18, 4)
62
+ src/app/presentation/api/v1/routers/bets.py:22:1: endpoint-declarations: POST /bets
63
+ did not name a response_model
64
+ ```
65
+
66
+ ## Why
67
+
68
+ - **A convention stops being spoken.** The rule is written once, with its
69
+ reason, and checked on every commit — rather than recalled at review by
70
+ whoever remembers it.
71
+ - **The rule is universal, the table is yours.** One rule, "this call lives
72
+ only here", covers both the transaction boundary and the ban on `float` in
73
+ the domain. The library contains not one name from your project.
74
+ - **A refusal explains itself.** The message says what is wrong and what to
75
+ write instead, not "violation of rule #14".
76
+ - **An exemption costs one line and owes a reason.**
77
+ `# check-ok: raw-sql: a liveness probe, there is no ORM form of it` — a mark
78
+ without a reason is itself a violation.
79
+ - **We do not do other people's work.** What ruff, pyright and import-linter
80
+ can do stays theirs; what was handed over, and why, is written down in
81
+ [`docs/service.md`](https://github.com/Armontex/py-checks/blob/main/docs/service.md).
82
+
83
+ ## Install
84
+
85
+ ```bash
86
+ uv add --dev python-checks
87
+ ```
88
+
89
+ Installed as `python-checks`, called as `py-checks`: a neighbour holds the
90
+ short name on PyPI, while the command, the settings section and the package
91
+ stayed as they were.
92
+
93
+ Needs Python 3.14+. Dependencies: `libcst`, `pydantic`, `pydantic-settings`,
94
+ `rich`, `typer`.
95
+
96
+ ## In a minute
97
+
98
+ Put a `py-checks.toml` next to `pyproject.toml`:
99
+
100
+ ```toml
101
+ src = "src"
102
+
103
+ [module-length]
104
+ max-lines = 300
105
+
106
+ # Rules that depend on place only work in the zones you name.
107
+ [model-columns]
108
+ zones = ["infra/database/models"]
109
+ types = { Numeric = "money is described by Numeric(18, 4)" }
110
+
111
+ [determinism]
112
+ zones = ["modules/*/domain", "modules/*/application"]
113
+ sources = { "datetime.now" = "take the clock as a port", "uuid4" = "hand the id out at the edge" }
114
+ ```
115
+
116
+ and run:
117
+
118
+ ```bash
119
+ py-checks run # check `src`
120
+ py-checks run --fix # and repair what repairs itself
121
+ py-checks list # which rules exist and which are on
122
+ py-checks explain determinism # what a rule asks for and what it can be told
123
+ ```
124
+
125
+ The settings can also live in a `[tool.py-checks]` section of
126
+ `pyproject.toml` — but one of the two: two places at once is an error to this
127
+ library, not a merge.
128
+
129
+ ## What is checked
130
+
131
+ Twenty-eight rules in nine groups:
132
+
133
+ | Group | About |
134
+ |---|---|
135
+ | `imports` | which package is allowed where, which zone is sealed |
136
+ | `placement` | what belongs in this directory and how an operation is shaped |
137
+ | `signatures` | module length, nesting depth, the shape of a signature |
138
+ | `types` | bounds on fields, the shape of an annotation, immutability |
139
+ | `database` | the model's boundary, a column's material, the shape of a query, the schema |
140
+ | `effects` | the clock, the dice, and the name of an event in the log |
141
+ | `api` | what a route answers with and what it must declare |
142
+ | `calls` | a function whose call sites can be listed |
143
+ | `hygiene` | a ceiling on a dependency |
144
+
145
+ <details>
146
+ <summary>All twenty-eight</summary>
147
+
148
+ | Code | What fails | Scope |
149
+ |---|---|:-:|
150
+ | `confined-imports` | a package is imported outside the places set aside for it | file |
151
+ | `sealed-imports` | a sealed zone imports a foreign package | file |
152
+ | `class-modules` | a module holds what its directory does not allow | file |
153
+ | `class-placement` | a class lies somewhere other than where its kind lives | file |
154
+ | `operation-shape` | an operation is not shaped like an operation | file |
155
+ | `required-class` | a module did not declare the class its directory exists for | file |
156
+ | `keyword-only-arguments` | a signature is not written out in full | file |
157
+ | `function-length` | a function is longer than the limit | file |
158
+ | `module-length` | a module is longer than the limit | file |
159
+ | `nesting` | control structures are nested deeper than the limit | file |
160
+ | `signature-layout` | a list of two or more entries is written on one line | file |
161
+ | `annotation-shapes` | a shape is named such that its fields have no names | file |
162
+ | `config-fields` | a settings field carries no bound | file |
163
+ | `confined-types` | a field in this part of the tree is declared with a type banned here | file |
164
+ | `constant-annotations` | a constant did not say by its type that it is one | file |
165
+ | `frozen-dataclasses` | a dataclass in a zone is declared without the required arguments | file |
166
+ | `bound-checks` | a bounded column did not restate its bound as a CHECK | file |
167
+ | `confined-calls` | a named method was called somewhere it does not belong | file |
168
+ | `model-boundary` | an ORM model is declared, built or handed out in the wrong place | file |
169
+ | `model-columns` | a column is built out of the wrong material | file |
170
+ | `raw-sql` | SQL is written as a string where an expression would do | file |
171
+ | `statement-keys` | a statement names a column by string, or goes to the database in a loop | file |
172
+ | `schema-drift` | the models and the migrations describe different schemas | environment |
173
+ | `determinism` | the code reads the clock, the dice or a new identifier itself | file |
174
+ | `log-events` | an event in the log is named by something other than an enum member | file |
175
+ | `endpoint-declarations` | a route did not say what it answers with | file |
176
+ | `confined-functions` | a named function was called from somewhere it may not be | file |
177
+ | `dependency-bounds` | a dependency may move to a version nobody has ever run | project |
178
+
179
+ </details>
180
+
181
+ Every rule explains itself in full — `py-checks explain <code>` prints the
182
+ docstring with the reason and the list of settings. A worked set of tables for
183
+ a typical service is in
184
+ [`docs/service.md`](https://github.com/Armontex/py-checks/blob/main/docs/service.md).
185
+
186
+ ### Three kinds of rule
187
+
188
+ What a rule is handed to judge, the rule declares itself, in its `scope`:
189
+
190
+ - **file** — a parsed source file; most rules are these;
191
+ - **project** — the root: the manifest, the agreement of the repository's files with one another;
192
+ - **environment** — the same, but it needs a live database or a long run. An ordinary run leaves these out: `py-checks run --all`, or by name; their place is CI.
193
+
194
+ ## Marks
195
+
196
+ A line can be taken out of a rule's judgement, but you have to say why:
197
+
198
+ ```python
199
+ text("SELECT 1") # db-ok: raw-sql: a liveness probe, there is no ORM form of it
200
+ ```
201
+
202
+ The canonical form is `# check-ok: <code>: <reason>`, and it lifts exactly one
203
+ rule. Every group has a short word of its own (`# db-ok`, `# type-ok`,
204
+ `# signature-ok`, …): a person remembers the group, not twenty-eight codes.
205
+
206
+ A line may carry several marks — a signature written in a column gathers them
207
+ on its last line:
208
+
209
+ ```python
210
+ ) -> object: # signature-ok: this is how pydantic calls it # type-ok: raw input
211
+ ```
212
+
213
+ A mark with no code, with a typo in the code, or with no reason is a violation
214
+ itself. A silently dead mark looks like a disabled check, while the check is in
215
+ fact running and simply does not see it.
216
+
217
+ ## pre-commit
218
+
219
+ ```yaml
220
+ - repo: https://github.com/Armontex/py-checks
221
+ rev: v0.3.1
222
+ hooks:
223
+ - id: py-checks
224
+ args: [--fix] # repair what repairs itself
225
+ - id: py-checks-sync # contracts and `.env.example` rebuilt
226
+ ```
227
+
228
+ One hook rather than one per rule: which rules run is the config's decision. A
229
+ set of rules is called with `args: [--select, "<code>,<code>"]`; a repeated
230
+ flag does the same.
231
+
232
+ It has to stand **before** `ruff-format`: the autofix writes characters, not
233
+ columns, and the project's formatter lays the signature out.
234
+
235
+ Everything else — ruff, pyright, import-linter, commitizen — the project
236
+ declares itself: each has a hook written by its own authors.
237
+
238
+ ## Import contracts
239
+
240
+ The project's layers are described once, and `.importlinter` is built from
241
+ that:
242
+
243
+ ```toml
244
+ [contracts.layers]
245
+ domain = ["domain"]
246
+ application = ["application", "domain"]
247
+ presentation = ["presentation", "application"]
248
+ ```
249
+
250
+ ```bash
251
+ py-checks sync # build
252
+ py-checks sync --check # fail if the file has fallen behind
253
+ ```
254
+
255
+ It is built not only from the table but from what is on disk: a layer that
256
+ does not exist is left out of the contract — otherwise import-linter would
257
+ fail on the first module that is not there. The graph itself is walked by
258
+ import-linter's own hook.
259
+
260
+ The header of the built file can be your own — `header` in `[contracts]`,
261
+ `#` included; as with `.env.example`, it is for a project whose comments are
262
+ in another language.
263
+
264
+ ## The environment example
265
+
266
+ The name of a variable is known to the settings field — it declares it as
267
+ `validation_alias`, and `config-fields` watches for that. So `.env.example` is
268
+ derived from the same classes the variables are read into, and there is no
269
+ reason to keep it by hand: it falls out of step silently, and that is noticed
270
+ when the variable turns out to be missing in production.
271
+
272
+ ```toml
273
+ [env-example]
274
+ settings = ["myservice.config.settings:Settings"]
275
+ ```
276
+
277
+ The same `py-checks sync` builds it alongside the contracts. The root class is
278
+ enough: it has already listed its sections as its own fields, and repeating
279
+ that list in the settings would mean keeping a second one that drifts from the
280
+ first. A section field does not become a variable — it has no name of its own
281
+ in the environment. What goes into the file is the variable's name, its
282
+ default, the first paragraph of the class docstring and the field's
283
+ `description` if it has one — so the explanation lives next to the field
284
+ rather than in a file that outlives it.
285
+
286
+ The header can be written by the project as well — `header = "# Generated by
287
+ py-checks."`, `#` included. It is for a project whose comments are in another
288
+ language; an empty one keeps the library's.
289
+
290
+ The classes are imported rather than read as text: the variable's name is an
291
+ attribute's value, assembled by a call, and reading it from the source would
292
+ mean performing that call yourself.
293
+
294
+ ## A rule of your own
295
+
296
+ A rule is a class with four fields and a `run`, declared through entry points.
297
+ There is no need to fork the library:
298
+
299
+ ```python
300
+ # myproject_checks/_no_print.py
301
+ import ast
302
+ from collections.abc import Iterator
303
+ from typing import ClassVar, Final
304
+
305
+ from py_checks.config import CheckSettings
306
+ from py_checks.core import ParsedFile, Scope, Violation
307
+
308
+ CODE: Final = "no-print"
309
+
310
+
311
+ class NoPrint:
312
+ """Fails if a `print` was left in the source."""
313
+
314
+ code: ClassVar[str] = CODE
315
+ Settings: ClassVar[type[CheckSettings]] = CheckSettings
316
+ scope: ClassVar[Scope] = Scope.FILE
317
+ marker: ClassVar[str] = "# my-ok"
318
+
319
+ @classmethod
320
+ def run(cls, *, file: ParsedFile, settings: CheckSettings) -> Iterator[Violation]:
321
+ for node in ast.walk(file.tree):
322
+ if isinstance(node, ast.Call) and getattr(node.func, "id", "") == "print":
323
+ yield Violation.from_node(
324
+ node=node,
325
+ path=file.path,
326
+ code=CODE,
327
+ message="a print in the source; an event is written to the log",
328
+ )
329
+ ```
330
+
331
+ ```toml
332
+ [project.entry-points."py_checks.checks"]
333
+ no-print = "myproject_checks:NoPrint"
334
+ ```
335
+
336
+ From there it behaves like a native one: it appears in `list` and `explain`,
337
+ obeys `ignore`, and is lifted by a mark.
338
+
339
+ ## Commands
340
+
341
+ | Command | |
342
+ |---|---|
343
+ | `py-checks run [paths]` | run the checks; `0` — clean, `1` — violations found |
344
+ | `py-checks run --fix` | apply the repairs that are unambiguous |
345
+ | `py-checks run --select <code>,<code>` | only the named rules, `ignore` notwithstanding |
346
+ | `py-checks run --all` | including the rules that need a live environment |
347
+ | `py-checks list` | every rule: code, state, one line of description |
348
+ | `py-checks explain <code>` | what a rule asks for and what it can be told |
349
+ | `py-checks sync [--check]` | build the import contracts and `.env.example` |
350
+
351
+ ## Development
352
+
353
+ ```bash
354
+ uv sync
355
+ uv run pre-commit install
356
+ uv run pytest -q
357
+ ```
358
+
359
+ A check is described by folders of examples rather than by a test:
360
+ `tests/checks/<code>/` with `ok/` and `bad/` inside, and syrupy compares the
361
+ snapshot of the output. Project rules have `tests/projects/<code>__<variant>/`.
362
+ The library checks itself: a rule that cannot survive its own repository has
363
+ no business reaching anybody else's.
364
+
365
+ The repository's own conventions are in
366
+ [`AGENTS.md`](https://github.com/Armontex/py-checks/blob/main/AGENTS.md).
367
+
368
+ ## License
369
+
370
+ [MIT](https://github.com/Armontex/py-checks/blob/main/LICENSE) — © 2026 Armontex.
@@ -94,8 +94,8 @@ py_checks/environment/_settings.py,sha256=Pr0xE05tt7iagffzK11NncTN22QeoZKtxA2zuC
94
94
  py_checks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
95
95
  py_checks/sync/__init__.py,sha256=Kg08BC7arCTqdFk2tO3qm95_jG-X0vxK-GMvVYJEkXc,1041
96
96
  py_checks/sync/_sync.py,sha256=KqA65H4zeP6y17LwlRR8svpCuhUdFCY3KIwG3YtuvAk,2254
97
- python_checks-0.3.1.dist-info/licenses/LICENSE,sha256=omcAXq_cAQNMI5X3fRdH7UC6W2Zc8AC-G9xIZ2U1xF0,1065
98
- python_checks-0.3.1.dist-info/WHEEL,sha256=R1d3uUTbmXM1FHXH_itQashbrqrOSVj-hvBCpmkIIGE,81
99
- python_checks-0.3.1.dist-info/entry_points.txt,sha256=59rS_KMwYdFnQ9HuhkBpKQNKySNAALyneIFO_-cVQvw,1679
100
- python_checks-0.3.1.dist-info/METADATA,sha256=4L29ylf6LRb_U_YQ9DBVDzGMBb0htYdIEAeusbx6T0A,20322
101
- python_checks-0.3.1.dist-info/RECORD,,
97
+ python_checks-0.3.2.dist-info/licenses/LICENSE,sha256=omcAXq_cAQNMI5X3fRdH7UC6W2Zc8AC-G9xIZ2U1xF0,1065
98
+ python_checks-0.3.2.dist-info/WHEEL,sha256=R1d3uUTbmXM1FHXH_itQashbrqrOSVj-hvBCpmkIIGE,81
99
+ python_checks-0.3.2.dist-info/entry_points.txt,sha256=59rS_KMwYdFnQ9HuhkBpKQNKySNAALyneIFO_-cVQvw,1679
100
+ python_checks-0.3.2.dist-info/METADATA,sha256=FRgpCD1htnYw4vlVy-sNTGZmAf9EpGUX89oC5lFAx-o,15209
101
+ python_checks-0.3.2.dist-info/RECORD,,
@@ -1,347 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: python-checks
3
- Version: 0.3.1
4
- Summary: Проверки архитектурных соглашений проекта
5
- Author: Armontex
6
- Author-email: Armontex <windle1337@gmail.com>
7
- License-Expression: MIT
8
- License-File: LICENSE
9
- Requires-Dist: libcst>=1.9,<2
10
- Requires-Dist: pydantic>=2.13.5,<3
11
- Requires-Dist: pydantic-settings>=2.15.0,<3
12
- Requires-Dist: rich>=14.0.0,<16.0.0
13
- Requires-Dist: typer>=0.27.2,<0.28
14
- Requires-Python: >=3.14
15
- Project-URL: Homepage, https://github.com/Armontex/py-checks
16
- Project-URL: Source, https://github.com/Armontex/py-checks
17
- Project-URL: Issues, https://github.com/Armontex/py-checks/issues
18
- Project-URL: Changelog, https://github.com/Armontex/py-checks/blob/main/CHANGELOG.md
19
- Project-URL: Documentation, https://github.com/Armontex/py-checks/blob/main/docs/service.md
20
- Description-Content-Type: text/markdown
21
-
22
- <div align="center">
23
-
24
- <img src="docs/logo.svg" width="112" alt="py-checks">
25
-
26
- # py-checks
27
-
28
- **Архитектурные соглашения проекта, проверяемые как код.**
29
-
30
- [![ci](https://github.com/Armontex/py-checks/actions/workflows/ci.yml/badge.svg)](https://github.com/Armontex/py-checks/actions/workflows/ci.yml)
31
- [![python](https://img.shields.io/badge/python-3.14%2B-3776AB)](https://www.python.org/)
32
- [![правил](https://img.shields.io/badge/checks-28-2ea043)](#что-проверяется)
33
- [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-FAB040)](#pre-commit)
34
- [![ruff](https://img.shields.io/badge/linted%20with-ruff-261230)](https://docs.astral.sh/ruff/)
35
- [![pyright](https://img.shields.io/badge/types-pyright%20strict-1f6feb)](https://microsoft.github.io/pyright/)
36
- [![license](https://img.shields.io/badge/license-MIT-750014)](https://github.com/Armontex/py-checks/blob/main/LICENSE)
37
-
38
- </div>
39
-
40
- ---
41
-
42
- Линтер знает язык, но не знает ваш проект. Он не скажет, что ORM-модель уехала
43
- в сценарий, что колонка `Numeric` осталась без CHECK, что `datetime.now()`
44
- позвали в домене, а не в порте. Это не ошибки языка — это нарушенные
45
- соглашения, и до сих пор их ловило ревью: глазами, у каждого свои, каждый раз
46
- заново.
47
-
48
- `py-checks` — движок для таких соглашений. Библиотека везёт правила, проект
49
- везёт свою архитектуру: имена слоёв, список запечатанных зон, где живёт ORM,
50
- чем ограничена колонка. Без таблиц проекта правила молчат — библиотека не
51
- догадывается за вас, как называется ваш домен.
52
-
53
- ```
54
- src/app/modules/cashout/application/offer.py:34:9: determinism: uuid4() не детерминирован;
55
- идентификатор выдают на краю и передают внутрь
56
- src/app/infra/database/models/bet.py:51:5: model-columns: stake — Numeric без ограничений;
57
- деньги описывают Numeric(18, 4)
58
- src/app/presentation/api/v1/routers/bets.py:22:1: endpoint-declarations: POST /bets
59
- не назвал response_model
60
- ```
61
-
62
- ## Зачем
63
-
64
- - **Соглашение перестаёт быть устным.** Правило записано один раз, с причиной, и проверяется на каждом коммите — а не вспоминается на ревью тем, кто его помнит.
65
- - **Правило универсально, таблица — ваша.** Одно правило «этот вызов живёт только здесь» закрывает и границу транзакции, и запрет `float` в домене. Библиотека не содержит ни одного имени вашего проекта.
66
- - **Отказ объясняет себя.** Сообщение говорит, что не так и чем это заменить, а не «нарушение правила №14».
67
- - **Исключение стоит одной строки, но требует причины.** `# check-ok: raw-sql: проба живости, формы ORM нет` — пометка без причины сама становится нарушением.
68
- - **Чужую работу мы не делаем.** Что умеют ruff, pyright и import-linter — остаётся за ними; что и почему туда отдано, записано в [`docs/service.md`](https://github.com/Armontex/py-checks/blob/main/docs/service.md).
69
-
70
- ## Установка
71
-
72
- ```bash
73
- uv add --dev python-checks
74
- ```
75
-
76
- Ставится как `python-checks`, зовётся `py-checks`: на PyPI живёт сосед по
77
- имени, а команда, секция настроек и пакет остались прежними.
78
-
79
- Нужен Python 3.14+. Зависимости: `libcst`, `pydantic`, `pydantic-settings`, `rich`, `typer`.
80
-
81
- ## За минуту
82
-
83
- Положите рядом с `pyproject.toml` файл `py-checks.toml`:
84
-
85
- ```toml
86
- src = "src"
87
-
88
- [module-length]
89
- max-lines = 300
90
-
91
- # Правила, зависящие от места, работают только в названных зонах.
92
- [model-columns]
93
- zones = ["infra/database/models"]
94
- types = { Numeric = "деньги описывают Numeric(18, 4)" }
95
-
96
- [determinism]
97
- zones = ["modules/*/domain", "modules/*/application"]
98
- sources = { "datetime.now" = "часы берут портом", "uuid4" = "идентификатор выдают на краю" }
99
- ```
100
-
101
- и запустите:
102
-
103
- ```bash
104
- py-checks run # проверить `src`
105
- py-checks run --fix # и починить то, что чинится само
106
- py-checks list # какие правила есть и что включено
107
- py-checks explain determinism # что правило требует и какие у него настройки
108
- ```
109
-
110
- Настройки можно держать и секцией `[tool.py-checks]` в `pyproject.toml` — но
111
- одно из двух: два места разом библиотека считает ошибкой, а не слиянием.
112
-
113
- ## Что проверяется
114
-
115
- Двадцать восемь правил в девяти группах:
116
-
117
- | Группа | О чём |
118
- |---|---|
119
- | `imports` | какой пакет где разрешён, какая зона запечатана |
120
- | `placement` | что лежит в этой директории и как устроена операция |
121
- | `signatures` | длина модуля, глубина вложенности, форма подписи |
122
- | `types` | границы у полей, форма аннотаций, неизменяемость |
123
- | `database` | граница модели, материал колонки, форма запроса, схема |
124
- | `effects` | часы, случайность и имя события в логе |
125
- | `api` | чем маршрут отвечает и что обязан объявить |
126
- | `calls` | функция, у которой есть список мест, откуда её зовут |
127
- | `hygiene` | потолок у зависимости |
128
-
129
- <details>
130
- <summary>Все двадцать восемь</summary>
131
-
132
- | Код | Что падает | Вид |
133
- |---|---|:-:|
134
- | `confined-imports` | пакет импортируется вне отведённых ему мест | файл |
135
- | `sealed-imports` | запечатанная зона импортирует чужой пакет | файл |
136
- | `class-modules` | в модуле лежит то, чего его директория не допускает | файл |
137
- | `class-placement` | класс лежит не там, где лежат классы его вида | файл |
138
- | `operation-shape` | операция устроена не как операция | файл |
139
- | `required-class` | модуль не объявил класс, ради которого лежит в этой директории | файл |
140
- | `keyword-only-arguments` | подпись записана не полностью | файл |
141
- | `function-length` | функция длиннее лимита | файл |
142
- | `module-length` | модуль длиннее лимита | файл |
143
- | `nesting` | управляющие конструкции вложены глубже предела | файл |
144
- | `signature-layout` | список из двух и более элементов записан в одну строку | файл |
145
- | `annotation-shapes` | форма названа так, что поля в ней безымянные | файл |
146
- | `config-fields` | поле настроек ничем не ограничено | файл |
147
- | `confined-types` | поле в этой части дерева объявлено запрещённым здесь типом | файл |
148
- | `constant-annotations` | константа не сказала типом, что она константа | файл |
149
- | `frozen-dataclasses` | dataclass в зоне объявлен без нужных аргументов | файл |
150
- | `bound-checks` | ограниченная колонка не повторила своё ограничение как CHECK | файл |
151
- | `confined-calls` | названный метод позвали не там, где ему место | файл |
152
- | `model-boundary` | ORM-модель объявлена, собрана или отдана не там | файл |
153
- | `model-columns` | колонка собрана не из того материала | файл |
154
- | `raw-sql` | SQL написан строкой там, где хватило бы выражения | файл |
155
- | `statement-keys` | запрос называет колонку строкой или ходит в базу в цикле | файл |
156
- | `schema-drift` | модели и миграции описывают уже разные схемы | среда |
157
- | `determinism` | код сам читает часы, случайность или новый идентификатор | файл |
158
- | `log-events` | событие в логе названо чем-то кроме члена перечисления | файл |
159
- | `endpoint-declarations` | маршрут не сказал, чем он отвечает | файл |
160
- | `confined-functions` | названная функция позвана не оттуда, откуда ей можно | файл |
161
- | `dependency-bounds` | зависимость может уехать на версию, которую никто не запускал | проект |
162
-
163
- </details>
164
-
165
- Каждое правило объясняет себя целиком — `py-checks explain <код>` печатает
166
- докстринг с причиной и список настроек. Заготовка таблиц для типового сервиса
167
- лежит в [`docs/service.md`](https://github.com/Armontex/py-checks/blob/main/docs/service.md).
168
-
169
- ### Три вида правил
170
-
171
- Что правилу дают на суд, оно объявляет само — полем `scope`:
172
-
173
- - **файл** — разобранный исходник; таких большинство;
174
- - **проект** — корень: манифест, согласие файлов репозитория между собой;
175
- - **среда** — то же, но нужна живая база или долгий прогон. В обычный прогон такое не входит: `py-checks run --all` или по имени, место ему в CI.
176
-
177
- ## Пометки
178
-
179
- Снять правило со строки можно, но придётся объяснить зачем:
180
-
181
- ```python
182
- text("SELECT 1") # db-ok: raw-sql: проба живости, формы ORM нет
183
- ```
184
-
185
- Каноническая форма — `# check-ok: <код>: <причина>`, она снимает ровно одно
186
- правило. У каждой группы есть своё короткое слово (`# db-ok`, `# type-ok`,
187
- `# signature-ok`, …): человек помнит группу, а не двадцать восемь кодов.
188
-
189
- Пометок в строке может стоять несколько — подпись в столбик собирает их на
190
- последней строке:
191
-
192
- ```python
193
- ) -> object: # signature-ok: так зовёт pydantic # type-ok: сырой ввод
194
- ```
195
-
196
- Пометка без кода, с опечаткой в коде или без причины — сама нарушение. Молча
197
- неработающая пометка выглядит как отключённая проверка, а на деле проверка
198
- работает и просто её не видит.
199
-
200
- ## pre-commit
201
-
202
- ```yaml
203
- - repo: https://github.com/Armontex/py-checks
204
- rev: v0.1.0
205
- hooks:
206
- - id: py-checks
207
- args: [--fix] # починить то, что чинится само
208
- - id: py-checks-sync # контракты и `.env.example` собраны заново
209
- ```
210
-
211
- Хук один, а не по хуку на правило: что включено, решает конфиг проекта. Набор
212
- правил зовут `args: [--select, "<код>,<код>"]`; повторённый флаг делает то же
213
- самое.
214
-
215
- Ставить его нужно **до** `ruff-format`: автофикс ставит символы, а не колонки,
216
- и раскладывает подпись форматтер проекта.
217
-
218
- Всё остальное — ruff, pyright, import-linter, commitizen — проект объявляет
219
- сам: у каждого есть свой хук, написанный его же авторами.
220
-
221
- ## Контракты импортов
222
-
223
- Слои проекта описываются один раз, а `.importlinter` под них собирается:
224
-
225
- ```toml
226
- [contracts.layers]
227
- domain = ["domain"]
228
- application = ["application", "domain"]
229
- presentation = ["presentation", "application"]
230
- ```
231
-
232
- ```bash
233
- py-checks sync # собрать
234
- py-checks sync --check # упасть, если файл отстал
235
- ```
236
-
237
- Собирается он не только из таблицы, но и из того, что лежит на диске: слой,
238
- которого нет, в контракт не попадает — иначе import-linter упал бы на первом же
239
- несуществующем модуле. Гоняет граф по собранному файлу хук самого import-linter.
240
-
241
- Шапку собранного файла можно написать свою — `header` в `[contracts]`, вместе
242
- с `#`; как и у `.env.example`, нужна она проекту с комментариями на другом
243
- языке.
244
-
245
- ## Пример окружения
246
-
247
- Имя переменной знает поле настроек — оно объявляет его `validation_alias`, и
248
- за этим следит `config-fields`. Значит, `.env.example` выводится из тех же
249
- классов, что переменные и читают, и вести его рядом руками незачем: расходится
250
- он молча, а замечают это, когда переменной не оказалось на проде.
251
-
252
- ```toml
253
- [env-example]
254
- settings = ["myservice.config.settings:Settings"]
255
- ```
256
-
257
- Тот же `py-checks sync` — файл собирается вместе с контрактами. Достаточно
258
- корневого класса: свои секции он уже перечислил собственными полями, и
259
- повторять их список в настройках значит завести второй, который с первым
260
- разойдётся. Поле-секция переменной не становится — у него своего имени в
261
- окружении нет. В файл едут имя переменной, значение по умолчанию, первый абзац
262
- докстринга класса и `description` поля, если оно у него есть, — так объяснение
263
- живёт рядом с полем, а не в файле, который его переживёт.
264
-
265
- Шапку файла можно написать свою — `header = "# Generated by py-checks."`,
266
- вместе с `#`. Нужна она проекту, который пишет комментарии на другом языке;
267
- пустая оставляет шапку библиотеки.
268
-
269
- Классы импортируются, а не читаются текстом: имя переменной — значение
270
- атрибута, собранное вызовом, и прочитать его исходником значит выполнить этот
271
- вызов самому.
272
-
273
- ## Своё правило
274
-
275
- Правило — это класс с четырьмя полями и `run`, объявленный через entry points.
276
- Форкать библиотеку не нужно:
277
-
278
- ```python
279
- # myproject_checks/_no_print.py
280
- import ast
281
- from collections.abc import Iterator
282
- from typing import ClassVar, Final
283
-
284
- from py_checks.config import CheckSettings
285
- from py_checks.core import ParsedFile, Scope, Violation
286
-
287
- CODE: Final = "no-print"
288
-
289
-
290
- class NoPrint:
291
- """Падает, если в исходнике остался `print`."""
292
-
293
- code: ClassVar[str] = CODE
294
- Settings: ClassVar[type[CheckSettings]] = CheckSettings
295
- scope: ClassVar[Scope] = Scope.FILE
296
- marker: ClassVar[str] = "# my-ok"
297
-
298
- @classmethod
299
- def run(cls, *, file: ParsedFile, settings: CheckSettings) -> Iterator[Violation]:
300
- for node in ast.walk(file.tree):
301
- if isinstance(node, ast.Call) and getattr(node.func, "id", "") == "print":
302
- yield Violation.from_node(
303
- node=node,
304
- path=file.path,
305
- code=CODE,
306
- message="print в исходнике; событие пишут логом",
307
- )
308
- ```
309
-
310
- ```toml
311
- [project.entry-points."py_checks.checks"]
312
- no-print = "myproject_checks:NoPrint"
313
- ```
314
-
315
- Дальше оно ведёт себя как родное: попадает в `list`, в `explain`, слушается
316
- `ignore` и снимается пометкой.
317
-
318
- ## Команды
319
-
320
- | Команда | |
321
- |---|---|
322
- | `py-checks run [пути]` | прогнать проверки; `0` — чисто, `1` — есть нарушения |
323
- | `py-checks run --fix` | наложить правки, которые однозначны |
324
- | `py-checks run --select <код>,<код>` | только названные правила, несмотря на `ignore` |
325
- | `py-checks run --all` | вместе с правилами, которым нужна живая среда |
326
- | `py-checks list` | все правила: код, состояние, строка описания |
327
- | `py-checks explain <код>` | что правило требует и какие у него настройки |
328
- | `py-checks sync [--check]` | собрать контракты импортов и `.env.example` |
329
-
330
- ## Разработка
331
-
332
- ```bash
333
- uv sync
334
- uv run pre-commit install
335
- uv run pytest -q
336
- ```
337
-
338
- Проверка описывается не тестом, а папками с примерами: `tests/checks/<код>/`
339
- с `ok/` и `bad/` внутри, снимок вывода сверяет syrupy. У правил про проект —
340
- `tests/projects/<код>__<вариант>/`. Библиотека проверяет сама себя: правило,
341
- которое не выдерживает свой же репозиторий, до чужого доезжать не должно.
342
-
343
- Соглашения репозитория — в [`AGENTS.md`](https://github.com/Armontex/py-checks/blob/main/AGENTS.md).
344
-
345
- ## Лицензия
346
-
347
- [MIT](https://github.com/Armontex/py-checks/blob/main/LICENSE) — © 2026 Armontex.