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,117 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ from typing import TYPE_CHECKING
5
+
6
+ from smelt.analysis.context import AnalysisContext, Index
7
+ from smelt.analysis.package_exports import direct_package_exports
8
+ from smelt.analysis.parsing import resolve_relative, type_checking_lines
9
+ from smelt.diagnostics.violation import Category, Severity, Violation
10
+ from smelt.model import is_within
11
+ from smelt.rules.base import BaseRule, RuleDoc
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Iterator
15
+
16
+
17
+ class PreferPackageImport(BaseRule):
18
+ code = "SMT319"
19
+ name = "prefer-package-import"
20
+ category = Category.STRUCTURE
21
+ default_severity = Severity.HINT
22
+ requires = frozenset({Index.SYNTAX})
23
+ doc = RuleDoc(
24
+ summary="Prefer an existing package re-export over an implementation import.",
25
+ rationale=(
26
+ "Importing supported names from a common package keeps callers independent "
27
+ "of implementation paths and allows related imports to be combined. This "
28
+ "opt-in hint requires every name in a from-import to have an unconditional, "
29
+ "direct, same-named public re-export in an analyzed ancestor __init__.py. "
30
+ "The nearest eligible package is suggested. Static __all__ is respected. "
31
+ "Imports inside that package are excluded to avoid routing its own "
32
+ "implementation through its initializer. Imports in package initializers "
33
+ "also stay unchanged. Conditional, rebound, private, "
34
+ "star and dynamic exports, re-export chains, module imports and unscanned "
35
+ "third-party packages are outside this check."
36
+ ),
37
+ bad=(
38
+ "# app/observation/__init__.py exports Observe and Snapshot\n"
39
+ "# app/client.py\nfrom app.observation import Observe\n"
40
+ "from app.observation.models import Snapshot"
41
+ ),
42
+ good="# app/client.py\nfrom app.observation import Observe, Snapshot",
43
+ fix=(
44
+ "Use the suggested package import and combine it with an existing import "
45
+ "there when both are in the same scope and guard. Preserve aliases, "
46
+ "comments and relative/absolute import policy. Review initializer side "
47
+ "effects and dependency cycles. No exports are created and no automatic "
48
+ "rewrite is performed; analyzed code is never executed."
49
+ ),
50
+ config=("rules", "architecture.imports.type_checking"),
51
+ )
52
+
53
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
54
+ facades = {
55
+ source.module: direct_package_exports(module)
56
+ for source in ctx.files.sources.values()
57
+ if source.is_package
58
+ and (module := ctx.syntax.for_path(source.path)) is not None
59
+ }
60
+ for source in ctx.files.sources.values():
61
+ if source.is_package:
62
+ continue
63
+ tree = ctx.asts.parse(source.path)
64
+ guarded = type_checking_lines(tree)
65
+ for node in ast.walk(tree):
66
+ if not isinstance(node, ast.ImportFrom) or any(
67
+ alias.name.startswith("_") or alias.name == "*"
68
+ for alias in node.names
69
+ ):
70
+ continue
71
+ if (
72
+ node.lineno in guarded
73
+ and ctx.config.architecture.imports.type_checking == "ignore"
74
+ ):
75
+ continue
76
+ base = resolve_relative(
77
+ source.module,
78
+ is_package=source.is_package,
79
+ level=node.level,
80
+ target=node.module,
81
+ )
82
+ if base not in ctx.files.sources:
83
+ continue
84
+ package = base.rpartition(".")[0]
85
+ while package:
86
+ exports = facades.get(package, {})
87
+ if not is_within(source.module, package) and all(
88
+ exports.get(alias.name) == f"{base}.{alias.name}"
89
+ for alias in node.names
90
+ ):
91
+ import_from = package
92
+ if node.level and node.module:
93
+ import_from = "." * node.level + node.module.removesuffix(
94
+ base.removeprefix(package)
95
+ )
96
+ replacement = f"from {import_from} import " + ", ".join(
97
+ ast.unparse(alias) for alias in node.names
98
+ )
99
+ yield self.violation(
100
+ f"import these names from the existing {package} package API",
101
+ path=source.path,
102
+ line=node.lineno,
103
+ column=node.col_offset + 1,
104
+ end_line=node.end_lineno,
105
+ end_column=(node.end_col_offset or node.col_offset) + 1,
106
+ source_module=source.module,
107
+ target_module=base,
108
+ expected={
109
+ "package": package,
110
+ "names": [alias.name for alias in node.names],
111
+ "replacement": replacement,
112
+ "automatic_rewrite": False,
113
+ },
114
+ hint=f"Use {replacement}; combine imports from {package} in the same scope and guard, preserving aliases and comments.",
115
+ )
116
+ break
117
+ package = package.rpartition(".")[0]
@@ -0,0 +1,79 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import Counter
4
+ from typing import TYPE_CHECKING
5
+
6
+ from smelt.analysis.context import AnalysisContext, Index
7
+ from smelt.analysis.type_dispatch import type_dispatches
8
+ from smelt.diagnostics.violation import Category, Severity, Violation
9
+ from smelt.rules.activation import POLICIES
10
+ from smelt.rules.base import BaseRule, RuleDoc
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Iterator
14
+
15
+
16
+ class PreferMatchTypeDispatch(BaseRule):
17
+ file_local = True
18
+ activation = POLICIES["SMT315"]
19
+ code = "SMT315"
20
+ name = "prefer-match-type-dispatch"
21
+ category = Category.STRUCTURE
22
+ default_severity = Severity.HINT
23
+ requires = frozenset({Index.SYNTAX})
24
+ doc = RuleDoc(
25
+ summary="Review a same-subject isinstance/elif chain for match/case under an explicit package policy.",
26
+ rationale="Long type-dispatch chains can be clearer as class patterns and guards. This opt-in hint recognizes positive builtin isinstance tests over the same simple name, optionally followed by and guards. It preserves independent adjacent if statements and reports one candidate per whole supported chain. It is a readability suggestion, not proof of equivalent class-pattern behavior.",
27
+ bad="if isinstance(event, Started):\n start(event)\nelif isinstance(event, Delta | Progress):\n update(event)\nelif isinstance(event, Finished) and event.ok:\n finish(event)",
28
+ good="match event:\n case Started():\n start(event)\n case Delta() | Progress():\n update(event)\n case Finished() if event.ok:\n finish(event)",
29
+ fix="Review class patterns, guards and subclass ordering. Preserve independent if statements, and keep nested body conditions inside their case: moving them into a case guard can introduce fallthrough. Match evaluates its subject once; custom instance checks, dynamic type expressions and side effects may differ. No automatic rewrite is performed. Declared Python minima before 3.10 are excluded; unknown minima require version review.",
30
+ config=("structure.contracts", "project.python_version"),
31
+ )
32
+
33
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
34
+ for source in ctx.files.sources.values():
35
+ contract = ctx.contracts.policy_for(source.module, "type_dispatch")
36
+ if (
37
+ contract is None
38
+ or contract.spec.type_dispatch is None
39
+ or contract.spec.type_dispatch.style != "match"
40
+ ):
41
+ continue
42
+ policy = contract.spec.type_dispatch
43
+ target = ctx.python_targets.for_path(source.absolute)
44
+ if target.minimum is not None and target.minimum < (3, 10):
45
+ continue
46
+ for candidate in type_dispatches(
47
+ ctx.asts.parse(source.path), policy.min_branches
48
+ ):
49
+ counts: Counter[str] = Counter()
50
+ edges: list[str] = []
51
+ for branch in candidate.branches:
52
+ key = f"{candidate.scope}:{candidate.subject}:{branch.types}:{branch.guard}"
53
+ edges.append(f"{key}#{counts[key]}")
54
+ counts[key] += 1
55
+ yield self.violation(
56
+ f"consider match {candidate.subject}: for {len(candidate.branches)} type-dispatch branches",
57
+ path=source.path,
58
+ line=candidate.node.lineno,
59
+ column=candidate.node.col_offset + 1,
60
+ source_module=source.module,
61
+ expected={
62
+ "contract": contract.name,
63
+ "type_dispatch": policy.model_dump(mode="json"),
64
+ "subject": candidate.subject,
65
+ "scope": candidate.scope,
66
+ "dispatch_edges": edges,
67
+ "branches": [
68
+ {
69
+ "line": branch.line,
70
+ "types": list(branch.types),
71
+ "guard": branch.guard,
72
+ }
73
+ for branch in candidate.branches
74
+ ],
75
+ "python": target.to_json(),
76
+ "automatic_rewrite": False,
77
+ },
78
+ hint=f"Review match {candidate.subject}: with class patterns and guards; preserve separate if statements and nested branch conditions.",
79
+ )
File without changes
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from smelt.analysis.context import AnalysisContext, Index
6
+ from smelt.analysis.test_awaits import call_only_async_mocks
7
+ from smelt.diagnostics.violation import Category, Severity, Violation
8
+ from smelt.rules.base import BaseRule, RuleDoc
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterator
12
+
13
+
14
+ class AsyncMockWithoutAwaitCheck(BaseRule):
15
+ test_local = True
16
+ scope = "test"
17
+ code = "SMT428"
18
+ name = "async-mock-without-await-check"
19
+ category = Category.TESTS
20
+ default_severity = Severity.WARNING
21
+ requires = frozenset({Index.TESTS})
22
+ doc = RuleDoc(
23
+ summary="A known async mock is checked for calls without corresponding await evidence.",
24
+ rationale="Calling an async mock can leave its coroutine unexecuted while call assertions still pass. This opt-in review checks direct known AsyncMock callables and explicitly async methods of known Mock/AsyncMock class specs, including aliases and consistent direct fixture returns. It accepts await assertions/history checks on the same mock and explicit negative call checks. Simple single-assignment locals can carry history values into assertions. Unknown specs, inherited or dynamically replaced methods, nested helpers and general data flow are not inferred. An AsyncMock object's arbitrary children are not assumed async. Deliberate creation/scheduling tests can assert_not_awaited or use a reasoned exception. This is evidence about an individual test, not proof that the suite misses a regression.",
25
+ bad="def test_connect():\n connect = AsyncMock()\n run_handler(connect)\n connect.assert_called_once_with('account')",
26
+ good="def test_connect():\n connect = AsyncMock()\n run_handler(connect)\n connect.assert_awaited_once_with('account')",
27
+ fix="When execution matters, check await arguments/counts or assert_awaited_once_with on this async mock. Preserve intentional scheduling tests with an explicit expectation; keep synchronous interactions unchanged.",
28
+ config=("rules", "tests.quality_exclude"),
29
+ )
30
+
31
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
32
+ for module in ctx.test_syntax.modules.values():
33
+ for test in module.tests:
34
+ for observation in call_only_async_mocks(test):
35
+ yield self.violation(
36
+ f"{test.name} checks calls to {observation.receiver} without await evidence",
37
+ path=module.path,
38
+ line=observation.node.lineno,
39
+ expected={
40
+ "test": test.name,
41
+ "receiver": observation.receiver,
42
+ "async_callable": observation.async_callable,
43
+ "provenance": observation.provenance,
44
+ },
45
+ hint="Check this operation was awaited when execution matters; review deliberate awaitable creation/scheduling.",
46
+ )
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ from typing import TYPE_CHECKING
5
+
6
+ from smelt.analysis.context import AnalysisContext, Index
7
+ from smelt.analysis.test_cases import independent_case_loops
8
+ from smelt.diagnostics.violation import Category, Severity, Violation
9
+ from smelt.rules.base import BaseRule, RuleDoc
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Iterator
13
+
14
+
15
+ class IndependentTestCaseLoop(BaseRule):
16
+ test_local = True
17
+ scope = "test"
18
+ code = "SMT427"
19
+ name = "independent-test-case-loop"
20
+ category = Category.TESTS
21
+ default_severity = Severity.HINT
22
+ requires = frozenset({Index.TESTS})
23
+ doc = RuleDoc(
24
+ summary="A small literal loop repeats a candidate independent arrange/action/assert case.",
25
+ rationale="A failure in the first independent case prevents later loop iterations from running and obscures case selection. This opt-in review aid considers top-level loops over 2-12 literal list/tuple cases with per-iteration construction/action and assertions. It excludes branches, context managers, control transfers, accumulated state, attribute writes and calls on pre-existing receivers. These exclusions preserve common replay, ownership-handoff and transaction/stream lifecycles. Independence cannot be proven syntactically; repeated calls alone and line counts are not smells.",
26
+ bad="def test_select():\n for path in ['app/a.py', 'app/b.py']:\n selected = select(path)\n assert selected == ['app']",
27
+ good="@pytest.mark.parametrize('path', ['app/a.py', 'app/b.py'], ids=['a', 'b'])\ndef test_select(path):\n assert select(path) == ['app']",
28
+ fix="Review whether cases are independent, then use pytest.mark.parametrize with meaningful IDs. Retain loops when later actions depend on earlier state.",
29
+ config=("rules", "tests.quality_exclude"),
30
+ )
31
+
32
+ def check(self, ctx: AnalysisContext) -> Iterator[Violation]:
33
+ for module in ctx.test_syntax.modules.values():
34
+ for test in module.tests:
35
+ for loop in independent_case_loops(test):
36
+ yield self.violation(
37
+ f"{test.name} repeats candidate independent cases in a literal loop",
38
+ path=module.path,
39
+ line=loop.lineno,
40
+ expected={
41
+ "test": test.name,
42
+ "cases": len(loop.iter.elts)
43
+ if isinstance(loop.iter, ast.List | ast.Tuple)
44
+ else 0,
45
+ },
46
+ hint="Review parametrization with descriptive IDs; preserve stateful lifecycles.",
47
+ )