resource-engine-devtools 0.1.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.
- resource_engine_devtools/__init__.py +6 -0
- resource_engine_devtools/ai/__init__.py +1 -0
- resource_engine_devtools/ai/example.py +66 -0
- resource_engine_devtools/ai/installer.py +424 -0
- resource_engine_devtools/ai/skill/SKILL.md +130 -0
- resource_engine_devtools/ai/skill/examples/README.md +7 -0
- resource_engine_devtools/ai/skill/examples/invoices/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/app.py +245 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/actions.py +61 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/balances.py +51 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/customers.py +35 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/hooks.py +61 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/processes.py +80 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/resource.py +112 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/schemas.py +164 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/tags.py +77 -0
- resource_engine_devtools/ai/skill/examples/invoices/authz.py +126 -0
- resource_engine_devtools/ai/skill/examples/invoices/bootstrap.py +80 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/entities.py +112 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/events.py +22 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/state_machine.py +88 -0
- resource_engine_devtools/ai/skill/examples/invoices/infrastructure/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/infrastructure/persistence.py +121 -0
- resource_engine_devtools/ai/skill/examples/invoices/locale/en/LC_MESSAGES/messages.po +682 -0
- resource_engine_devtools/ai/skill/examples/invoices/locale/es/LC_MESSAGES/messages.po +685 -0
- resource_engine_devtools/ai/skill/examples/invoices/notifications.py +47 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/base.html +7 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.html +5 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt +1 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.txt +5 -0
- resource_engine_devtools/ai/skill/examples/invoices/tests/conftest.py +40 -0
- resource_engine_devtools/ai/skill/examples/invoices/tests/test_invoices_engine.py +241 -0
- resource_engine_devtools/ai/skill/examples/invoices/worker.py +53 -0
- resource_engine_devtools/ai/skill/llms.txt +25 -0
- resource_engine_devtools/ai/skill/references/anti-patterns.md +209 -0
- resource_engine_devtools/ai/skill/references/docstrings.md +97 -0
- resource_engine_devtools/ai/skill/references/errors.md +81 -0
- resource_engine_devtools/ai/skill/references/lifecycle.md +118 -0
- resource_engine_devtools/ai/skill/references/permissions.md +111 -0
- resource_engine_devtools/ai/skill/references/resource.md +301 -0
- resource_engine_devtools/ai/skill/references/state-machines.md +126 -0
- resource_engine_devtools/ai/skill/references/testing.md +80 -0
- resource_engine_devtools/ai/templates/agents_block.md +26 -0
- resource_engine_devtools/ai/templates/cursor_rule.mdc +7 -0
- resource_engine_devtools/check.py +67 -0
- resource_engine_devtools/cli.py +1112 -0
- resource_engine_devtools/consumer_scaffold.py +715 -0
- resource_engine_devtools/contracts.py +471 -0
- resource_engine_devtools/db.py +132 -0
- resource_engine_devtools/declarations_check.py +116 -0
- resource_engine_devtools/documentation/__init__.py +10 -0
- resource_engine_devtools/documentation/docstrings.py +72 -0
- resource_engine_devtools/documentation/generators/__init__.py +9 -0
- resource_engine_devtools/documentation/generators/ai_context.py +121 -0
- resource_engine_devtools/documentation/generators/api.py +63 -0
- resource_engine_devtools/documentation/generators/json.py +12 -0
- resource_engine_devtools/documentation/generators/markdown.py +687 -0
- resource_engine_devtools/documentation/generators/mermaid.py +22 -0
- resource_engine_devtools/documentation/generators/site.py +379 -0
- resource_engine_devtools/documentation/generators/site_assets/site.css +62 -0
- resource_engine_devtools/documentation/generators/site_assets/site.js +54 -0
- resource_engine_devtools/documentation/i18n.py +185 -0
- resource_engine_devtools/documentation/introspector.py +563 -0
- resource_engine_devtools/documentation/locale/ca/LC_MESSAGES/docs.po +628 -0
- resource_engine_devtools/documentation/locale/es/LC_MESSAGES/docs.po +627 -0
- resource_engine_devtools/documentation/model.py +311 -0
- resource_engine_devtools/documentation/validator.py +128 -0
- resource_engine_devtools/emails.py +172 -0
- resource_engine_devtools/events_check.py +124 -0
- resource_engine_devtools/gates_check.py +133 -0
- resource_engine_devtools/hooks_check.py +287 -0
- resource_engine_devtools/i18n.py +312 -0
- resource_engine_devtools/loader.py +93 -0
- resource_engine_devtools/logic_check.py +136 -0
- resource_engine_devtools/mcp_server.py +685 -0
- resource_engine_devtools/py.typed +0 -0
- resource_engine_devtools/scaffold.py +805 -0
- resource_engine_devtools/scaffold_parts.py +637 -0
- resource_engine_devtools/source_edit.py +424 -0
- resource_engine_devtools/templates_check.py +59 -0
- resource_engine_devtools/worker.py +68 -0
- resource_engine_devtools-0.1.0.dist-info/METADATA +38 -0
- resource_engine_devtools-0.1.0.dist-info/RECORD +88 -0
- resource_engine_devtools-0.1.0.dist-info/WHEEL +4 -0
- resource_engine_devtools-0.1.0.dist-info/entry_points.txt +2 -0
- resource_engine_devtools-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""``resource-engine i18n``: the application's translation catalogues.
|
|
2
|
+
|
|
3
|
+
```toml
|
|
4
|
+
[tool.resource-engine.i18n]
|
|
5
|
+
directory = "invoices/locale" # <locale>/LC_MESSAGES/messages.po and .mo
|
|
6
|
+
source_locale = "ca" # the language the code's texts are written in
|
|
7
|
+
locales = ["ca", "en", "es"]
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
- ``extract``: ``messages.pot`` from the code (``_()``, ``gettext``,
|
|
11
|
+
``ngettext``, ``pgettext``), the Jinja templates (``{% trans %}``, ``_()``)
|
|
12
|
+
and the documentation texts (docstrings, descriptions, state names).
|
|
13
|
+
- ``update``: creates or updates ``<locale>/LC_MESSAGES/messages.po`` for every
|
|
14
|
+
locale but the source one, keeping translations and marking changed texts fuzzy.
|
|
15
|
+
- ``compile``: ``.po`` → ``.mo`` for the runtime (``resource_engine.i18n``).
|
|
16
|
+
- ``status``: translated, fuzzy and missing per locale; ``--strict`` fails on gaps.
|
|
17
|
+
- ``export``: a JSON catalogue per locale for front ends (the application's
|
|
18
|
+
messages and the engine's error titles by code).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
from collections.abc import Callable, Iterator
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from babel.messages.catalog import Catalog
|
|
30
|
+
from babel.messages.extract import extract_from_dir
|
|
31
|
+
from babel.messages.mofile import write_mo
|
|
32
|
+
from babel.messages.pofile import read_po, write_po
|
|
33
|
+
|
|
34
|
+
KEYWORDS = {
|
|
35
|
+
"_": None,
|
|
36
|
+
"gettext": None,
|
|
37
|
+
"ngettext": (1, 2),
|
|
38
|
+
"pgettext": ((1, "c"), 2),
|
|
39
|
+
"lazy_gettext": None,
|
|
40
|
+
}
|
|
41
|
+
TEMPLATE_EXTENSIONS = (".html", ".txt", ".xml", ".md")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class I18nConfig:
|
|
46
|
+
"""Where the application's translations live and which locales it has."""
|
|
47
|
+
|
|
48
|
+
directory: Path
|
|
49
|
+
source_locale: str = "en"
|
|
50
|
+
locales: list[str] = field(default_factory=list)
|
|
51
|
+
domain: str = "messages"
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def targets(self) -> list[str]:
|
|
55
|
+
"""Locales that need a catalogue (all but the source language)."""
|
|
56
|
+
return [loc for loc in self.locales if loc != self.source_locale]
|
|
57
|
+
|
|
58
|
+
def po(self, locale: str) -> Path:
|
|
59
|
+
"""The catalogue source of ``locale``."""
|
|
60
|
+
return self.directory / locale / "LC_MESSAGES" / f"{self.domain}.po"
|
|
61
|
+
|
|
62
|
+
def mo(self, locale: str) -> Path:
|
|
63
|
+
"""The compiled catalogue of ``locale``."""
|
|
64
|
+
return self.directory / locale / "LC_MESSAGES" / f"{self.domain}.mo"
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def pot(self) -> Path:
|
|
68
|
+
"""The template the catalogues are updated from."""
|
|
69
|
+
return self.directory / f"{self.domain}.pot"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def load_config(config: dict[str, Any], root: Path) -> I18nConfig | None:
|
|
73
|
+
"""The ``[tool.resource-engine.i18n]`` settings, if the application has them."""
|
|
74
|
+
section = config.get("i18n")
|
|
75
|
+
if not section:
|
|
76
|
+
return None
|
|
77
|
+
source = section.get("source_locale", "en")
|
|
78
|
+
locales = list(section.get("locales") or [source])
|
|
79
|
+
if source not in locales:
|
|
80
|
+
locales.insert(0, source)
|
|
81
|
+
return I18nConfig(
|
|
82
|
+
directory=root / section.get("directory", "locale"),
|
|
83
|
+
source_locale=source,
|
|
84
|
+
locales=locales,
|
|
85
|
+
domain=section.get("domain", "messages"),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ------------------------------------------------------------------ extract
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def extract(
|
|
93
|
+
config: I18nConfig, paths: list[Path], *, model: Any = None, project: str = "application"
|
|
94
|
+
) -> Catalog:
|
|
95
|
+
"""Every translatable text of the application, as a template catalogue."""
|
|
96
|
+
from resource_engine_devtools.documentation.i18n import model_texts
|
|
97
|
+
|
|
98
|
+
catalog = Catalog(project=project, locale=None, domain=config.domain, fuzzy=False)
|
|
99
|
+
method_map = [
|
|
100
|
+
("**/templates/**.html", "jinja2.ext:babel_extract"),
|
|
101
|
+
("**/templates/**.txt", "jinja2.ext:babel_extract"),
|
|
102
|
+
("**/templates/**.xml", "jinja2.ext:babel_extract"),
|
|
103
|
+
("**/templates/**.md", "jinja2.ext:babel_extract"),
|
|
104
|
+
("**/tests/**", "ignore"),
|
|
105
|
+
("**/migrations/**", "ignore"),
|
|
106
|
+
("**.py", "python"),
|
|
107
|
+
]
|
|
108
|
+
options = {"**/templates/**": {"extensions": "jinja2.ext.i18n", "trimmed": "true"}}
|
|
109
|
+
for base in paths:
|
|
110
|
+
for filename, lineno, message, comments, context in extract_from_dir(
|
|
111
|
+
str(base), method_map, options, keywords=KEYWORDS, comment_tags=("i18n:",)
|
|
112
|
+
):
|
|
113
|
+
location = (str(Path(base, filename)), lineno)
|
|
114
|
+
catalog.add(message, locations=[location], auto_comments=comments, context=context)
|
|
115
|
+
if model is not None:
|
|
116
|
+
for text, where in model_texts(model):
|
|
117
|
+
catalog.add(text, auto_comments=[f"docs:{where}".rstrip(":")])
|
|
118
|
+
return catalog
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def write_template(config: I18nConfig, catalog: Catalog) -> Path:
|
|
122
|
+
"""Write the message template (``.pot``) from the extracted catalogue."""
|
|
123
|
+
config.directory.mkdir(parents=True, exist_ok=True)
|
|
124
|
+
with config.pot.open("wb") as handle:
|
|
125
|
+
write_po(handle, catalog, width=100, sort_output=True)
|
|
126
|
+
return config.pot
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# ------------------------------------------------------------------ update
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def update(config: I18nConfig) -> dict[str, str]:
|
|
133
|
+
"""Create or update each target locale's ``.po`` from the template."""
|
|
134
|
+
with config.pot.open("rb") as handle:
|
|
135
|
+
template = read_po(handle)
|
|
136
|
+
done = {}
|
|
137
|
+
for locale in config.targets:
|
|
138
|
+
path = config.po(locale)
|
|
139
|
+
if path.exists():
|
|
140
|
+
with path.open("rb") as handle:
|
|
141
|
+
catalog = read_po(handle, locale=locale)
|
|
142
|
+
catalog.update(template, no_fuzzy_matching=False)
|
|
143
|
+
done[locale] = "updated"
|
|
144
|
+
else:
|
|
145
|
+
catalog = Catalog(locale=locale, domain=config.domain, project=template.project)
|
|
146
|
+
for message in template:
|
|
147
|
+
if message.id:
|
|
148
|
+
catalog.add(
|
|
149
|
+
message.id,
|
|
150
|
+
locations=message.locations,
|
|
151
|
+
auto_comments=message.auto_comments,
|
|
152
|
+
context=message.context,
|
|
153
|
+
)
|
|
154
|
+
done[locale] = "created"
|
|
155
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
156
|
+
with path.open("wb") as handle:
|
|
157
|
+
write_po(handle, catalog, width=100, sort_output=True, ignore_obsolete=True)
|
|
158
|
+
return done
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# ----------------------------------------------------------------- compile
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def compile_catalogues(config: I18nConfig) -> dict[str, Path]:
|
|
165
|
+
"""``.po`` → ``.mo`` (fuzzy entries left out, as gettext does)."""
|
|
166
|
+
written = {}
|
|
167
|
+
for locale in config.targets:
|
|
168
|
+
path = config.po(locale)
|
|
169
|
+
if not path.exists():
|
|
170
|
+
continue
|
|
171
|
+
with path.open("rb") as handle:
|
|
172
|
+
catalog = read_po(handle, locale=locale)
|
|
173
|
+
with config.mo(locale).open("wb") as handle:
|
|
174
|
+
write_mo(handle, catalog, use_fuzzy=False)
|
|
175
|
+
written[locale] = config.mo(locale)
|
|
176
|
+
return written
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass
|
|
180
|
+
class LocaleStatus:
|
|
181
|
+
"""How much of one locale is translated."""
|
|
182
|
+
|
|
183
|
+
locale: str
|
|
184
|
+
total: int
|
|
185
|
+
translated: int
|
|
186
|
+
fuzzy: int
|
|
187
|
+
missing: list[str]
|
|
188
|
+
compiled: bool # the .mo holds exactly the .po's translations
|
|
189
|
+
|
|
190
|
+
def to_dict(self) -> dict[str, Any]:
|
|
191
|
+
"""The status as JSON-ready data."""
|
|
192
|
+
return {
|
|
193
|
+
"locale": self.locale,
|
|
194
|
+
"total": self.total,
|
|
195
|
+
"translated": self.translated,
|
|
196
|
+
"fuzzy": self.fuzzy,
|
|
197
|
+
"missing": self.missing,
|
|
198
|
+
"compiled": self.compiled,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def status(config: I18nConfig) -> list[LocaleStatus]:
|
|
203
|
+
"""The translation status of each locale."""
|
|
204
|
+
out = []
|
|
205
|
+
for locale in config.targets:
|
|
206
|
+
path = config.po(locale)
|
|
207
|
+
if not path.exists():
|
|
208
|
+
out.append(LocaleStatus(locale, 0, 0, 0, ["(no catalogue: run i18n update)"], False))
|
|
209
|
+
continue
|
|
210
|
+
with path.open("rb") as handle:
|
|
211
|
+
catalog = read_po(handle, locale=locale)
|
|
212
|
+
messages = [m for m in catalog if m.id]
|
|
213
|
+
missing = [
|
|
214
|
+
str(m.id if isinstance(m.id, str) else m.id[0]) for m in messages if not m.string
|
|
215
|
+
]
|
|
216
|
+
fuzzy = sum(1 for m in messages if m.fuzzy and m.string)
|
|
217
|
+
compiled = _compiled(config.mo(locale), messages)
|
|
218
|
+
out.append(
|
|
219
|
+
LocaleStatus(
|
|
220
|
+
locale,
|
|
221
|
+
len(messages),
|
|
222
|
+
len(messages) - len(missing) - fuzzy,
|
|
223
|
+
fuzzy,
|
|
224
|
+
missing,
|
|
225
|
+
compiled,
|
|
226
|
+
)
|
|
227
|
+
)
|
|
228
|
+
return out
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _compiled(mo: Path, messages: list[Any]) -> bool:
|
|
232
|
+
"""Whether the ``.mo`` has the ``.po``'s current translations (by content:
|
|
233
|
+
file times mean nothing after a git checkout)."""
|
|
234
|
+
import gettext
|
|
235
|
+
|
|
236
|
+
if not mo.exists():
|
|
237
|
+
return False
|
|
238
|
+
with mo.open("rb") as handle:
|
|
239
|
+
catalogue = gettext.GNUTranslations(handle)._catalog # type: ignore[attr-defined]
|
|
240
|
+
for m in messages:
|
|
241
|
+
if not m.string or m.fuzzy:
|
|
242
|
+
continue
|
|
243
|
+
key = m.id if isinstance(m.id, str) else (m.id[0], 0)
|
|
244
|
+
if m.context:
|
|
245
|
+
key = f"{m.context}\x04{m.id}"
|
|
246
|
+
found = catalogue.get(key)
|
|
247
|
+
expected = m.string if isinstance(m.string, str) else m.string[0]
|
|
248
|
+
if found != expected:
|
|
249
|
+
return False
|
|
250
|
+
return True
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ------------------------------------------------------------- application
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def po_gettext(config: I18nConfig, locale: str) -> Callable[[str], str]:
|
|
257
|
+
"""The application's texts in ``locale``, read from its ``.po`` (no compile
|
|
258
|
+
step needed for the docs). The source locale returns texts unchanged."""
|
|
259
|
+
if locale == config.source_locale or locale.split("-")[0] == config.source_locale:
|
|
260
|
+
return lambda text: text
|
|
261
|
+
texts: dict[str, str] = {}
|
|
262
|
+
for candidate in (locale, locale.split("-")[0]):
|
|
263
|
+
path = config.po(candidate)
|
|
264
|
+
if path.exists():
|
|
265
|
+
with path.open("rb") as handle:
|
|
266
|
+
for m in read_po(handle, locale=candidate):
|
|
267
|
+
if m.id and m.string and not m.fuzzy and isinstance(m.id, str):
|
|
268
|
+
texts.setdefault(m.id, str(m.string))
|
|
269
|
+
return lambda text: texts.get(text, text)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def export(config: I18nConfig, out: Path) -> list[Path]:
|
|
273
|
+
"""One JSON file per locale for front ends: the application's messages and
|
|
274
|
+
the engine's error titles, by code."""
|
|
275
|
+
from resource_engine.errors import TITLES
|
|
276
|
+
from resource_engine.i18n import engine_translations
|
|
277
|
+
|
|
278
|
+
engine = engine_translations()
|
|
279
|
+
written = []
|
|
280
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
281
|
+
for locale in config.locales:
|
|
282
|
+
gettext = po_gettext(config, locale)
|
|
283
|
+
messages: dict[str, str] = {}
|
|
284
|
+
path = config.po(locale)
|
|
285
|
+
source = path if path.exists() else config.pot
|
|
286
|
+
if source.exists():
|
|
287
|
+
with source.open("rb") as handle:
|
|
288
|
+
for m in read_po(handle):
|
|
289
|
+
if m.id and isinstance(m.id, str) and not m.context:
|
|
290
|
+
messages[m.id] = gettext(m.id)
|
|
291
|
+
errors = {code: engine.pgettext(code, title, locale) for code, title in TITLES.items()}
|
|
292
|
+
target = out / f"{locale}.json"
|
|
293
|
+
target.write_text(
|
|
294
|
+
json.dumps(
|
|
295
|
+
{"locale": locale, "messages": messages, "errors": errors},
|
|
296
|
+
ensure_ascii=False,
|
|
297
|
+
indent=2,
|
|
298
|
+
sort_keys=True,
|
|
299
|
+
)
|
|
300
|
+
+ "\n",
|
|
301
|
+
encoding="utf-8",
|
|
302
|
+
)
|
|
303
|
+
written.append(target)
|
|
304
|
+
return written
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def iter_docs_locales(config: I18nConfig | None, wanted: list[str] | None) -> Iterator[str]:
|
|
308
|
+
"""The locales to render the docs in: the requested ones, or every configured one."""
|
|
309
|
+
if wanted:
|
|
310
|
+
yield from wanted
|
|
311
|
+
elif config is not None:
|
|
312
|
+
yield from config.locales
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Locate the application's ResourceRegistry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import sys
|
|
7
|
+
import tomllib
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
from resource_engine import ResourceRegistry
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from resource_engine.messaging import EventRouter
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def find_config(start: Path) -> dict[str, Any]:
|
|
18
|
+
"""``[tool.resource-engine]`` of the nearest ``pyproject.toml``, with its
|
|
19
|
+
directory as ``_root`` (empty when there is none)."""
|
|
20
|
+
for directory in (start, *start.parents):
|
|
21
|
+
pyproject = directory / "pyproject.toml"
|
|
22
|
+
if pyproject.is_file():
|
|
23
|
+
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
|
|
24
|
+
config = data.get("tool", {}).get("resource-engine")
|
|
25
|
+
if config:
|
|
26
|
+
return {**config, "_root": directory}
|
|
27
|
+
return {}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def add_paths(config: dict[str, Any], cwd: Path) -> None:
|
|
31
|
+
"""Put ``[tool.resource-engine] paths`` and the working directory on ``sys.path``."""
|
|
32
|
+
root = Path(config.get("_root", cwd))
|
|
33
|
+
for extra in config.get("paths", []):
|
|
34
|
+
path = str((root / str(extra)).resolve())
|
|
35
|
+
if path not in sys.path:
|
|
36
|
+
sys.path.insert(0, path)
|
|
37
|
+
if str(cwd) not in sys.path:
|
|
38
|
+
sys.path.insert(0, str(cwd))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def load_registry(spec: str | None, cwd: Path) -> ResourceRegistry:
|
|
42
|
+
"""Load ``module:attribute``, falling back to ``[tool.resource-engine] registry``."""
|
|
43
|
+
config = find_config(cwd)
|
|
44
|
+
add_paths(config, cwd)
|
|
45
|
+
spec = spec or config.get("registry")
|
|
46
|
+
if not spec:
|
|
47
|
+
raise SystemExit(
|
|
48
|
+
"No registry given. Pass --app module:attribute or set "
|
|
49
|
+
'[tool.resource-engine] registry = "pkg.bootstrap:registry" in pyproject.toml'
|
|
50
|
+
)
|
|
51
|
+
module_name, _, attr = spec.partition(":")
|
|
52
|
+
module = importlib.import_module(module_name)
|
|
53
|
+
registry = getattr(module, attr or "registry")
|
|
54
|
+
if not isinstance(registry, ResourceRegistry):
|
|
55
|
+
raise SystemExit(f"{spec} is not a ResourceRegistry")
|
|
56
|
+
return registry
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load_authz(cwd: Path) -> object | None:
|
|
60
|
+
"""``[tool.resource-engine] authz = "pkg.bootstrap:authz"`` (an ``AuthzConfig``)."""
|
|
61
|
+
spec = find_config(cwd).get("authz")
|
|
62
|
+
if not spec:
|
|
63
|
+
return None
|
|
64
|
+
module_name, _, attr = str(spec).partition(":")
|
|
65
|
+
authz: object = getattr(importlib.import_module(module_name), attr or "authz")
|
|
66
|
+
return authz
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def load_object(spec: str) -> Any:
|
|
70
|
+
"""``module:attribute``."""
|
|
71
|
+
module_name, _, attr = spec.partition(":")
|
|
72
|
+
if not attr:
|
|
73
|
+
raise SystemExit(f"{spec!r} must be module:attribute")
|
|
74
|
+
return getattr(importlib.import_module(module_name), attr)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def load_consumers(specs: list[str] | None, cwd: Path) -> list[EventRouter]:
|
|
78
|
+
"""``EventRouter`` objects from ``specs``, falling back to
|
|
79
|
+
``[tool.resource-engine] consumers``. An entry may also name a function
|
|
80
|
+
returning a router; it is called without arguments."""
|
|
81
|
+
from resource_engine.messaging import EventRouter
|
|
82
|
+
|
|
83
|
+
config = find_config(cwd)
|
|
84
|
+
add_paths(config, cwd)
|
|
85
|
+
routers = []
|
|
86
|
+
for spec in specs or config.get("consumers", []):
|
|
87
|
+
target = load_object(str(spec))
|
|
88
|
+
if not isinstance(target, EventRouter) and callable(target):
|
|
89
|
+
target = target()
|
|
90
|
+
if not isinstance(target, EventRouter):
|
|
91
|
+
raise SystemExit(f"{spec} is not an EventRouter")
|
|
92
|
+
routers.append(target)
|
|
93
|
+
return routers
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Where-logic-belongs lint (``resource-engine check``): RE-C009.
|
|
2
|
+
|
|
3
|
+
A hook or an action that writes another resource's records through
|
|
4
|
+
``ctx.repository("x")`` (``.add``, ``.update``, ``.delete``) skips that
|
|
5
|
+
resource's own lifecycle: its permissions, validation, hooks, audit entries
|
|
6
|
+
and events. Work on other resources goes through the manager: a process or a
|
|
7
|
+
consumer reacting to a domain event (``step.manager``,
|
|
8
|
+
``MessageProcessor(manager=...)``), or application code calling the manager
|
|
9
|
+
inside ``manager.transaction()`` (see docs/resources.md#where-logic-belongs).
|
|
10
|
+
|
|
11
|
+
Reading other resources (``.get``, ``.list``) is fine. Helpers defined in the
|
|
12
|
+
application are followed, a few calls deep. Resource names that aren't
|
|
13
|
+
literal strings are not followed.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import ast
|
|
19
|
+
import inspect
|
|
20
|
+
import types
|
|
21
|
+
from collections.abc import Callable, Iterator
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from resource_engine import ResourceRegistry
|
|
25
|
+
|
|
26
|
+
from resource_engine_devtools.check import Violation
|
|
27
|
+
from resource_engine_devtools.hooks_check import (
|
|
28
|
+
_UNRESOLVED,
|
|
29
|
+
MAX_DEPTH,
|
|
30
|
+
_is_application,
|
|
31
|
+
_name,
|
|
32
|
+
_parse,
|
|
33
|
+
_resolve,
|
|
34
|
+
_scope,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
WRITES = ("add", "update", "delete")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def check_logic(registry: ResourceRegistry) -> list[Violation]:
|
|
41
|
+
"""RE-C009: hooks or actions that write another resource's records directly."""
|
|
42
|
+
violations: list[Violation] = []
|
|
43
|
+
seen: set[tuple[str, int]] = set()
|
|
44
|
+
for definition in registry:
|
|
45
|
+
if definition.resource_cls.__module__.startswith("resource_engine."):
|
|
46
|
+
continue # the engine's built-in resources
|
|
47
|
+
own = {definition.name, definition.family}
|
|
48
|
+
code: list[tuple[Callable[..., Any], str]] = [
|
|
49
|
+
(hook, f"{definition.name} {key}")
|
|
50
|
+
for key, hooks in definition.hooks.items()
|
|
51
|
+
for hook in hooks
|
|
52
|
+
]
|
|
53
|
+
for action in definition.actions.values():
|
|
54
|
+
execute = getattr(action.action_cls, "execute", None)
|
|
55
|
+
if execute is not None:
|
|
56
|
+
code.append((execute, f"{definition.name} action {action.name}"))
|
|
57
|
+
for fn, where in code:
|
|
58
|
+
for path, line, other, write, chain in _writes(fn, own, depth=0, seen=set()):
|
|
59
|
+
if (path, line) in seen:
|
|
60
|
+
continue
|
|
61
|
+
seen.add((path, line))
|
|
62
|
+
via = f" (via {' → '.join(chain)})" if chain else ""
|
|
63
|
+
violations.append(
|
|
64
|
+
Violation(
|
|
65
|
+
code="RE-C009",
|
|
66
|
+
path=path,
|
|
67
|
+
line=line,
|
|
68
|
+
message=f"{_name(fn)} ({where}) writes {other} records "
|
|
69
|
+
f"({write}){via}, skipping their permissions, hooks and audit",
|
|
70
|
+
hint=f"Record a domain event and create the {other} record in a "
|
|
71
|
+
"process or consumer (step.manager, MessageProcessor(manager=)), "
|
|
72
|
+
"or call the manager from application code in "
|
|
73
|
+
"manager.transaction().",
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
return violations
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _writes(
|
|
80
|
+
fn: Callable[..., Any], own: set[str], *, depth: int, seen: set[int]
|
|
81
|
+
) -> Iterator[tuple[str, int, str, str, list[str]]]:
|
|
82
|
+
"""(path, line, other resource, write, call chain) for each write found."""
|
|
83
|
+
fn = inspect.unwrap(fn)
|
|
84
|
+
if id(fn) in seen or depth > MAX_DEPTH:
|
|
85
|
+
return
|
|
86
|
+
seen.add(id(fn))
|
|
87
|
+
parsed = _parse(fn)
|
|
88
|
+
if parsed is None:
|
|
89
|
+
return
|
|
90
|
+
tree, path, first_line = parsed
|
|
91
|
+
scope = _scope(fn)
|
|
92
|
+
repos: dict[str, str] = {} # variable → the other resource it holds
|
|
93
|
+
for node in ast.walk(tree):
|
|
94
|
+
if isinstance(node, ast.Assign | ast.AnnAssign):
|
|
95
|
+
value = node.value
|
|
96
|
+
if isinstance(value, ast.Await):
|
|
97
|
+
value = value.value
|
|
98
|
+
other = _repository_of(value)
|
|
99
|
+
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
|
100
|
+
if other is not None and other not in own:
|
|
101
|
+
for target in targets:
|
|
102
|
+
if isinstance(target, ast.Name):
|
|
103
|
+
repos[target.id] = other
|
|
104
|
+
for node in ast.walk(tree):
|
|
105
|
+
if not isinstance(node, ast.Call):
|
|
106
|
+
continue
|
|
107
|
+
func = node.func
|
|
108
|
+
line = first_line + node.lineno - 1
|
|
109
|
+
if isinstance(func, ast.Attribute) and func.attr in WRITES:
|
|
110
|
+
holder = func.value
|
|
111
|
+
other = _repository_of(holder)
|
|
112
|
+
if other is None and isinstance(holder, ast.Name):
|
|
113
|
+
other = repos.get(holder.id)
|
|
114
|
+
if other is not None and other not in own:
|
|
115
|
+
yield path, line, other, func.attr, []
|
|
116
|
+
continue
|
|
117
|
+
target = _resolve(func, scope)
|
|
118
|
+
if target is _UNRESOLVED:
|
|
119
|
+
continue
|
|
120
|
+
if isinstance(target, types.FunctionType | types.MethodType) and _is_application(target):
|
|
121
|
+
for inner in _writes(target, own, depth=depth + 1, seen=seen):
|
|
122
|
+
yield inner[0], inner[1], inner[2], inner[3], [_name(target), *inner[4]]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _repository_of(node: ast.AST | None) -> str | None:
|
|
126
|
+
"""``<anything>.repository("name")`` → ``"name"``."""
|
|
127
|
+
if not (
|
|
128
|
+
isinstance(node, ast.Call)
|
|
129
|
+
and isinstance(node.func, ast.Attribute)
|
|
130
|
+
and node.func.attr == "repository"
|
|
131
|
+
and node.args
|
|
132
|
+
and isinstance(node.args[0], ast.Constant)
|
|
133
|
+
and isinstance(node.args[0].value, str)
|
|
134
|
+
):
|
|
135
|
+
return None
|
|
136
|
+
return node.args[0].value
|