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/registry.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Explicit rule registration, with generated lightweight selection metadata."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from functools import cached_property
|
|
7
|
+
from importlib import import_module
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
10
|
+
|
|
11
|
+
from smelt.analysis.context import Index
|
|
12
|
+
from smelt.diagnostics.violation import Category, Severity
|
|
13
|
+
from smelt.rules.activation import POLICIES
|
|
14
|
+
from smelt.rules.base import RuleSet
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Iterable
|
|
18
|
+
|
|
19
|
+
from smelt.analysis.context import AnalysisContext
|
|
20
|
+
from smelt.diagnostics.violation import Violation
|
|
21
|
+
from smelt.rules.base import Rule, RuleDoc
|
|
22
|
+
|
|
23
|
+
_IMPLEMENTATIONS = (
|
|
24
|
+
"smelt.rules.dependencies.layers:LayerBoundary",
|
|
25
|
+
"smelt.rules.dependencies.features:CrossFeatureImport",
|
|
26
|
+
"smelt.rules.dependencies.third_party:ThirdPartyDenied",
|
|
27
|
+
"smelt.rules.dependencies.cycles:ImportCycle",
|
|
28
|
+
"smelt.rules.dependencies.features:SharedImportsFeature",
|
|
29
|
+
"smelt.rules.dependencies.composition_root:CompositionRootLeak",
|
|
30
|
+
"smelt.rules.dependencies.interfaces:PrivateModuleImport",
|
|
31
|
+
"smelt.rules.dependencies.fanout:PackageImportFanout",
|
|
32
|
+
"smelt.rules.structure.layout:UnknownLayer",
|
|
33
|
+
"smelt.rules.structure.naming:ForbiddenPackageName",
|
|
34
|
+
"smelt.rules.structure.layout:UnclassifiedModule",
|
|
35
|
+
"smelt.rules.structure.coverage:IncompleteCoverage",
|
|
36
|
+
"smelt.rules.structure.contracts:MissingRequiredModule",
|
|
37
|
+
"smelt.rules.structure.import_style:ImportStyle",
|
|
38
|
+
"smelt.rules.structure.headers:ForbiddenModuleDocstring",
|
|
39
|
+
"smelt.rules.structure.headers:ForbiddenFutureAnnotations",
|
|
40
|
+
"smelt.rules.structure.headers:UnnecessaryFutureAnnotations",
|
|
41
|
+
"smelt.rules.structure.naming:NoPrivateModules",
|
|
42
|
+
"smelt.rules.structure.ordering:PublicDefinitionsFirst",
|
|
43
|
+
"smelt.rules.structure.assignments:BundledInstanceAssignment",
|
|
44
|
+
"smelt.rules.structure.type_dispatch:PreferMatchTypeDispatch",
|
|
45
|
+
"smelt.rules.structure.members:InternalPublicMember",
|
|
46
|
+
"smelt.rules.structure.members:InternalStaticHelper",
|
|
47
|
+
"smelt.rules.structure.enum_values:RedundantStrEnumValue",
|
|
48
|
+
"smelt.rules.structure.package_imports:PreferPackageImport",
|
|
49
|
+
"smelt.rules.testing.location:MisplacedTestFile",
|
|
50
|
+
"smelt.rules.testing.private_access:PrivateTestAccess",
|
|
51
|
+
"smelt.rules.testing.mocking:ForbiddenTestMock",
|
|
52
|
+
"smelt.rules.testing.mocking:StringPatchTarget",
|
|
53
|
+
"smelt.rules.testing.mocking:ExcessiveTestPatches",
|
|
54
|
+
"smelt.rules.testing.outcomes:TestWithoutOutcomeCheck",
|
|
55
|
+
"smelt.rules.testing.outcomes:TestOnlyChecksPossiblyEmptyData",
|
|
56
|
+
"smelt.rules.testing.timing:UnboundedTestWait",
|
|
57
|
+
"smelt.rules.testing.cases:IndependentTestCaseLoop",
|
|
58
|
+
"smelt.rules.testing.awaits:AsyncMockWithoutAwaitCheck",
|
|
59
|
+
"smelt.rules.testing.public_functions:TestOnlyPublicFunction",
|
|
60
|
+
"smelt.rules.testing.public_attributes:TestOnlyPublicAttribute",
|
|
61
|
+
"smelt.rules.meta:UnusedSuppression",
|
|
62
|
+
"smelt.rules.meta:SuppressionWithoutReason",
|
|
63
|
+
"smelt.rules.meta:ResolvedDebt",
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _load(target: str) -> Rule:
|
|
68
|
+
module, name = target.split(":")
|
|
69
|
+
return cast("Rule", getattr(import_module(module), name)())
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class _LazyRule:
|
|
73
|
+
def __init__(self, metadata: dict[str, Any]) -> None:
|
|
74
|
+
self.code = str(metadata["code"])
|
|
75
|
+
self.name = str(metadata["name"])
|
|
76
|
+
self.category = Category(metadata["category"])
|
|
77
|
+
self.default_severity = Severity(metadata["default_severity"])
|
|
78
|
+
self.requires = frozenset(Index(value) for value in metadata["requires"])
|
|
79
|
+
self.scope = str(metadata["scope"])
|
|
80
|
+
self.enabled_by_default = bool(metadata["enabled_by_default"])
|
|
81
|
+
self.activation = POLICIES.get(self.code)
|
|
82
|
+
self.file_local = bool(metadata["file_local"])
|
|
83
|
+
self.test_local = bool(metadata["test_local"])
|
|
84
|
+
self.member_local = bool(metadata["member_local"])
|
|
85
|
+
self._target = str(metadata["target"])
|
|
86
|
+
|
|
87
|
+
@cached_property
|
|
88
|
+
def _implementation(self) -> Rule:
|
|
89
|
+
return _load(self._target)
|
|
90
|
+
|
|
91
|
+
def check(self, ctx: AnalysisContext) -> Iterable[Violation]:
|
|
92
|
+
return self._implementation.check(ctx)
|
|
93
|
+
|
|
94
|
+
def explain(self) -> RuleDoc:
|
|
95
|
+
return self._implementation.explain()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def catalog_metadata() -> list[dict[str, Any]]:
|
|
99
|
+
return [
|
|
100
|
+
{
|
|
101
|
+
"target": f"{type(rule).__module__}:{type(rule).__name__}",
|
|
102
|
+
"code": rule.code,
|
|
103
|
+
"name": rule.name,
|
|
104
|
+
"category": rule.category.value,
|
|
105
|
+
"default_severity": rule.default_severity.value,
|
|
106
|
+
"requires": sorted(index.value for index in rule.requires),
|
|
107
|
+
**{
|
|
108
|
+
flag: getattr(rule, flag, False)
|
|
109
|
+
for flag in (
|
|
110
|
+
"enabled_by_default",
|
|
111
|
+
"file_local",
|
|
112
|
+
"test_local",
|
|
113
|
+
"member_local",
|
|
114
|
+
)
|
|
115
|
+
},
|
|
116
|
+
"scope": getattr(rule, "scope", "source"),
|
|
117
|
+
}
|
|
118
|
+
for rule in sorted(_builtin_rules(), key=lambda rule: rule.code)
|
|
119
|
+
]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def build_rule_set(*, lazy: bool = False) -> RuleSet:
|
|
123
|
+
if lazy:
|
|
124
|
+
entries = json.loads(
|
|
125
|
+
Path(__file__).with_name("catalog.json").read_text(encoding="utf-8")
|
|
126
|
+
)
|
|
127
|
+
return RuleSet([_LazyRule(entry) for entry in entries])
|
|
128
|
+
return RuleSet(sorted(_builtin_rules(), key=lambda rule: rule.code))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _builtin_rules() -> list[Rule]:
|
|
132
|
+
return [_load(target) for target in _IMPLEMENTATIONS]
|
|
File without changes
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
from smelt.analysis.context import AnalysisContext, Index
|
|
7
|
+
from smelt.diagnostics.violation import Category, Violation
|
|
8
|
+
from smelt.rules.base import BaseRule, RuleDoc
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _assignments(node: ast.AST) -> Iterator[ast.Assign]:
|
|
15
|
+
if isinstance(
|
|
16
|
+
node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef | ast.Lambda
|
|
17
|
+
):
|
|
18
|
+
return
|
|
19
|
+
if isinstance(node, ast.Assign):
|
|
20
|
+
yield node
|
|
21
|
+
for child in ast.iter_child_nodes(node):
|
|
22
|
+
yield from _assignments(child)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _attributes(target: ast.expr, receiver: str) -> Iterator[ast.Attribute]:
|
|
26
|
+
match target:
|
|
27
|
+
case ast.Attribute(value=ast.Name(id=name)) if name == receiver:
|
|
28
|
+
yield target
|
|
29
|
+
case ast.Tuple(elts=elements) | ast.List(elts=elements):
|
|
30
|
+
for element in elements:
|
|
31
|
+
yield from _attributes(element, receiver)
|
|
32
|
+
case ast.Starred(value=value):
|
|
33
|
+
yield from _attributes(value, receiver)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _qualified(node: ast.expr, bindings: dict[str, str]) -> str | None:
|
|
37
|
+
if isinstance(node, ast.Name):
|
|
38
|
+
return bindings.get(node.id, node.id)
|
|
39
|
+
if isinstance(node, ast.Attribute):
|
|
40
|
+
parent = _qualified(node.value, bindings)
|
|
41
|
+
return f"{parent}.{node.attr}" if parent else None
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BundledInstanceAssignment(BaseRule):
|
|
46
|
+
file_local = True
|
|
47
|
+
code = "SMT314"
|
|
48
|
+
name = "bundled-instance-assignment"
|
|
49
|
+
category = Category.STRUCTURE
|
|
50
|
+
requires = frozenset({Index.SYNTAX})
|
|
51
|
+
doc = RuleDoc(
|
|
52
|
+
summary="An assignment writes multiple direct instance attributes under a separate-assignment convention.",
|
|
53
|
+
rationale="Separate field assignments make object initialization easy to scan and extend. This opt-in package convention reports tuple/list unpacking and chained assignments that write multiple direct attributes of a method's first positional parameter, regardless of its name. It leaves local unpacking and single-field assignments alone. Recognized static/class methods and nested helper bodies are excluded; nested classes are inspected with their own receiver. This is a readability policy, not a logic error.",
|
|
54
|
+
bad="class Inbox:\n def __init__(self, log, control):\n self.log, self.control = log, control",
|
|
55
|
+
good="class Inbox:\n def __init__(self, log, control):\n self.log = log\n self.control = control",
|
|
56
|
+
fix="Use one direct instance attribute write per statement. Preserve evaluation timing: unpack computed values into locals before assigning fields when appropriate. Parallel assignments, swaps, descriptors and unpacking failures can behave differently when split, so there is no automatic rewrite.",
|
|
57
|
+
config=("rules", "structure.contracts"),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
61
|
+
for source in ctx.files.sources.values():
|
|
62
|
+
syntax = ctx.syntax.for_path(source.path)
|
|
63
|
+
if syntax is None:
|
|
64
|
+
continue
|
|
65
|
+
for cls in ast.walk(syntax.tree):
|
|
66
|
+
if not isinstance(cls, ast.ClassDef):
|
|
67
|
+
continue
|
|
68
|
+
for method in cls.body:
|
|
69
|
+
if not isinstance(method, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
70
|
+
continue
|
|
71
|
+
args = [*method.args.posonlyargs, *method.args.args]
|
|
72
|
+
if (
|
|
73
|
+
method.name
|
|
74
|
+
in {"__new__", "__init_subclass__", "__class_getitem__"}
|
|
75
|
+
or not args
|
|
76
|
+
or any(
|
|
77
|
+
_qualified(decorator, syntax.bindings)
|
|
78
|
+
in {
|
|
79
|
+
"staticmethod",
|
|
80
|
+
"classmethod",
|
|
81
|
+
"builtins.staticmethod",
|
|
82
|
+
"builtins.classmethod",
|
|
83
|
+
}
|
|
84
|
+
for decorator in method.decorator_list
|
|
85
|
+
)
|
|
86
|
+
):
|
|
87
|
+
continue
|
|
88
|
+
for statement in method.body:
|
|
89
|
+
for assignment in _assignments(statement):
|
|
90
|
+
targets = [
|
|
91
|
+
target
|
|
92
|
+
for root in assignment.targets
|
|
93
|
+
for target in _attributes(root, args[0].arg)
|
|
94
|
+
]
|
|
95
|
+
if len(targets) <= 1:
|
|
96
|
+
continue
|
|
97
|
+
yield self.violation(
|
|
98
|
+
f"assignment writes {len(targets)} instance attributes; use separate statements",
|
|
99
|
+
path=source.path,
|
|
100
|
+
line=assignment.lineno,
|
|
101
|
+
column=assignment.col_offset + 1,
|
|
102
|
+
end_line=assignment.end_lineno,
|
|
103
|
+
end_column=(assignment.end_col_offset or 0) + 1,
|
|
104
|
+
source_module=source.module,
|
|
105
|
+
expected={
|
|
106
|
+
"class": cls.name,
|
|
107
|
+
"method": method.name,
|
|
108
|
+
"attributes": [
|
|
109
|
+
ast.unparse(target) for target in targets
|
|
110
|
+
],
|
|
111
|
+
"automatic_split": False,
|
|
112
|
+
},
|
|
113
|
+
hint="Write each field separately, preserving the original evaluation order and unpacking behavior.",
|
|
114
|
+
)
|
|
@@ -0,0 +1,71 @@
|
|
|
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.rules.activation import POLICIES
|
|
8
|
+
from smelt.rules.base import BaseRule, RuleDoc
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MissingRequiredModule(BaseRule):
|
|
15
|
+
activation = POLICIES["SMT307"]
|
|
16
|
+
code = "SMT307"
|
|
17
|
+
name = "missing-required-module"
|
|
18
|
+
category = Category.STRUCTURE
|
|
19
|
+
default_severity = Severity.ERROR
|
|
20
|
+
requires = frozenset({Index.FILES})
|
|
21
|
+
doc = RuleDoc(
|
|
22
|
+
summary="A package contract is missing a required module or public entry point.",
|
|
23
|
+
rationale=(
|
|
24
|
+
"Explicit package contracts let contributors and agents follow the same "
|
|
25
|
+
"structure. They apply only to matching packages and require no particular "
|
|
26
|
+
"framework, feature layout or layer names. Excluded code does not fulfill "
|
|
27
|
+
"a contract. This checks presence, not implementation quality."
|
|
28
|
+
),
|
|
29
|
+
bad="structure:\n contracts:\n slices:\n match: app.slices.*\n required: [api] # app.slices.orders.api is absent",
|
|
30
|
+
good="structure:\n contracts:\n slices:\n match: app.slices.*\n required: [api] # every matching package has an api module or package",
|
|
31
|
+
fix=(
|
|
32
|
+
"Implement the missing module in the matching package. If that package "
|
|
33
|
+
"should follow a different structure, narrow or split the contract. Do "
|
|
34
|
+
"not add empty implementation stubs solely to satisfy the check."
|
|
35
|
+
),
|
|
36
|
+
config=("structure.contracts",),
|
|
37
|
+
example_language="yaml",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
41
|
+
index = ctx.contracts
|
|
42
|
+
for contract in index.resolved:
|
|
43
|
+
missing = index.missing(contract)
|
|
44
|
+
absent = [
|
|
45
|
+
*[(module, "required module") for module in missing],
|
|
46
|
+
*[
|
|
47
|
+
(pattern, "public entry point")
|
|
48
|
+
for pattern in index.missing_public(contract)
|
|
49
|
+
if pattern not in missing
|
|
50
|
+
],
|
|
51
|
+
]
|
|
52
|
+
info = ctx.model.info(contract.package)
|
|
53
|
+
for module, kind in absent:
|
|
54
|
+
yield self.violation(
|
|
55
|
+
f'contract "{contract.name}" on {contract.package} is missing {kind} {module}',
|
|
56
|
+
path=ctx.files.path_for_module(contract.package),
|
|
57
|
+
source_module=contract.package,
|
|
58
|
+
target_module=module,
|
|
59
|
+
feature=info.feature if info else None,
|
|
60
|
+
layer=info.layer if info else None,
|
|
61
|
+
expected={
|
|
62
|
+
"contract": contract.name,
|
|
63
|
+
"package": contract.package,
|
|
64
|
+
"module": module,
|
|
65
|
+
"kind": kind,
|
|
66
|
+
},
|
|
67
|
+
hint=(
|
|
68
|
+
f"Implement {module} under {contract.package}, or narrow "
|
|
69
|
+
f"structure.contracts.{contract.name} to packages sharing that structure."
|
|
70
|
+
),
|
|
71
|
+
)
|
|
@@ -0,0 +1,100 @@
|
|
|
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.rules.activation import POLICIES
|
|
8
|
+
from smelt.rules.base import BaseRule, RuleDoc
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class IncompleteCoverage(BaseRule):
|
|
15
|
+
scope = "project"
|
|
16
|
+
activation = POLICIES["SMT306"]
|
|
17
|
+
code = "SMT306"
|
|
18
|
+
name = "incomplete-coverage"
|
|
19
|
+
category = Category.STRUCTURE
|
|
20
|
+
default_severity = Severity.ERROR
|
|
21
|
+
requires = frozenset({Index.FILES})
|
|
22
|
+
doc = RuleDoc(
|
|
23
|
+
summary="Strict coverage found source outside the architecture policy or an exclusion without a reason.",
|
|
24
|
+
rationale=(
|
|
25
|
+
"A passing architecture check is only useful when production code cannot "
|
|
26
|
+
"silently escape its package selection or classification. Strict coverage "
|
|
27
|
+
"inventories source roots and Python workspace members independently of "
|
|
28
|
+
"project.root_packages. Pure package facades do not need their own layer."
|
|
29
|
+
),
|
|
30
|
+
bad=(
|
|
31
|
+
"# smelt.yaml\nproject:\n root_packages: [backend]\n coverage: strict\n"
|
|
32
|
+
"# A new workspace library exists but is not selected or classified."
|
|
33
|
+
),
|
|
34
|
+
good=(
|
|
35
|
+
"# smelt.yaml\nproject:\n root_packages: [backend, client]\n"
|
|
36
|
+
" source_roots: [backend/src, libs/client/src]\n coverage: strict\n"
|
|
37
|
+
"architecture:\n modules: {client: infrastructure}"
|
|
38
|
+
),
|
|
39
|
+
fix=(
|
|
40
|
+
"Select missing production packages and assign their architecture role. "
|
|
41
|
+
"Move unclassified implementation into an existing layer. Deliberately "
|
|
42
|
+
"excluded code needs project.exclude entries with path and reason. "
|
|
43
|
+
"Coverage gaps cannot be hidden by debt, inline ignores or a narrowed check."
|
|
44
|
+
),
|
|
45
|
+
config=(
|
|
46
|
+
"project.coverage",
|
|
47
|
+
"project.root_packages",
|
|
48
|
+
"project.source_roots",
|
|
49
|
+
"project.exclude",
|
|
50
|
+
"architecture.modules",
|
|
51
|
+
),
|
|
52
|
+
example_language="yaml",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
56
|
+
if ctx.config.project.coverage != "strict":
|
|
57
|
+
return
|
|
58
|
+
for pattern in ctx.coverage.unexplained_exclusions:
|
|
59
|
+
yield self.violation(
|
|
60
|
+
f'exclusion "{pattern}" has no coverage reason',
|
|
61
|
+
expected={
|
|
62
|
+
"exclusion": {
|
|
63
|
+
"path": pattern,
|
|
64
|
+
"reason": "<why this code is outside this policy>",
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
hint="Use a project.exclude entry with path and a nonempty reason.",
|
|
68
|
+
)
|
|
69
|
+
for entry in ctx.coverage.gaps:
|
|
70
|
+
package = entry.module.split(".")[0] if entry.module else None
|
|
71
|
+
standalone = bool(
|
|
72
|
+
entry.module
|
|
73
|
+
and "." not in entry.module
|
|
74
|
+
and not entry.path.endswith("__init__.py")
|
|
75
|
+
)
|
|
76
|
+
hint = (
|
|
77
|
+
f"Select {package or 'the package'} under project.root_packages and "
|
|
78
|
+
f"{entry.source_root or 'its import root'} under project.source_roots, then declare its architecture role."
|
|
79
|
+
if entry.status == "uncovered"
|
|
80
|
+
else "Move the implementation into a declared layer, or assign its intended "
|
|
81
|
+
"role under architecture.modules. Reserve wiring for actual assembly."
|
|
82
|
+
)
|
|
83
|
+
if entry.status == "uncovered" and standalone:
|
|
84
|
+
package = None
|
|
85
|
+
hint = "Move the standalone module into a governed package; project.root_packages selects directories, not individual Python files."
|
|
86
|
+
yield self.violation(
|
|
87
|
+
f"{entry.path} is {entry.status}: {entry.reason}",
|
|
88
|
+
path=entry.path,
|
|
89
|
+
source_module=entry.module,
|
|
90
|
+
feature=entry.feature,
|
|
91
|
+
layer=entry.layer,
|
|
92
|
+
expected={
|
|
93
|
+
"coverage_status": "governed, facade or excluded with a reason",
|
|
94
|
+
"actual_status": entry.status,
|
|
95
|
+
"root_package": package,
|
|
96
|
+
"source_root": entry.source_root,
|
|
97
|
+
},
|
|
98
|
+
hint=hint
|
|
99
|
+
+ " For deliberate exclusions, declare path and reason under project.exclude.",
|
|
100
|
+
)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
from smelt.analysis.context import AnalysisContext, Index
|
|
7
|
+
from smelt.analysis.enum_values import str_enum_value_accesses
|
|
8
|
+
from smelt.diagnostics.violation import Category, Severity, Violation
|
|
9
|
+
from smelt.rules.base import BaseRule, RuleDoc
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Iterator
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RedundantStrEnumValue(BaseRule):
|
|
16
|
+
code = "SMT318"
|
|
17
|
+
name = "redundant-str-enum-value"
|
|
18
|
+
category = Category.STRUCTURE
|
|
19
|
+
default_severity = Severity.HINT
|
|
20
|
+
requires = frozenset({Index.SYNTAX})
|
|
21
|
+
doc = RuleDoc(
|
|
22
|
+
summary="Review .value on a known StrEnum member for direct use of the member.",
|
|
23
|
+
rationale="StrEnum members are already strings, so extracting .value often adds noise and loses the enum type unnecessarily. This opt-in hint recognizes direct Class.MEMBER.value reads on analyzed, top-level classes inheriting directly from enum.StrEnum, including import aliases, relative imports and analyzed re-exports. Simple string, auto() and member-alias declarations are supported. Ordinary Enum, str/Enum mixins, unknown or shadowed bindings, custom enum construction/value access, instance variables and dynamic lookups are excluded. Shadowing anywhere in a module conservatively limits recognition there.",
|
|
24
|
+
bad='from enum import StrEnum\n\nclass MouseEventKind(StrEnum):\n WHEEL = "mouseWheel"\n\ndispatch_mouse_event(type=MouseEventKind.WHEEL.value)',
|
|
25
|
+
good='from enum import StrEnum\n\nclass MouseEventKind(StrEnum):\n WHEEL = "mouseWheel"\n\ndispatch_mouse_event(type=MouseEventKind.WHEEL)',
|
|
26
|
+
fix="Prefer the member directly when the consumer accepts string subclasses. Review boundary behavior first: exact str checks, identity, repr and serialization contracts can distinguish the member from its raw value. Keep .value or an explicit str(member) conversion where a plain string is intentional, and suppress the hint with a reason. No automatic rewrite is performed; analyzed code is never executed.",
|
|
27
|
+
config=("rules",),
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
31
|
+
for access in str_enum_value_accesses(ctx.syntax):
|
|
32
|
+
replacement = ast.unparse(access.node.value)
|
|
33
|
+
yield self.violation(
|
|
34
|
+
f"consider {replacement} directly; StrEnum members are already strings",
|
|
35
|
+
path=access.path,
|
|
36
|
+
line=access.node.lineno,
|
|
37
|
+
column=access.node.col_offset + 1,
|
|
38
|
+
end_line=access.node.end_lineno,
|
|
39
|
+
end_column=(access.node.end_col_offset + 1)
|
|
40
|
+
if access.node.end_col_offset is not None
|
|
41
|
+
else None,
|
|
42
|
+
source_module=access.module,
|
|
43
|
+
expected={
|
|
44
|
+
"enum": access.enum,
|
|
45
|
+
"member": access.member,
|
|
46
|
+
"replacement": replacement,
|
|
47
|
+
"automatic_rewrite": False,
|
|
48
|
+
},
|
|
49
|
+
hint=f"Use {replacement} if the consumer accepts string subclasses; retain an explicit conversion when it requires an exact str.",
|
|
50
|
+
)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
from smelt.analysis.annotations import has_postponement_evidence
|
|
7
|
+
from smelt.analysis.context import AnalysisContext, Index
|
|
8
|
+
from smelt.diagnostics.violation import Category, Severity, Violation
|
|
9
|
+
from smelt.rules.activation import POLICIES
|
|
10
|
+
from smelt.rules.base import BaseRule, RuleDoc
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ForbiddenModuleDocstring(BaseRule):
|
|
17
|
+
file_local = True
|
|
18
|
+
activation = POLICIES["SMT309"]
|
|
19
|
+
code = "SMT309"
|
|
20
|
+
name = "forbidden-module-docstring"
|
|
21
|
+
category = Category.STRUCTURE
|
|
22
|
+
default_severity = Severity.ERROR
|
|
23
|
+
requires = frozenset({Index.SYNTAX})
|
|
24
|
+
doc = RuleDoc(
|
|
25
|
+
summary="A module docstring is forbidden by the package's explicit convention.",
|
|
26
|
+
rationale="Some projects keep module descriptions in their architecture documentation. This opt-in convention checks the module's initial docstring, not function or class documentation or ordinary strings.",
|
|
27
|
+
bad='"""Redundant module introduction."""\nVALUE = 1',
|
|
28
|
+
good='VALUE = 1\n\ndef calculate():\n """Explain the calculation contract."""',
|
|
29
|
+
fix="Remove or move the module introduction according to the package's policy. No documentation is deleted automatically.",
|
|
30
|
+
config=("structure.contracts",),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
34
|
+
for source in ctx.files.sources.values():
|
|
35
|
+
contract = ctx.contracts.policy_for(source.module, "module_docstrings")
|
|
36
|
+
if contract is None or contract.spec.module_docstrings != "forbid":
|
|
37
|
+
continue
|
|
38
|
+
tree = ctx.asts.parse(source.path)
|
|
39
|
+
if ast.get_docstring(tree, clean=False) is not None:
|
|
40
|
+
node = tree.body[0]
|
|
41
|
+
yield self.violation(
|
|
42
|
+
f'contract "{contract.name}" forbids module docstrings',
|
|
43
|
+
path=source.path,
|
|
44
|
+
line=node.lineno,
|
|
45
|
+
column=node.col_offset + 1,
|
|
46
|
+
end_line=node.end_lineno,
|
|
47
|
+
end_column=(node.end_col_offset or 0) + 1,
|
|
48
|
+
source_module=source.module,
|
|
49
|
+
expected={"contract": contract.name, "module_docstrings": "forbid"},
|
|
50
|
+
hint="Remove or relocate the module docstring; keep useful class and function documentation.",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ForbiddenFutureAnnotations(BaseRule):
|
|
55
|
+
file_local = True
|
|
56
|
+
activation = POLICIES["SMT310"]
|
|
57
|
+
code = "SMT310"
|
|
58
|
+
name = "forbidden-future-annotations"
|
|
59
|
+
category = Category.STRUCTURE
|
|
60
|
+
default_severity = Severity.ERROR
|
|
61
|
+
requires = frozenset({Index.SYNTAX})
|
|
62
|
+
doc = RuleDoc(
|
|
63
|
+
summary="The annotations future import violates a package or Python-version policy.",
|
|
64
|
+
rationale="An explicit source convention can forbid this import. In when-needed mode, a declared Python 3.14+ minimum also makes it a violation because annotations are already deferred by default. The future import still changes runtime representation, so removal requires checking annotation consumers and never happens automatically.",
|
|
65
|
+
bad="from __future__ import annotations\n\nVALUE = 1",
|
|
66
|
+
good="VALUE = 1",
|
|
67
|
+
fix="Follow the declared convention while preserving forward references and runtime behavior. When-needed mode gives review hints on earlier or unknown targets and rejects the import on declared Python 3.14+ targets. An explicit allow exception can retain a runtime compatibility contract. No automatic rewrite is performed.",
|
|
68
|
+
config=("structure.contracts",),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
72
|
+
yield from _future_findings(self, ctx, forbid=True)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class UnnecessaryFutureAnnotations(BaseRule):
|
|
76
|
+
file_local = True
|
|
77
|
+
activation = POLICIES["SMT311"]
|
|
78
|
+
code = "SMT311"
|
|
79
|
+
name = "unnecessary-future-annotations"
|
|
80
|
+
category = Category.STRUCTURE
|
|
81
|
+
default_severity = Severity.HINT
|
|
82
|
+
requires = frozenset({Index.SYNTAX})
|
|
83
|
+
doc = RuleDoc(
|
|
84
|
+
summary="Review an annotations future import with no detected postponement need.",
|
|
85
|
+
rationale="On targets before Python 3.14 or with an unknown minimum, when-needed mode retains imports for quoted and unresolved forward references, TYPE_CHECKING, runtime annotation inspection, decorated definitions and complex annotation expressions. Other cases get a conservative review hint, not proof of safe removal. Declared Python 3.14+ targets are handled by SMT310.",
|
|
86
|
+
bad="from __future__ import annotations\n\ndef count(value: int) -> int:\n return value",
|
|
87
|
+
good="def count(value: int) -> int:\n return value",
|
|
88
|
+
fix="Review whether postponement is part of the module's runtime contract, then remove unnecessary boilerplate and verify types and behavior. Keep the import if it serves a real purpose; annotate a justified exception if required.",
|
|
89
|
+
config=("structure.contracts",),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
|
|
93
|
+
yield from _future_findings(self, ctx, forbid=False)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _future_findings(
|
|
97
|
+
rule: BaseRule, ctx: AnalysisContext, *, forbid: bool
|
|
98
|
+
) -> Iterator[Violation]:
|
|
99
|
+
for source in ctx.files.sources.values():
|
|
100
|
+
contract = ctx.contracts.policy_for(source.module, "future_annotations")
|
|
101
|
+
if contract is None:
|
|
102
|
+
continue
|
|
103
|
+
mode = contract.spec.future_annotations
|
|
104
|
+
if mode not in {"forbid", "when-needed"}:
|
|
105
|
+
continue
|
|
106
|
+
python_target = ctx.python_targets.for_path(source.absolute)
|
|
107
|
+
prohibited = mode == "forbid" or (
|
|
108
|
+
mode == "when-needed" and python_target.deferred_annotations
|
|
109
|
+
)
|
|
110
|
+
if prohibited != forbid:
|
|
111
|
+
continue
|
|
112
|
+
tree = ctx.asts.parse(source.path)
|
|
113
|
+
imports = [
|
|
114
|
+
node
|
|
115
|
+
for node in tree.body
|
|
116
|
+
if isinstance(node, ast.ImportFrom)
|
|
117
|
+
and node.module == "__future__"
|
|
118
|
+
and node.level == 0
|
|
119
|
+
and any(alias.name == "annotations" for alias in node.names)
|
|
120
|
+
]
|
|
121
|
+
if not imports or (
|
|
122
|
+
not prohibited and has_postponement_evidence(tree, python_target.minimum)
|
|
123
|
+
):
|
|
124
|
+
continue
|
|
125
|
+
for node in imports:
|
|
126
|
+
yield rule.violation(
|
|
127
|
+
f'contract "{contract.name}" forbids the annotations future import'
|
|
128
|
+
if prohibited
|
|
129
|
+
else "no static postponement need found; review the annotations future import",
|
|
130
|
+
path=source.path,
|
|
131
|
+
line=node.lineno,
|
|
132
|
+
column=node.col_offset + 1,
|
|
133
|
+
end_line=node.end_lineno,
|
|
134
|
+
end_column=(node.end_col_offset or 0) + 1,
|
|
135
|
+
source_module=source.module,
|
|
136
|
+
expected={
|
|
137
|
+
"contract": contract.name,
|
|
138
|
+
"future_annotations": mode,
|
|
139
|
+
"automatic_removal": False,
|
|
140
|
+
"python": python_target.to_json(),
|
|
141
|
+
},
|
|
142
|
+
hint="Follow the package convention and verify forward references, runtime annotation consumers and tests before removing the import.",
|
|
143
|
+
)
|