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
smelt/rules/common.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import replace
|
|
4
|
+
from typing import TYPE_CHECKING, Any
|
|
5
|
+
|
|
6
|
+
from smelt.diagnostics.violation import ImportLink
|
|
7
|
+
from smelt.model import ArchitectureModel, ModuleInfo, ModuleKind, is_within
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Iterator
|
|
11
|
+
|
|
12
|
+
from smelt.analysis.context import AnalysisContext
|
|
13
|
+
from smelt.analysis.imports import ImportDetail
|
|
14
|
+
from smelt.diagnostics.violation import Violation
|
|
15
|
+
from smelt.rules.base import BaseRule
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def skip_import(ctx: AnalysisContext, detail: ImportDetail) -> bool:
|
|
19
|
+
return (
|
|
20
|
+
detail.type_checking
|
|
21
|
+
and ctx.config.architecture.imports.type_checking == "ignore"
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def boundary_imports(
|
|
26
|
+
ctx: AnalysisContext,
|
|
27
|
+
) -> Iterator[tuple[ImportDetail, tuple[ImportLink, ...]]]:
|
|
28
|
+
"""Direct imports and, when enabled, all reachable module dependencies.
|
|
29
|
+
|
|
30
|
+
Indirect findings retain the first import's location and the final import's
|
|
31
|
+
resolved target/names, plus a shortest chain with source lines for each hop.
|
|
32
|
+
Public facade visibility is a separate, symbol-aware contract (SMT107).
|
|
33
|
+
"""
|
|
34
|
+
for detail in ctx.imports.all_imports():
|
|
35
|
+
yield detail, ()
|
|
36
|
+
if not ctx.config.architecture.imports.transitive:
|
|
37
|
+
return
|
|
38
|
+
include_tc = ctx.config.architecture.imports.type_checking == "include"
|
|
39
|
+
for module in ctx.imports.modules():
|
|
40
|
+
seen = {
|
|
41
|
+
(detail.imported, detail.names)
|
|
42
|
+
for detail in ctx.imports.imports_of(module)
|
|
43
|
+
if not skip_import(ctx, detail)
|
|
44
|
+
}
|
|
45
|
+
for path in ctx.imports.shortest_chains_from(
|
|
46
|
+
module, include_type_checking=include_tc
|
|
47
|
+
):
|
|
48
|
+
target = path[-1]
|
|
49
|
+
key = (target.imported, target.names)
|
|
50
|
+
if len(path) == 1 or key in seen:
|
|
51
|
+
continue
|
|
52
|
+
seen.add(key)
|
|
53
|
+
yield (
|
|
54
|
+
replace(
|
|
55
|
+
path[0],
|
|
56
|
+
imported=target.imported,
|
|
57
|
+
names=target.names,
|
|
58
|
+
external=target.external,
|
|
59
|
+
),
|
|
60
|
+
tuple(ImportLink(d.importer, d.imported, d.line) for d in path),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def wiring_facade(
|
|
65
|
+
model: ArchitectureModel, source: ModuleInfo, target: ModuleInfo
|
|
66
|
+
) -> bool:
|
|
67
|
+
"""A feature or package initializer may export its own provider module."""
|
|
68
|
+
return target.wiring and (
|
|
69
|
+
source.name == target.name.rsplit(".", 1)[0]
|
|
70
|
+
or (
|
|
71
|
+
target.feature is not None
|
|
72
|
+
and source.feature == target.feature
|
|
73
|
+
and source.name == model.feature_package_for(target.feature)
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def import_violation( # noqa: PLR0913
|
|
79
|
+
rule: BaseRule,
|
|
80
|
+
ctx: AnalysisContext,
|
|
81
|
+
detail: ImportDetail,
|
|
82
|
+
message: str,
|
|
83
|
+
*,
|
|
84
|
+
expected: dict[str, Any] | None = None,
|
|
85
|
+
hint: str | None = None,
|
|
86
|
+
chain: tuple[ImportLink, ...] = (),
|
|
87
|
+
edge: str | None = None,
|
|
88
|
+
) -> Violation:
|
|
89
|
+
source = ctx.files.sources[detail.importer]
|
|
90
|
+
info = ctx.model.info(detail.importer)
|
|
91
|
+
target_module = (
|
|
92
|
+
chain[-1].imported if chain and rule.code != "SMT104" else detail.imported
|
|
93
|
+
)
|
|
94
|
+
if edge is None:
|
|
95
|
+
target = (
|
|
96
|
+
detail.imported.split(".")[0]
|
|
97
|
+
if detail.external
|
|
98
|
+
else _architecture_node(ctx, target_module)
|
|
99
|
+
)
|
|
100
|
+
edge = f"{_architecture_node(ctx, detail.importer)} -> {target}"
|
|
101
|
+
return rule.violation(
|
|
102
|
+
message,
|
|
103
|
+
path=source.path,
|
|
104
|
+
line=detail.line,
|
|
105
|
+
column=detail.column,
|
|
106
|
+
end_line=detail.line,
|
|
107
|
+
end_column=detail.end_column,
|
|
108
|
+
source_module=detail.importer,
|
|
109
|
+
target_module=target_module,
|
|
110
|
+
import_chain=chain,
|
|
111
|
+
feature=info.feature if info else None,
|
|
112
|
+
layer=info.layer if info else None,
|
|
113
|
+
expected=expected,
|
|
114
|
+
hint=hint,
|
|
115
|
+
edge=edge,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def matches_any(name: str, entries: list[str]) -> bool:
|
|
120
|
+
return any(is_within(name, entry) for entry in entries)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def display_module_path(
|
|
124
|
+
model: ArchitectureModel, module: str, *, package: bool = False
|
|
125
|
+
) -> str:
|
|
126
|
+
"""A short path for hints: relative to the feature container (``voice/application/ports.py``)."""
|
|
127
|
+
spec = model.config.architecture.features
|
|
128
|
+
container: str | None = None
|
|
129
|
+
if spec is not None and spec.root is not None:
|
|
130
|
+
container = spec.root
|
|
131
|
+
elif spec is not None and spec.pattern is not None:
|
|
132
|
+
container = spec.pattern.rsplit(".", 1)[0]
|
|
133
|
+
if container and module.startswith(f"{container}."):
|
|
134
|
+
module = module[len(container) + 1 :]
|
|
135
|
+
elif spec is None:
|
|
136
|
+
root = module.split(".")[0]
|
|
137
|
+
if root in model.config.project.root_packages and "." in module:
|
|
138
|
+
module = module[len(root) + 1 :]
|
|
139
|
+
return module.replace(".", "/") + ("/" if package else ".py")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def join(values: list[str] | tuple[str, ...], empty: str = "(nothing)") -> str:
|
|
143
|
+
return ", ".join(values) if values else empty
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def last_segment(name: str) -> str:
|
|
147
|
+
return name.rsplit(".", 1)[-1]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _architecture_node(ctx: AnalysisContext, module: str) -> str:
|
|
151
|
+
"""The part of the architecture ``module`` belongs to: ``user.domain``,
|
|
152
|
+
a central package, a shared or composition root entry, else the module."""
|
|
153
|
+
info = ctx.model.info(module)
|
|
154
|
+
if info is None:
|
|
155
|
+
return module
|
|
156
|
+
if info.in_grid and (info.feature or info.layer):
|
|
157
|
+
return ".".join(part for part in (info.feature, info.layer) if part)
|
|
158
|
+
architecture = ctx.config.architecture
|
|
159
|
+
entries = {
|
|
160
|
+
ModuleKind.SHARED: architecture.shared,
|
|
161
|
+
ModuleKind.COMPOSITION_ROOT: architecture.composition_root,
|
|
162
|
+
}.get(info.kind, list(architecture.modules) if info.central else [])
|
|
163
|
+
matching = [entry for entry in entries if is_within(module, entry)]
|
|
164
|
+
return max(matching, key=len) if matching else module
|
|
File without changes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
from smelt.analysis.context import AnalysisContext, Index
|
|
6
|
+
from smelt.diagnostics.violation import Category, Severity, Violation
|
|
7
|
+
from smelt.model import ModuleKind
|
|
8
|
+
from smelt.rules.activation import POLICIES
|
|
9
|
+
from smelt.rules.base import BaseRule, RuleDoc
|
|
10
|
+
from smelt.rules.common import (
|
|
11
|
+
boundary_imports,
|
|
12
|
+
import_violation,
|
|
13
|
+
skip_import,
|
|
14
|
+
wiring_facade,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from collections.abc import Iterator
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CompositionRootLeak(BaseRule):
|
|
22
|
+
activation = POLICIES["SMT106"]
|
|
23
|
+
code = "SMT106"
|
|
24
|
+
name = "composition-root-leak"
|
|
25
|
+
category = Category.DEPENDENCIES
|
|
26
|
+
default_severity = Severity.ERROR
|
|
27
|
+
requires = frozenset({Index.IMPORTS})
|
|
28
|
+
doc = RuleDoc(
|
|
29
|
+
summary="A module imports the composition root or a declared wiring module.",
|
|
30
|
+
rationale=(
|
|
31
|
+
"Wiring belongs in one place. When features reach for the container or the "
|
|
32
|
+
"bootstrap module, construction logic spreads and dependencies become hidden. "
|
|
33
|
+
"With architecture.imports.transitive, paths through arbitrary project "
|
|
34
|
+
"modules are checked and reported with a shortest import chain."
|
|
35
|
+
),
|
|
36
|
+
bad="# voice/application/session.py\nfrom gateway.main import container",
|
|
37
|
+
good=(
|
|
38
|
+
"# voice/application/session.py\n"
|
|
39
|
+
"class StartSession:\n"
|
|
40
|
+
" def __init__(self, sessions: VoiceSessionRepository) -> None: ..."
|
|
41
|
+
),
|
|
42
|
+
fix=(
|
|
43
|
+
"Receive dependencies through constructor parameters and register them in the "
|
|
44
|
+
"composition root."
|
|
45
|
+
),
|
|
46
|
+
config=(
|
|
47
|
+
"architecture.composition_root",
|
|
48
|
+
"architecture.wiring",
|
|
49
|
+
"architecture.imports.transitive",
|
|
50
|
+
"architecture.imports.type_checking",
|
|
51
|
+
),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
55
|
+
roots = ctx.config.architecture.composition_root
|
|
56
|
+
model = ctx.model
|
|
57
|
+
for detail, chain in boundary_imports(ctx):
|
|
58
|
+
if detail.external or skip_import(ctx, detail):
|
|
59
|
+
continue
|
|
60
|
+
source = model.info(detail.importer)
|
|
61
|
+
if (
|
|
62
|
+
source is None
|
|
63
|
+
or source.kind is ModuleKind.COMPOSITION_ROOT
|
|
64
|
+
or source.wiring
|
|
65
|
+
):
|
|
66
|
+
continue
|
|
67
|
+
target = model.info(detail.imported)
|
|
68
|
+
if target is None or (
|
|
69
|
+
target.kind is not ModuleKind.COMPOSITION_ROOT and not target.wiring
|
|
70
|
+
):
|
|
71
|
+
continue
|
|
72
|
+
if wiring_facade(model, source, target):
|
|
73
|
+
continue
|
|
74
|
+
label = "wiring module" if target.wiring else "composition root"
|
|
75
|
+
yield import_violation(
|
|
76
|
+
self,
|
|
77
|
+
ctx,
|
|
78
|
+
detail,
|
|
79
|
+
f"{detail.importer} must not import the {label} {detail.imported}",
|
|
80
|
+
expected={"composition_root": list(roots)},
|
|
81
|
+
hint=(
|
|
82
|
+
"The composition root depends on everything; nothing depends on it. "
|
|
83
|
+
"Pass what you need in from the root instead."
|
|
84
|
+
),
|
|
85
|
+
chain=chain,
|
|
86
|
+
)
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from collections.abc import Callable, Hashable, Iterator
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from functools import partial
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from smelt.analysis.context import AnalysisContext, Index
|
|
11
|
+
from smelt.analysis.graphs import shortest_cycle, strongly_connected_components
|
|
12
|
+
from smelt.diagnostics.violation import Category, ImportLink, Severity, Violation
|
|
13
|
+
from smelt.model import ModuleInfo, ModuleKind, is_within
|
|
14
|
+
from smelt.rules.base import BaseRule, RuleDoc
|
|
15
|
+
from smelt.rules.common import import_violation, skip_import, wiring_facade
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from smelt.analysis.imports import ImportDetail
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class _Graph[T: Hashable]:
|
|
23
|
+
adjacency: dict[T, set[T]] = field(default_factory=lambda: defaultdict(set))
|
|
24
|
+
witnesses: dict[tuple[T, T], list[ImportDetail]] = field(
|
|
25
|
+
default_factory=lambda: defaultdict(list)
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
def add(self, a: T, b: T, detail: ImportDetail) -> None:
|
|
29
|
+
if a == b:
|
|
30
|
+
return
|
|
31
|
+
self.adjacency[a].add(b)
|
|
32
|
+
self.witnesses[(a, b)].append(detail)
|
|
33
|
+
|
|
34
|
+
def chain(self, cycle: list[T]) -> list[ImportDetail]:
|
|
35
|
+
"""One import per hop, preferring imports that connect module to module."""
|
|
36
|
+
hops: list[ImportDetail] = []
|
|
37
|
+
for a, b in itertools.pairwise(cycle):
|
|
38
|
+
candidates = self.witnesses[(a, b)]
|
|
39
|
+
previous = hops[-1].imported if hops else None
|
|
40
|
+
connected = [d for d in candidates if d.importer == previous]
|
|
41
|
+
hops.append((connected or candidates)[0])
|
|
42
|
+
return hops
|
|
43
|
+
|
|
44
|
+
def type_checking_only(self, a: T, b: T) -> bool:
|
|
45
|
+
"""Every import from ``a`` to ``b`` sits under ``if TYPE_CHECKING:``."""
|
|
46
|
+
return all(d.type_checking for d in self.witnesses[(a, b)])
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ImportCycle(BaseRule):
|
|
50
|
+
code = "SMT104"
|
|
51
|
+
name = "import-cycle"
|
|
52
|
+
category = Category.DEPENDENCIES
|
|
53
|
+
default_severity = Severity.ERROR
|
|
54
|
+
requires = frozenset({Index.IMPORTS})
|
|
55
|
+
doc = RuleDoc(
|
|
56
|
+
summary="Import cycles between features, between layers, or between sibling modules.",
|
|
57
|
+
rationale=(
|
|
58
|
+
"Cycles mean two parts can only be understood, tested and changed together. "
|
|
59
|
+
"They also cause import-order bugs at runtime, unless one edge is imported "
|
|
60
|
+
"only under `if TYPE_CHECKING:`; such cycles are marked "
|
|
61
|
+
"`(type checking only)`. Imports that other rules "
|
|
62
|
+
"already forbid (SMT101, SMT102, SMT106) and outbound imports from "
|
|
63
|
+
"declared wiring are left out, so a cycle report means the cycle is built "
|
|
64
|
+
"entirely from ordinary allowed dependencies."
|
|
65
|
+
),
|
|
66
|
+
bad=(
|
|
67
|
+
"# billing/application/invoices.py\n"
|
|
68
|
+
"from gateway.features.voice.application import calls\n"
|
|
69
|
+
"# voice/application/calls.py\n"
|
|
70
|
+
"from gateway.features.billing.application import invoices"
|
|
71
|
+
),
|
|
72
|
+
good=(
|
|
73
|
+
"# voice/application/calls.py publishes an event;\n"
|
|
74
|
+
"# billing/application/invoices.py subscribes to it."
|
|
75
|
+
),
|
|
76
|
+
fix=(
|
|
77
|
+
"Break one edge of the cycle: extract the shared piece into a module both can "
|
|
78
|
+
"import, invert one dependency behind an abstraction, or merge the parts."
|
|
79
|
+
),
|
|
80
|
+
config=("architecture.imports.cycles", "architecture.imports.type_checking"),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
84
|
+
scopes: set[str] = set(ctx.config.architecture.imports.cycles)
|
|
85
|
+
features: _Graph[str] = _Graph()
|
|
86
|
+
layers: _Graph[tuple[str | None, str]] = _Graph()
|
|
87
|
+
siblings: dict[str, _Graph[str]] = defaultdict(_Graph)
|
|
88
|
+
skip_packages = _packages_covered_by_other_scopes(ctx, scopes)
|
|
89
|
+
|
|
90
|
+
for detail in ctx.imports.all_imports():
|
|
91
|
+
if detail.external or skip_import(ctx, detail):
|
|
92
|
+
continue
|
|
93
|
+
source = ctx.model.info(detail.importer)
|
|
94
|
+
target = ctx.model.info(detail.imported)
|
|
95
|
+
if (
|
|
96
|
+
source is None
|
|
97
|
+
or target is None
|
|
98
|
+
or _reported_elsewhere(ctx, source, target)
|
|
99
|
+
):
|
|
100
|
+
continue
|
|
101
|
+
if source.in_grid and target.in_grid:
|
|
102
|
+
if source.feature and target.feature:
|
|
103
|
+
features.add(source.feature, target.feature, detail)
|
|
104
|
+
if source.feature == target.feature and source.layer and target.layer:
|
|
105
|
+
layers.add(
|
|
106
|
+
(source.feature, source.layer),
|
|
107
|
+
(target.feature, target.layer),
|
|
108
|
+
detail,
|
|
109
|
+
)
|
|
110
|
+
parent, a, b = _sibling_pair(detail.importer, detail.imported)
|
|
111
|
+
if parent is not None and parent not in skip_packages:
|
|
112
|
+
siblings[parent].add(a, b, detail)
|
|
113
|
+
|
|
114
|
+
model = ctx.model
|
|
115
|
+
|
|
116
|
+
def feature_of(module: str) -> str | None:
|
|
117
|
+
info = model.info(module)
|
|
118
|
+
return info.feature if info else None
|
|
119
|
+
|
|
120
|
+
def layer_of(module: str) -> tuple[str | None, str] | None:
|
|
121
|
+
info = model.info(module)
|
|
122
|
+
return (info.feature, info.layer) if info and info.layer else None
|
|
123
|
+
|
|
124
|
+
if "features" in scopes:
|
|
125
|
+
yield from self._report(ctx, features, "features", str, feature_of)
|
|
126
|
+
if "layers" in scopes:
|
|
127
|
+
yield from self._report(ctx, layers, "layers", _layer_label, layer_of)
|
|
128
|
+
if "siblings" in scopes:
|
|
129
|
+
for parent in sorted(siblings):
|
|
130
|
+
yield from self._report(
|
|
131
|
+
ctx,
|
|
132
|
+
siblings[parent],
|
|
133
|
+
f"modules in {parent}",
|
|
134
|
+
_last_segment,
|
|
135
|
+
partial(_child_of, parent),
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def _report[T: Hashable](
|
|
139
|
+
self,
|
|
140
|
+
ctx: AnalysisContext,
|
|
141
|
+
graph: _Graph[T],
|
|
142
|
+
scope: str,
|
|
143
|
+
label: Callable[[T], str],
|
|
144
|
+
node_of: Callable[[str], T | None],
|
|
145
|
+
) -> Iterator[Violation]:
|
|
146
|
+
for component in strongly_connected_components(graph.adjacency):
|
|
147
|
+
if len(component) < 2: # noqa: PLR2004
|
|
148
|
+
continue
|
|
149
|
+
start = min(component, key=str)
|
|
150
|
+
cycle = shortest_cycle(start, graph.adjacency, component)
|
|
151
|
+
if cycle is None:
|
|
152
|
+
continue
|
|
153
|
+
hops = graph.chain(cycle)
|
|
154
|
+
names = [label(node) for node in cycle]
|
|
155
|
+
static = [
|
|
156
|
+
f"{label(a)} -> {label(b)}"
|
|
157
|
+
for a, b in itertools.pairwise(cycle)
|
|
158
|
+
if graph.type_checking_only(a, b)
|
|
159
|
+
]
|
|
160
|
+
message = f"import cycle between {scope}: {' -> '.join(names)}"
|
|
161
|
+
members = sorted(label(node) for node in component)
|
|
162
|
+
expected: dict[str, list[str]] = {
|
|
163
|
+
"cycle": names,
|
|
164
|
+
"members": members,
|
|
165
|
+
"cyclic_edges": sorted(
|
|
166
|
+
f"{scope}:{label(a)} -> {label(b)}"
|
|
167
|
+
for a in component
|
|
168
|
+
for b in graph.adjacency.get(a, ())
|
|
169
|
+
if b in component
|
|
170
|
+
),
|
|
171
|
+
}
|
|
172
|
+
hint = (
|
|
173
|
+
"Break one edge: extract what both sides need into a separate module, "
|
|
174
|
+
"or invert one dependency behind an abstraction."
|
|
175
|
+
)
|
|
176
|
+
if len(component) > len(set(cycle)):
|
|
177
|
+
hint += f" The cyclic group contains: {', '.join(members)}."
|
|
178
|
+
if static:
|
|
179
|
+
message += " (type checking only)"
|
|
180
|
+
expected["type_checking_only"] = static
|
|
181
|
+
verb = "is" if len(static) == 1 else "are"
|
|
182
|
+
hint = (
|
|
183
|
+
f"Only type checkers see this cycle: {', '.join(static)} {verb} "
|
|
184
|
+
"imported under `if TYPE_CHECKING:`, so it cannot fail at import "
|
|
185
|
+
"time. It still couples both sides. " + hint + " To leave such "
|
|
186
|
+
"edges out, set architecture.imports.type_checking: ignore."
|
|
187
|
+
)
|
|
188
|
+
yield import_violation(
|
|
189
|
+
self,
|
|
190
|
+
ctx,
|
|
191
|
+
hops[0],
|
|
192
|
+
message,
|
|
193
|
+
expected=expected,
|
|
194
|
+
hint=hint,
|
|
195
|
+
edge=" -> ".join(names),
|
|
196
|
+
chain=_witness(ctx, hops, node_of),
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# A witness hop inside one node is short; a longer path explains little.
|
|
201
|
+
_MAX_INNER_HOPS = 6
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _witness[T: Hashable](
|
|
205
|
+
ctx: AnalysisContext,
|
|
206
|
+
hops: list[ImportDetail],
|
|
207
|
+
node_of: Callable[[str], T | None],
|
|
208
|
+
) -> tuple[ImportLink, ...]:
|
|
209
|
+
"""The cycle's imports, joined inside each node where a module path exists.
|
|
210
|
+
|
|
211
|
+
``features -> platform -> features`` crosses into ``platform.auth`` and leaves
|
|
212
|
+
from ``platform.auth.guard``; the witness adds ``platform.auth -> ...guard``.
|
|
213
|
+
Where no path inside the node joins two hops, the gap stays visible.
|
|
214
|
+
"""
|
|
215
|
+
include = ctx.config.architecture.imports.type_checking == "include"
|
|
216
|
+
adjacency = ctx.imports.first_party_edges(include_type_checking=include)
|
|
217
|
+
links: list[ImportLink] = []
|
|
218
|
+
for hop, following in itertools.zip_longest(hops, hops[1:]):
|
|
219
|
+
links.append(ImportLink(hop.importer, hop.imported, hop.line))
|
|
220
|
+
if following is None or following.importer == hop.imported:
|
|
221
|
+
continue
|
|
222
|
+
path = _path_within(adjacency, hop.imported, following.importer, node_of)
|
|
223
|
+
links.extend(
|
|
224
|
+
ImportLink(a, b, _line(ctx, a, b)) for a, b in itertools.pairwise(path)
|
|
225
|
+
)
|
|
226
|
+
return tuple(links)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _path_within[T: Hashable](
|
|
230
|
+
adjacency: dict[str, set[str]],
|
|
231
|
+
start: str,
|
|
232
|
+
goal: str,
|
|
233
|
+
node_of: Callable[[str], T | None],
|
|
234
|
+
) -> list[str]:
|
|
235
|
+
node = node_of(start)
|
|
236
|
+
previous: dict[str, str | None] = {start: None}
|
|
237
|
+
frontier = [start]
|
|
238
|
+
for _ in range(_MAX_INNER_HOPS):
|
|
239
|
+
following: list[str] = []
|
|
240
|
+
for module in frontier:
|
|
241
|
+
for child in sorted(adjacency.get(module, ())):
|
|
242
|
+
if child in previous or node_of(child) != node:
|
|
243
|
+
continue
|
|
244
|
+
previous[child] = module
|
|
245
|
+
if child == goal:
|
|
246
|
+
path = [goal]
|
|
247
|
+
while (parent := previous[path[-1]]) is not None:
|
|
248
|
+
path.append(parent)
|
|
249
|
+
return list(reversed(path))
|
|
250
|
+
following.append(child)
|
|
251
|
+
frontier = following
|
|
252
|
+
return []
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _line(ctx: AnalysisContext, importer: str, imported: str) -> int | None:
|
|
256
|
+
return next(
|
|
257
|
+
(d.line for d in ctx.imports.imports_of(importer) if d.imported == imported),
|
|
258
|
+
None,
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _child_of(parent: str, module: str) -> str | None:
|
|
263
|
+
"""The child of ``parent`` containing ``module``: the node of a sibling cycle."""
|
|
264
|
+
if not is_within(module, parent) or module == parent:
|
|
265
|
+
return None
|
|
266
|
+
return ".".join(module.split(".")[: parent.count(".") + 2])
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _reported_elsewhere(
|
|
270
|
+
ctx: AnalysisContext, source: ModuleInfo, target: ModuleInfo
|
|
271
|
+
) -> bool:
|
|
272
|
+
"""Ignore wiring edges and imports already reported by boundary rules."""
|
|
273
|
+
if source.wiring:
|
|
274
|
+
return True
|
|
275
|
+
if (
|
|
276
|
+
(target.kind is ModuleKind.COMPOSITION_ROOT or target.wiring)
|
|
277
|
+
and source.kind is not ModuleKind.COMPOSITION_ROOT
|
|
278
|
+
and not source.wiring
|
|
279
|
+
and not wiring_facade(ctx.model, source, target)
|
|
280
|
+
):
|
|
281
|
+
return True
|
|
282
|
+
if not (source.in_grid and target.in_grid and source.layer and target.layer):
|
|
283
|
+
return False
|
|
284
|
+
if source.feature == target.feature:
|
|
285
|
+
allowed = ctx.model.layers[source.layer].may_depend_on
|
|
286
|
+
return source.layer != target.layer and target.layer not in allowed
|
|
287
|
+
cross = ctx.config.architecture.cross_feature
|
|
288
|
+
return (
|
|
289
|
+
cross.default == "deny"
|
|
290
|
+
and source.feature is not None
|
|
291
|
+
and target.feature is not None
|
|
292
|
+
and not cross.allows(source.feature, source.layer, target.feature, target.layer)
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _packages_covered_by_other_scopes(
|
|
297
|
+
ctx: AnalysisContext, scopes: set[str]
|
|
298
|
+
) -> set[str]:
|
|
299
|
+
model = ctx.model
|
|
300
|
+
covered: set[str] = set()
|
|
301
|
+
if "features" in scopes and model.has_features:
|
|
302
|
+
covered.update(
|
|
303
|
+
info.package.rsplit(".", 1)[0] for info in model.features.values()
|
|
304
|
+
)
|
|
305
|
+
if "layers" in scopes and model.layers:
|
|
306
|
+
covered.update(model.grid_containers())
|
|
307
|
+
return covered
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _layer_label(node: tuple[str | None, str]) -> str:
|
|
311
|
+
feature, layer = node
|
|
312
|
+
return f"{feature}.{layer}" if feature else layer
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _last_segment(module: str) -> str:
|
|
316
|
+
return module.rsplit(".", 1)[-1]
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _sibling_pair(importer: str, imported: str) -> tuple[str | None, str, str]:
|
|
320
|
+
if is_within(importer, imported) or is_within(imported, importer):
|
|
321
|
+
return None, "", ""
|
|
322
|
+
a, b = importer.split("."), imported.split(".")
|
|
323
|
+
common = 0
|
|
324
|
+
while common < min(len(a), len(b)) and a[common] == b[common]:
|
|
325
|
+
common += 1
|
|
326
|
+
if common == 0:
|
|
327
|
+
return None, "", ""
|
|
328
|
+
parent = ".".join(a[:common])
|
|
329
|
+
return parent, ".".join(a[: common + 1]), ".".join(b[: common + 1])
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
from smelt.analysis.context import AnalysisContext, Index
|
|
7
|
+
from smelt.diagnostics.violation import Category, Severity, Violation
|
|
8
|
+
from smelt.model import is_within
|
|
9
|
+
from smelt.rules.activation import POLICIES
|
|
10
|
+
from smelt.rules.base import BaseRule, RuleDoc
|
|
11
|
+
from smelt.rules.common import import_violation, skip_import
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Iterator
|
|
15
|
+
|
|
16
|
+
from smelt.analysis.imports import ImportDetail
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PackageImportFanout(BaseRule):
|
|
20
|
+
activation = POLICIES["SMT108"]
|
|
21
|
+
code = "SMT108"
|
|
22
|
+
name = "package-import-fanout"
|
|
23
|
+
category = Category.DEPENDENCIES
|
|
24
|
+
default_severity = Severity.HINT
|
|
25
|
+
requires = frozenset({Index.IMPORTS})
|
|
26
|
+
doc = RuleDoc(
|
|
27
|
+
summary="One caller imports many implementation modules of the same package.",
|
|
28
|
+
rationale=(
|
|
29
|
+
"Repeated imports of neighboring implementation modules can indicate a "
|
|
30
|
+
"missing package API. This is an opt-in design hint, not proof of poor "
|
|
31
|
+
"architecture. Count distinct target modules per source file and contracted "
|
|
32
|
+
"package, not statements, symbols, or imports across the whole repository."
|
|
33
|
+
),
|
|
34
|
+
bad="# caller.py\nfrom app.users.application.get_user import GetUser\nfrom app.users.application.update_user import UpdateUser\nfrom app.users.application.delete_user import DeleteUser",
|
|
35
|
+
good="# caller.py, after deliberate facade exports are defined\nfrom app.users.application import DeleteUser, GetUser, UpdateUser",
|
|
36
|
+
fix=(
|
|
37
|
+
"Consider exporting the caller's supported API from the package facade. "
|
|
38
|
+
"Check dependency direction and cycles before changing exports. If these "
|
|
39
|
+
"independent dependencies are intentional, retain them or adjust the "
|
|
40
|
+
"advisory threshold. Declare public: ['.'] to enforce facade-only imports."
|
|
41
|
+
),
|
|
42
|
+
config=("structure.contracts", "architecture.imports.type_checking"),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
46
|
+
for contract in ctx.contracts.resolved:
|
|
47
|
+
threshold = contract.spec.bundle_imports_at
|
|
48
|
+
if threshold is None:
|
|
49
|
+
continue
|
|
50
|
+
callers: dict[str, dict[str, ImportDetail]] = defaultdict(dict)
|
|
51
|
+
for detail in ctx.imports.all_imports():
|
|
52
|
+
if (
|
|
53
|
+
detail.external
|
|
54
|
+
or skip_import(ctx, detail)
|
|
55
|
+
or is_within(detail.importer, contract.package)
|
|
56
|
+
or detail.imported == contract.package
|
|
57
|
+
or not is_within(detail.imported, contract.package)
|
|
58
|
+
):
|
|
59
|
+
continue
|
|
60
|
+
callers[detail.importer].setdefault(detail.imported, detail)
|
|
61
|
+
for caller, targets in sorted(callers.items()):
|
|
62
|
+
if len(targets) < threshold:
|
|
63
|
+
continue
|
|
64
|
+
first = min(
|
|
65
|
+
targets.values(), key=lambda detail: (detail.line, detail.column)
|
|
66
|
+
)
|
|
67
|
+
yield import_violation(
|
|
68
|
+
self,
|
|
69
|
+
ctx,
|
|
70
|
+
first,
|
|
71
|
+
f"{caller} imports {len(targets)} modules of {contract.package}; consider its package facade",
|
|
72
|
+
expected={
|
|
73
|
+
"contract": contract.name,
|
|
74
|
+
"package": contract.package,
|
|
75
|
+
"bundle_imports_at": threshold,
|
|
76
|
+
"modules": sorted(targets),
|
|
77
|
+
"count": len(targets),
|
|
78
|
+
},
|
|
79
|
+
hint=f"Consider deliberate exports from {contract.package}, then combine the imports there. Preserve the dependency direction and check for cycles.",
|
|
80
|
+
edge=f"{caller} -> {contract.package} ({contract.name})",
|
|
81
|
+
)
|