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.
Files changed (133) hide show
  1. smelt/__init__.py +6 -0
  2. smelt/__main__.py +5 -0
  3. smelt/analysis/__init__.py +45 -0
  4. smelt/analysis/annotations.py +105 -0
  5. smelt/analysis/cache.py +168 -0
  6. smelt/analysis/context.py +147 -0
  7. smelt/analysis/contracts.py +210 -0
  8. smelt/analysis/coverage.py +377 -0
  9. smelt/analysis/definition_blocks.py +569 -0
  10. smelt/analysis/enum_values.py +217 -0
  11. smelt/analysis/errors.py +11 -0
  12. smelt/analysis/exports.py +166 -0
  13. smelt/analysis/files.py +279 -0
  14. smelt/analysis/function_usage.py +123 -0
  15. smelt/analysis/graphs.py +77 -0
  16. smelt/analysis/identity.py +64 -0
  17. smelt/analysis/import_cache.py +98 -0
  18. smelt/analysis/imports.py +452 -0
  19. smelt/analysis/literals.py +17 -0
  20. smelt/analysis/member_state.py +108 -0
  21. smelt/analysis/members.py +975 -0
  22. smelt/analysis/ordering.py +399 -0
  23. smelt/analysis/ordering_rewrite.py +232 -0
  24. smelt/analysis/package_exports.py +58 -0
  25. smelt/analysis/parsing.py +126 -0
  26. smelt/analysis/python_version.py +164 -0
  27. smelt/analysis/retained.py +84 -0
  28. smelt/analysis/syntax.py +109 -0
  29. smelt/analysis/test_awaits.py +91 -0
  30. smelt/analysis/test_cases.py +84 -0
  31. smelt/analysis/test_deadlines.py +90 -0
  32. smelt/analysis/test_outcomes.py +71 -0
  33. smelt/analysis/test_subprocesses.py +107 -0
  34. smelt/analysis/test_syntax.py +1425 -0
  35. smelt/analysis/test_timing.py +76 -0
  36. smelt/analysis/type_dispatch.py +193 -0
  37. smelt/analysis/workspace.py +146 -0
  38. smelt/cli/__init__.py +3 -0
  39. smelt/cli/app.py +300 -0
  40. smelt/cli/commands/__init__.py +62 -0
  41. smelt/cli/commands/adopt.py +274 -0
  42. smelt/cli/commands/check.py +151 -0
  43. smelt/cli/commands/discover.py +51 -0
  44. smelt/cli/commands/info.py +112 -0
  45. smelt/cli/session.py +163 -0
  46. smelt/cli/session_slots.py +43 -0
  47. smelt/cli/support.py +90 -0
  48. smelt/config/__init__.py +36 -0
  49. smelt/config/discovery.py +93 -0
  50. smelt/config/errors.py +51 -0
  51. smelt/config/loader.py +282 -0
  52. smelt/config/models.py +717 -0
  53. smelt/config/patterns.py +47 -0
  54. smelt/config/schema.py +23 -0
  55. smelt/config/source.py +56 -0
  56. smelt/config/validation.py +180 -0
  57. smelt/diagnostics/__init__.py +0 -0
  58. smelt/diagnostics/debt.py +226 -0
  59. smelt/diagnostics/dedupe.py +41 -0
  60. smelt/diagnostics/groups.py +109 -0
  61. smelt/diagnostics/render/__init__.py +0 -0
  62. smelt/diagnostics/render/machine.py +237 -0
  63. smelt/diagnostics/render/text.py +321 -0
  64. smelt/diagnostics/report.py +104 -0
  65. smelt/diagnostics/suppressions.py +80 -0
  66. smelt/diagnostics/violation.py +120 -0
  67. smelt/docs.py +98 -0
  68. smelt/engine/__init__.py +0 -0
  69. smelt/engine/briefing.py +630 -0
  70. smelt/engine/cache.py +65 -0
  71. smelt/engine/changes.py +260 -0
  72. smelt/engine/check.py +724 -0
  73. smelt/engine/coverage.py +151 -0
  74. smelt/engine/evaluation.py +291 -0
  75. smelt/engine/file_checks.py +94 -0
  76. smelt/engine/git_source.py +140 -0
  77. smelt/engine/inference.py +854 -0
  78. smelt/engine/mirror_inference.py +95 -0
  79. smelt/engine/native_git.py +190 -0
  80. smelt/engine/ordering_fixes.py +132 -0
  81. smelt/engine/paths.py +163 -0
  82. smelt/engine/result_cache.py +208 -0
  83. smelt/engine/rule_settings.py +164 -0
  84. smelt/engine/schema.py +58 -0
  85. smelt/engine/staged.py +75 -0
  86. smelt/engine/workspace.py +5 -0
  87. smelt/model/__init__.py +9 -0
  88. smelt/model/architecture.py +234 -0
  89. smelt/py.typed +0 -0
  90. smelt/rules/__init__.py +0 -0
  91. smelt/rules/activation.py +129 -0
  92. smelt/rules/base.py +131 -0
  93. smelt/rules/catalog.json +600 -0
  94. smelt/rules/common.py +164 -0
  95. smelt/rules/dependencies/__init__.py +0 -0
  96. smelt/rules/dependencies/composition_root.py +86 -0
  97. smelt/rules/dependencies/cycles.py +329 -0
  98. smelt/rules/dependencies/fanout.py +81 -0
  99. smelt/rules/dependencies/features.py +165 -0
  100. smelt/rules/dependencies/interfaces.py +84 -0
  101. smelt/rules/dependencies/layers.py +138 -0
  102. smelt/rules/dependencies/third_party.py +132 -0
  103. smelt/rules/member_names.py +13 -0
  104. smelt/rules/meta.py +74 -0
  105. smelt/rules/registry.py +132 -0
  106. smelt/rules/structure/__init__.py +0 -0
  107. smelt/rules/structure/assignments.py +114 -0
  108. smelt/rules/structure/contracts.py +71 -0
  109. smelt/rules/structure/coverage.py +100 -0
  110. smelt/rules/structure/enum_values.py +50 -0
  111. smelt/rules/structure/headers.py +143 -0
  112. smelt/rules/structure/import_style.py +145 -0
  113. smelt/rules/structure/layout.py +202 -0
  114. smelt/rules/structure/members.py +116 -0
  115. smelt/rules/structure/naming.py +132 -0
  116. smelt/rules/structure/ordering.py +83 -0
  117. smelt/rules/structure/package_imports.py +117 -0
  118. smelt/rules/structure/type_dispatch.py +79 -0
  119. smelt/rules/testing/__init__.py +0 -0
  120. smelt/rules/testing/awaits.py +46 -0
  121. smelt/rules/testing/cases.py +47 -0
  122. smelt/rules/testing/location.py +537 -0
  123. smelt/rules/testing/mocking.py +140 -0
  124. smelt/rules/testing/outcomes.py +119 -0
  125. smelt/rules/testing/private_access.py +93 -0
  126. smelt/rules/testing/public_attributes.py +62 -0
  127. smelt/rules/testing/public_functions.py +52 -0
  128. smelt/rules/testing/timing.py +62 -0
  129. smelt_cli-0.2.0.data/scripts/smelt.exe +0 -0
  130. smelt_cli-0.2.0.dist-info/METADATA +103 -0
  131. smelt_cli-0.2.0.dist-info/RECORD +133 -0
  132. smelt_cli-0.2.0.dist-info/WHEEL +4 -0
  133. smelt_cli-0.2.0.dist-info/sboms/smelt-cli.cyclonedx.json +5462 -0
@@ -0,0 +1,165 @@
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 boundary_imports, import_violation, join, skip_import
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Iterator
14
+
15
+
16
+ class CrossFeatureImport(BaseRule):
17
+ activation = POLICIES["SMT102"]
18
+ code = "SMT102"
19
+ name = "cross-feature-import"
20
+ category = Category.DEPENDENCIES
21
+ default_severity = Severity.ERROR
22
+ requires = frozenset({Index.IMPORTS})
23
+ doc = RuleDoc(
24
+ summary="A feature imports another feature outside the allowed layer pairs.",
25
+ rationale=(
26
+ "Features are independent slices. Direct imports between them couple release "
27
+ "cycles and make it impossible to reason about one feature in isolation. "
28
+ "With architecture.imports.transitive, allowed pairs also apply to all "
29
+ "reachable feature modules, with a shortest import chain as evidence."
30
+ ),
31
+ bad="# billing/infra/charges.py\nfrom gateway.features.voice.infra.sql import CallLog",
32
+ good=(
33
+ "# billing/application/charges.py\n"
34
+ "from gateway.features.voice.application.api import CallSummaryQuery"
35
+ ),
36
+ fix=(
37
+ "Go through an allowed relationship, declare an intended one explicitly "
38
+ "(`allow: [{from: orders.application, to: billing.application}]`), move the "
39
+ "shared concept into a `shared` package, or merge the features."
40
+ ),
41
+ config=(
42
+ "architecture.cross_feature.default",
43
+ "architecture.cross_feature.allow",
44
+ "architecture.imports.transitive",
45
+ "architecture.imports.type_checking",
46
+ ),
47
+ )
48
+
49
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
50
+ cross = ctx.config.architecture.cross_feature
51
+ if cross.default == "allow":
52
+ return
53
+ model = ctx.model
54
+ for detail, chain in boundary_imports(ctx):
55
+ if detail.external or skip_import(ctx, detail):
56
+ continue
57
+ source = model.info(detail.importer)
58
+ target = model.info(detail.imported)
59
+ if (
60
+ source is None
61
+ or target is None
62
+ or source.wiring
63
+ or not (source.in_grid and target.in_grid)
64
+ ):
65
+ continue
66
+ if source.feature is None or target.feature is None:
67
+ continue
68
+ if source.feature == target.feature:
69
+ continue
70
+ if (
71
+ source.layer
72
+ and target.layer
73
+ and cross.allows(
74
+ source.feature, source.layer, target.feature, target.layer
75
+ )
76
+ ):
77
+ continue
78
+ pair = f"{source.layer or '(feature root)'} -> {target.layer or '(feature root)'}"
79
+ allowed = cross.labels()
80
+ shared = ctx.config.architecture.shared
81
+ hints = [f"Use an allowed pair ({join(allowed)})."] if allowed else []
82
+ if shared:
83
+ hints.append(f"Move the shared concept into {shared[0]}.")
84
+ if source.layer and target.layer:
85
+ hints.append(
86
+ f"If {source.feature} may rely on {target.feature}, that is a "
87
+ "policy decision rather than a bug: allow it under "
88
+ f"architecture.cross_feature.allow as {{from: {source.feature}."
89
+ f"{source.layer}, to: {target.feature}.{target.layer}}}."
90
+ )
91
+ yield import_violation(
92
+ self,
93
+ ctx,
94
+ detail,
95
+ f"feature {source.feature} must not import feature {target.feature} ({pair})",
96
+ expected={"cross_feature_allow": allowed},
97
+ hint=" ".join(hints) or None,
98
+ chain=chain,
99
+ )
100
+
101
+
102
+ _MAY_IMPORT = {
103
+ "shared": "shared code and third-party packages, no feature",
104
+ "central": "shared code, central modules of its layers and third-party packages, "
105
+ "no feature",
106
+ }
107
+
108
+
109
+ class SharedImportsFeature(BaseRule):
110
+ activation = POLICIES["SMT105"]
111
+ code = "SMT105"
112
+ name = "shared-imports-feature"
113
+ category = Category.DEPENDENCIES
114
+ default_severity = Severity.ERROR
115
+ requires = frozenset({Index.IMPORTS})
116
+ doc = RuleDoc(
117
+ summary=(
118
+ "A `shared` module or a central module (`architecture.modules`) imports a "
119
+ "feature module."
120
+ ),
121
+ rationale=(
122
+ "Shared code and central layers such as a platform package are importable by "
123
+ "every feature. If they depend on a feature, every feature transitively "
124
+ "depends on that feature and the slices collapse. With "
125
+ "architecture.imports.transitive, paths through arbitrary project helpers "
126
+ "and facades are checked and reported with a shortest import chain."
127
+ ),
128
+ bad="# gateway/shared/money.py\nfrom gateway.features.billing.domain import Currency",
129
+ good="# gateway/shared/money.py\nclass Currency: ...",
130
+ fix="Move the needed concept into shared, or move the shared code into the feature.",
131
+ config=(
132
+ "architecture.shared",
133
+ "architecture.modules",
134
+ "architecture.imports.transitive",
135
+ "architecture.imports.type_checking",
136
+ ),
137
+ )
138
+
139
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
140
+ model = ctx.model
141
+ for detail, chain in boundary_imports(ctx):
142
+ if detail.external or skip_import(ctx, detail):
143
+ continue
144
+ source = model.info(detail.importer)
145
+ target = model.info(detail.imported)
146
+ if source is None or target is None:
147
+ continue
148
+ if source.kind is not ModuleKind.SHARED and not source.central:
149
+ continue
150
+ if not target.in_grid or target.feature is None:
151
+ continue
152
+ kind = "shared" if source.kind is ModuleKind.SHARED else "central"
153
+ yield import_violation(
154
+ self,
155
+ ctx,
156
+ detail,
157
+ f"{kind} module {detail.importer} must not import feature {target.feature}",
158
+ expected={"may_import": _MAY_IMPORT[kind]},
159
+ hint=(
160
+ f"Move what {detail.importer} needs out of {target.feature} into "
161
+ f"{kind} code, or move {detail.importer} into the {target.feature} "
162
+ "feature."
163
+ ),
164
+ chain=chain,
165
+ )
@@ -0,0 +1,84 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import replace
4
+ from typing import TYPE_CHECKING
5
+
6
+ from smelt.analysis.context import AnalysisContext, Index
7
+ from smelt.analysis.exports import resolve_dotted
8
+ from smelt.diagnostics.violation import Category, Severity, Violation
9
+ from smelt.model import is_within
10
+ from smelt.rules.activation import POLICIES
11
+ from smelt.rules.base import BaseRule, RuleDoc
12
+ from smelt.rules.common import import_violation, join, skip_import
13
+
14
+ if TYPE_CHECKING:
15
+ from collections.abc import Iterator
16
+
17
+ from smelt.analysis.imports import ImportDetail
18
+
19
+
20
+ class PrivateModuleImport(BaseRule):
21
+ activation = POLICIES["SMT107"]
22
+ code = "SMT107"
23
+ name = "private-module-import"
24
+ category = Category.DEPENDENCIES
25
+ default_severity = Severity.ERROR
26
+ requires = frozenset({Index.IMPORTS, Index.SYNTAX})
27
+ doc = RuleDoc(
28
+ summary="Code outside a contracted package imports a private implementation module.",
29
+ rationale=(
30
+ "Explicit entry points keep callers coupled to a package's supported "
31
+ "interface. Internal imports and intentional symbol re-exports through "
32
+ "public facades remain valid. Wiring and composition roots still obey "
33
+ "these contracts. Layer and feature policies apply independently."
34
+ ),
35
+ bad="# app/client.py\nfrom app.orders.storage import OrderStore",
36
+ good="# app/client.py\nfrom app.orders.api import place_order",
37
+ fix=(
38
+ "Import through one of the contract's public entry points. Expose a "
39
+ "deliberate API there if needed, or explicitly revise the contract. "
40
+ "Public entries are exact module patterns; add .** only when the whole "
41
+ "subtree is intentionally public."
42
+ ),
43
+ config=("structure.contracts", "architecture.imports.type_checking"),
44
+ )
45
+
46
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
47
+ if not any(contract.public is not None for contract in ctx.contracts.resolved):
48
+ return
49
+ for detail in ctx.imports.all_imports():
50
+ if detail.external or skip_import(ctx, detail):
51
+ continue
52
+ for target in _module_targets(ctx, detail):
53
+ for contract in ctx.contracts.resolved:
54
+ if (
55
+ contract.public is None
56
+ or not is_within(target, contract.package)
57
+ or is_within(detail.importer, contract.package)
58
+ or contract.exposes(target)
59
+ ):
60
+ continue
61
+ yield import_violation(
62
+ self,
63
+ ctx,
64
+ replace(detail, imported=target),
65
+ f'{detail.importer} imports private module {target} of contract "{contract.name}"',
66
+ expected={
67
+ "contract": contract.name,
68
+ "package": contract.package,
69
+ "public": list(contract.public),
70
+ },
71
+ hint=f"Use a public entry point of {contract.package}: {join(contract.public, empty='none; this package is private')}.",
72
+ edge=f"{detail.importer} -> {contract.package} ({contract.name})",
73
+ )
74
+
75
+
76
+ def _module_targets(ctx: AnalysisContext, detail: ImportDetail) -> Iterator[str]:
77
+ """Keep symbol re-exports public, but resolve explicit module-valued aliases."""
78
+ seen = {detail.imported}
79
+ yield detail.imported
80
+ for name in detail.names:
81
+ resolved = resolve_dotted(name, ctx.syntax.namespace)
82
+ if resolved is not None and resolved[1] is None and resolved[0] not in seen:
83
+ seen.add(resolved[0])
84
+ yield resolved[0]
@@ -0,0 +1,138 @@
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, ImportLink, Severity, Violation
7
+ from smelt.rules.activation import POLICIES
8
+ from smelt.rules.base import BaseRule, RuleDoc
9
+ from smelt.rules.common import (
10
+ boundary_imports,
11
+ import_violation,
12
+ join,
13
+ skip_import,
14
+ )
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Iterator
18
+
19
+ from smelt.analysis.imports import ImportDetail
20
+ from smelt.model import ModuleInfo
21
+
22
+
23
+ class LayerBoundary(BaseRule):
24
+ activation = POLICIES["SMT101"]
25
+ code = "SMT101"
26
+ name = "layer-boundary"
27
+ category = Category.DEPENDENCIES
28
+ default_severity = Severity.ERROR
29
+ requires = frozenset({Index.IMPORTS})
30
+ doc = RuleDoc(
31
+ summary="A layer imports a layer outside its `may_depend_on` allowlist.",
32
+ rationale=(
33
+ "Layers only stay replaceable and testable when dependencies point in one "
34
+ "direction. An application service that imports infrastructure cannot be "
35
+ "used without the database, HTTP client or framework behind it. With "
36
+ "architecture.imports.transitive, the allowlist also applies to every "
37
+ "reachable layer, including paths through allowed layers and helpers. "
38
+ "Indirect findings include a shortest import chain."
39
+ ),
40
+ bad=(
41
+ "# voice/application/session.py\n"
42
+ "from gateway.features.voice.infra.sql import SqlVoiceSessionRepository"
43
+ ),
44
+ good=(
45
+ "# voice/application/session.py\n"
46
+ "from gateway.features.voice.application.ports import VoiceSessionRepository\n\n"
47
+ "# gateway/bootstrap.py wires SqlVoiceSessionRepository to the port"
48
+ ),
49
+ fix=(
50
+ "Depend on an abstraction (a port) owned by the importing layer or an allowed "
51
+ "layer, and wire the concrete implementation in the composition root."
52
+ ),
53
+ config=(
54
+ "architecture.layers.<layer>.may_depend_on",
55
+ "architecture.modules",
56
+ "architecture.imports.transitive",
57
+ "architecture.imports.type_checking",
58
+ ),
59
+ )
60
+
61
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
62
+ model = ctx.model
63
+ for detail, chain in boundary_imports(ctx):
64
+ if detail.external or skip_import(ctx, detail):
65
+ continue
66
+ source = model.info(detail.importer)
67
+ forbidden = _forbidden_layer(ctx, source, model.info(detail.imported))
68
+ if source is not None and forbidden is not None:
69
+ yield self._violation(ctx, detail, source, forbidden, chain)
70
+
71
+ def _violation(
72
+ self,
73
+ ctx: AnalysisContext,
74
+ detail: ImportDetail,
75
+ source: ModuleInfo,
76
+ target_layer: str,
77
+ chain: tuple[ImportLink, ...] = (),
78
+ ) -> Violation:
79
+ layer = source.layer or ""
80
+ allowed = list(ctx.model.layers[layer].may_depend_on)
81
+ via = " (indirectly)" if chain else ""
82
+ return import_violation(
83
+ self,
84
+ ctx,
85
+ detail,
86
+ f"{layer} must not depend on {target_layer}{via}",
87
+ expected={"may_depend_on": allowed},
88
+ hint=_hint(ctx, detail, source, chain),
89
+ chain=chain,
90
+ )
91
+
92
+
93
+ def _forbidden_layer(
94
+ ctx: AnalysisContext, source: ModuleInfo | None, target: ModuleInfo | None
95
+ ) -> str | None:
96
+ """The target's layer if ``source`` must not import ``target``."""
97
+ if (
98
+ source is None
99
+ or target is None
100
+ or source.wiring
101
+ or not (source.in_grid and target.in_grid)
102
+ ):
103
+ return None
104
+ if source.layer is None or target.layer is None:
105
+ return None
106
+ if source.layer == target.layer:
107
+ return None
108
+ # across features SMT102 decides; a central module shares its layer rules with all
109
+ if source.feature != target.feature and not (source.central or target.central):
110
+ return None
111
+ if target.layer in ctx.model.layers[source.layer].may_depend_on:
112
+ return None
113
+ return target.layer
114
+
115
+
116
+ def _hint(
117
+ ctx: AnalysisContext,
118
+ detail: ImportDetail,
119
+ source: ModuleInfo,
120
+ chain: tuple[ImportLink, ...],
121
+ ) -> str:
122
+ model = ctx.model
123
+ layer = source.layer or ""
124
+ allowed = join(list(model.layers[layer].may_depend_on))
125
+ if not model.layers[layer].may_depend_on and not chain:
126
+ return (
127
+ f"{layer} depends on no other layer. Define what it needs as an "
128
+ f"abstraction in {layer} and implement it in an outer layer."
129
+ )
130
+ if chain:
131
+ return (
132
+ f"The dependency goes through {join([link.imported for link in chain[:-1]])}; "
133
+ f"break the chain or move the code into a layer {layer} may use ({allowed})."
134
+ )
135
+ return (
136
+ f"Move what {layer} needs into a layer it may depend on ({allowed}), "
137
+ "or invert the dependency behind an abstraction."
138
+ )
@@ -0,0 +1,132 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from smelt.analysis.context import AnalysisContext, Index
6
+ from smelt.analysis.parsing import is_stdlib
7
+ from smelt.diagnostics.violation import Category, Severity, Violation
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
+ join,
14
+ matches_any,
15
+ skip_import,
16
+ )
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Iterator
20
+
21
+ from smelt.analysis.imports import ImportDetail
22
+ from smelt.config.models import ThirdPartyPolicy
23
+
24
+
25
+ def _is_denied(policy: ThirdPartyPolicy, names: tuple[str, ...]) -> bool:
26
+ if policy.default == "allow":
27
+ return any(matches_any(name, policy.deny) for name in names)
28
+ return not all(matches_any(name, policy.allow) for name in names)
29
+
30
+
31
+ class ThirdPartyDenied(BaseRule):
32
+ activation = POLICIES["SMT103"]
33
+ code = "SMT103"
34
+ name = "third-party-denied"
35
+ category = Category.DEPENDENCIES
36
+ default_severity = Severity.ERROR
37
+ requires = frozenset({Index.IMPORTS})
38
+ doc = RuleDoc(
39
+ summary="A layer imports a third-party package its `third_party` policy does not allow.",
40
+ rationale=(
41
+ "Inner layers should not know about frameworks, drivers or SDKs. Keeping them "
42
+ "out makes the core portable and cheap to test. With "
43
+ "architecture.imports.transitive, the importing layer's policy also "
44
+ "applies to packages reached through project modules, such as "
45
+ "domain -> shared.utils -> sqlalchemy. A shortest chain includes each "
46
+ "import's source line. External packages are leaves: their own source "
47
+ "is not scanned. Standard-library imports remain allowed."
48
+ ),
49
+ bad="# voice/domain/session.py\nfrom sqlalchemy.orm import Mapped",
50
+ good="# voice/domain/session.py\nfrom dataclasses import dataclass",
51
+ fix=(
52
+ "Move the code that needs the package into a layer that allows it and expose "
53
+ "it through a port, or extend the layer's `third_party` policy."
54
+ ),
55
+ config=(
56
+ "architecture.layers.<layer>.third_party.default",
57
+ "architecture.layers.<layer>.third_party.allow",
58
+ "architecture.layers.<layer>.third_party.deny",
59
+ "architecture.imports.transitive",
60
+ "architecture.imports.type_checking",
61
+ ),
62
+ )
63
+
64
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
65
+ model = ctx.model
66
+ reported: set[tuple[str, str]] = set()
67
+ for detail, chain in boundary_imports(ctx):
68
+ if (
69
+ not detail.external
70
+ or is_stdlib(detail.imported)
71
+ or skip_import(ctx, detail)
72
+ ):
73
+ continue
74
+ source = model.info(detail.importer)
75
+ if source is None or not source.in_grid or source.layer is None:
76
+ continue
77
+ policy = model.layers[source.layer].third_party
78
+ names = detail.names or (detail.imported,)
79
+ if not _is_denied(policy, names):
80
+ continue
81
+ key = (detail.importer, detail.imported)
82
+ if chain and key in reported:
83
+ continue
84
+ reported.add(key)
85
+ message = _message(source.layer, detail, policy)
86
+ if chain:
87
+ message += " (indirectly)"
88
+ yield import_violation(
89
+ self,
90
+ ctx,
91
+ detail,
92
+ message,
93
+ expected=_expected(policy),
94
+ hint=_hint(ctx, detail, source.layer),
95
+ chain=chain,
96
+ )
97
+
98
+
99
+ def _message(layer: str, detail: ImportDetail, policy: ThirdPartyPolicy) -> str:
100
+ package = detail.top_level
101
+ if policy.default == "deny":
102
+ allowed = join(policy.allow, "")
103
+ suffix = (
104
+ f"{layer} allows only: {allowed}"
105
+ if allowed
106
+ else f"{layer} allows no third-party packages"
107
+ )
108
+ return f"{layer} must not import {package} ({suffix})"
109
+ return f"{layer} must not import {package} (denied: {join(policy.deny)})"
110
+
111
+
112
+ def _expected(policy: ThirdPartyPolicy) -> dict[str, object]:
113
+ if policy.default == "deny":
114
+ return {"third_party": {"default": "deny", "allow": list(policy.allow)}}
115
+ return {"third_party": {"default": "allow", "deny": list(policy.deny)}}
116
+
117
+
118
+ def _hint(ctx: AnalysisContext, detail: ImportDetail, layer: str) -> str:
119
+ names = detail.names or (detail.imported,)
120
+ welcoming = [
121
+ name
122
+ for name, config in ctx.model.layers.items()
123
+ if name != layer and not _is_denied(config.third_party, names)
124
+ ]
125
+ if welcoming:
126
+ return (
127
+ f"Keep {detail.top_level} in a layer that allows it ({join(welcoming)}) "
128
+ f"and let {layer} depend on an abstraction."
129
+ )
130
+ return (
131
+ f"No layer allows {detail.top_level}; add it to a layer's third_party policy."
132
+ )
@@ -0,0 +1,13 @@
1
+ """Name suggestions shared by public-member review rules."""
2
+
3
+
4
+ def private_name(name: str, occupied: frozenset[str]) -> str:
5
+ preferred = f"_{name.lstrip('_')}"
6
+ if preferred not in occupied:
7
+ return preferred
8
+ candidate = f"{preferred}_internal"
9
+ suffix = 2
10
+ while candidate in occupied:
11
+ candidate = f"{preferred}_internal_{suffix}"
12
+ suffix += 1
13
+ return candidate
smelt/rules/meta.py ADDED
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from smelt.diagnostics.violation import Category, Severity
6
+ from smelt.rules.base import BaseRule, RuleDoc
7
+
8
+ if TYPE_CHECKING:
9
+ from collections.abc import Iterator
10
+
11
+ from smelt.analysis.context import AnalysisContext
12
+ from smelt.diagnostics.violation import Violation
13
+
14
+
15
+ class _EngineRule(BaseRule):
16
+ """Meta rules are evaluated by the engine after filtering, not by ``check``."""
17
+
18
+ category = Category.META
19
+ scope = "project"
20
+ enabled_by_default = True
21
+
22
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
23
+ return iter(())
24
+
25
+
26
+ class UnusedSuppression(_EngineRule):
27
+ code = "SMT901"
28
+ name = "unused-suppression"
29
+ default_severity = Severity.WARNING
30
+ doc = RuleDoc(
31
+ summary="An inline `# smelt: ignore[...]` comment that suppresses nothing.",
32
+ rationale=(
33
+ "Stale suppressions hide future violations on the same line and make readers "
34
+ "believe there is an exception where there is none."
35
+ ),
36
+ bad="import os # smelt: ignore[SMT101] -- legacy",
37
+ good="import os",
38
+ fix="Remove the comment, or the unused codes from it.",
39
+ config=("suppressions.require_reason",),
40
+ )
41
+
42
+
43
+ class SuppressionWithoutReason(_EngineRule):
44
+ code = "SMT902"
45
+ name = "suppression-without-reason"
46
+ default_severity = Severity.ERROR
47
+ doc = RuleDoc(
48
+ summary="An inline suppression without a `-- reason`.",
49
+ rationale=(
50
+ "Every exception to the architecture should explain itself, so the next "
51
+ "person (or agent) knows whether it can be removed."
52
+ ),
53
+ bad="from app.infra import Db # smelt: ignore[SMT101]",
54
+ good="from app.infra import Db # smelt: ignore[SMT101] -- migration tracked in #123",
55
+ fix="Append ` -- <reason>` to the comment.",
56
+ config=("suppressions.require_reason",),
57
+ )
58
+
59
+
60
+ class ResolvedDebt(_EngineRule):
61
+ code = "SMT903"
62
+ name = "resolved-debt"
63
+ default_severity = Severity.WARNING
64
+ doc = RuleDoc(
65
+ summary="A debt entry that no longer matches any violation.",
66
+ rationale=(
67
+ "Fixed violations should leave the debt file, otherwise they could silently "
68
+ "come back."
69
+ ),
70
+ bad='{"code": "SMT101", "path": "app/application/old.py", ...}',
71
+ good="(entry removed after the violation was fixed)",
72
+ fix="Run `smelt debt --prune`.",
73
+ config=("debt",),
74
+ )