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,93 @@
1
+ """Find top-level packages on disk; shared by `smelt init` and config loading."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from typing import TYPE_CHECKING
7
+
8
+ from smelt.config.source import SourceStore
9
+
10
+ if TYPE_CHECKING:
11
+ from pathlib import Path
12
+
13
+ IGNORED_DIRS = frozenset(
14
+ {
15
+ "tests",
16
+ "test",
17
+ "docs",
18
+ "doc",
19
+ "scripts",
20
+ "examples",
21
+ "build",
22
+ "dist",
23
+ "node_modules",
24
+ "site-packages",
25
+ "migrations",
26
+ "venv",
27
+ "env",
28
+ }
29
+ )
30
+
31
+
32
+ def has_python(directory: Path, *, store: SourceStore | None = None) -> bool:
33
+ store = store or SourceStore()
34
+ return (
35
+ store.is_dir(directory)
36
+ and directory.name.isidentifier()
37
+ and directory.name not in IGNORED_DIRS
38
+ and any(store.glob(directory, "**/*.py"))
39
+ )
40
+
41
+
42
+ def child_packages(directory: Path, *, store: SourceStore | None = None) -> list[Path]:
43
+ store = store or SourceStore()
44
+ if not store.is_dir(directory):
45
+ return []
46
+ return sorted(
47
+ (child for child in store.iterdir(directory) if has_python(child, store=store)),
48
+ key=lambda p: p.name,
49
+ )
50
+
51
+
52
+ def packages_in(
53
+ base: Path, *, namespace: bool | None = None, store: SourceStore | None = None
54
+ ) -> list[Path]:
55
+ """Packages under an import root, including supported namespace packages.
56
+
57
+ ``src/`` and build metadata permit a directory containing regular packages
58
+ without Python files of its own. Loose script directories stay excluded.
59
+ """
60
+ store = store or SourceStore()
61
+ declared, enabled = build_package_settings(
62
+ base.parent if base.name == "src" else base, store=store
63
+ )
64
+ if namespace is None:
65
+ namespace = base.name == "src" or enabled or bool(declared)
66
+ found = [
67
+ child
68
+ for child in child_packages(base, store=store)
69
+ if any(store.glob(child, "*.py"))
70
+ or (
71
+ namespace
72
+ and any(store.is_file(c / "__init__.py") for c in store.iterdir(child))
73
+ )
74
+ ]
75
+ return ([p for p in found if p.name in declared] or found) if declared else found
76
+
77
+
78
+ def build_package_settings(
79
+ directory: Path, *, store: SourceStore | None = None
80
+ ) -> tuple[set[str], bool]:
81
+ """Top-level modules and namespace support declared by the uv build backend."""
82
+ try:
83
+ data = tomllib.loads(
84
+ (store or SourceStore()).read_text(directory / "pyproject.toml")
85
+ )
86
+ except (OSError, tomllib.TOMLDecodeError):
87
+ return set(), False
88
+ backend = data.get("tool", {}).get("uv", {}).get("build-backend", {})
89
+ raw = backend.get("module-name")
90
+ names = [raw] if isinstance(raw, str) else raw if isinstance(raw, list) else []
91
+ return {name.split(".")[0] for name in names if isinstance(name, str)}, backend.get(
92
+ "namespace"
93
+ ) is True
smelt/config/errors.py ADDED
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ import difflib
4
+ from dataclasses import dataclass
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Iterable, Sequence
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class ConfigIssue:
13
+ path: str
14
+ message: str
15
+
16
+ def __str__(self) -> str:
17
+ return f"{self.path}: {self.message}" if self.path else self.message
18
+
19
+
20
+ class ConfigError(Exception):
21
+ def __init__(
22
+ self, issues: Sequence[ConfigIssue], source: str | None = None
23
+ ) -> None:
24
+ self.issues = tuple(issues)
25
+ self.source = source
26
+ header = (
27
+ f"invalid configuration in {source}" if source else "invalid configuration"
28
+ )
29
+ lines = [header, *(f" {issue}" for issue in self.issues)]
30
+ super().__init__("\n".join(lines))
31
+
32
+
33
+ def format_loc(loc: Iterable[str | int]) -> str:
34
+ """Render a location tuple as ``a.b[1].c``."""
35
+ parts: list[str] = []
36
+ for item in loc:
37
+ if isinstance(item, int):
38
+ parts.append(f"[{item}]")
39
+ elif parts:
40
+ parts.append(f".{item}")
41
+ else:
42
+ parts.append(item)
43
+ return "".join(parts)
44
+
45
+
46
+ def did_you_mean(value: str, candidates: Iterable[str]) -> str:
47
+ options = sorted(candidates)
48
+ matches = difflib.get_close_matches(value, options, n=1, cutoff=0.6)
49
+ if not matches:
50
+ matches = [option for option in options if option.startswith(value)][:1]
51
+ return f' (did you mean "{matches[0]}"?)' if matches else ""
smelt/config/loader.py ADDED
@@ -0,0 +1,282 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import types
5
+ import typing
6
+ from collections.abc import Hashable
7
+ from dataclasses import dataclass
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ import yaml
11
+ from pydantic import BaseModel, ValidationError
12
+
13
+ from smelt.config.discovery import packages_in
14
+ from smelt.config.errors import ConfigError, ConfigIssue, did_you_mean, format_loc
15
+ from smelt.config.models import SmeltConfig
16
+ from smelt.config.source import SourceStore
17
+ from smelt.config.validation import validate_semantics
18
+
19
+ if TYPE_CHECKING:
20
+ from collections.abc import Sequence
21
+ from pathlib import Path
22
+
23
+ CONFIG_FILENAME = "smelt.yaml"
24
+ CONFIG_FILENAMES = (CONFIG_FILENAME, "smelt.yml")
25
+
26
+ _REMOVED_SWITCHES = {
27
+ "member_visibility": "internal-public-member",
28
+ "static_methods": "internal-static-helper",
29
+ "instance_assignments": "bundled-instance-assignment",
30
+ "forbid_private_imports": "private-test-access",
31
+ "forbid_string_patch_targets": "string-patch-target",
32
+ "require_assertions": "test-without-outcome-check",
33
+ "require_non_vacuous_assertions": "test-only-checks-possibly-empty-data",
34
+ "review_test_deadlines": "unbounded-test-wait",
35
+ "review_case_loops": "independent-test-case-loop",
36
+ "review_async_mock_assertions": "async-mock-without-await-check",
37
+ "review_test_only_public_functions": "test-only-public-function",
38
+ "review_test_only_public_attributes": "test-only-public-attribute",
39
+ }
40
+
41
+
42
+ class _StrictBoolLoader(yaml.SafeLoader):
43
+ """YAML 1.2 booleans: only ``true``/``false``, so ``off`` stays a string."""
44
+
45
+ def construct_mapping(
46
+ self, node: yaml.MappingNode, deep: bool = False
47
+ ) -> dict[Any, Any]:
48
+ if isinstance(node, yaml.MappingNode):
49
+ keys: dict[Hashable, yaml.Node] = {}
50
+ for key_node, _ in node.value:
51
+ if key_node.tag == "tag:yaml.org,2002:merge":
52
+ continue # Explicit keys may override inherited YAML defaults.
53
+ key = self.construct_object(key_node, deep=deep)
54
+ if not isinstance(key, Hashable):
55
+ continue # The standard constructor diagnoses invalid keys.
56
+ if key in keys:
57
+ raise yaml.constructor.ConstructorError(
58
+ "first definition of key",
59
+ keys[key].start_mark,
60
+ f"duplicate key {key!r}",
61
+ key_node.start_mark,
62
+ )
63
+ keys[key] = key_node
64
+ return super().construct_mapping(node, deep=deep)
65
+
66
+
67
+ _StrictBoolLoader.yaml_implicit_resolvers = {
68
+ key: [(tag, regex) for tag, regex in resolvers if tag != "tag:yaml.org,2002:bool"]
69
+ for key, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items()
70
+ }
71
+ _StrictBoolLoader.add_implicit_resolver(
72
+ "tag:yaml.org,2002:bool",
73
+ re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$"),
74
+ list("tTfF"),
75
+ )
76
+
77
+
78
+ def _load_yaml(text: str) -> object:
79
+ return yaml.load(text, Loader=_StrictBoolLoader) # noqa: S506
80
+
81
+
82
+ @dataclass(frozen=True, slots=True)
83
+ class LoadedConfig:
84
+ config: SmeltConfig
85
+ path: Path
86
+ warnings: tuple[ConfigIssue, ...] = ()
87
+ source: SourceStore | None = None
88
+
89
+ @property
90
+ def root(self) -> Path:
91
+ """Project root: the directory containing the config file."""
92
+ return self.path.parent
93
+
94
+
95
+ def discover_config(start: Path, *, store: SourceStore | None = None) -> Path | None:
96
+ """Walk up from ``start`` looking for ``smelt.yaml`` or ``smelt.yml``."""
97
+ store = store or SourceStore()
98
+ current = store.resolve(start)
99
+ for directory in (current, *current.parents):
100
+ for filename in CONFIG_FILENAMES:
101
+ candidate = directory / filename
102
+ if store.is_file(candidate):
103
+ return candidate
104
+ return None
105
+
106
+
107
+ def load_config(path: Path, *, store: SourceStore | None = None) -> LoadedConfig:
108
+ source = path.name
109
+ try:
110
+ raw = _load_yaml((store or SourceStore()).read_text(path))
111
+ except (OSError, UnicodeError) as exc:
112
+ raise ConfigError([ConfigIssue("", f"cannot read {path}: {exc}")]) from exc
113
+ except yaml.YAMLError as exc:
114
+ raise ConfigError([ConfigIssue("", f"invalid YAML: {exc}")], source) from exc
115
+ config, warnings = parse_config(raw, source=source, root=path.parent, store=store)
116
+ return LoadedConfig(
117
+ config=config,
118
+ path=(store or SourceStore()).resolve(path),
119
+ warnings=warnings,
120
+ source=store,
121
+ )
122
+
123
+
124
+ def parse_config(
125
+ raw: object,
126
+ *,
127
+ source: str | None = None,
128
+ root: Path | None = None,
129
+ store: SourceStore | None = None,
130
+ ) -> tuple[SmeltConfig, tuple[ConfigIssue, ...]]:
131
+ """Validate a raw config; ``root`` lets omitted root_packages be discovered."""
132
+ if raw is None:
133
+ raw = {}
134
+ if not isinstance(raw, dict):
135
+ raise ConfigError([ConfigIssue("", "the top level must be a mapping")], source)
136
+ if "version" not in raw:
137
+ raise ConfigError([ConfigIssue("version", "`version: 1` is required")], source)
138
+ try:
139
+ config = SmeltConfig.model_validate(raw)
140
+ except ValidationError as exc:
141
+ raise ConfigError(_issues_from_validation(exc), source) from exc
142
+ config = _with_root_packages(config, root, source, store=store)
143
+ errors, warnings = validate_semantics(config)
144
+ if errors:
145
+ raise ConfigError(errors, source)
146
+ return config, tuple(warnings)
147
+
148
+
149
+ def _with_root_packages(
150
+ config: SmeltConfig,
151
+ root: Path | None,
152
+ source: str | None,
153
+ *,
154
+ store: SourceStore | None = None,
155
+ ) -> SmeltConfig:
156
+ project = config.project
157
+ if project.root_packages:
158
+ return config
159
+ found = (
160
+ list(
161
+ dict.fromkeys(
162
+ package.name
163
+ for source_root in project.source_roots
164
+ for package in packages_in(root / source_root, store=store)
165
+ )
166
+ )
167
+ if root is not None
168
+ else []
169
+ )
170
+ if not found:
171
+ where = ", ".join(project.source_roots)
172
+ raise ConfigError(
173
+ [
174
+ ConfigIssue(
175
+ "project.root_packages",
176
+ f"no packages found under source_roots ({where}); "
177
+ "set root_packages or source_roots",
178
+ )
179
+ ],
180
+ source,
181
+ )
182
+ return config.model_copy(
183
+ update={"project": project.model_copy(update={"root_packages": found})}
184
+ )
185
+
186
+
187
+ def _issues_from_validation(exc: ValidationError) -> list[ConfigIssue]:
188
+ issues: list[ConfigIssue] = []
189
+ allowance_prefix = ("architecture", "cross_feature", "allow")
190
+ branch_index = len(allowance_prefix) + 1
191
+ exclusion_prefix = ("project", "exclude")
192
+ exclusion_branch_index = len(exclusion_prefix) + 1
193
+ for error in exc.errors():
194
+ loc = tuple(error["loc"])
195
+ # Expose YAML keys, not the internal branches of the allowance union.
196
+ if loc[: len(allowance_prefix)] == allowance_prefix and len(loc) > branch_index:
197
+ branch = str(loc[branch_index])
198
+ if branch == "str" and isinstance(error.get("input"), dict):
199
+ continue
200
+ if (
201
+ len(loc) == branch_index + 1
202
+ and branch.startswith("function-after")
203
+ and isinstance(error.get("input"), str)
204
+ ):
205
+ continue
206
+ loc = (*loc[:branch_index], *loc[branch_index + 1 :])
207
+ elif (
208
+ loc[: len(exclusion_prefix)] == exclusion_prefix
209
+ and len(loc) > exclusion_branch_index
210
+ ):
211
+ branch = str(loc[exclusion_branch_index])
212
+ if branch == "str" and isinstance(error.get("input"), dict):
213
+ continue
214
+ if (
215
+ len(loc) == exclusion_branch_index + 1
216
+ and branch == "SourceExclusion"
217
+ and isinstance(error.get("input"), str)
218
+ ):
219
+ continue
220
+ loc = (*loc[:exclusion_branch_index], *loc[exclusion_branch_index + 1 :])
221
+ message = str(error["msg"]).removeprefix("Value error, ")
222
+ if error["type"] == "extra_forbidden":
223
+ key = str(loc[-1])
224
+ known = _known_fields(SmeltConfig, loc[:-1])
225
+ message = _unknown_key_message(key, known, loc)
226
+ elif error["type"] == "missing":
227
+ message = "required key is missing"
228
+ elif error["type"] == "literal_error":
229
+ message = f"{message}, got {error.get('input')!r}"
230
+ issues.append(ConfigIssue(format_loc(loc), message))
231
+ return issues
232
+
233
+
234
+ def _unknown_key_message(key: str, known: list[str], loc: tuple[str | int, ...]) -> str:
235
+ message = f'unknown key "{key}"{did_you_mean(key, known)}'
236
+ if key in _REMOVED_SWITCHES:
237
+ return (
238
+ message
239
+ + f"; this switch was removed: configure rules.{_REMOVED_SWITCHES[key]} with error, warning, hint or off instead"
240
+ )
241
+ if key == "enabled" and "ordering" in loc:
242
+ return message + "; enable or disable rules.public-definitions-first instead"
243
+ if key == "preset":
244
+ return (
245
+ message
246
+ + "; presets were removed: init --maintainability writes explicit rule entries"
247
+ )
248
+ return message
249
+
250
+
251
+ def _known_fields(model: type[BaseModel], loc: Sequence[str | int]) -> list[str]:
252
+ current: Any = model
253
+ for item in loc:
254
+ current = _step(current, item)
255
+ if current is None:
256
+ return []
257
+ if isinstance(current, type) and issubclass(current, BaseModel):
258
+ return [field.alias or name for name, field in current.model_fields.items()]
259
+ return []
260
+
261
+
262
+ def _step(annotation: Any, item: str | int) -> Any:
263
+ annotation = _unwrap_optional(annotation)
264
+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):
265
+ field = annotation.model_fields.get(str(item))
266
+ return field.annotation if field else None
267
+ origin = typing.get_origin(annotation)
268
+ args = typing.get_args(annotation)
269
+ if origin is list and args:
270
+ return args[0]
271
+ if origin is dict and len(args) == 2: # noqa: PLR2004
272
+ return args[1]
273
+ return None
274
+
275
+
276
+ def _unwrap_optional(annotation: Any) -> Any:
277
+ origin = typing.get_origin(annotation)
278
+ if origin is types.UnionType or origin is typing.Union:
279
+ args = [arg for arg in typing.get_args(annotation) if arg is not type(None)]
280
+ if len(args) == 1:
281
+ return args[0]
282
+ return annotation