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,76 @@
1
+ """Known blocking/wait families and local syntactic deadline guards."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING
8
+
9
+ from smelt.analysis.test_deadlines import async_deadline, has_timeout
10
+
11
+ if TYPE_CHECKING:
12
+ from smelt.analysis.test_syntax import TestFunction
13
+
14
+ _PROCESS_WAITS = frozenset(
15
+ {
16
+ "subprocess.run",
17
+ "subprocess.call",
18
+ "subprocess.check_call",
19
+ "subprocess.check_output",
20
+ "subprocess.Popen.wait",
21
+ "subprocess.Popen.communicate",
22
+ }
23
+ )
24
+ _ASYNC_WAITS = frozenset(
25
+ {
26
+ "asyncio.Event.wait",
27
+ "asyncio.locks.Event.wait",
28
+ "asyncio.subprocess.Process.wait",
29
+ "asyncio.subprocess.Process.communicate",
30
+ }
31
+ )
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class TestWait:
36
+ node: ast.Call | ast.Await
37
+ qualified: str
38
+ provenance: str
39
+
40
+
41
+ def unbounded_waits(test: TestFunction, helpers: list[str]) -> list[TestWait]:
42
+ calls = {call.node: call.qualified for call in test.calls}
43
+ parents = {
44
+ child: node
45
+ for node in ast.walk(test.node)
46
+ for child in ast.iter_child_nodes(node)
47
+ }
48
+ unbounded: list[TestWait] = []
49
+ waits = [
50
+ TestWait(call.node, call.qualified, call.provenance)
51
+ for call in test.calls
52
+ if call.qualified in _PROCESS_WAITS | _ASYNC_WAITS
53
+ ]
54
+ waits.extend(
55
+ TestWait(node, qualified, provenance)
56
+ for node, qualified, provenance in test.awaited_tasks
57
+ )
58
+ for call in waits:
59
+ if call.qualified in _PROCESS_WAITS:
60
+ # Async cancellation cannot interrupt a blocking synchronous process call.
61
+ position = (
62
+ 0
63
+ if call.qualified == "subprocess.Popen.wait"
64
+ else 1
65
+ if call.qualified == "subprocess.Popen.communicate"
66
+ else None
67
+ )
68
+ if isinstance(call.node, ast.Call) and not has_timeout(
69
+ call.node, position=position
70
+ ):
71
+ unbounded.append(call)
72
+ continue
73
+ deadline = async_deadline(call.node, calls, parents, helpers)
74
+ if deadline.awaited and not deadline.bounded:
75
+ unbounded.append(call)
76
+ return unbounded
@@ -0,0 +1,193 @@
1
+ """Syntactic candidates for reviewing type dispatch, never automatic conversions."""
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
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterator
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class DispatchBranch:
16
+ line: int
17
+ types: tuple[str, ...]
18
+ guard: str | None
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class TypeDispatch:
23
+ node: ast.If
24
+ subject: str
25
+ branches: tuple[DispatchBranch, ...]
26
+ scope: str
27
+
28
+
29
+ def type_dispatches(tree: ast.Module, minimum: int) -> Iterator[TypeDispatch]:
30
+ checkers = _checker_names(tree)
31
+ if not checkers:
32
+ return
33
+ conditions = [node for node in ast.walk(tree) if isinstance(node, ast.If)]
34
+ parents = {
35
+ child: parent
36
+ for parent in ast.walk(tree)
37
+ for child in ast.iter_child_nodes(parent)
38
+ }
39
+ tails = {id(tail) for node in conditions if (tail := _elif(node)) is not None}
40
+ for root in conditions:
41
+ if id(root) in tails:
42
+ continue
43
+ node: ast.If | None = root
44
+ branches: list[DispatchBranch] = []
45
+ subject: str | None = None
46
+ supported = True
47
+ while node is not None:
48
+ head = _head(node.test, checkers)
49
+ if head is None or (subject is not None and head[0] != subject):
50
+ supported = False
51
+ break
52
+ subject, types, guard = head
53
+ branches.append(DispatchBranch(node.lineno, types, guard))
54
+ node = _elif(node)
55
+ if supported and subject is not None and len(branches) >= minimum:
56
+ yield TypeDispatch(root, subject, tuple(branches), _scope(root, parents))
57
+
58
+
59
+ def _bound_names(node: ast.AST) -> tuple[str, ...]:
60
+ match node:
61
+ case (
62
+ ast.Name(id=name, ctx=ast.Store() | ast.Del())
63
+ | ast.arg(arg=name)
64
+ | ast.FunctionDef(name=name)
65
+ | ast.AsyncFunctionDef(name=name)
66
+ | ast.ClassDef(name=name)
67
+ ):
68
+ return (name,)
69
+ case ast.Import() | ast.ImportFrom():
70
+ return tuple(
71
+ alias.asname or alias.name.split(".")[0] for alias in node.names
72
+ )
73
+ case (
74
+ ast.ExceptHandler(name=name)
75
+ | ast.MatchAs(name=name)
76
+ | ast.MatchStar(name=name)
77
+ ):
78
+ return (name,) if name else ()
79
+ case ast.Global(names=names) | ast.Nonlocal(names=names):
80
+ return tuple(names)
81
+ return ()
82
+
83
+
84
+ def _checker_names(tree: ast.Module) -> set[str]:
85
+ """Reject spellings rebound anywhere in the file rather than guessing scope."""
86
+ bound = Counter(name for node in ast.walk(tree) for name in _bound_names(node))
87
+ if bound["*"]:
88
+ return set()
89
+ names = {"isinstance"} if not bound["isinstance"] else set()
90
+ builtin_modules: set[str] = set()
91
+ for node in tree.body:
92
+ if isinstance(node, ast.Import):
93
+ for alias in node.names:
94
+ name = alias.asname or alias.name
95
+ if alias.name == "builtins" and bound[name] == 1:
96
+ names.add(f"{name}.isinstance")
97
+ builtin_modules.add(name)
98
+ elif (
99
+ isinstance(node, ast.ImportFrom)
100
+ and node.level == 0
101
+ and node.module == "builtins"
102
+ ):
103
+ for alias in node.names:
104
+ name = alias.asname or alias.name
105
+ if alias.name == "isinstance" and bound[name] == 1:
106
+ names.add(name)
107
+ for candidate in ast.walk(tree):
108
+ if (
109
+ isinstance(candidate, ast.Attribute | ast.Subscript)
110
+ and isinstance(candidate.ctx, ast.Store | ast.Del)
111
+ and any(
112
+ isinstance(child, ast.Name) and child.id in builtin_modules
113
+ for child in ast.walk(candidate)
114
+ )
115
+ ):
116
+ return set()
117
+ return names
118
+
119
+
120
+ def _type_names(node: ast.expr) -> tuple[str, ...] | None:
121
+ match node:
122
+ case ast.Name():
123
+ return (node.id,)
124
+ case ast.Attribute(value=value):
125
+ parent = _type_names(value)
126
+ return (
127
+ (f"{parent[0]}.{node.attr}",) if parent and len(parent) == 1 else None
128
+ )
129
+ case ast.Tuple(elts=elements) if elements:
130
+ names: list[str] = []
131
+ for element in elements:
132
+ part = _type_names(element)
133
+ if part is None:
134
+ return None
135
+ names.extend(part)
136
+ return tuple(names)
137
+ case ast.BinOp(left=left, op=ast.BitOr(), right=right):
138
+ first, second = _type_names(left), _type_names(right)
139
+ return (*first, *second) if first and second else None
140
+ case _:
141
+ return None
142
+
143
+
144
+ def _head(
145
+ test: ast.expr, checkers: set[str]
146
+ ) -> tuple[str, tuple[str, ...], str | None] | None:
147
+ values = (
148
+ test.values
149
+ if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And)
150
+ else [test]
151
+ )
152
+ call = values[0]
153
+ match call:
154
+ case ast.Call(func=func, args=[ast.Name(id=subject), types], keywords=[]) if (
155
+ ast.unparse(func) in checkers
156
+ ):
157
+ pass
158
+ case _:
159
+ return None
160
+ names = _type_names(types)
161
+ if not names or any(
162
+ isinstance(node, ast.NamedExpr)
163
+ and isinstance(node.target, ast.Name)
164
+ and node.target.id == subject
165
+ for node in ast.walk(test)
166
+ ):
167
+ return None
168
+ guard = None
169
+ guards = values[1:]
170
+ if guards:
171
+ guard = ast.unparse(
172
+ guards[0] if len(guards) == 1 else ast.BoolOp(op=ast.And(), values=guards)
173
+ )
174
+ return subject, names, guard
175
+
176
+
177
+ def _elif(node: ast.If) -> ast.If | None:
178
+ if (
179
+ len(node.orelse) == 1
180
+ and isinstance(node.orelse[0], ast.If)
181
+ and node.orelse[0].col_offset == node.col_offset
182
+ ):
183
+ return node.orelse[0]
184
+ return None
185
+
186
+
187
+ def _scope(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> str:
188
+ names: list[str] = []
189
+ while node in parents:
190
+ node = parents[node]
191
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
192
+ names.append(node.name)
193
+ return ".".join(["module", *reversed(names)])
@@ -0,0 +1,146 @@
1
+ from __future__ import annotations
2
+
3
+ import tomllib
4
+ from dataclasses import dataclass
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from smelt.analysis.errors import AnalysisError
8
+ from smelt.config.discovery import build_package_settings, packages_in
9
+ from smelt.config.source import SourceStore
10
+
11
+ if TYPE_CHECKING:
12
+ from pathlib import Path
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class WorkspaceMember:
17
+ """A declared uv workspace member and what ``init`` found in it."""
18
+
19
+ path: str # POSIX, relative to the workspace root
20
+ source_root: str | None = None
21
+ packages: tuple[str, ...] = ()
22
+ namespace: tuple[str, ...] = () # the packages without an ``__init__.py``
23
+ skipped: str | None = None # why nothing was taken from it
24
+
25
+ def to_json(self) -> dict[str, Any]:
26
+ return {
27
+ "path": self.path,
28
+ "source_root": self.source_root,
29
+ "packages": list(self.packages),
30
+ "skipped": self.skipped,
31
+ }
32
+
33
+
34
+ def import_root(
35
+ directory: Path, *, store: SourceStore | None = None
36
+ ) -> tuple[Path, list[Path], list[Path]] | None:
37
+ """The source root of a project or member, its packages and their namespaces.
38
+
39
+ ``src/`` wins when it holds a package; it and a project whose build backend
40
+ declares ``namespace`` or a ``module-name`` may hold namespace packages.
41
+ Otherwise the directory itself, with regular packages only.
42
+ """
43
+ store = store or SourceStore()
44
+ declared, namespace = build_package_settings(directory, store=store)
45
+ for base in (directory / "src", directory):
46
+ allowed = base.name == "src" or namespace or bool(declared)
47
+ found = packages_in(base, namespace=allowed, store=store)
48
+ if declared:
49
+ found = [p for p in found if p.name in declared] or found
50
+ if found:
51
+ namespaces = [p for p in found if not any(store.glob(p, "*.py"))]
52
+ return base, found, namespaces
53
+ return None
54
+
55
+
56
+ def workspace_members(
57
+ root: Path, *, strict: bool = False, store: SourceStore | None = None
58
+ ) -> list[WorkspaceMember]:
59
+ """Every member ``tool.uv.workspace`` declares, with its packages or why it has none."""
60
+ store = store or SourceStore()
61
+ workspace = _pyproject(root, strict=strict, store=store)
62
+ for key in ("tool", "uv", "workspace"):
63
+ value = workspace.get(key, {})
64
+ if not isinstance(value, dict):
65
+ if strict:
66
+ raise AnalysisError(
67
+ f"pyproject.toml: {key} must be a table for workspace discovery"
68
+ )
69
+ return []
70
+ workspace = value
71
+ patterns = _strings(
72
+ workspace.get("members"), strict=strict, field="tool.uv.workspace.members"
73
+ )
74
+ excluded = _strings(
75
+ workspace.get("exclude"), strict=strict, field="tool.uv.workspace.exclude"
76
+ )
77
+ resolved_root = store.resolve(root)
78
+ found: dict[str, WorkspaceMember] = {}
79
+ for pattern in patterns:
80
+ matches = [
81
+ candidate
82
+ for candidate in store.glob(root, pattern)
83
+ if store.is_dir(candidate)
84
+ and store.resolve(candidate).is_relative_to(resolved_root)
85
+ and store.resolve(candidate) != resolved_root
86
+ ]
87
+ if not matches:
88
+ found.setdefault(
89
+ pattern, WorkspaceMember(pattern, skipped="matches no directory")
90
+ )
91
+ for candidate in matches:
92
+ relative = candidate.relative_to(root).as_posix()
93
+ if any(candidate in store.glob(root, entry) for entry in excluded):
94
+ reason = "excluded by tool.uv.workspace.exclude"
95
+ found[relative] = WorkspaceMember(relative, skipped=reason)
96
+ else:
97
+ found[relative] = _member(root, candidate, store=store)
98
+ return [found[key] for key in sorted(found)]
99
+
100
+
101
+ def _member(root: Path, directory: Path, *, store: SourceStore) -> WorkspaceMember:
102
+ relative = directory.relative_to(root).as_posix()
103
+ located = import_root(directory, store=store)
104
+ if located is None:
105
+ reason = "no Python package in src/ or the member directory"
106
+ return WorkspaceMember(relative, skipped=reason)
107
+ base, packages, namespaces = located
108
+ return WorkspaceMember(
109
+ relative,
110
+ source_root=base.relative_to(root).as_posix(),
111
+ packages=tuple(p.name for p in packages),
112
+ namespace=tuple(p.name for p in namespaces),
113
+ )
114
+
115
+
116
+ def _pyproject(
117
+ directory: Path, *, strict: bool = False, store: SourceStore
118
+ ) -> dict[str, Any]:
119
+ try:
120
+ text = store.read_text(directory / "pyproject.toml")
121
+ return tomllib.loads(text)
122
+ except FileNotFoundError:
123
+ return {}
124
+ except (OSError, UnicodeError, tomllib.TOMLDecodeError) as exc:
125
+ if strict:
126
+ raise AnalysisError(
127
+ f"cannot discover workspace from pyproject.toml: {exc}"
128
+ ) from exc
129
+ return {}
130
+
131
+
132
+ def _strings(
133
+ value: object, *, strict: bool = False, field: str = "workspace"
134
+ ) -> list[str]:
135
+ if (
136
+ strict
137
+ and value is not None
138
+ and (
139
+ not isinstance(value, list)
140
+ or not all(isinstance(item, str) for item in value)
141
+ )
142
+ ):
143
+ raise AnalysisError(f"pyproject.toml: {field} must be a list of strings")
144
+ if not isinstance(value, list):
145
+ return []
146
+ return [item for item in value if isinstance(item, str)]
smelt/cli/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from smelt.cli.app import main
2
+
3
+ __all__ = ["main"]