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,377 @@
1
+ """An inventory independent of configured package selection and import rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from collections import Counter
7
+ from dataclasses import dataclass
8
+ from typing import TYPE_CHECKING, Any, Literal
9
+
10
+ from pydantic import TypeAdapter
11
+
12
+ from smelt.analysis.errors import AnalysisError
13
+ from smelt.analysis.files import python_files
14
+ from smelt.analysis.workspace import import_root, workspace_members
15
+ from smelt.config.models import SourceExclusion
16
+ from smelt.config.patterns import path_matches
17
+ from smelt.model import ModuleKind
18
+
19
+ if TYPE_CHECKING:
20
+ from pathlib import Path
21
+
22
+ from smelt.analysis.files import FileIndex, SourceFile
23
+ from smelt.analysis.parsing import AstCache
24
+ from smelt.model import ArchitectureModel, ModuleInfo
25
+
26
+ type CoverageStatus = Literal[
27
+ "governed", "facade", "unclassified", "uncovered", "excluded"
28
+ ]
29
+ _BOOL = TypeAdapter(bool)
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class CoverageEntry:
34
+ path: str
35
+ module: str | None
36
+ status: CoverageStatus
37
+ kind: str | None = None
38
+ feature: str | None = None
39
+ layer: str | None = None
40
+ wiring: bool = False
41
+ central: bool = False
42
+ reason: str | None = None
43
+ policies: tuple[str, ...] = ()
44
+ source_root: str | None = None
45
+
46
+ def to_json(self) -> dict[str, Any]:
47
+ return {
48
+ "path": self.path,
49
+ "module": self.module,
50
+ "status": self.status,
51
+ "kind": self.kind,
52
+ "feature": self.feature,
53
+ "layer": self.layer,
54
+ "wiring": self.wiring,
55
+ "central": self.central,
56
+ "reason": self.reason,
57
+ "policies": list(self.policies),
58
+ "source_root": self.source_root,
59
+ }
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class CoverageIndex:
64
+ entries: tuple[CoverageEntry, ...]
65
+ scan_roots: tuple[str, ...]
66
+ unexplained_exclusions: tuple[str, ...]
67
+ discovery_errors: tuple[str, ...] = ()
68
+
69
+ @classmethod
70
+ def build(
71
+ cls, files: FileIndex, model: ArchitectureModel, asts: AstCache
72
+ ) -> CoverageIndex:
73
+ roots = {
74
+ files.resolve_path(files.root / value)
75
+ for value in files.config.project.source_roots
76
+ }
77
+ test_roots = {
78
+ files.resolve_path(files.root / value)
79
+ for value in files.config.project.test_roots
80
+ }
81
+ discovery_errors: tuple[str, ...] = ()
82
+ try:
83
+ members = workspace_members(files.root, strict=True, store=files.store)
84
+ except AnalysisError as exc:
85
+ if files.config.project.coverage == "strict":
86
+ raise
87
+ members = []
88
+ discovery_errors = (str(exc),)
89
+ for member in members:
90
+ directory = files.root / member.path
91
+ if not files.store.is_dir(directory):
92
+ continue
93
+ # uv excludes control packaging, not architecture coverage. Inspect
94
+ # their Python files too, unless the policy explicitly excludes them.
95
+ located = import_root(directory, store=files.store)
96
+ fallback = (
97
+ directory / "src"
98
+ if files.store.is_dir(directory / "src")
99
+ else directory
100
+ )
101
+ roots.add(files.resolve_path(located[0] if located else fallback))
102
+ test_roots.update(
103
+ files.resolve_path(directory / name) for name in ("tests", "test")
104
+ )
105
+ inventory = {
106
+ source.path: _classify_source(source, files, model, asts)
107
+ for source in files.sources.values()
108
+ }
109
+ # The most specific import root names a module in nested workspaces.
110
+ ordered = sorted(roots, key=lambda value: (-len(value.parts), value.as_posix()))
111
+ for directory in ordered:
112
+ if not files.store.is_dir(directory):
113
+ continue
114
+ for path in python_files(directory, store=files.store):
115
+ absolute = files.resolve_path(path)
116
+ relative = files.relative(path)
117
+ if relative in inventory or any(
118
+ absolute.is_relative_to(root) for root in test_roots
119
+ ):
120
+ continue
121
+ exclusion = next(
122
+ (
123
+ entry
124
+ for entry in files.config.project.exclude
125
+ if path_matches(
126
+ entry if isinstance(entry, str) else entry.path, relative
127
+ )
128
+ ),
129
+ None,
130
+ )
131
+ module = _module_name(path, directory)
132
+ if exclusion is not None:
133
+ reason = (
134
+ exclusion.reason
135
+ if isinstance(exclusion, SourceExclusion)
136
+ else None
137
+ )
138
+ inventory[relative] = CoverageEntry(
139
+ relative,
140
+ module,
141
+ "excluded",
142
+ reason=reason,
143
+ source_root=files.relative(directory),
144
+ )
145
+ else:
146
+ inventory[relative] = CoverageEntry(
147
+ relative,
148
+ module,
149
+ "uncovered",
150
+ reason="Not selected by project.root_packages/source_roots, or not an importable module.",
151
+ source_root=files.relative(directory),
152
+ )
153
+ return cls(
154
+ tuple(inventory[path] for path in sorted(inventory)),
155
+ tuple(sorted(files.relative(path) for path in roots)),
156
+ tuple(
157
+ entry
158
+ for entry in files.config.project.exclude
159
+ if isinstance(entry, str)
160
+ ),
161
+ discovery_errors,
162
+ )
163
+
164
+ @property
165
+ def gaps(self) -> tuple[CoverageEntry, ...]:
166
+ return tuple(
167
+ entry
168
+ for entry in self.entries
169
+ if entry.status in ("unclassified", "uncovered")
170
+ )
171
+
172
+ @property
173
+ def complete(self) -> bool:
174
+ return (
175
+ not self.gaps
176
+ and not self.unexplained_exclusions
177
+ and not self.discovery_errors
178
+ )
179
+
180
+ def for_path(self, path: str) -> CoverageEntry | None:
181
+ return next((entry for entry in self.entries if entry.path == path), None)
182
+
183
+ def summary(self) -> dict[str, Any]:
184
+ counts = Counter(entry.status for entry in self.entries)
185
+ return {
186
+ "complete": self.complete,
187
+ "counts": {
188
+ status: counts[status]
189
+ for status in (
190
+ "governed",
191
+ "facade",
192
+ "unclassified",
193
+ "uncovered",
194
+ "excluded",
195
+ )
196
+ },
197
+ "scan_roots": list(self.scan_roots),
198
+ "unexplained_exclusions": list(self.unexplained_exclusions),
199
+ "discovery_errors": list(self.discovery_errors),
200
+ }
201
+
202
+
203
+ def is_governed(info: ModuleInfo | None, *, layers_declared: bool = True) -> bool:
204
+ return bool(
205
+ info
206
+ and (
207
+ info.layer
208
+ or (info.feature is not None and not layers_declared)
209
+ or info.wiring
210
+ or info.kind in (ModuleKind.SHARED, ModuleKind.COMPOSITION_ROOT)
211
+ )
212
+ )
213
+
214
+
215
+ def _classify_source(
216
+ source: SourceFile, files: FileIndex, model: ArchitectureModel, asts: AstCache
217
+ ) -> CoverageEntry:
218
+ info = model.info(source.module)
219
+ status: CoverageStatus = "unclassified"
220
+ reason = (
221
+ "No architecture layer or explicit shared, wiring or composition-root policy."
222
+ )
223
+ if is_governed(info, layers_declared=bool(model.layers)):
224
+ status, reason = "governed", "Explicit architecture policy."
225
+ elif source.is_package and _is_facade(source, asts):
226
+ status, reason = (
227
+ "facade",
228
+ "Package facade containing imports, documentation and package metadata only.",
229
+ )
230
+ return CoverageEntry(
231
+ source.path,
232
+ source.module,
233
+ status,
234
+ kind=info.kind.value if info else None,
235
+ feature=info.feature if info else None,
236
+ layer=info.layer if info else None,
237
+ wiring=bool(info and info.wiring),
238
+ central=bool(info and info.central),
239
+ reason=reason,
240
+ policies=_policies(info),
241
+ source_root=files.source_root_dir(source.module),
242
+ )
243
+
244
+
245
+ def _policies(info: ModuleInfo | None) -> tuple[str, ...]:
246
+ if info is None:
247
+ return ()
248
+ policies = []
249
+ if info.layer:
250
+ policies.append(f"architecture.layers.{info.layer}")
251
+ if info.central:
252
+ policies.append("architecture.modules")
253
+ if info.feature:
254
+ policies.append("architecture.features")
255
+ if info.wiring:
256
+ policies.append("architecture.wiring")
257
+ if info.kind is ModuleKind.SHARED:
258
+ policies.append("architecture.shared")
259
+ if info.kind is ModuleKind.COMPOSITION_ROOT:
260
+ policies.append("architecture.composition_root")
261
+ return tuple(policies)
262
+
263
+
264
+ def _is_facade(source: SourceFile, asts: AstCache) -> bool:
265
+ if asts.cache is not None:
266
+ return asts.cache.get(
267
+ "facade",
268
+ [source.path, asts.files.content_id(source.path)],
269
+ _BOOL,
270
+ lambda: _facade_syntax(source, asts),
271
+ )
272
+ return _facade_syntax(source, asts)
273
+
274
+
275
+ def _facade_syntax(source: SourceFile, asts: AstCache) -> bool:
276
+ try:
277
+ tree = asts.parse(source.path)
278
+ except AnalysisError:
279
+ return False
280
+ version_calls = _version_calls(tree)
281
+ return all(_facade_statement(node, version_calls) for node in tree.body)
282
+
283
+
284
+ def _version_calls(tree: ast.Module) -> set[str]:
285
+ calls: set[str] = set()
286
+ for node in ast.walk(tree):
287
+ if isinstance(node, ast.ImportFrom) and node.module == "importlib.metadata":
288
+ calls.update(
289
+ alias.asname or alias.name
290
+ for alias in node.names
291
+ if alias.name == "version"
292
+ )
293
+ elif isinstance(node, ast.ImportFrom) and node.module == "importlib":
294
+ calls.update(
295
+ f"{alias.asname or alias.name}.version"
296
+ for alias in node.names
297
+ if alias.name == "metadata"
298
+ )
299
+ elif isinstance(node, ast.Import):
300
+ calls.update(
301
+ f"{alias.asname or alias.name}.version"
302
+ for alias in node.names
303
+ if alias.name == "importlib.metadata"
304
+ )
305
+ return calls
306
+
307
+
308
+ def _facade_statement(node: ast.stmt, version_calls: set[str]) -> bool:
309
+ if isinstance(node, ast.Import | ast.ImportFrom | ast.Pass):
310
+ return True
311
+ if isinstance(node, ast.Expr):
312
+ return isinstance(node.value, ast.Constant) and isinstance(
313
+ node.value.value, str
314
+ )
315
+ if isinstance(node, ast.Assign | ast.AnnAssign):
316
+ return _metadata_assignment(node, version_calls)
317
+ if isinstance(node, ast.If) and ast.unparse(node.test) in (
318
+ "TYPE_CHECKING",
319
+ "typing.TYPE_CHECKING",
320
+ ):
321
+ return all(
322
+ _facade_statement(child, version_calls)
323
+ for child in (*node.body, *node.orelse)
324
+ )
325
+ if isinstance(node, ast.Try):
326
+ blocks = [
327
+ node.body,
328
+ node.orelse,
329
+ node.finalbody,
330
+ *(handler.body for handler in node.handlers),
331
+ ]
332
+ safe_handlers = all(
333
+ handler.type is None or isinstance(handler.type, ast.Name | ast.Attribute)
334
+ for handler in node.handlers
335
+ )
336
+ return safe_handlers and all(
337
+ _facade_statement(child, version_calls)
338
+ for block in blocks
339
+ for child in block
340
+ )
341
+ return False
342
+
343
+
344
+ def _metadata_assignment(
345
+ node: ast.Assign | ast.AnnAssign, version_calls: set[str]
346
+ ) -> bool:
347
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
348
+ names = [target.id for target in targets if isinstance(target, ast.Name)]
349
+ if len(names) != len(targets) or not set(names) <= {"__all__", "__version__"}:
350
+ return False
351
+ if node.value is None:
352
+ return False
353
+ try:
354
+ ast.literal_eval(node.value)
355
+ except (ValueError, TypeError):
356
+ value = node.value
357
+ return (
358
+ names == ["__version__"]
359
+ and isinstance(value, ast.Call)
360
+ and ast.unparse(value.func) in version_calls
361
+ and len(value.args) == 1
362
+ and isinstance(value.args[0], ast.Constant)
363
+ and isinstance(value.args[0].value, str)
364
+ and not value.keywords
365
+ )
366
+ return True
367
+
368
+
369
+ def _module_name(path: Path, root: Path) -> str | None:
370
+ parts = list(path.relative_to(root).with_suffix("").parts)
371
+ if parts and parts[-1] == "__init__":
372
+ parts.pop()
373
+ return (
374
+ ".".join(parts)
375
+ if parts and all(part.isidentifier() for part in parts)
376
+ else None
377
+ )