smelt-cli 0.2.0__py3-none-win_amd64.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.
- smelt/__init__.py +6 -0
- smelt/__main__.py +5 -0
- smelt/analysis/__init__.py +45 -0
- smelt/analysis/annotations.py +105 -0
- smelt/analysis/cache.py +168 -0
- smelt/analysis/context.py +147 -0
- smelt/analysis/contracts.py +210 -0
- smelt/analysis/coverage.py +377 -0
- smelt/analysis/definition_blocks.py +569 -0
- smelt/analysis/enum_values.py +217 -0
- smelt/analysis/errors.py +11 -0
- smelt/analysis/exports.py +166 -0
- smelt/analysis/files.py +279 -0
- smelt/analysis/function_usage.py +123 -0
- smelt/analysis/graphs.py +77 -0
- smelt/analysis/identity.py +64 -0
- smelt/analysis/import_cache.py +98 -0
- smelt/analysis/imports.py +452 -0
- smelt/analysis/literals.py +17 -0
- smelt/analysis/member_state.py +108 -0
- smelt/analysis/members.py +975 -0
- smelt/analysis/ordering.py +399 -0
- smelt/analysis/ordering_rewrite.py +232 -0
- smelt/analysis/package_exports.py +58 -0
- smelt/analysis/parsing.py +126 -0
- smelt/analysis/python_version.py +164 -0
- smelt/analysis/retained.py +84 -0
- smelt/analysis/syntax.py +109 -0
- smelt/analysis/test_awaits.py +91 -0
- smelt/analysis/test_cases.py +84 -0
- smelt/analysis/test_deadlines.py +90 -0
- smelt/analysis/test_outcomes.py +71 -0
- smelt/analysis/test_subprocesses.py +107 -0
- smelt/analysis/test_syntax.py +1425 -0
- smelt/analysis/test_timing.py +76 -0
- smelt/analysis/type_dispatch.py +193 -0
- smelt/analysis/workspace.py +146 -0
- smelt/cli/__init__.py +3 -0
- smelt/cli/app.py +300 -0
- smelt/cli/commands/__init__.py +62 -0
- smelt/cli/commands/adopt.py +274 -0
- smelt/cli/commands/check.py +151 -0
- smelt/cli/commands/discover.py +51 -0
- smelt/cli/commands/info.py +112 -0
- smelt/cli/session.py +163 -0
- smelt/cli/session_slots.py +43 -0
- smelt/cli/support.py +90 -0
- smelt/config/__init__.py +36 -0
- smelt/config/discovery.py +93 -0
- smelt/config/errors.py +51 -0
- smelt/config/loader.py +282 -0
- smelt/config/models.py +717 -0
- smelt/config/patterns.py +47 -0
- smelt/config/schema.py +23 -0
- smelt/config/source.py +56 -0
- smelt/config/validation.py +180 -0
- smelt/diagnostics/__init__.py +0 -0
- smelt/diagnostics/debt.py +226 -0
- smelt/diagnostics/dedupe.py +41 -0
- smelt/diagnostics/groups.py +109 -0
- smelt/diagnostics/render/__init__.py +0 -0
- smelt/diagnostics/render/machine.py +237 -0
- smelt/diagnostics/render/text.py +321 -0
- smelt/diagnostics/report.py +104 -0
- smelt/diagnostics/suppressions.py +80 -0
- smelt/diagnostics/violation.py +120 -0
- smelt/docs.py +98 -0
- smelt/engine/__init__.py +0 -0
- smelt/engine/briefing.py +630 -0
- smelt/engine/cache.py +65 -0
- smelt/engine/changes.py +260 -0
- smelt/engine/check.py +724 -0
- smelt/engine/coverage.py +151 -0
- smelt/engine/evaluation.py +291 -0
- smelt/engine/file_checks.py +94 -0
- smelt/engine/git_source.py +140 -0
- smelt/engine/inference.py +854 -0
- smelt/engine/mirror_inference.py +95 -0
- smelt/engine/native_git.py +190 -0
- smelt/engine/ordering_fixes.py +132 -0
- smelt/engine/paths.py +163 -0
- smelt/engine/result_cache.py +208 -0
- smelt/engine/rule_settings.py +164 -0
- smelt/engine/schema.py +58 -0
- smelt/engine/staged.py +75 -0
- smelt/engine/workspace.py +5 -0
- smelt/model/__init__.py +9 -0
- smelt/model/architecture.py +234 -0
- smelt/py.typed +0 -0
- smelt/rules/__init__.py +0 -0
- smelt/rules/activation.py +129 -0
- smelt/rules/base.py +131 -0
- smelt/rules/catalog.json +600 -0
- smelt/rules/common.py +164 -0
- smelt/rules/dependencies/__init__.py +0 -0
- smelt/rules/dependencies/composition_root.py +86 -0
- smelt/rules/dependencies/cycles.py +329 -0
- smelt/rules/dependencies/fanout.py +81 -0
- smelt/rules/dependencies/features.py +165 -0
- smelt/rules/dependencies/interfaces.py +84 -0
- smelt/rules/dependencies/layers.py +138 -0
- smelt/rules/dependencies/third_party.py +132 -0
- smelt/rules/member_names.py +13 -0
- smelt/rules/meta.py +74 -0
- smelt/rules/registry.py +132 -0
- smelt/rules/structure/__init__.py +0 -0
- smelt/rules/structure/assignments.py +114 -0
- smelt/rules/structure/contracts.py +71 -0
- smelt/rules/structure/coverage.py +100 -0
- smelt/rules/structure/enum_values.py +50 -0
- smelt/rules/structure/headers.py +143 -0
- smelt/rules/structure/import_style.py +145 -0
- smelt/rules/structure/layout.py +202 -0
- smelt/rules/structure/members.py +116 -0
- smelt/rules/structure/naming.py +132 -0
- smelt/rules/structure/ordering.py +83 -0
- smelt/rules/structure/package_imports.py +117 -0
- smelt/rules/structure/type_dispatch.py +79 -0
- smelt/rules/testing/__init__.py +0 -0
- smelt/rules/testing/awaits.py +46 -0
- smelt/rules/testing/cases.py +47 -0
- smelt/rules/testing/location.py +537 -0
- smelt/rules/testing/mocking.py +140 -0
- smelt/rules/testing/outcomes.py +119 -0
- smelt/rules/testing/private_access.py +93 -0
- smelt/rules/testing/public_attributes.py +62 -0
- smelt/rules/testing/public_functions.py +52 -0
- smelt/rules/testing/timing.py +62 -0
- smelt_cli-0.2.0.data/scripts/smelt.exe +0 -0
- smelt_cli-0.2.0.dist-info/METADATA +103 -0
- smelt_cli-0.2.0.dist-info/RECORD +133 -0
- smelt_cli-0.2.0.dist-info/WHEEL +4 -0
- smelt_cli-0.2.0.dist-info/sboms/smelt-cli.cyclonedx.json +5462 -0
|
@@ -0,0 +1,854 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import re
|
|
5
|
+
from collections import Counter, deque
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from smelt.analysis.exports import Namespace, namespace_of, resolve_dotted
|
|
10
|
+
from smelt.config.discovery import IGNORED_DIRS, child_packages, has_python
|
|
11
|
+
from smelt.config.patterns import module_matches
|
|
12
|
+
from smelt.engine.mirror_inference import DEFAULT_MIRROR, MirrorGuess, infer_mirror
|
|
13
|
+
from smelt.engine.workspace import (
|
|
14
|
+
WorkspaceMember,
|
|
15
|
+
import_root,
|
|
16
|
+
workspace_members,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from smelt.analysis.exports import Loader
|
|
23
|
+
# layer -> directory names, most conventional first
|
|
24
|
+
LAYER_ALIASES: dict[str, tuple[str, ...]] = {
|
|
25
|
+
"domain": ("domain", "entities"),
|
|
26
|
+
"application": ("application", "use_cases", "usecases", "services"),
|
|
27
|
+
"infrastructure": ("infrastructure", "infra", "adapters", "persistence"),
|
|
28
|
+
"presentation": ("presentation", "api", "web", "http", "interfaces", "ui"),
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
_FEATURE_CONTAINERS = (
|
|
32
|
+
"features",
|
|
33
|
+
"modules",
|
|
34
|
+
"domains",
|
|
35
|
+
"contexts",
|
|
36
|
+
"bounded_contexts",
|
|
37
|
+
"components",
|
|
38
|
+
"apps",
|
|
39
|
+
)
|
|
40
|
+
_SHARED_NAMES = ("shared", "common", "kernel", "shared_kernel")
|
|
41
|
+
# root-level modules every layer may read: settings, logging setup
|
|
42
|
+
_SHARED_MODULES = ("settings", "config", "env", "logging_config", "_logging")
|
|
43
|
+
# central packages next to the features, by the layer they usually belong to
|
|
44
|
+
_CENTRAL_NAMES: dict[str, tuple[str, ...]] = {
|
|
45
|
+
"infrastructure": (
|
|
46
|
+
"platform",
|
|
47
|
+
"infrastructure",
|
|
48
|
+
"infra",
|
|
49
|
+
"adapters",
|
|
50
|
+
"persistence",
|
|
51
|
+
"database",
|
|
52
|
+
"db",
|
|
53
|
+
"storage",
|
|
54
|
+
),
|
|
55
|
+
"presentation": ("presentation", "api", "web", "http", "interfaces"),
|
|
56
|
+
"application": ("application", "services", "use_cases"),
|
|
57
|
+
"domain": ("domain",),
|
|
58
|
+
}
|
|
59
|
+
_COMPOSITION_NAMES = (
|
|
60
|
+
"bootstrap",
|
|
61
|
+
"composition_root",
|
|
62
|
+
"container",
|
|
63
|
+
"containers",
|
|
64
|
+
"di",
|
|
65
|
+
"wiring",
|
|
66
|
+
"main",
|
|
67
|
+
"__main__",
|
|
68
|
+
"lifespan",
|
|
69
|
+
)
|
|
70
|
+
_LAYER_DEPENDENCIES: dict[str, tuple[str, ...]] = {
|
|
71
|
+
"domain": (),
|
|
72
|
+
"application": ("domain",),
|
|
73
|
+
"infrastructure": ("domain", "application"),
|
|
74
|
+
"presentation": ("application", "domain"),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class InferredLayer:
|
|
80
|
+
name: str
|
|
81
|
+
path: str
|
|
82
|
+
may_depend_on: list[str]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class CompositionCandidate:
|
|
87
|
+
"""A package that may belong to the composition root; proposed, not applied."""
|
|
88
|
+
|
|
89
|
+
module: str
|
|
90
|
+
chain: list[str] # how the composition root reaches it
|
|
91
|
+
confidence: str # medium: only the root imports it; low: others do too
|
|
92
|
+
reason: str
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class InferredConfig:
|
|
97
|
+
root_packages: list[str]
|
|
98
|
+
source_roots: list[str]
|
|
99
|
+
test_roots: list[str]
|
|
100
|
+
features_root: str | None = None
|
|
101
|
+
features_pattern: str | None = None
|
|
102
|
+
features: list[str] = field(default_factory=list)
|
|
103
|
+
shared: list[str] = field(default_factory=list)
|
|
104
|
+
composition_root: list[str] = field(default_factory=list)
|
|
105
|
+
wiring: list[str] = field(default_factory=list)
|
|
106
|
+
modules: dict[str, str] = field(default_factory=dict)
|
|
107
|
+
unclassified_roots: list[str] = field(default_factory=list)
|
|
108
|
+
mirror: MirrorGuess | None = None
|
|
109
|
+
layers: list[InferredLayer] = field(default_factory=list)
|
|
110
|
+
tests_layout: str = "none"
|
|
111
|
+
members: list[WorkspaceMember] = field(default_factory=list)
|
|
112
|
+
# composition root or wiring module -> why init put it there
|
|
113
|
+
evidence: dict[str, str] = field(default_factory=dict)
|
|
114
|
+
candidates: list[CompositionCandidate] = field(default_factory=list)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def has_features(self) -> bool:
|
|
118
|
+
return self.features_root is not None or self.features_pattern is not None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def infer_config(root: Path) -> InferredConfig | None:
|
|
122
|
+
members = workspace_members(root)
|
|
123
|
+
located = import_root(root)
|
|
124
|
+
member_directories = {(root / member.path).resolve() for member in members}
|
|
125
|
+
packages = (
|
|
126
|
+
[
|
|
127
|
+
package
|
|
128
|
+
for package in located[1]
|
|
129
|
+
if package.resolve() not in member_directories
|
|
130
|
+
]
|
|
131
|
+
if located
|
|
132
|
+
else []
|
|
133
|
+
)
|
|
134
|
+
source_roots = (
|
|
135
|
+
[located[0].relative_to(root).as_posix()] if located and packages else []
|
|
136
|
+
)
|
|
137
|
+
member_roots: list[Path] = []
|
|
138
|
+
for member in members:
|
|
139
|
+
if member.source_root is None:
|
|
140
|
+
continue
|
|
141
|
+
packages.extend(root / member.source_root / name for name in member.packages)
|
|
142
|
+
source_roots.append(member.source_root)
|
|
143
|
+
member_roots.append(root / member.path)
|
|
144
|
+
if not packages:
|
|
145
|
+
return None
|
|
146
|
+
test_roots = [name for name in ("tests", "test") if (root / name).is_dir()]
|
|
147
|
+
test_roots.extend(
|
|
148
|
+
(member / name).relative_to(root).as_posix()
|
|
149
|
+
for member in member_roots
|
|
150
|
+
for name in ("tests", "test")
|
|
151
|
+
if (member / name).is_dir()
|
|
152
|
+
)
|
|
153
|
+
inferred = InferredConfig(
|
|
154
|
+
root_packages=list(dict.fromkeys(p.name for p in packages)),
|
|
155
|
+
source_roots=list(dict.fromkeys(source_roots)),
|
|
156
|
+
test_roots=test_roots or ["tests"],
|
|
157
|
+
members=members,
|
|
158
|
+
)
|
|
159
|
+
_infer_features(inferred, packages)
|
|
160
|
+
containers = _layer_containers(inferred, packages)
|
|
161
|
+
_infer_layers(inferred, containers)
|
|
162
|
+
if inferred.has_features and not inferred.layers:
|
|
163
|
+
inferred.features_root = inferred.features_pattern = None
|
|
164
|
+
inferred.features = []
|
|
165
|
+
_infer_special_modules(inferred, packages)
|
|
166
|
+
_infer_wiring(inferred, packages)
|
|
167
|
+
_infer_app_factories(inferred, packages)
|
|
168
|
+
traces = _infer_assemblies(inferred, packages)
|
|
169
|
+
_infer_central_modules(inferred, packages)
|
|
170
|
+
_infer_candidates(inferred, packages, traces)
|
|
171
|
+
inferred.wiring = _wiring_patterns(inferred.wiring, _all_modules(packages))
|
|
172
|
+
inferred.mirror = infer_mirror(root, inferred.test_roots, packages)
|
|
173
|
+
if inferred.mirror is not None:
|
|
174
|
+
inferred.tests_layout = "mirror"
|
|
175
|
+
return inferred
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _infer_features(inferred: InferredConfig, packages: list[Path]) -> None:
|
|
179
|
+
for package in packages:
|
|
180
|
+
for depth_one in [package, *child_packages(package)]:
|
|
181
|
+
for name in _FEATURE_CONTAINERS:
|
|
182
|
+
candidate = depth_one / name
|
|
183
|
+
children = child_packages(candidate)
|
|
184
|
+
if children:
|
|
185
|
+
dotted = ".".join(candidate.relative_to(package.parent).parts)
|
|
186
|
+
inferred.features_root = dotted
|
|
187
|
+
inferred.features = [c.name for c in children]
|
|
188
|
+
return
|
|
189
|
+
layer_names = {alias for aliases in LAYER_ALIASES.values() for alias in aliases}
|
|
190
|
+
for package in packages:
|
|
191
|
+
layered = [
|
|
192
|
+
child
|
|
193
|
+
for child in child_packages(package)
|
|
194
|
+
if child.name not in _SHARED_NAMES
|
|
195
|
+
and len({c.name for c in child_packages(child)} & layer_names) >= 2 # noqa: PLR2004
|
|
196
|
+
]
|
|
197
|
+
if len(layered) >= 2: # noqa: PLR2004
|
|
198
|
+
inferred.features_pattern = f"{package.name}.{{feature}}"
|
|
199
|
+
inferred.features = [child.name for child in layered]
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _layer_containers(inferred: InferredConfig, packages: list[Path]) -> list[Path]:
|
|
204
|
+
by_name = {p.name: p for p in packages}
|
|
205
|
+
if inferred.features_root is not None:
|
|
206
|
+
first, *rest = inferred.features_root.split(".")
|
|
207
|
+
container = by_name[first].joinpath(*rest)
|
|
208
|
+
return child_packages(container)
|
|
209
|
+
if inferred.features_pattern is not None:
|
|
210
|
+
root_name = inferred.features_pattern.split(".")[0]
|
|
211
|
+
return [by_name[root_name] / name for name in inferred.features]
|
|
212
|
+
return packages
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _infer_layers(inferred: InferredConfig, containers: list[Path]) -> None:
|
|
216
|
+
counts: Counter[str] = Counter(
|
|
217
|
+
child.name for container in containers for child in child_packages(container)
|
|
218
|
+
)
|
|
219
|
+
found: dict[str, str] = {}
|
|
220
|
+
for name, aliases in LAYER_ALIASES.items():
|
|
221
|
+
count, _, alias = max(
|
|
222
|
+
(counts[alias], -index, alias) for index, alias in enumerate(aliases)
|
|
223
|
+
)
|
|
224
|
+
if count > 0:
|
|
225
|
+
found[name] = alias
|
|
226
|
+
inferred.layers = [
|
|
227
|
+
InferredLayer(name, path, _dependencies(name, found))
|
|
228
|
+
for name, path in found.items()
|
|
229
|
+
]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _dependencies(layer: str, found: dict[str, str]) -> list[str]:
|
|
233
|
+
if layer == "presentation" and "application" not in found:
|
|
234
|
+
return ["domain"] if "domain" in found else []
|
|
235
|
+
return [dep for dep in _LAYER_DEPENDENCIES[layer] if dep in found]
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _infer_special_modules(inferred: InferredConfig, packages: list[Path]) -> None:
|
|
239
|
+
for package in packages:
|
|
240
|
+
for name in _SHARED_NAMES:
|
|
241
|
+
if has_python(package / name):
|
|
242
|
+
inferred.shared.append(f"{package.name}.{name}")
|
|
243
|
+
for name in _COMPOSITION_NAMES:
|
|
244
|
+
if (package / f"{name}.py").is_file() or has_python(package / name):
|
|
245
|
+
inferred.composition_root.append(f"{package.name}.{name}")
|
|
246
|
+
for name in _SHARED_MODULES:
|
|
247
|
+
if (package / f"{name}.py").is_file():
|
|
248
|
+
inferred.shared.append(f"{package.name}.{name}")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _infer_app_factories(inferred: InferredConfig, packages: list[Path]) -> None:
|
|
252
|
+
"""Root-level modules between the entry point and the wiring, like ``app.py``.
|
|
253
|
+
|
|
254
|
+
A module counts when a composition root refers to it, by import or as a
|
|
255
|
+
``"backend.app:app"`` server target, and it reaches a composition root or
|
|
256
|
+
wiring module itself: it assembles the app and is part of the root. Package
|
|
257
|
+
facades count as the wiring they re-export: ``app.py`` importing
|
|
258
|
+
``backend.features``, whose ``__init__`` collects the feature providers.
|
|
259
|
+
"""
|
|
260
|
+
load = _loader(packages)
|
|
261
|
+
roots = list(inferred.composition_root)
|
|
262
|
+
targets = [*roots, *inferred.wiring]
|
|
263
|
+
for package in packages:
|
|
264
|
+
for path in sorted(package.glob("*.py")):
|
|
265
|
+
module = f"{package.name}.{path.stem}"
|
|
266
|
+
if path.stem == "__init__" or module in roots or module in inferred.shared:
|
|
267
|
+
continue
|
|
268
|
+
referred = next(
|
|
269
|
+
(
|
|
270
|
+
(root, how)
|
|
271
|
+
for root in roots
|
|
272
|
+
if (how := _reference(packages, root, module)) is not None
|
|
273
|
+
),
|
|
274
|
+
None,
|
|
275
|
+
)
|
|
276
|
+
if referred is None:
|
|
277
|
+
continue
|
|
278
|
+
imports = _imports(path, package.name)
|
|
279
|
+
reached = _first_hit(_trace(load, module), targets) or next(
|
|
280
|
+
(
|
|
281
|
+
f"{name}, which re-exports wiring"
|
|
282
|
+
for name in sorted(imports)
|
|
283
|
+
if _reaches(packages, name, targets)
|
|
284
|
+
),
|
|
285
|
+
None,
|
|
286
|
+
)
|
|
287
|
+
if reached is None:
|
|
288
|
+
continue
|
|
289
|
+
root, how = referred
|
|
290
|
+
inferred.composition_root.append(module)
|
|
291
|
+
inferred.evidence[module] = f"{root} {how} it; {reached}"
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _infer_assemblies(
|
|
295
|
+
inferred: InferredConfig, packages: list[Path]
|
|
296
|
+
) -> dict[str, dict[_Node, _Node | None]]:
|
|
297
|
+
"""Modules that assemble wiring for the composition root become wiring too.
|
|
298
|
+
|
|
299
|
+
From each composition root, the names it imports are followed to where they are
|
|
300
|
+
defined and on through the names those definitions use: ``app.py`` imports
|
|
301
|
+
``FEATURES`` from the features facade, which lists ``telegram.feature``, defined
|
|
302
|
+
in ``telegram/feature.py`` from ``TelegramProvider`` in ``telegram/di.py``. A
|
|
303
|
+
module (not a facade) whose definition refers to wiring builds the app from it,
|
|
304
|
+
as the wiring itself does. Merely importing a framework type is no assembly.
|
|
305
|
+
"""
|
|
306
|
+
load = _loader(packages)
|
|
307
|
+
traces: dict[str, dict[_Node, _Node | None]] = {}
|
|
308
|
+
for root in list(inferred.composition_root):
|
|
309
|
+
parents = _trace(load, root)
|
|
310
|
+
traces[root] = parents
|
|
311
|
+
for node, parent in parents.items():
|
|
312
|
+
if parent is None or not _within_any(node[0], inferred.wiring):
|
|
313
|
+
continue
|
|
314
|
+
module = parent[0]
|
|
315
|
+
path = _module_file(packages, module)
|
|
316
|
+
taken = [*inferred.composition_root, *inferred.wiring, *inferred.shared]
|
|
317
|
+
if path is None or path.name == "__init__.py" or _within_any(module, taken):
|
|
318
|
+
continue
|
|
319
|
+
inferred.wiring.append(module)
|
|
320
|
+
inferred.evidence[module] = " → ".join(_chain(parents, node))
|
|
321
|
+
inferred.wiring.sort()
|
|
322
|
+
return traces
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _infer_candidates(
|
|
326
|
+
inferred: InferredConfig,
|
|
327
|
+
packages: list[Path],
|
|
328
|
+
traces: dict[str, dict[_Node, _Node | None]],
|
|
329
|
+
) -> None:
|
|
330
|
+
"""Unclassified packages the composition root uses: proposed, not applied.
|
|
331
|
+
|
|
332
|
+
``app.py`` mounting ``backend.rpc.feature`` suggests that ``backend.rpc`` belongs
|
|
333
|
+
to the root too, but it may also be an ordinary package missing a layer.
|
|
334
|
+
"""
|
|
335
|
+
container = (
|
|
336
|
+
inferred.features_root or (inferred.features_pattern or "").rsplit(".", 1)[0]
|
|
337
|
+
)
|
|
338
|
+
classified = [
|
|
339
|
+
*inferred.shared,
|
|
340
|
+
*inferred.composition_root,
|
|
341
|
+
*inferred.wiring,
|
|
342
|
+
*inferred.modules,
|
|
343
|
+
*([container] if container else []),
|
|
344
|
+
]
|
|
345
|
+
found: dict[str, list[str]] = {}
|
|
346
|
+
for root, parents in traces.items():
|
|
347
|
+
for node in parents:
|
|
348
|
+
package = ".".join(node[0].split(".")[:2])
|
|
349
|
+
if (
|
|
350
|
+
package.count(".") != 1
|
|
351
|
+
or package.split(".")[0] != root.split(".")[0]
|
|
352
|
+
or _within_any(package, classified)
|
|
353
|
+
or package in found
|
|
354
|
+
):
|
|
355
|
+
continue
|
|
356
|
+
found[package] = _chain(parents, node)
|
|
357
|
+
if not found:
|
|
358
|
+
return
|
|
359
|
+
modules = sorted(_all_modules(packages))
|
|
360
|
+
roots = set(inferred.composition_root)
|
|
361
|
+
for package, chain in found.items():
|
|
362
|
+
importers = {
|
|
363
|
+
module
|
|
364
|
+
for module in modules
|
|
365
|
+
if not _within_any(module, [package])
|
|
366
|
+
and any(
|
|
367
|
+
_within_any(name, [package])
|
|
368
|
+
for name in _module_imports(packages, module)
|
|
369
|
+
)
|
|
370
|
+
}
|
|
371
|
+
others = sorted(importers - roots)
|
|
372
|
+
reason = (
|
|
373
|
+
f"also imported by {', '.join(others[:3])}"
|
|
374
|
+
if others
|
|
375
|
+
else "only the composition root imports it"
|
|
376
|
+
)
|
|
377
|
+
confidence = "low" if others else "medium"
|
|
378
|
+
inferred.candidates.append(
|
|
379
|
+
CompositionCandidate(package, chain, confidence, reason)
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _infer_central_modules(inferred: InferredConfig, packages: list[Path]) -> None:
|
|
384
|
+
"""Map packages beside the features to a layer by their name."""
|
|
385
|
+
if not inferred.has_features:
|
|
386
|
+
return
|
|
387
|
+
layers = {layer.name for layer in inferred.layers}
|
|
388
|
+
container = (
|
|
389
|
+
inferred.features_root or (inferred.features_pattern or "").rsplit(".", 1)[0]
|
|
390
|
+
)
|
|
391
|
+
taken = [*inferred.shared, *inferred.composition_root]
|
|
392
|
+
for package in packages:
|
|
393
|
+
if not _within_any(container, [package.name]):
|
|
394
|
+
inferred.unclassified_roots.append(package.name)
|
|
395
|
+
continue
|
|
396
|
+
for child in child_packages(package):
|
|
397
|
+
module = f"{package.name}.{child.name}"
|
|
398
|
+
if _within_any(container, [module]) or _within_any(module, taken):
|
|
399
|
+
continue
|
|
400
|
+
if inferred.features_pattern and child.name in inferred.features:
|
|
401
|
+
continue
|
|
402
|
+
layer = next(
|
|
403
|
+
(
|
|
404
|
+
name
|
|
405
|
+
for name, aliases in _CENTRAL_NAMES.items()
|
|
406
|
+
if child.name in aliases and name in layers
|
|
407
|
+
),
|
|
408
|
+
None,
|
|
409
|
+
)
|
|
410
|
+
if layer is not None:
|
|
411
|
+
inferred.modules[module] = layer
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _wiring_patterns(modules: list[str], known: set[str]) -> list[str]:
|
|
415
|
+
"""Collapse ``a.x.di`` and ``a.y.di`` into ``a.*.di`` when it matches only wiring."""
|
|
416
|
+
remaining = sorted(modules)
|
|
417
|
+
patterns: list[str] = []
|
|
418
|
+
while remaining:
|
|
419
|
+
parts = remaining[0].split(".")
|
|
420
|
+
best: tuple[str, list[str]] | None = None
|
|
421
|
+
for index in range(1, len(parts)):
|
|
422
|
+
pattern = ".".join([*parts[:index], "*", *parts[index + 1 :]])
|
|
423
|
+
group = [m for m in remaining if module_matches(pattern, m)]
|
|
424
|
+
exact = all(m in modules for m in known if module_matches(pattern, m))
|
|
425
|
+
if len(group) > 1 and exact and (best is None or len(group) > len(best[1])):
|
|
426
|
+
best = (pattern, group)
|
|
427
|
+
if best is None:
|
|
428
|
+
patterns.append(remaining.pop(0))
|
|
429
|
+
continue
|
|
430
|
+
patterns.append(best[0])
|
|
431
|
+
remaining = [m for m in remaining if m not in best[1]]
|
|
432
|
+
return sorted(patterns)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _all_modules(packages: list[Path]) -> set[str]:
|
|
436
|
+
found: set[str] = set()
|
|
437
|
+
for package in packages:
|
|
438
|
+
for path in package.rglob("*.py"):
|
|
439
|
+
parts = path.relative_to(package.parent).with_suffix("").parts
|
|
440
|
+
if parts[-1] == "__init__":
|
|
441
|
+
parts = parts[:-1]
|
|
442
|
+
found.add(".".join(parts))
|
|
443
|
+
return found
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _module_file(packages: list[Path], module: str) -> Path | None:
|
|
447
|
+
first, *rest = module.split(".")
|
|
448
|
+
for package in packages:
|
|
449
|
+
if package.name == first:
|
|
450
|
+
candidate = package.joinpath(*rest)
|
|
451
|
+
if candidate.with_suffix(".py").is_file():
|
|
452
|
+
return candidate.with_suffix(".py")
|
|
453
|
+
if (candidate / "__init__.py").is_file():
|
|
454
|
+
return candidate / "__init__.py"
|
|
455
|
+
return None
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _reaches(
|
|
459
|
+
packages: list[Path],
|
|
460
|
+
name: str,
|
|
461
|
+
targets: list[str],
|
|
462
|
+
depth: int = 3,
|
|
463
|
+
seen: set[str] | None = None,
|
|
464
|
+
) -> bool:
|
|
465
|
+
"""``name`` is one of ``targets`` or a package facade re-exporting one."""
|
|
466
|
+
if _within_any(name, targets):
|
|
467
|
+
return True
|
|
468
|
+
seen = set() if seen is None else seen
|
|
469
|
+
path = _module_file(packages, name)
|
|
470
|
+
if depth == 0 or path is None or path.name != "__init__.py" or name in seen:
|
|
471
|
+
return False
|
|
472
|
+
seen.add(name)
|
|
473
|
+
return any(
|
|
474
|
+
_reaches(packages, imported, targets, depth - 1, seen)
|
|
475
|
+
for imported in sorted(_module_imports(packages, name))
|
|
476
|
+
if _within_any(imported, [name])
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
type _Node = tuple[str, str | None]
|
|
481
|
+
# Symbols followed from one composition root; plenty for hundreds of features.
|
|
482
|
+
_TRACE_LIMIT = 2000
|
|
483
|
+
_SERVER_TARGET = re.compile(r"([A-Za-z_][\w.]*):([A-Za-z_]\w*)")
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def render_config(inferred: InferredConfig, *, maintainability: bool = False) -> str:
|
|
487
|
+
out = [
|
|
488
|
+
"# yaml-language-server: $schema=.smelt.schema.json",
|
|
489
|
+
"# Python guardrails for smelt. Reference: `smelt config schema`,",
|
|
490
|
+
"# rule details: `smelt explain <code>`.",
|
|
491
|
+
"version: 1",
|
|
492
|
+
]
|
|
493
|
+
out.extend(
|
|
494
|
+
[
|
|
495
|
+
"",
|
|
496
|
+
"project:",
|
|
497
|
+
f" source_roots: {_list(inferred.source_roots)}",
|
|
498
|
+
f" # root_packages: {_list(inferred.root_packages)} # discovered from source_roots",
|
|
499
|
+
f" test_roots: {_list(inferred.test_roots)}",
|
|
500
|
+
' # exclude: ["**/migrations/**"]',
|
|
501
|
+
]
|
|
502
|
+
)
|
|
503
|
+
out.extend(
|
|
504
|
+
f" # not analyzed: workspace member {member.path} ({member.skipped})"
|
|
505
|
+
for member in inferred.members
|
|
506
|
+
if member.skipped
|
|
507
|
+
)
|
|
508
|
+
if not maintainability or inferred.layers:
|
|
509
|
+
out.extend(["", "architecture:"])
|
|
510
|
+
out.extend(_architecture(inferred))
|
|
511
|
+
out.extend(
|
|
512
|
+
[
|
|
513
|
+
"",
|
|
514
|
+
"# Optional naming convention:",
|
|
515
|
+
"# structure:",
|
|
516
|
+
"# forbidden_names: [utils, helpers]",
|
|
517
|
+
"",
|
|
518
|
+
"tests:",
|
|
519
|
+
" layout: none # opt in to mirror after reviewing the test layout",
|
|
520
|
+
]
|
|
521
|
+
)
|
|
522
|
+
if inferred.mirror is not None and inferred.mirror.pattern != DEFAULT_MIRROR:
|
|
523
|
+
out.append(f' mirror: "{inferred.mirror.pattern}"')
|
|
524
|
+
if inferred.tests_layout == "mirror":
|
|
525
|
+
out.append(" # Detected a mirrored layout; use layout: mirror to enforce it.")
|
|
526
|
+
if maintainability:
|
|
527
|
+
out.extend(
|
|
528
|
+
[
|
|
529
|
+
"",
|
|
530
|
+
"# Each named check is explicit; hover for examples and analysis limits.",
|
|
531
|
+
"rules:",
|
|
532
|
+
" public-definitions-first: error",
|
|
533
|
+
" bundled-instance-assignment: error",
|
|
534
|
+
" internal-public-member: warning",
|
|
535
|
+
" internal-static-helper: hint",
|
|
536
|
+
" test-without-outcome-check: warning",
|
|
537
|
+
" test-only-checks-possibly-empty-data: warning",
|
|
538
|
+
" unbounded-test-wait: warning",
|
|
539
|
+
" independent-test-case-loop: hint",
|
|
540
|
+
" async-mock-without-await-check: warning",
|
|
541
|
+
" test-only-public-function: warning",
|
|
542
|
+
" test-only-public-attribute: warning",
|
|
543
|
+
]
|
|
544
|
+
)
|
|
545
|
+
out.extend(
|
|
546
|
+
[
|
|
547
|
+
"",
|
|
548
|
+
"# Severity overrides by rule name or code: error | warning | hint | off",
|
|
549
|
+
"# rules:",
|
|
550
|
+
"# SMT104: error # opt in to import-cycle detection",
|
|
551
|
+
"# SMT305: warning # opt in to unclassified-module hints",
|
|
552
|
+
"# unclassified-module: off # same as SMT305: off",
|
|
553
|
+
"",
|
|
554
|
+
"# Adopt incrementally: `smelt debt` records today's violations.",
|
|
555
|
+
"# debt: .smelt/debt.json",
|
|
556
|
+
]
|
|
557
|
+
)
|
|
558
|
+
return "\n".join(out) + "\n"
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _loader(packages: list[Path]) -> Loader:
|
|
562
|
+
cache: dict[str, Namespace | None] = {}
|
|
563
|
+
|
|
564
|
+
def load(module: str) -> Namespace | None:
|
|
565
|
+
if module not in cache:
|
|
566
|
+
path = _module_file(packages, module)
|
|
567
|
+
cache[module] = None if path is None else _namespace(path, module)
|
|
568
|
+
return cache[module]
|
|
569
|
+
|
|
570
|
+
return load
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _namespace(path: Path, module: str) -> Namespace | None:
|
|
574
|
+
try:
|
|
575
|
+
tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
|
|
576
|
+
except SyntaxError:
|
|
577
|
+
return None
|
|
578
|
+
return namespace_of(tree, module, is_package=path.name == "__init__.py")
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _reference(packages: list[Path], root: str, module: str) -> str | None:
|
|
582
|
+
"""How ``root`` refers to ``module``: an import or a ``"module:attr"`` string."""
|
|
583
|
+
if module in _module_imports(packages, root):
|
|
584
|
+
return "imports"
|
|
585
|
+
for target in _server_targets(packages, root):
|
|
586
|
+
if target.split(":")[0] == module:
|
|
587
|
+
return f'serves "{target}" from'
|
|
588
|
+
return None
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _server_targets(packages: list[Path], module: str) -> list[str]:
|
|
592
|
+
"""``"backend.app:app"`` strings naming a first-party module, as uvicorn takes them."""
|
|
593
|
+
path = _module_file(packages, module)
|
|
594
|
+
if path is None:
|
|
595
|
+
return []
|
|
596
|
+
try:
|
|
597
|
+
tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
|
|
598
|
+
except SyntaxError:
|
|
599
|
+
return []
|
|
600
|
+
return [
|
|
601
|
+
node.value
|
|
602
|
+
for node in ast.walk(tree)
|
|
603
|
+
if isinstance(node, ast.Constant)
|
|
604
|
+
and isinstance(node.value, str)
|
|
605
|
+
and (match := _SERVER_TARGET.fullmatch(node.value))
|
|
606
|
+
and _module_file(packages, match.group(1)) is not None
|
|
607
|
+
]
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _trace(load: Loader, root: str) -> dict[_Node, _Node | None]:
|
|
611
|
+
"""Every symbol ``root`` uses, and those their definitions use, by first referrer.
|
|
612
|
+
|
|
613
|
+
Each symbol is visited once and the walk stops at ``_TRACE_LIMIT``, so cycles
|
|
614
|
+
and huge graphs end.
|
|
615
|
+
"""
|
|
616
|
+
start: _Node = (root, None)
|
|
617
|
+
parents: dict[_Node, _Node | None] = {start: None}
|
|
618
|
+
namespace = load(root)
|
|
619
|
+
if namespace is None:
|
|
620
|
+
return parents
|
|
621
|
+
queue: deque[_Node] = deque()
|
|
622
|
+
for local in sorted(namespace.defined | namespace.imported.keys()):
|
|
623
|
+
node = (
|
|
624
|
+
resolve_dotted(namespace.imported[local], load)
|
|
625
|
+
if local in namespace.imported
|
|
626
|
+
else (root, local)
|
|
627
|
+
)
|
|
628
|
+
if node is not None and node not in parents:
|
|
629
|
+
parents[node] = start
|
|
630
|
+
queue.append(node)
|
|
631
|
+
while queue and len(parents) < _TRACE_LIMIT:
|
|
632
|
+
module, name = queue.popleft()
|
|
633
|
+
namespace = load(module)
|
|
634
|
+
if namespace is None or name is None:
|
|
635
|
+
continue
|
|
636
|
+
for head, *rest in namespace.references.get(name, ()):
|
|
637
|
+
target: _Node | None = None
|
|
638
|
+
if head in namespace.defined:
|
|
639
|
+
target = (module, head)
|
|
640
|
+
elif head in namespace.imported:
|
|
641
|
+
dotted = ".".join([namespace.imported[head], *rest])
|
|
642
|
+
target = resolve_dotted(dotted, load)
|
|
643
|
+
if target is not None and target not in parents:
|
|
644
|
+
parents[target] = (module, name)
|
|
645
|
+
queue.append(target)
|
|
646
|
+
return parents
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _first_hit(parents: dict[_Node, _Node | None], targets: list[str]) -> str | None:
|
|
650
|
+
"""The first traced module among ``targets``, with the chain that leads there."""
|
|
651
|
+
for node, parent in parents.items():
|
|
652
|
+
if parent is not None and _within_any(node[0], targets):
|
|
653
|
+
return " → ".join(_chain(parents, node))
|
|
654
|
+
return None
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _chain(parents: dict[_Node, _Node | None], node: _Node) -> list[str]:
|
|
658
|
+
"""``backend.app → backend.features.FEATURES → … → telegram.di.TelegramProvider``."""
|
|
659
|
+
labels: list[str] = []
|
|
660
|
+
current: _Node | None = node
|
|
661
|
+
while current is not None:
|
|
662
|
+
module, name = current
|
|
663
|
+
labels.append(f"{module}.{name}" if name else module)
|
|
664
|
+
current = parents.get(current)
|
|
665
|
+
return list(reversed(labels))
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def _module_imports(packages: list[Path], module: str) -> set[str]:
|
|
669
|
+
"""Absolute names ``module`` imports; relative ones resolved from its package."""
|
|
670
|
+
path = _module_file(packages, module)
|
|
671
|
+
if path is None:
|
|
672
|
+
return set()
|
|
673
|
+
parent = module if path.name == "__init__.py" else module.rsplit(".", 1)[0]
|
|
674
|
+
return _imports(path, parent)
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _imports(path: Path | None, package: str) -> set[str]:
|
|
678
|
+
"""Absolute names a module directly inside ``package`` imports."""
|
|
679
|
+
if path is None:
|
|
680
|
+
return set()
|
|
681
|
+
try:
|
|
682
|
+
tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
|
|
683
|
+
except SyntaxError:
|
|
684
|
+
return set()
|
|
685
|
+
found: set[str] = set()
|
|
686
|
+
for node in ast.walk(tree):
|
|
687
|
+
if isinstance(node, ast.Import):
|
|
688
|
+
found.update(alias.name for alias in node.names)
|
|
689
|
+
elif isinstance(node, ast.ImportFrom):
|
|
690
|
+
base = node.module or ""
|
|
691
|
+
if node.level:
|
|
692
|
+
parent = package.rsplit(".", node.level - 1)[0]
|
|
693
|
+
base = f"{parent}.{base}" if base else parent
|
|
694
|
+
found.add(base)
|
|
695
|
+
found.update(f"{base}.{alias.name}" for alias in node.names)
|
|
696
|
+
return found
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _within_any(module: str, packages: list[str]) -> bool:
|
|
700
|
+
return any(
|
|
701
|
+
module == package or module.startswith(f"{package}.") for package in packages
|
|
702
|
+
)
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def _infer_wiring(inferred: InferredConfig, packages: list[Path]) -> None:
|
|
706
|
+
for package in packages:
|
|
707
|
+
for path in package.rglob("*.py"):
|
|
708
|
+
relative = path.relative_to(package.parent)
|
|
709
|
+
if any(part in IGNORED_DIRS for part in relative.parts):
|
|
710
|
+
continue
|
|
711
|
+
content = path.read_text(encoding="utf-8", errors="replace")
|
|
712
|
+
if "from dishka import" not in content or not re.search(
|
|
713
|
+
r"class\s+\w+\s*\(\s*Provider\b", content
|
|
714
|
+
):
|
|
715
|
+
continue
|
|
716
|
+
inferred.wiring.append(".".join(relative.with_suffix("").parts))
|
|
717
|
+
inferred.wiring.sort()
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def _architecture(inferred: InferredConfig) -> list[str]:
|
|
721
|
+
out: list[str] = []
|
|
722
|
+
if inferred.features_root is not None:
|
|
723
|
+
out.append(" features:")
|
|
724
|
+
out.append(
|
|
725
|
+
f" root: {inferred.features_root} # every direct child package is a feature"
|
|
726
|
+
)
|
|
727
|
+
elif inferred.features_pattern is not None:
|
|
728
|
+
out.append(" features:")
|
|
729
|
+
out.append(f' pattern: "{inferred.features_pattern}"')
|
|
730
|
+
else:
|
|
731
|
+
out.append(" # features:")
|
|
732
|
+
out.append(
|
|
733
|
+
" # root: myapp.features # every direct child package is a feature"
|
|
734
|
+
)
|
|
735
|
+
if inferred.shared:
|
|
736
|
+
out.append(
|
|
737
|
+
f" shared: {_list(inferred.shared)} # importable everywhere; must not import features"
|
|
738
|
+
)
|
|
739
|
+
else:
|
|
740
|
+
out.append(" # shared: [myapp.shared]")
|
|
741
|
+
out.extend(_composition_lines(inferred))
|
|
742
|
+
out.extend(_wiring_lines(inferred.wiring, inferred.evidence))
|
|
743
|
+
out.extend(_module_lines(inferred))
|
|
744
|
+
out.append("")
|
|
745
|
+
if inferred.layers:
|
|
746
|
+
out.append(" layers:")
|
|
747
|
+
for layer in inferred.layers:
|
|
748
|
+
out.extend(
|
|
749
|
+
[
|
|
750
|
+
f" {layer.name}:",
|
|
751
|
+
f" path: {layer.path}",
|
|
752
|
+
f" may_depend_on: {_list(layer.may_depend_on)}",
|
|
753
|
+
" third_party: allow # review which frameworks this layer may use",
|
|
754
|
+
]
|
|
755
|
+
)
|
|
756
|
+
if layer.name in ("domain", "application"):
|
|
757
|
+
out.append(
|
|
758
|
+
" # For a framework-free core: third_party: {default: deny, allow: [pydantic]}"
|
|
759
|
+
)
|
|
760
|
+
else:
|
|
761
|
+
out.extend(
|
|
762
|
+
[
|
|
763
|
+
" # layers:",
|
|
764
|
+
" # domain:",
|
|
765
|
+
" # path: domain",
|
|
766
|
+
" # may_depend_on: []",
|
|
767
|
+
" # application:",
|
|
768
|
+
" # path: application",
|
|
769
|
+
" # may_depend_on: [domain]",
|
|
770
|
+
]
|
|
771
|
+
)
|
|
772
|
+
if inferred.has_features:
|
|
773
|
+
out.extend([" cross_feature:", " default: deny", *_allow_lines(inferred)])
|
|
774
|
+
out.extend(
|
|
775
|
+
[
|
|
776
|
+
" imports:",
|
|
777
|
+
" transitive: false # direct imports only; true checks all reachable architectural and third-party dependencies",
|
|
778
|
+
" type_checking: include",
|
|
779
|
+
]
|
|
780
|
+
)
|
|
781
|
+
return out
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def _allow_lines(inferred: InferredConfig) -> list[str]:
|
|
785
|
+
"""No blanket layer pair: each feature relationship is declared on purpose."""
|
|
786
|
+
layer = next(
|
|
787
|
+
(
|
|
788
|
+
name
|
|
789
|
+
for name in ("application", "domain")
|
|
790
|
+
if any(inferred_layer.name == name for inferred_layer in inferred.layers)
|
|
791
|
+
),
|
|
792
|
+
inferred.layers[0].name if inferred.layers else None,
|
|
793
|
+
)
|
|
794
|
+
names = inferred.features or ["orders", "billing"]
|
|
795
|
+
if layer is None or len(names) < 2: # noqa: PLR2004
|
|
796
|
+
return [" allow: []"]
|
|
797
|
+
return [
|
|
798
|
+
" allow: [] # declare each feature relationship explicitly, e.g.:",
|
|
799
|
+
f" # - from: {names[1]}.{layer}",
|
|
800
|
+
f" # to: {names[0]}.{layer}",
|
|
801
|
+
]
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def _composition_lines(inferred: InferredConfig) -> list[str]:
|
|
805
|
+
roots = inferred.composition_root
|
|
806
|
+
explained = any(root in inferred.evidence for root in roots)
|
|
807
|
+
if not explained and not inferred.candidates:
|
|
808
|
+
if roots:
|
|
809
|
+
return [f" composition_root: {_list(roots)}"]
|
|
810
|
+
return [" # composition_root: [myapp.bootstrap]"]
|
|
811
|
+
out = [" composition_root:"]
|
|
812
|
+
for root in roots:
|
|
813
|
+
if root in inferred.evidence:
|
|
814
|
+
out.append(f" # {inferred.evidence[root]}")
|
|
815
|
+
out.append(f" - {root}")
|
|
816
|
+
for candidate in inferred.candidates:
|
|
817
|
+
out.extend(
|
|
818
|
+
[
|
|
819
|
+
f" # Candidate ({candidate.confidence} confidence, {candidate.reason}):",
|
|
820
|
+
f" # {' → '.join(candidate.chain)}",
|
|
821
|
+
f" # - {candidate.module}",
|
|
822
|
+
]
|
|
823
|
+
)
|
|
824
|
+
return out
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def _wiring_lines(modules: list[str], evidence: dict[str, str]) -> list[str]:
|
|
828
|
+
if not modules:
|
|
829
|
+
return []
|
|
830
|
+
out = [" wiring: # provider modules; they keep their feature and layer"]
|
|
831
|
+
for module in modules:
|
|
832
|
+
if module in evidence:
|
|
833
|
+
out.append(f" # assembles providers: {evidence[module]}")
|
|
834
|
+
out.append(f" - {module}")
|
|
835
|
+
return out
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def _module_lines(inferred: InferredConfig) -> list[str]:
|
|
839
|
+
if not inferred.has_features:
|
|
840
|
+
return []
|
|
841
|
+
if not inferred.modules and not inferred.unclassified_roots:
|
|
842
|
+
return []
|
|
843
|
+
header = "modules: # packages outside the features and their layer"
|
|
844
|
+
out = [f" {header}" if inferred.modules else f" # {header}"]
|
|
845
|
+
out.extend(f" {module}: {layer}" for module, layer in inferred.modules.items())
|
|
846
|
+
out.extend(
|
|
847
|
+
f" # {package}: infrastructure # pick the layer that may use it"
|
|
848
|
+
for package in inferred.unclassified_roots
|
|
849
|
+
)
|
|
850
|
+
return out
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _list(values: list[str]) -> str:
|
|
854
|
+
return "[" + ", ".join(values) + "]"
|