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
smelt/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ try:
4
+ __version__ = version("smelt-cli")
5
+ except PackageNotFoundError: # pragma: no cover
6
+ __version__ = "0.0.0"
smelt/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from smelt.cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,45 @@
1
+ from importlib import import_module
2
+ from typing import TYPE_CHECKING, Any
3
+
4
+ from smelt.analysis.errors import AnalysisError
5
+
6
+ if TYPE_CHECKING:
7
+ from smelt.analysis.context import AnalysisContext, Index
8
+ from smelt.analysis.files import FileIndex, SourceFile, TestFile
9
+ from smelt.analysis.imports import ImportDetail, ImportIndex, is_stdlib
10
+ from smelt.analysis.syntax import ModuleSyntax, SyntaxIndex
11
+
12
+
13
+ __all__ = [
14
+ "AnalysisContext",
15
+ "AnalysisError",
16
+ "FileIndex",
17
+ "ImportDetail",
18
+ "ImportIndex",
19
+ "Index",
20
+ "ModuleSyntax",
21
+ "SourceFile",
22
+ "SyntaxIndex",
23
+ "TestFile",
24
+ "is_stdlib",
25
+ ]
26
+
27
+
28
+ def __getattr__(name: str) -> Any:
29
+ if name not in _MODULES:
30
+ raise AttributeError(name)
31
+ return getattr(import_module(f"smelt.analysis.{_MODULES[name]}"), name)
32
+
33
+
34
+ _MODULES = {
35
+ "AnalysisContext": "context",
36
+ "Index": "context",
37
+ "FileIndex": "files",
38
+ "SourceFile": "files",
39
+ "TestFile": "files",
40
+ "ImportDetail": "imports",
41
+ "ImportIndex": "imports",
42
+ "is_stdlib": "imports",
43
+ "ModuleSyntax": "syntax",
44
+ "SyntaxIndex": "syntax",
45
+ }
@@ -0,0 +1,105 @@
1
+ """Conservative evidence for reviewing an annotations future import.
2
+
3
+ This does not prove removal preserves reflection or framework behavior. Unknown
4
+ expressions and forward references retain postponement; callers emit hints only.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ import builtins
11
+
12
+ _GENERICS_VERSION = (3, 9)
13
+ _UNIONS_VERSION = (3, 10)
14
+ _BUILTIN_GENERICS = frozenset({"list", "dict", "tuple", "set", "frozenset", "type"})
15
+
16
+
17
+ def has_postponement_evidence(
18
+ tree: ast.Module, minimum: tuple[int, int] | None = None
19
+ ) -> bool:
20
+ annotations: list[ast.expr] = []
21
+ for node in ast.walk(tree):
22
+ if isinstance(node, ast.AnnAssign | ast.arg) and node.annotation is not None:
23
+ annotations.append(node.annotation)
24
+ elif (
25
+ isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
26
+ and node.returns is not None
27
+ ):
28
+ annotations.append(node.returns)
29
+ if not annotations:
30
+ return False
31
+ if _runtime_sensitive(tree):
32
+ return True
33
+ available = _bindings(tree)
34
+ for annotation in annotations:
35
+ for node in ast.walk(annotation):
36
+ if isinstance(node, ast.Name):
37
+ if node.id not in vars(builtins) and not any(
38
+ end < annotation.lineno and name == node.id
39
+ for name, end in available
40
+ ):
41
+ return True
42
+ elif isinstance(node, ast.Constant):
43
+ if node.value is not None:
44
+ return True
45
+ elif not _supported_expression(node, minimum):
46
+ # Calls, generics, unions, attributes and other expressions can
47
+ # depend on runtime protocols or an older supported interpreter.
48
+ return True
49
+ return False
50
+
51
+
52
+ def _supported_expression(node: ast.AST, minimum: tuple[int, int] | None) -> bool:
53
+ if isinstance(node, ast.Subscript):
54
+ return (
55
+ minimum is not None
56
+ and minimum >= _GENERICS_VERSION
57
+ and isinstance(node.value, ast.Name)
58
+ and node.value.id in _BUILTIN_GENERICS
59
+ )
60
+ if isinstance(node, ast.BinOp):
61
+ return (
62
+ minimum is not None
63
+ and minimum >= _UNIONS_VERSION
64
+ and isinstance(node.op, ast.BitOr)
65
+ )
66
+ return isinstance(node, ast.Load | ast.Tuple | ast.BitOr)
67
+
68
+
69
+ def _runtime_sensitive(tree: ast.Module) -> bool:
70
+ for node in ast.walk(tree):
71
+ if isinstance(node, ast.Delete):
72
+ return True
73
+ if isinstance(node, ast.Name | ast.Attribute):
74
+ name = node.id if isinstance(node, ast.Name) else node.attr
75
+ if name in {"__annotations__", "get_type_hints", "TYPE_CHECKING"}:
76
+ return True
77
+ if (
78
+ isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
79
+ and node.decorator_list
80
+ ):
81
+ return True
82
+ if isinstance(node, ast.ClassDef) and (
83
+ node.bases or node.keywords or node.decorator_list
84
+ ):
85
+ return True
86
+ return False
87
+
88
+
89
+ def _bindings(tree: ast.Module) -> list[tuple[str, int]]:
90
+ bound: list[tuple[str, int]] = []
91
+ for node in tree.body:
92
+ end = node.end_lineno or node.lineno
93
+ if isinstance(node, ast.Import | ast.ImportFrom):
94
+ for alias in node.names:
95
+ if alias.name != "*":
96
+ name = alias.asname or (
97
+ alias.name.split(".")[0]
98
+ if isinstance(node, ast.Import)
99
+ else alias.name
100
+ )
101
+ bound.append((name, end))
102
+ elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
103
+ bound.append((node.name, end))
104
+ # Assignments may be dynamic aliases rather than types; keep those unknown.
105
+ return bound
@@ -0,0 +1,168 @@
1
+ """Disposable, content-addressed JSON facts; never deserialize executable objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import sqlite3
8
+ from contextlib import suppress
9
+ from typing import TYPE_CHECKING
10
+
11
+ from pydantic import TypeAdapter, ValidationError
12
+
13
+ from smelt.analysis.identity import analyzer_identity
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Callable
17
+ from pathlib import Path
18
+
19
+ _SHA1_LENGTH = 40
20
+
21
+
22
+ class FactCache:
23
+ def __init__(self, directory: Path) -> None:
24
+ self.directory = directory / "v1" / analyzer_identity()
25
+ self.hits = 0
26
+ self.misses = 0
27
+ self._connection: sqlite3.Connection | None = None
28
+ self._disabled = False
29
+
30
+ def close(self) -> None:
31
+ self._disabled = True
32
+ if self._connection is not None:
33
+ try:
34
+ self._connection.commit()
35
+ self._connection.close()
36
+ self._connection = None
37
+ except sqlite3.Error:
38
+ self._disable()
39
+
40
+ def key(self, kind: str, inputs: object) -> str:
41
+ payload = json.dumps([kind, inputs], sort_keys=True, ensure_ascii=True)
42
+ return hashlib.sha256(payload.encode()).hexdigest()
43
+
44
+ def missing(self, keys: list[str]) -> set[str]:
45
+ """Plan batched source reads; payloads still go through validated read()."""
46
+ connection = self._connect()
47
+ if connection is None:
48
+ return set(keys)
49
+ present: set[str] = set()
50
+ try:
51
+ for start in range(0, len(keys), 500):
52
+ batch = keys[start : start + 500]
53
+ placeholders = ",".join("?" for _ in batch)
54
+ query = f"SELECT key FROM facts WHERE key IN ({placeholders})" # noqa: S608 - placeholders only; values are bound
55
+ present.update(row[0] for row in connection.execute(query, batch))
56
+ except sqlite3.Error:
57
+ return set(keys)
58
+ return set(keys) - present
59
+
60
+ def read_blobs(self, identifiers: list[str]) -> dict[str, bytes]:
61
+ """Validate cached bytes against Git's object ID before using them."""
62
+ connection = self._connect()
63
+ result: dict[str, bytes] = {}
64
+ if connection is None:
65
+ return result
66
+ try:
67
+ for start in range(0, len(identifiers), 500):
68
+ batch = identifiers[start : start + 500]
69
+ placeholders = ",".join("?" for _ in batch)
70
+ query = (
71
+ f"SELECT oid, payload FROM objects WHERE oid IN ({placeholders})" # noqa: S608 - placeholders only; IDs are bound
72
+ )
73
+ for oid, data in connection.execute(query, batch):
74
+ if not isinstance(data, bytes):
75
+ continue
76
+ digest = hashlib.new(
77
+ "sha1" if len(oid) == _SHA1_LENGTH else "sha256",
78
+ usedforsecurity=False,
79
+ )
80
+ digest.update(f"blob {len(data)}\0".encode("ascii"))
81
+ digest.update(data)
82
+ if digest.hexdigest() == oid:
83
+ result[oid] = data
84
+ except (ValueError, TypeError, sqlite3.Error):
85
+ return {}
86
+ return result
87
+
88
+ def write_blobs(self, contents: dict[str, bytes]) -> None:
89
+ connection = self._connect()
90
+ if connection is not None:
91
+ try:
92
+ connection.executemany(
93
+ "INSERT OR REPLACE INTO objects VALUES (?, ?)", contents.items()
94
+ )
95
+ except sqlite3.Error:
96
+ self._disable()
97
+
98
+ def _connect(self) -> sqlite3.Connection | None:
99
+ if self._disabled:
100
+ return None
101
+ if self._connection is None:
102
+ try:
103
+ self.directory.mkdir(parents=True, exist_ok=True)
104
+ self._connection = sqlite3.connect(
105
+ self.directory / "facts.sqlite3", timeout=0.02
106
+ )
107
+ self._connection.execute("PRAGMA journal_mode=WAL")
108
+ self._connection.execute("PRAGMA synchronous=NORMAL")
109
+ self._connection.execute(
110
+ "CREATE TABLE IF NOT EXISTS facts (key TEXT PRIMARY KEY, payload BLOB NOT NULL)"
111
+ )
112
+ self._connection.execute(
113
+ "CREATE TABLE IF NOT EXISTS objects (oid TEXT PRIMARY KEY, payload BLOB NOT NULL)"
114
+ )
115
+ self._connection.commit()
116
+ except (OSError, sqlite3.Error):
117
+ self._disable()
118
+ return self._connection
119
+
120
+ def _disable(self) -> None:
121
+ self._disabled = True
122
+ if self._connection is not None:
123
+ with suppress(sqlite3.Error):
124
+ self._connection.close()
125
+ self._connection = None
126
+
127
+ def read[T](self, key: str, adapter: TypeAdapter[T]) -> T | None:
128
+ connection = self._connect()
129
+ if connection is None:
130
+ self.misses += 1
131
+ return None
132
+ try:
133
+ row = connection.execute(
134
+ "SELECT payload FROM facts WHERE key = ?", (key,)
135
+ ).fetchone()
136
+ if row is None:
137
+ self.misses += 1
138
+ return None
139
+ result = adapter.validate_json(row[0])
140
+ except (ValueError, ValidationError, sqlite3.Error):
141
+ self.misses += 1
142
+ return None
143
+ self.hits += 1
144
+ return result
145
+
146
+ def write[T](self, key: str, value: T, adapter: TypeAdapter[T]) -> None:
147
+ connection = self._connect()
148
+ if connection is None:
149
+ return
150
+ try:
151
+ connection.execute(
152
+ "INSERT OR REPLACE INTO facts (key, payload) VALUES (?, ?)",
153
+ (key, adapter.dump_json(value)),
154
+ )
155
+ except sqlite3.Error:
156
+ # A read-only checkout, concurrent cleaner or full disk cannot make
157
+ # a disposable optimization change the check's result.
158
+ self._disable()
159
+
160
+ def get[T](
161
+ self, kind: str, inputs: object, adapter: TypeAdapter[T], build: Callable[[], T]
162
+ ) -> T:
163
+ key = self.key(kind, inputs)
164
+ result = self.read(key, adapter)
165
+ if result is None:
166
+ result = build()
167
+ self.write(key, result, adapter)
168
+ return result
@@ -0,0 +1,147 @@
1
+ from __future__ import annotations
2
+
3
+ from copy import copy
4
+ from dataclasses import replace
5
+ from enum import StrEnum
6
+ from functools import cached_property
7
+ from typing import TYPE_CHECKING
8
+
9
+ from smelt.config.source import SourceStore
10
+
11
+ if TYPE_CHECKING:
12
+ from pathlib import Path
13
+
14
+ from smelt.analysis.cache import FactCache
15
+ from smelt.analysis.contracts import ContractIndex
16
+ from smelt.analysis.coverage import CoverageIndex
17
+ from smelt.analysis.files import FileIndex, SourceFile
18
+ from smelt.analysis.imports import ImportIndex
19
+ from smelt.analysis.members import MemberUsageIndex
20
+ from smelt.analysis.ordering import DefinitionOrderIndex
21
+ from smelt.analysis.parsing import AstCache
22
+ from smelt.analysis.python_version import PythonTargetIndex
23
+ from smelt.analysis.syntax import SyntaxIndex
24
+ from smelt.analysis.test_syntax import TestSyntaxIndex
25
+ from smelt.config.models import SmeltConfig
26
+ from smelt.model import ArchitectureModel
27
+
28
+
29
+ class Index(StrEnum):
30
+ COVERAGE = "coverage"
31
+ FILES = "files"
32
+ IMPORTS = "imports"
33
+ MEMBERS = "member_usage"
34
+ ORDERING = "ordering"
35
+ SYNTAX = "syntax"
36
+ TESTS = "test_syntax"
37
+
38
+
39
+ class AnalysisContext:
40
+ def __init__(
41
+ self,
42
+ root: Path,
43
+ config: SmeltConfig,
44
+ *,
45
+ cache: FactCache | None = None,
46
+ store: SourceStore | None = None,
47
+ ) -> None:
48
+ # grimp resolves its search paths; the file index must agree on the prefix
49
+ self.store = store or SourceStore()
50
+ self.root = self.store.resolve(root)
51
+ self.config = config
52
+ self.cache = cache
53
+
54
+ def file_view(self, source: SourceFile) -> AnalysisContext:
55
+ """A source-loop view for rules explicitly declaring file-local inputs."""
56
+ view = copy(self)
57
+ view.files = replace(self.files, sources={source.module: source}, tests={})
58
+ return view
59
+
60
+ def test_view(self, path: str) -> AnalysisContext:
61
+ view = copy(self)
62
+ view.test_syntax = self.test_syntax.for_file(path)
63
+ return view
64
+
65
+ def member_view(self, path: str) -> AnalysisContext:
66
+ view = copy(self)
67
+ view.member_usage = copy(self.member_usage)
68
+ view.member_usage.members = self.member_usage.members_for_path(path)
69
+ return view
70
+
71
+ @cached_property
72
+ def files(self) -> FileIndex:
73
+ # Load indexes only when the selected checks need them.
74
+ from smelt.analysis.files import FileIndex # noqa: PLC0415
75
+
76
+ return FileIndex.discover(self.root, self.config, store=self.store)
77
+
78
+ @cached_property
79
+ def asts(self) -> AstCache:
80
+ from smelt.analysis.parsing import AstCache # noqa: PLC0415
81
+
82
+ return AstCache(self.files, cache=self.cache)
83
+
84
+ @cached_property
85
+ def model(self) -> ArchitectureModel:
86
+ from smelt.model import ArchitectureModel # noqa: PLC0415
87
+
88
+ return ArchitectureModel.build(
89
+ self.config, self.files.sources, self.files.packages
90
+ )
91
+
92
+ @cached_property
93
+ def coverage(self) -> CoverageIndex:
94
+ from smelt.analysis.coverage import CoverageIndex # noqa: PLC0415
95
+
96
+ return CoverageIndex.build(self.files, self.model, self.asts)
97
+
98
+ @cached_property
99
+ def imports(self) -> ImportIndex:
100
+ from smelt.analysis.imports import ImportIndex # noqa: PLC0415
101
+
102
+ return ImportIndex.build(self.files, self.asts, cache=self.cache)
103
+
104
+ @cached_property
105
+ def syntax(self) -> SyntaxIndex:
106
+ from smelt.analysis.syntax import SyntaxIndex # noqa: PLC0415
107
+
108
+ return SyntaxIndex(self.files, self.asts, cache=self.cache)
109
+
110
+ @cached_property
111
+ def member_usage(self) -> MemberUsageIndex:
112
+ from smelt.analysis.members import MemberUsageIndex # noqa: PLC0415
113
+
114
+ return MemberUsageIndex(self.syntax)
115
+
116
+ @cached_property
117
+ def test_syntax(self) -> TestSyntaxIndex:
118
+ from smelt.analysis.test_syntax import TestSyntaxIndex # noqa: PLC0415
119
+
120
+ return TestSyntaxIndex(
121
+ self.files, self.asts, cache=self.cache, syntax=self.syntax
122
+ )
123
+
124
+ @cached_property
125
+ def contracts(self) -> ContractIndex:
126
+ from smelt.analysis.contracts import ContractIndex # noqa: PLC0415
127
+
128
+ return ContractIndex(self.files)
129
+
130
+ @cached_property
131
+ def python_targets(self) -> PythonTargetIndex:
132
+ from smelt.analysis.python_version import PythonTargetIndex # noqa: PLC0415
133
+
134
+ return PythonTargetIndex(self.files)
135
+
136
+ @cached_property
137
+ def ordering(self) -> DefinitionOrderIndex:
138
+ from smelt.analysis.ordering import DefinitionOrderIndex # noqa: PLC0415
139
+
140
+ return DefinitionOrderIndex(
141
+ self.files, self.contracts, self.asts, self.python_targets
142
+ )
143
+
144
+ def ensure(self, indexes: frozenset[Index]) -> None:
145
+ """Build the requested indexes up front so failures surface before rules run."""
146
+ for index in sorted(indexes):
147
+ getattr(self, index.value)
@@ -0,0 +1,210 @@
1
+ """Resolve package contracts against the analyzed inventory, without importing code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING, Any, Literal
7
+
8
+ from smelt.config.patterns import module_matches
9
+ from smelt.model import is_within
10
+
11
+ if TYPE_CHECKING:
12
+ from smelt.analysis.files import FileIndex
13
+ from smelt.config.models import PackageContract
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ResolvedContract:
18
+ name: str
19
+ package: str
20
+ spec: PackageContract
21
+
22
+ def qualify(self, relative: str) -> str:
23
+ return self.package if relative == "." else f"{self.package}.{relative}"
24
+
25
+ @property
26
+ def public(self) -> tuple[str, ...] | None:
27
+ if self.spec.public is None:
28
+ return None
29
+ return tuple(self.qualify(entry) for entry in self.spec.public)
30
+
31
+ def exposes(self, module: str) -> bool:
32
+ public = self.public
33
+ return public is None or any(
34
+ module_matches(pattern, module) for pattern in public
35
+ )
36
+
37
+
38
+ class ContractIndex:
39
+ def __init__(self, files: FileIndex) -> None:
40
+ self.files = files
41
+ self.known = frozenset(files.sources) | frozenset(files.packages)
42
+ self.resolved = tuple(
43
+ ResolvedContract(name, package, spec)
44
+ for name, spec in sorted(files.config.structure.contracts.items())
45
+ for package in sorted(files.packages)
46
+ if module_matches(spec.match, package)
47
+ )
48
+
49
+ def style_for(self, module: str) -> ResolvedContract | None:
50
+ return self.policy_for(module, "imports")
51
+
52
+ def policy_for(
53
+ self,
54
+ module: str,
55
+ policy: Literal[
56
+ "imports",
57
+ "module_docstrings",
58
+ "future_annotations",
59
+ "private_modules",
60
+ "ordering",
61
+ "type_dispatch",
62
+ ],
63
+ ) -> ResolvedContract | None:
64
+ return max(
65
+ (
66
+ contract
67
+ for contract in self.resolved
68
+ if getattr(contract.spec, policy) is not None
69
+ and is_within(module, contract.package)
70
+ ),
71
+ key=lambda contract: len(contract.package),
72
+ default=None,
73
+ )
74
+
75
+ def header_brief(self, module: str | None) -> dict[str, Any]:
76
+ policies: dict[str, Any] = {}
77
+ if module is None:
78
+ return policies
79
+ for key in ("module_docstrings", "future_annotations"):
80
+ contract = self.policy_for(module, key)
81
+ if contract is not None:
82
+ policies[key] = {
83
+ "contract": contract.name,
84
+ "package": contract.package,
85
+ "policy": getattr(contract.spec, key),
86
+ }
87
+ return policies
88
+
89
+ def naming_brief(self, module: str | None) -> dict[str, Any]:
90
+ contract = self.policy_for(module, "private_modules") if module else None
91
+ if contract is None:
92
+ return {}
93
+ return {
94
+ "private_modules": {
95
+ "contract": contract.name,
96
+ "package": contract.package,
97
+ "policy": contract.spec.private_modules,
98
+ }
99
+ }
100
+
101
+ def style_brief(self, module: str | None) -> dict[str, Any] | None:
102
+ contract = self.style_for(module) if module else None
103
+ if contract is None or contract.spec.imports is None:
104
+ return None
105
+ return {
106
+ "contract": contract.name,
107
+ "package": contract.package,
108
+ **contract.spec.imports.model_dump(mode="json"),
109
+ }
110
+
111
+ def ordering_brief(self, module: str | None) -> dict[str, Any] | None:
112
+ contract = self.policy_for(module, "ordering") if module else None
113
+ if contract is None or contract.spec.ordering is None:
114
+ return None
115
+ return {
116
+ "contract": contract.name,
117
+ "package": contract.package,
118
+ **contract.spec.ordering.model_dump(mode="json", by_alias=True),
119
+ }
120
+
121
+ def dispatch_brief(self, module: str | None) -> dict[str, Any] | None:
122
+ contract = self.policy_for(module, "type_dispatch") if module else None
123
+ if contract is None or contract.spec.type_dispatch is None:
124
+ return None
125
+ return {
126
+ "contract": contract.name,
127
+ "package": contract.package,
128
+ **contract.spec.type_dispatch.model_dump(mode="json"),
129
+ }
130
+
131
+ def missing(self, contract: ResolvedContract) -> list[str]:
132
+ return [
133
+ contract.qualify(entry)
134
+ for entry in contract.spec.required
135
+ if contract.qualify(entry) not in self.known
136
+ ]
137
+
138
+ def missing_public(self, contract: ResolvedContract) -> list[str]:
139
+ return [
140
+ pattern
141
+ for pattern in contract.public or ()
142
+ if not any(module_matches(pattern, module) for module in self.known)
143
+ ]
144
+
145
+ def describe(self, module: str | None = None) -> list[dict[str, Any]]:
146
+ """Contracts containing a target, or below a package/project target."""
147
+ return [
148
+ {
149
+ "name": contract.name,
150
+ "package": contract.package,
151
+ "match": contract.spec.match,
152
+ "rules": dict(contract.spec.rules),
153
+ "required": [
154
+ contract.qualify(entry) for entry in contract.spec.required
155
+ ],
156
+ "missing": self.missing(contract),
157
+ "public": list(contract.public)
158
+ if contract.public is not None
159
+ else None,
160
+ "missing_public": self.missing_public(contract),
161
+ **(
162
+ {
163
+ "type_dispatch": contract.spec.type_dispatch.model_dump(
164
+ mode="json"
165
+ )
166
+ }
167
+ if contract.spec.type_dispatch
168
+ else {}
169
+ ),
170
+ **(
171
+ {
172
+ "ordering": contract.spec.ordering.model_dump(
173
+ mode="json", by_alias=True
174
+ )
175
+ }
176
+ if contract.spec.ordering
177
+ else {}
178
+ ),
179
+ "target_public": contract.exposes(module)
180
+ if module
181
+ and is_within(module, contract.package)
182
+ and contract.public is not None
183
+ else None,
184
+ **(
185
+ {"imports": contract.spec.imports.model_dump(mode="json")}
186
+ if contract.spec.imports
187
+ else {}
188
+ ),
189
+ **(
190
+ {"bundle_imports_at": contract.spec.bundle_imports_at}
191
+ if contract.spec.bundle_imports_at is not None
192
+ else {}
193
+ ),
194
+ **(
195
+ {
196
+ key: getattr(contract.spec, key)
197
+ for key in (
198
+ "module_docstrings",
199
+ "future_annotations",
200
+ "private_modules",
201
+ )
202
+ if getattr(contract.spec, key) is not None
203
+ }
204
+ ),
205
+ }
206
+ for contract in self.resolved
207
+ if module is None
208
+ or is_within(module, contract.package)
209
+ or is_within(contract.package, module)
210
+ ]