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,234 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import StrEnum
5
+ from typing import TYPE_CHECKING
6
+
7
+ from smelt.config.patterns import module_matches
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Iterable, Mapping
11
+
12
+ from smelt.config.models import LayerConfig, SmeltConfig
13
+
14
+
15
+ class ModuleKind(StrEnum):
16
+ FEATURE = "feature"
17
+ SHARED = "shared"
18
+ COMPOSITION_ROOT = "composition_root"
19
+ UNCLASSIFIED = "unclassified"
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class ModuleInfo:
24
+ """Where a module sits in the architecture.
25
+
26
+ ``kind`` is ``FEATURE`` for every module in the feature/layer grid. When no
27
+ features are configured, the grid spans the root packages and ``feature`` is None.
28
+ A ``central`` module sits outside the features but in a layer
29
+ (``architecture.modules``), so layer rules apply to it as well.
30
+ """
31
+
32
+ name: str
33
+ kind: ModuleKind
34
+ feature: str | None = None
35
+ layer: str | None = None
36
+ wiring: bool = False
37
+ central: bool = False
38
+
39
+ @property
40
+ def in_grid(self) -> bool:
41
+ return self.kind is ModuleKind.FEATURE
42
+
43
+
44
+ @dataclass(frozen=True, slots=True)
45
+ class FeatureInfo:
46
+ name: str
47
+ package: str
48
+
49
+
50
+ def is_within(module: str, package: str) -> bool:
51
+ return module == package or module.startswith(f"{package}.")
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ArchitectureModel:
56
+ config: SmeltConfig
57
+ modules: Mapping[str, ModuleInfo]
58
+ packages: frozenset[str]
59
+ features: Mapping[str, FeatureInfo] = field(default_factory=dict)
60
+
61
+ @classmethod
62
+ def build(
63
+ cls,
64
+ config: SmeltConfig,
65
+ modules: Iterable[str],
66
+ packages: Iterable[str],
67
+ ) -> ArchitectureModel:
68
+ package_set = frozenset(packages)
69
+ classifier = _Classifier(config, package_set)
70
+ infos: dict[str, ModuleInfo] = {}
71
+ features: dict[str, FeatureInfo] = {}
72
+ for name in sorted(set(modules)):
73
+ info = classifier.classify(name)
74
+ infos[name] = info
75
+ if info.feature is not None and info.feature not in features:
76
+ package = classifier.feature_package(name)
77
+ if package is not None:
78
+ features[info.feature] = FeatureInfo(info.feature, package)
79
+ return cls(config, infos, package_set, dict(sorted(features.items())))
80
+
81
+ @property
82
+ def layers(self) -> Mapping[str, LayerConfig]:
83
+ return self.config.architecture.layers
84
+
85
+ @property
86
+ def has_features(self) -> bool:
87
+ return self.config.architecture.features is not None
88
+
89
+ def info(self, module: str) -> ModuleInfo | None:
90
+ info = self.modules.get(module)
91
+ if info is not None:
92
+ return info
93
+ if not self.is_first_party(module):
94
+ return None
95
+ return _Classifier(self.config, self.packages).classify(module)
96
+
97
+ def is_first_party(self, module: str) -> bool:
98
+ return any(
99
+ is_within(module, root) for root in self.config.project.root_packages
100
+ )
101
+
102
+ def is_package(self, module: str) -> bool:
103
+ return module in self.packages
104
+
105
+ def layer_package(self, feature: str | None, layer: str) -> str | None:
106
+ """The dotted package of ``layer`` inside ``feature`` (or the root package)."""
107
+ path = self.layers[layer].path
108
+ if feature is not None:
109
+ info = self.features.get(feature)
110
+ if info is not None:
111
+ return f"{info.package}.{path}"
112
+ return self.feature_package_for(feature) + f".{path}"
113
+ roots = self.config.project.root_packages
114
+ return f"{roots[0]}.{path}" if roots else None
115
+
116
+ def feature_package_for(self, feature: str) -> str:
117
+ if feature in self.features:
118
+ return self.features[feature].package
119
+ spec = self.config.architecture.features
120
+ if spec is not None and spec.root is not None:
121
+ return f"{spec.root}.{feature}"
122
+ if spec is not None and spec.pattern is not None:
123
+ return spec.pattern.replace("{feature}", feature)
124
+ return feature
125
+
126
+ def feature_pattern(self) -> str | None:
127
+ spec = self.config.architecture.features
128
+ if spec is None:
129
+ return None
130
+ if spec.root is not None:
131
+ return f"{spec.root}.{{feature}}"
132
+ return spec.pattern
133
+
134
+ def modules_in(self, feature: str | None, layer: str) -> list[str]:
135
+ return [
136
+ name
137
+ for name, info in self.modules.items()
138
+ if info.in_grid and info.feature == feature and info.layer == layer
139
+ ]
140
+
141
+ def grid_containers(self) -> list[str]:
142
+ """Packages whose direct child packages must be declared layers."""
143
+ if not self.layers:
144
+ return []
145
+ if self.has_features:
146
+ return sorted(info.package for info in self.features.values())
147
+ return [
148
+ root for root in self.config.project.root_packages if root in self.packages
149
+ ]
150
+
151
+
152
+ class _Classifier:
153
+ def __init__(self, config: SmeltConfig, packages: frozenset[str]) -> None:
154
+ arch = config.architecture
155
+ self._roots = config.project.root_packages
156
+ self._shared = arch.shared
157
+ self._composition_root = arch.composition_root
158
+ self._wiring = arch.wiring
159
+ # longest package first, so backend.platform.storage wins over backend.platform
160
+ self._central = sorted(arch.modules.items(), key=lambda item: -len(item[0]))
161
+ self._packages = packages
162
+ self._layer_paths = sorted(
163
+ ((layer.path.split("."), name) for name, layer in arch.layers.items()),
164
+ key=lambda item: -len(item[0]),
165
+ )
166
+ self._features = arch.features
167
+ self._feature_prefix: list[str] | None = None
168
+ if arch.features is not None and arch.features.root is not None:
169
+ self._feature_prefix = arch.features.root.split(".")
170
+ elif arch.features is not None and arch.features.pattern is not None:
171
+ self._feature_prefix = arch.features.pattern.split(".")[:-1]
172
+
173
+ def classify(self, module: str) -> ModuleInfo:
174
+ wiring = any(module_matches(pattern, module) for pattern in self._wiring)
175
+ if any(is_within(module, root) for root in self._composition_root):
176
+ return ModuleInfo(module, ModuleKind.COMPOSITION_ROOT, wiring=wiring)
177
+ if any(is_within(module, shared) for shared in self._shared):
178
+ return ModuleInfo(module, ModuleKind.SHARED, wiring=wiring)
179
+ central = next(
180
+ (layer for package, layer in self._central if is_within(module, package)),
181
+ None,
182
+ )
183
+ if central is not None:
184
+ return ModuleInfo(
185
+ module, ModuleKind.FEATURE, None, central, wiring, central=True
186
+ )
187
+ if self._features is None:
188
+ layer = self._root_layer(module)
189
+ kind = ModuleKind.UNCLASSIFIED if layer is None else ModuleKind.FEATURE
190
+ return ModuleInfo(module, kind, None, layer, wiring)
191
+ match = self._match_feature(module)
192
+ if match is None:
193
+ return ModuleInfo(module, ModuleKind.UNCLASSIFIED, wiring=wiring)
194
+ feature, rest = match
195
+ return ModuleInfo(
196
+ module,
197
+ ModuleKind.FEATURE,
198
+ feature,
199
+ self._match_layer(rest),
200
+ wiring,
201
+ )
202
+
203
+ def feature_package(self, module: str) -> str | None:
204
+ match = self._match_feature(module)
205
+ if match is None:
206
+ return None
207
+ _, rest = match
208
+ segments = module.split(".")
209
+ return ".".join(segments[: len(segments) - len(rest)])
210
+
211
+ def _root_layer(self, module: str) -> str | None:
212
+ """Without features, layers sit directly in a root package."""
213
+ for root in self._roots:
214
+ if module.startswith(f"{root}."):
215
+ return self._match_layer(module[len(root) + 1 :].split("."))
216
+ return None
217
+
218
+ def _match_feature(self, module: str) -> tuple[str, list[str]] | None:
219
+ prefix = self._feature_prefix
220
+ if prefix is None:
221
+ return None
222
+ segments = module.split(".")
223
+ index = len(prefix)
224
+ if len(segments) <= index or segments[:index] != prefix:
225
+ return None
226
+ if ".".join(segments[: index + 1]) not in self._packages:
227
+ return None
228
+ return segments[index], segments[index + 1 :]
229
+
230
+ def _match_layer(self, rest: list[str]) -> str | None:
231
+ for path, name in self._layer_paths:
232
+ if rest[: len(path)] == path:
233
+ return name
234
+ return None
smelt/py.typed ADDED
File without changes
File without changes
@@ -0,0 +1,129 @@
1
+ """Typed, declarative activation metadata for configuration-driven rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING
7
+
8
+ if TYPE_CHECKING:
9
+ from collections.abc import Callable
10
+
11
+ from smelt.config.models import SmeltConfig
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class PolicyActivation:
16
+ description: str
17
+ matches: Callable[[SmeltConfig], bool]
18
+
19
+
20
+ POLICIES = {
21
+ "SMT101": PolicyActivation(
22
+ "architecture.layers defines layer dependencies.",
23
+ lambda config: bool(config.architecture.layers),
24
+ ),
25
+ "SMT102": PolicyActivation(
26
+ "architecture.features defines feature boundaries.",
27
+ lambda config: config.architecture.features is not None,
28
+ ),
29
+ "SMT103": PolicyActivation(
30
+ "A layer's third_party policy restricts dependencies.",
31
+ lambda config: any(
32
+ layer.third_party.default == "deny" or layer.third_party.deny
33
+ for layer in config.architecture.layers.values()
34
+ ),
35
+ ),
36
+ "SMT105": PolicyActivation(
37
+ "architecture.shared or architecture.modules declares shared/central modules.",
38
+ lambda config: bool(config.architecture.shared or config.architecture.modules),
39
+ ),
40
+ "SMT106": PolicyActivation(
41
+ "architecture.composition_root or architecture.wiring declares assembly boundaries.",
42
+ lambda config: bool(
43
+ config.architecture.composition_root or config.architecture.wiring
44
+ ),
45
+ ),
46
+ "SMT107": PolicyActivation(
47
+ "A package contract declares public entry points, including an explicitly empty public list.",
48
+ lambda config: any(
49
+ contract.public is not None
50
+ for contract in config.structure.contracts.values()
51
+ ),
52
+ ),
53
+ "SMT108": PolicyActivation(
54
+ "A package contract sets bundle_imports_at.",
55
+ lambda config: any(
56
+ contract.bundle_imports_at is not None
57
+ for contract in config.structure.contracts.values()
58
+ ),
59
+ ),
60
+ "SMT302": PolicyActivation(
61
+ "structure.forbidden_names contains naming restrictions.",
62
+ lambda config: bool(config.structure.forbidden_names),
63
+ ),
64
+ "SMT306": PolicyActivation(
65
+ "project.coverage is strict, including --strict-coverage; the guard cannot be disabled in strict mode.",
66
+ lambda config: config.project.coverage == "strict",
67
+ ),
68
+ "SMT307": PolicyActivation(
69
+ "A package contract requires modules or named public entry points.",
70
+ lambda config: any(
71
+ contract.required or contract.public
72
+ for contract in config.structure.contracts.values()
73
+ ),
74
+ ),
75
+ "SMT308": PolicyActivation(
76
+ "A package contract declares an imports style.",
77
+ lambda config: any(
78
+ contract.imports is not None
79
+ for contract in config.structure.contracts.values()
80
+ ),
81
+ ),
82
+ "SMT309": PolicyActivation(
83
+ "A package contract forbids module docstrings.",
84
+ lambda config: any(
85
+ contract.module_docstrings == "forbid"
86
+ for contract in config.structure.contracts.values()
87
+ ),
88
+ ),
89
+ "SMT310": PolicyActivation(
90
+ "A package contract sets future_annotations to forbid or when-needed.",
91
+ lambda config: any(
92
+ contract.future_annotations in {"forbid", "when-needed"}
93
+ for contract in config.structure.contracts.values()
94
+ ),
95
+ ),
96
+ "SMT311": PolicyActivation(
97
+ "A package contract sets future_annotations to when-needed.",
98
+ lambda config: any(
99
+ contract.future_annotations == "when-needed"
100
+ for contract in config.structure.contracts.values()
101
+ ),
102
+ ),
103
+ "SMT312": PolicyActivation(
104
+ "A package contract forbids private module names.",
105
+ lambda config: any(
106
+ contract.private_modules == "forbid"
107
+ for contract in config.structure.contracts.values()
108
+ ),
109
+ ),
110
+ "SMT315": PolicyActivation(
111
+ "A package contract sets type_dispatch.style to match.",
112
+ lambda config: any(
113
+ contract.type_dispatch is not None
114
+ and contract.type_dispatch.style == "match"
115
+ for contract in config.structure.contracts.values()
116
+ ),
117
+ ),
118
+ "SMT401": PolicyActivation(
119
+ "tests.layout is mirror.", lambda config: config.tests.layout == "mirror"
120
+ ),
121
+ "SMT421": PolicyActivation(
122
+ "tests.forbid_mocks_in contains test path patterns.",
123
+ lambda config: bool(config.tests.forbid_mocks_in),
124
+ ),
125
+ "SMT423": PolicyActivation(
126
+ "tests.max_patches_per_test is set, including zero.",
127
+ lambda config: config.tests.max_patches_per_test is not None,
128
+ ),
129
+ }
smelt/rules/base.py ADDED
@@ -0,0 +1,131 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import TYPE_CHECKING, Any, ClassVar, Protocol, runtime_checkable
5
+
6
+ from smelt.diagnostics.violation import (
7
+ Category,
8
+ ImportLink,
9
+ Severity,
10
+ Violation,
11
+ docs_url,
12
+ )
13
+
14
+ if TYPE_CHECKING:
15
+ from collections.abc import Iterable, Mapping
16
+
17
+ from smelt.analysis.context import AnalysisContext, Index
18
+ from smelt.rules.activation import PolicyActivation
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class RuleDoc:
23
+ summary: str
24
+ rationale: str
25
+ bad: str
26
+ good: str
27
+ fix: str
28
+ config: tuple[str, ...] = ()
29
+ example_language: str = "python"
30
+
31
+
32
+ @runtime_checkable
33
+ class Rule(Protocol):
34
+ code: str
35
+ name: str
36
+ category: Category
37
+ default_severity: Severity
38
+ requires: frozenset[Index]
39
+
40
+ def check(self, ctx: AnalysisContext) -> Iterable[Violation]: ...
41
+
42
+ def explain(self) -> RuleDoc: ...
43
+
44
+
45
+ class BaseRule:
46
+ """Convenience base: fills in rule metadata on every violation."""
47
+
48
+ code: str
49
+ name: str
50
+ category: Category
51
+ default_severity: Severity = Severity.ERROR
52
+ requires: frozenset[Index] = frozenset()
53
+ enabled_by_default: ClassVar[bool] = False
54
+ activation: ClassVar[PolicyActivation | None] = None
55
+ scope: ClassVar[str] = "source"
56
+ file_local: ClassVar[bool] = False
57
+ test_local: ClassVar[bool] = False
58
+ member_local: ClassVar[bool] = False
59
+ doc: ClassVar[RuleDoc]
60
+
61
+ def check(self, ctx: AnalysisContext) -> Iterable[Violation]:
62
+ raise NotImplementedError
63
+
64
+ def explain(self) -> RuleDoc:
65
+ return self.doc
66
+
67
+ def violation( # noqa: PLR0913 - mirrors the Violation fields
68
+ self,
69
+ message: str,
70
+ *,
71
+ path: str | None = None,
72
+ line: int | None = None,
73
+ column: int | None = None,
74
+ end_line: int | None = None,
75
+ end_column: int | None = None,
76
+ source_module: str | None = None,
77
+ target_module: str | None = None,
78
+ import_chain: Iterable[ImportLink] = (),
79
+ feature: str | None = None,
80
+ layer: str | None = None,
81
+ expected: Mapping[str, Any] | None = None,
82
+ hint: str | None = None,
83
+ edge: str | None = None,
84
+ ) -> Violation:
85
+ return Violation(
86
+ code=self.code,
87
+ rule=self.name,
88
+ severity=self.default_severity,
89
+ message=message,
90
+ path=path,
91
+ line=line,
92
+ column=column,
93
+ end_line=end_line if end_line is not None else (line if column else None),
94
+ end_column=end_column,
95
+ source_module=source_module,
96
+ target_module=target_module,
97
+ import_chain=tuple(import_chain),
98
+ feature=feature,
99
+ layer=layer,
100
+ expected=expected,
101
+ hint=hint,
102
+ edge=edge,
103
+ docs_url=docs_url(self.code),
104
+ category=self.category,
105
+ )
106
+
107
+
108
+ @dataclass
109
+ class RuleSet:
110
+ rules: list[Rule] = field(default_factory=list)
111
+
112
+ def __post_init__(self) -> None:
113
+ codes: set[str] = set()
114
+ names: set[str] = set()
115
+ for rule in self.rules:
116
+ if rule.code in codes:
117
+ raise ValueError(f"duplicate rule code: {rule.code}")
118
+ if rule.name in names:
119
+ raise ValueError(f"duplicate rule name: {rule.name}")
120
+ codes.add(rule.code)
121
+ names.add(rule.name)
122
+
123
+ def by_code(self, code: str) -> Rule | None:
124
+ return next((r for r in self.rules if r.code == code), None)
125
+
126
+ def lookup(self, code_or_name: str) -> Rule | None:
127
+ wanted = code_or_name.strip()
128
+ return next(
129
+ (r for r in self.rules if wanted.upper() == r.code or wanted == r.name),
130
+ None,
131
+ )