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.
- smelt/__init__.py +6 -0
- smelt/__main__.py +5 -0
- smelt/analysis/__init__.py +45 -0
- smelt/analysis/annotations.py +105 -0
- smelt/analysis/cache.py +168 -0
- smelt/analysis/context.py +147 -0
- smelt/analysis/contracts.py +210 -0
- smelt/analysis/coverage.py +377 -0
- smelt/analysis/definition_blocks.py +569 -0
- smelt/analysis/enum_values.py +217 -0
- smelt/analysis/errors.py +11 -0
- smelt/analysis/exports.py +166 -0
- smelt/analysis/files.py +279 -0
- smelt/analysis/function_usage.py +123 -0
- smelt/analysis/graphs.py +77 -0
- smelt/analysis/identity.py +64 -0
- smelt/analysis/import_cache.py +98 -0
- smelt/analysis/imports.py +452 -0
- smelt/analysis/literals.py +17 -0
- smelt/analysis/member_state.py +108 -0
- smelt/analysis/members.py +975 -0
- smelt/analysis/ordering.py +399 -0
- smelt/analysis/ordering_rewrite.py +232 -0
- smelt/analysis/package_exports.py +58 -0
- smelt/analysis/parsing.py +126 -0
- smelt/analysis/python_version.py +164 -0
- smelt/analysis/retained.py +84 -0
- smelt/analysis/syntax.py +109 -0
- smelt/analysis/test_awaits.py +91 -0
- smelt/analysis/test_cases.py +84 -0
- smelt/analysis/test_deadlines.py +90 -0
- smelt/analysis/test_outcomes.py +71 -0
- smelt/analysis/test_subprocesses.py +107 -0
- smelt/analysis/test_syntax.py +1425 -0
- smelt/analysis/test_timing.py +76 -0
- smelt/analysis/type_dispatch.py +193 -0
- smelt/analysis/workspace.py +146 -0
- smelt/cli/__init__.py +3 -0
- smelt/cli/app.py +300 -0
- smelt/cli/commands/__init__.py +62 -0
- smelt/cli/commands/adopt.py +274 -0
- smelt/cli/commands/check.py +151 -0
- smelt/cli/commands/discover.py +51 -0
- smelt/cli/commands/info.py +112 -0
- smelt/cli/session.py +163 -0
- smelt/cli/session_slots.py +43 -0
- smelt/cli/support.py +90 -0
- smelt/config/__init__.py +36 -0
- smelt/config/discovery.py +93 -0
- smelt/config/errors.py +51 -0
- smelt/config/loader.py +282 -0
- smelt/config/models.py +717 -0
- smelt/config/patterns.py +47 -0
- smelt/config/schema.py +23 -0
- smelt/config/source.py +56 -0
- smelt/config/validation.py +180 -0
- smelt/diagnostics/__init__.py +0 -0
- smelt/diagnostics/debt.py +226 -0
- smelt/diagnostics/dedupe.py +41 -0
- smelt/diagnostics/groups.py +109 -0
- smelt/diagnostics/render/__init__.py +0 -0
- smelt/diagnostics/render/machine.py +237 -0
- smelt/diagnostics/render/text.py +321 -0
- smelt/diagnostics/report.py +104 -0
- smelt/diagnostics/suppressions.py +80 -0
- smelt/diagnostics/violation.py +120 -0
- smelt/docs.py +98 -0
- smelt/engine/__init__.py +0 -0
- smelt/engine/briefing.py +630 -0
- smelt/engine/cache.py +65 -0
- smelt/engine/changes.py +260 -0
- smelt/engine/check.py +724 -0
- smelt/engine/coverage.py +151 -0
- smelt/engine/evaluation.py +291 -0
- smelt/engine/file_checks.py +94 -0
- smelt/engine/git_source.py +140 -0
- smelt/engine/inference.py +854 -0
- smelt/engine/mirror_inference.py +95 -0
- smelt/engine/native_git.py +190 -0
- smelt/engine/ordering_fixes.py +132 -0
- smelt/engine/paths.py +163 -0
- smelt/engine/result_cache.py +208 -0
- smelt/engine/rule_settings.py +164 -0
- smelt/engine/schema.py +58 -0
- smelt/engine/staged.py +75 -0
- smelt/engine/workspace.py +5 -0
- smelt/model/__init__.py +9 -0
- smelt/model/architecture.py +234 -0
- smelt/py.typed +0 -0
- smelt/rules/__init__.py +0 -0
- smelt/rules/activation.py +129 -0
- smelt/rules/base.py +131 -0
- smelt/rules/catalog.json +600 -0
- smelt/rules/common.py +164 -0
- smelt/rules/dependencies/__init__.py +0 -0
- smelt/rules/dependencies/composition_root.py +86 -0
- smelt/rules/dependencies/cycles.py +329 -0
- smelt/rules/dependencies/fanout.py +81 -0
- smelt/rules/dependencies/features.py +165 -0
- smelt/rules/dependencies/interfaces.py +84 -0
- smelt/rules/dependencies/layers.py +138 -0
- smelt/rules/dependencies/third_party.py +132 -0
- smelt/rules/member_names.py +13 -0
- smelt/rules/meta.py +74 -0
- smelt/rules/registry.py +132 -0
- smelt/rules/structure/__init__.py +0 -0
- smelt/rules/structure/assignments.py +114 -0
- smelt/rules/structure/contracts.py +71 -0
- smelt/rules/structure/coverage.py +100 -0
- smelt/rules/structure/enum_values.py +50 -0
- smelt/rules/structure/headers.py +143 -0
- smelt/rules/structure/import_style.py +145 -0
- smelt/rules/structure/layout.py +202 -0
- smelt/rules/structure/members.py +116 -0
- smelt/rules/structure/naming.py +132 -0
- smelt/rules/structure/ordering.py +83 -0
- smelt/rules/structure/package_imports.py +117 -0
- smelt/rules/structure/type_dispatch.py +79 -0
- smelt/rules/testing/__init__.py +0 -0
- smelt/rules/testing/awaits.py +46 -0
- smelt/rules/testing/cases.py +47 -0
- smelt/rules/testing/location.py +537 -0
- smelt/rules/testing/mocking.py +140 -0
- smelt/rules/testing/outcomes.py +119 -0
- smelt/rules/testing/private_access.py +93 -0
- smelt/rules/testing/public_attributes.py +62 -0
- smelt/rules/testing/public_functions.py +52 -0
- smelt/rules/testing/timing.py +62 -0
- smelt_cli-0.2.0.data/scripts/smelt.exe +0 -0
- smelt_cli-0.2.0.dist-info/METADATA +103 -0
- smelt_cli-0.2.0.dist-info/RECORD +133 -0
- smelt_cli-0.2.0.dist-info/WHEEL +4 -0
- smelt_cli-0.2.0.dist-info/sboms/smelt-cli.cyclonedx.json +5462 -0
smelt/cli/app.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import itertools
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import NoReturn, TextIO, cast
|
|
9
|
+
|
|
10
|
+
from smelt import __version__
|
|
11
|
+
from smelt.analysis.errors import AnalysisError, InvalidOptionError
|
|
12
|
+
from smelt.cli import commands
|
|
13
|
+
from smelt.cli.support import (
|
|
14
|
+
EXIT_ERROR,
|
|
15
|
+
CliError,
|
|
16
|
+
Console,
|
|
17
|
+
configure_streams,
|
|
18
|
+
use_color,
|
|
19
|
+
)
|
|
20
|
+
from smelt.config import ConfigError
|
|
21
|
+
from smelt.diagnostics.render.machine import render_error_json
|
|
22
|
+
from smelt.engine.native_git import check_scope
|
|
23
|
+
from smelt.engine.result_cache import RecordingStream, ResultCache
|
|
24
|
+
|
|
25
|
+
type Handler = Callable[[argparse.Namespace, Console, Path], int]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
type Subparsers = argparse._SubParsersAction[_Parser]
|
|
29
|
+
|
|
30
|
+
_INVALID_CHOICE = re.compile(r"argument ([^:]+): invalid choice: '([^']*)'")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _ParseError(CliError):
|
|
34
|
+
def __init__(self, parser: argparse.ArgumentParser, message: str) -> None:
|
|
35
|
+
choice = _INVALID_CHOICE.match(message)
|
|
36
|
+
option, value = choice.groups() if choice else (None, None)
|
|
37
|
+
super().__init__(message, option=option, value=value)
|
|
38
|
+
self.parser = parser
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _Parser(argparse.ArgumentParser):
|
|
42
|
+
"""Raises instead of exiting, so a JSON caller gets argument errors as JSON."""
|
|
43
|
+
|
|
44
|
+
def error(self, message: str) -> NoReturn:
|
|
45
|
+
raise _ParseError(self, message)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
49
|
+
parser = _Parser(
|
|
50
|
+
prog="smelt",
|
|
51
|
+
description="Static guardrails for Python architecture.",
|
|
52
|
+
)
|
|
53
|
+
parser.add_argument("--version", action="version", version=f"smelt {__version__}")
|
|
54
|
+
parser.add_argument("--config", metavar="PATH", help="path to smelt.yaml")
|
|
55
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
56
|
+
_add_check(sub)
|
|
57
|
+
_add_discovery(sub)
|
|
58
|
+
_add_maintenance(sub)
|
|
59
|
+
_add_config(sub)
|
|
60
|
+
for command in sub.choices.values():
|
|
61
|
+
_allow_local_config(command)
|
|
62
|
+
return parser
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _allow_local_config(parser: argparse.ArgumentParser) -> None:
|
|
66
|
+
if "--config" not in parser._option_string_actions:
|
|
67
|
+
parser.add_argument(
|
|
68
|
+
"--config",
|
|
69
|
+
metavar="PATH",
|
|
70
|
+
default=argparse.SUPPRESS,
|
|
71
|
+
help="path to smelt.yaml",
|
|
72
|
+
)
|
|
73
|
+
for action in parser._actions:
|
|
74
|
+
if isinstance(action, argparse._SubParsersAction):
|
|
75
|
+
for child in action.choices.values():
|
|
76
|
+
_allow_local_config(child)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _add_check(sub: Subparsers) -> None:
|
|
80
|
+
check = sub.add_parser("check", help="check the project against smelt.yaml")
|
|
81
|
+
check.add_argument(
|
|
82
|
+
"paths", nargs="*", metavar="PATHS", help="only report these files"
|
|
83
|
+
)
|
|
84
|
+
scope = check.add_mutually_exclusive_group()
|
|
85
|
+
scope.add_argument(
|
|
86
|
+
"--changed",
|
|
87
|
+
action="store_true",
|
|
88
|
+
help="only report violations introduced since HEAD (incl. uncommitted files)",
|
|
89
|
+
)
|
|
90
|
+
scope.add_argument(
|
|
91
|
+
"--staged",
|
|
92
|
+
action="store_true",
|
|
93
|
+
help="only report violations introduced by the Git index since HEAD",
|
|
94
|
+
)
|
|
95
|
+
check.add_argument(
|
|
96
|
+
"--base",
|
|
97
|
+
metavar="REF",
|
|
98
|
+
help="compare --changed against the merge-base with REF",
|
|
99
|
+
)
|
|
100
|
+
check.add_argument(
|
|
101
|
+
"--format", choices=["text", "json", "sarif", "github"], default="text"
|
|
102
|
+
)
|
|
103
|
+
check.add_argument("--fail-on", choices=["error", "warning"], default="error")
|
|
104
|
+
check.add_argument(
|
|
105
|
+
"--select",
|
|
106
|
+
metavar="CODES",
|
|
107
|
+
help="run rule names, code prefixes or ALL; architecture/style parameters are still required",
|
|
108
|
+
)
|
|
109
|
+
check.add_argument(
|
|
110
|
+
"--ignore",
|
|
111
|
+
metavar="CODES",
|
|
112
|
+
help="skip rule names, code prefixes or ALL; strict coverage remains mandatory",
|
|
113
|
+
)
|
|
114
|
+
check.add_argument(
|
|
115
|
+
"--show-hints",
|
|
116
|
+
action="store_true",
|
|
117
|
+
help="list hints in text output (always on with --changed)",
|
|
118
|
+
)
|
|
119
|
+
check.add_argument(
|
|
120
|
+
"--statistics",
|
|
121
|
+
action="store_true",
|
|
122
|
+
help="show counts per rule instead of each violation",
|
|
123
|
+
)
|
|
124
|
+
check.add_argument("--no-color", action="store_true")
|
|
125
|
+
check.add_argument("--no-debt", action="store_true", help="ignore the debt file")
|
|
126
|
+
check.add_argument(
|
|
127
|
+
"--no-cache",
|
|
128
|
+
action="store_true",
|
|
129
|
+
help="recompute all analysis without reading or writing the persistent cache",
|
|
130
|
+
)
|
|
131
|
+
check.add_argument(
|
|
132
|
+
"--fix",
|
|
133
|
+
action="store_true",
|
|
134
|
+
help="apply permitted safe public-definitions-first fixes, then check again",
|
|
135
|
+
)
|
|
136
|
+
check.add_argument(
|
|
137
|
+
"--strict-coverage",
|
|
138
|
+
action="store_true",
|
|
139
|
+
help="require every discovered production source to have a policy or a reasoned exclusion",
|
|
140
|
+
)
|
|
141
|
+
check.add_argument(
|
|
142
|
+
"--show-coverage",
|
|
143
|
+
action="store_true",
|
|
144
|
+
help="include the per-file coverage inventory in JSON or text output",
|
|
145
|
+
)
|
|
146
|
+
check.set_defaults(handler=commands.handler("check"))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _add_discovery(sub: Subparsers) -> None:
|
|
150
|
+
explain = sub.add_parser("explain", help="explain a rule")
|
|
151
|
+
explain.add_argument("rule", metavar="CODE|NAME")
|
|
152
|
+
explain.add_argument("--format", choices=["text", "json"], default="text")
|
|
153
|
+
explain.set_defaults(handler=commands.handler("explain"))
|
|
154
|
+
|
|
155
|
+
rules = sub.add_parser("rules", help="list all rules")
|
|
156
|
+
rules.add_argument("--format", choices=["text", "json"], default="text")
|
|
157
|
+
rules.set_defaults(handler=commands.handler("rules"))
|
|
158
|
+
|
|
159
|
+
context = sub.add_parser(
|
|
160
|
+
"context",
|
|
161
|
+
help="architecture briefing for a feature, module or planned source path",
|
|
162
|
+
)
|
|
163
|
+
context.add_argument("target", nargs="?", metavar="FEATURE|MODULE|PATH")
|
|
164
|
+
context.add_argument("--format", choices=["text", "json"], default="text")
|
|
165
|
+
context.set_defaults(handler=commands.handler("context"))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _add_maintenance(sub: Subparsers) -> None:
|
|
169
|
+
init = sub.add_parser("init", help="write a starter smelt.yaml")
|
|
170
|
+
init.add_argument(
|
|
171
|
+
"--config",
|
|
172
|
+
metavar="PATH",
|
|
173
|
+
default=argparse.SUPPRESS,
|
|
174
|
+
help="write the config here (default: smelt.yaml); its directory is the project root",
|
|
175
|
+
)
|
|
176
|
+
init.add_argument(
|
|
177
|
+
"--force", action="store_true", help="overwrite the target if it exists"
|
|
178
|
+
)
|
|
179
|
+
init.add_argument(
|
|
180
|
+
"--maintainability",
|
|
181
|
+
action="store_true",
|
|
182
|
+
help="write explicit source/test review rules into the starter (no runtime preset)",
|
|
183
|
+
)
|
|
184
|
+
init.set_defaults(handler=commands.handler("init"))
|
|
185
|
+
|
|
186
|
+
debt = sub.add_parser("debt", help="record current violations as known debt")
|
|
187
|
+
debt.add_argument(
|
|
188
|
+
"--prune", action="store_true", help="only remove resolved entries"
|
|
189
|
+
)
|
|
190
|
+
debt.set_defaults(handler=commands.handler("debt"))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _add_config(sub: Subparsers) -> None:
|
|
194
|
+
config = sub.add_parser("config", help="show the resolved config or its schema")
|
|
195
|
+
config_sub = config.add_subparsers(dest="config_command", metavar="ACTION")
|
|
196
|
+
show = config_sub.add_parser("show", help="print the resolved config")
|
|
197
|
+
show.add_argument("--format", choices=["yaml", "json"], default="yaml")
|
|
198
|
+
show.set_defaults(handler=commands.handler("config_show"))
|
|
199
|
+
schema = config_sub.add_parser("schema", help="print the JSON schema")
|
|
200
|
+
schema.set_defaults(handler=commands.handler("config_schema"))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
204
|
+
configure_streams()
|
|
205
|
+
console = Console(sys.stdout, sys.stderr)
|
|
206
|
+
parser = _build_parser()
|
|
207
|
+
raw = list(sys.argv[1:] if argv is None else argv)
|
|
208
|
+
try:
|
|
209
|
+
args = parser.parse_args(raw)
|
|
210
|
+
except _ParseError as exc:
|
|
211
|
+
if _asks_for_json(raw):
|
|
212
|
+
console.print(_error_json(exc), end="")
|
|
213
|
+
else:
|
|
214
|
+
exc.parser.print_usage(console.err)
|
|
215
|
+
console.err.write(f"{exc.parser.prog}: error: {exc}\n")
|
|
216
|
+
return EXIT_ERROR
|
|
217
|
+
handler: Handler | None = getattr(args, "handler", None)
|
|
218
|
+
if handler is None:
|
|
219
|
+
parser.print_help(sys.stderr)
|
|
220
|
+
return EXIT_ERROR
|
|
221
|
+
with check_scope(enabled=not getattr(args, "no_cache", False)):
|
|
222
|
+
return _run(args, console, handler)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _run(args: argparse.Namespace, console: Console, handler: Handler) -> int:
|
|
226
|
+
try:
|
|
227
|
+
cwd = Path.cwd()
|
|
228
|
+
cache = ResultCache.prepare(
|
|
229
|
+
args,
|
|
230
|
+
cwd,
|
|
231
|
+
color=use_color(console.out, disabled=getattr(args, "no_color", False)),
|
|
232
|
+
)
|
|
233
|
+
if cache is None:
|
|
234
|
+
return handler(args, console, cwd)
|
|
235
|
+
cached = cache.read()
|
|
236
|
+
if cached is not None:
|
|
237
|
+
code, out, err = cached
|
|
238
|
+
console.out.write(out)
|
|
239
|
+
console.err.write(err)
|
|
240
|
+
return code
|
|
241
|
+
out_stream, err_stream = (
|
|
242
|
+
RecordingStream(console.out),
|
|
243
|
+
RecordingStream(console.err),
|
|
244
|
+
)
|
|
245
|
+
recording = Console(cast("TextIO", out_stream), cast("TextIO", err_stream))
|
|
246
|
+
code = handler(args, recording, cwd)
|
|
247
|
+
cache.write(
|
|
248
|
+
code,
|
|
249
|
+
"".join(out_stream.parts),
|
|
250
|
+
"".join(err_stream.parts),
|
|
251
|
+
dependencies=getattr(args, "_staged_inputs", None),
|
|
252
|
+
)
|
|
253
|
+
return code
|
|
254
|
+
except (
|
|
255
|
+
AnalysisError,
|
|
256
|
+
CliError,
|
|
257
|
+
ConfigError,
|
|
258
|
+
json.JSONDecodeError,
|
|
259
|
+
OSError,
|
|
260
|
+
UnicodeError,
|
|
261
|
+
) as exc:
|
|
262
|
+
if getattr(args, "format", None) == "json":
|
|
263
|
+
console.print(_error_json(exc), end="")
|
|
264
|
+
elif isinstance(exc, ConfigError):
|
|
265
|
+
console.err.write(f"{exc}\n")
|
|
266
|
+
else:
|
|
267
|
+
console.error(_message(exc))
|
|
268
|
+
return EXIT_ERROR
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _asks_for_json(argv: list[str]) -> bool:
|
|
272
|
+
pairs = itertools.pairwise(argv)
|
|
273
|
+
return "--format=json" in argv or ("--format", "json") in pairs
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _message(exc: Exception) -> str:
|
|
277
|
+
return f"invalid JSON: {exc}" if isinstance(exc, json.JSONDecodeError) else str(exc)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _error_json(exc: Exception) -> str:
|
|
281
|
+
"""Errors in the format the agent asked for, so it needs no text parser."""
|
|
282
|
+
if isinstance(exc, ConfigError):
|
|
283
|
+
header, *_ = str(exc).splitlines()
|
|
284
|
+
issues = [
|
|
285
|
+
{"location": i.path or None, "message": i.message} for i in exc.issues
|
|
286
|
+
]
|
|
287
|
+
return render_error_json(
|
|
288
|
+
"config", header, config={"file": exc.source, "issues": issues}
|
|
289
|
+
)
|
|
290
|
+
kind, option, value = "analysis", None, None
|
|
291
|
+
if isinstance(exc, CliError):
|
|
292
|
+
kind, option, value = exc.kind, exc.option, exc.value
|
|
293
|
+
elif isinstance(exc, InvalidOptionError):
|
|
294
|
+
kind, option, value = "usage", exc.option, exc.value
|
|
295
|
+
given = (
|
|
296
|
+
{"option": option, "value": value}
|
|
297
|
+
if option is not None and value is not None
|
|
298
|
+
else None
|
|
299
|
+
)
|
|
300
|
+
return render_error_json(kind, _message(exc), invalid_input=given)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Load only the command being executed, after argument parsing and cache lookup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib import import_module
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
import argparse
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from smelt.cli.commands.adopt import debt, init
|
|
14
|
+
from smelt.cli.commands.check import check
|
|
15
|
+
from smelt.cli.commands.discover import context
|
|
16
|
+
from smelt.cli.commands.info import config_schema, config_show, explain, rules
|
|
17
|
+
from smelt.cli.support import Console
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"check",
|
|
22
|
+
"config_schema",
|
|
23
|
+
"config_show",
|
|
24
|
+
"context",
|
|
25
|
+
"debt",
|
|
26
|
+
"explain",
|
|
27
|
+
"handler",
|
|
28
|
+
"init",
|
|
29
|
+
"rules",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def handler(name: str) -> Callable[[argparse.Namespace, Console, Path], int]:
|
|
34
|
+
"""Resolve command imports only when the parsed handler is called."""
|
|
35
|
+
|
|
36
|
+
def dispatch(args: argparse.Namespace, console: Console, cwd: Path) -> int:
|
|
37
|
+
target = __getattr__(name)
|
|
38
|
+
return int(target(args, console, cwd))
|
|
39
|
+
|
|
40
|
+
return dispatch
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def __getattr__(name: str) -> Any:
|
|
44
|
+
if name not in _MODULES:
|
|
45
|
+
raise AttributeError(name)
|
|
46
|
+
target = getattr(import_module(f"smelt.cli.commands.{_MODULES[name]}"), name)
|
|
47
|
+
# Importing the check submodule also assigns package.check to the module.
|
|
48
|
+
# Preserve the previously exported callable after either import path.
|
|
49
|
+
globals()[name] = target
|
|
50
|
+
return target
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
_MODULES = {
|
|
54
|
+
"check": "check",
|
|
55
|
+
"config_schema": "info",
|
|
56
|
+
"config_show": "info",
|
|
57
|
+
"context": "discover",
|
|
58
|
+
"debt": "adopt",
|
|
59
|
+
"explain": "info",
|
|
60
|
+
"init": "adopt",
|
|
61
|
+
"rules": "info",
|
|
62
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
from smelt.analysis.parsing import AnalysisError
|
|
8
|
+
from smelt.cli.support import EXIT_OK, CliError, Console, load_project_config
|
|
9
|
+
from smelt.config import CONFIG_FILENAME, CONFIG_FILENAMES, load_config
|
|
10
|
+
from smelt.diagnostics.debt import Debt
|
|
11
|
+
from smelt.diagnostics.violation import Severity
|
|
12
|
+
from smelt.engine.check import CheckOptions, run_check, snippet_reader
|
|
13
|
+
from smelt.engine.inference import infer_config, render_config
|
|
14
|
+
from smelt.engine.rule_settings import RuleSettings
|
|
15
|
+
from smelt.engine.schema import SCHEMA_COMMENT, config_json_schema
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
import argparse
|
|
19
|
+
|
|
20
|
+
from smelt.engine.inference import InferredConfig
|
|
21
|
+
from smelt.engine.workspace import WorkspaceMember
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def init(args: argparse.Namespace, console: Console, cwd: Path) -> int:
|
|
25
|
+
custom: str | None = args.config
|
|
26
|
+
target, shown = _init_target(custom, cwd)
|
|
27
|
+
if target.is_dir():
|
|
28
|
+
msg = f"{shown} is a directory; pass the path of the config file to write"
|
|
29
|
+
raise CliError(msg, option="--config", value=custom)
|
|
30
|
+
if target.exists() and not args.force:
|
|
31
|
+
msg = f"{shown} already exists (use --force to overwrite)"
|
|
32
|
+
raise CliError(msg, option="--config" if custom else None, value=custom)
|
|
33
|
+
root = target.parent
|
|
34
|
+
if not root.is_dir():
|
|
35
|
+
msg = (
|
|
36
|
+
f"directory {root} does not exist; it would be the project root of {shown}"
|
|
37
|
+
)
|
|
38
|
+
raise CliError(msg, option="--config", value=custom)
|
|
39
|
+
inferred = infer_config(root)
|
|
40
|
+
if inferred is None:
|
|
41
|
+
msg = (
|
|
42
|
+
"no Python package found in this directory, src/, or declared uv workspace members; "
|
|
43
|
+
"run `smelt init` from the project root or configure source_roots manually"
|
|
44
|
+
)
|
|
45
|
+
raise CliError(msg)
|
|
46
|
+
schema_path = root / ".smelt.schema.json"
|
|
47
|
+
schema_text = json.dumps(config_json_schema(), indent=2) + "\n"
|
|
48
|
+
if schema_path.exists():
|
|
49
|
+
try:
|
|
50
|
+
existing_schema = json.loads(schema_path.read_text(encoding="utf-8"))
|
|
51
|
+
except (ValueError, UnicodeError) as exc:
|
|
52
|
+
raise CliError(
|
|
53
|
+
f"cannot replace non-Smelt editor schema {schema_path}"
|
|
54
|
+
) from exc
|
|
55
|
+
if (
|
|
56
|
+
not isinstance(existing_schema, dict)
|
|
57
|
+
or existing_schema.get("$comment") != SCHEMA_COMMENT
|
|
58
|
+
):
|
|
59
|
+
raise CliError(
|
|
60
|
+
f"{schema_path} already exists and was not generated by Smelt; move it before running init"
|
|
61
|
+
)
|
|
62
|
+
schema_path.write_text(schema_text, encoding="utf-8", newline="\n")
|
|
63
|
+
target.write_text(
|
|
64
|
+
render_config(inferred, maintainability=args.maintainability),
|
|
65
|
+
encoding="utf-8",
|
|
66
|
+
newline="\n",
|
|
67
|
+
)
|
|
68
|
+
console.print(f"Wrote {shown}")
|
|
69
|
+
console.print(
|
|
70
|
+
" Wrote .smelt.schema.json for editor completion, validation and hover examples."
|
|
71
|
+
)
|
|
72
|
+
for line in _summary(
|
|
73
|
+
inferred, architecture=not args.maintainability or bool(inferred.layers)
|
|
74
|
+
):
|
|
75
|
+
console.print(f" {line}")
|
|
76
|
+
console.print(_violation_summary(target))
|
|
77
|
+
if target.name not in CONFIG_FILENAMES:
|
|
78
|
+
console.print(
|
|
79
|
+
f"smelt only finds {' or '.join(CONFIG_FILENAMES)} on its own; "
|
|
80
|
+
f"pass --config {shown} to every command."
|
|
81
|
+
)
|
|
82
|
+
return EXIT_OK
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
DEFAULT_DEBT = ".smelt/debt.json"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def debt(args: argparse.Namespace, console: Console, cwd: Path) -> int:
|
|
89
|
+
loaded = load_project_config(args.config, cwd)
|
|
90
|
+
configured = loaded.config.debt
|
|
91
|
+
relative = configured or DEFAULT_DEBT
|
|
92
|
+
path = loaded.root / relative
|
|
93
|
+
outcome = run_check(loaded, CheckOptions(use_debt=False))
|
|
94
|
+
if any(v.code == "SMT306" for v in outcome.unfiltered):
|
|
95
|
+
raise CliError(
|
|
96
|
+
"Resolve strict coverage gaps before recording or pruning debt; coverage cannot be accepted as debt."
|
|
97
|
+
)
|
|
98
|
+
snippet = snippet_reader(outcome.context)
|
|
99
|
+
current = [
|
|
100
|
+
v
|
|
101
|
+
for v in outcome.unfiltered
|
|
102
|
+
if v.code != "SMT903" and v.severity is not Severity.HINT
|
|
103
|
+
]
|
|
104
|
+
existing = Debt.load(path)
|
|
105
|
+
policy = RuleSettings(outcome.rules, loaded)
|
|
106
|
+
active = {rule.code: rule for rule, _ in outcome.active if rule.code != "SMT903"}
|
|
107
|
+
eligible = [
|
|
108
|
+
entry
|
|
109
|
+
for entry in existing.entries
|
|
110
|
+
if (rule := active.get(entry.code)) is not None
|
|
111
|
+
and policy.severity_for_path(rule, outcome.context, entry.path)
|
|
112
|
+
not in (None, Severity.HINT)
|
|
113
|
+
]
|
|
114
|
+
dormant = [entry for entry in existing.entries if entry not in eligible]
|
|
115
|
+
if args.prune:
|
|
116
|
+
checked = Debt(eligible)
|
|
117
|
+
_, known, resolved = checked.match(current, snippet)
|
|
118
|
+
# Upgrade legacy import fingerprints without accepting any new debt.
|
|
119
|
+
updated = Debt.from_violations(known, snippet)
|
|
120
|
+
Debt([*updated.entries, *dormant]).write(path)
|
|
121
|
+
remaining = len(existing.entries) - len(resolved)
|
|
122
|
+
console.print(
|
|
123
|
+
f"Removed {len(resolved)} resolved entr{'y' if len(resolved) == 1 else 'ies'} "
|
|
124
|
+
f"from {relative} ({remaining} remain)"
|
|
125
|
+
)
|
|
126
|
+
else:
|
|
127
|
+
updated = Debt.from_violations(current, snippet)
|
|
128
|
+
Debt([*updated.entries, *dormant]).write(path)
|
|
129
|
+
console.print(
|
|
130
|
+
f"Wrote {relative} ({len(current)} violation{'s' * (len(current) != 1)})"
|
|
131
|
+
)
|
|
132
|
+
if dormant:
|
|
133
|
+
console.print(
|
|
134
|
+
f"Kept {len(dormant)} unassessed debt entries for inactive or hint-only rules."
|
|
135
|
+
)
|
|
136
|
+
if configured is None:
|
|
137
|
+
_enable_debt(loaded.path, relative)
|
|
138
|
+
console.print(f"Added `debt: {relative}` to {loaded.path.name}")
|
|
139
|
+
return EXIT_OK
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _init_target(custom: str | None, cwd: Path) -> tuple[Path, str]:
|
|
143
|
+
"""The one file ``init`` writes: ``--config``, else the default config here.
|
|
144
|
+
|
|
145
|
+
Only that file is checked and overwritten; a reviewed config elsewhere stays.
|
|
146
|
+
Without ``--config`` an existing ``smelt.yml`` is the target, not a second file.
|
|
147
|
+
"""
|
|
148
|
+
if custom is not None:
|
|
149
|
+
path = Path(custom)
|
|
150
|
+
return (path if path.is_absolute() else cwd / path), custom
|
|
151
|
+
existing = next((name for name in CONFIG_FILENAMES if (cwd / name).exists()), None)
|
|
152
|
+
name = existing or CONFIG_FILENAME
|
|
153
|
+
return cwd / name, name
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _summary(inferred: InferredConfig, *, architecture: bool = True) -> list[str]:
|
|
157
|
+
lines = [f"root packages: {', '.join(inferred.root_packages)}"]
|
|
158
|
+
if inferred.members:
|
|
159
|
+
lines.append("workspace members:")
|
|
160
|
+
lines.extend(f" {_member_status(member)}" for member in inferred.members)
|
|
161
|
+
if architecture:
|
|
162
|
+
lines.extend(_architecture_summary(inferred))
|
|
163
|
+
else:
|
|
164
|
+
lines.append("architecture: not configured; add boundaries when needed")
|
|
165
|
+
mirror = inferred.mirror
|
|
166
|
+
if mirror is None:
|
|
167
|
+
lines.append("tests: no test mirrors a module yet, mirroring is off")
|
|
168
|
+
else:
|
|
169
|
+
lines.append(
|
|
170
|
+
f"tests: mirror {mirror.pattern} "
|
|
171
|
+
f"({mirror.mirrored} of {mirror.total} test files already mirror)"
|
|
172
|
+
)
|
|
173
|
+
if mirror.name_clashes:
|
|
174
|
+
lines.append(
|
|
175
|
+
f"pytest: {', '.join(mirror.name_clashes)} "
|
|
176
|
+
f"{'has' if len(mirror.name_clashes) == 1 else 'have'} no __init__.py, so two "
|
|
177
|
+
"mirrored test_router.py files clash; add --import-mode=importlib to "
|
|
178
|
+
"the pytest addopts"
|
|
179
|
+
)
|
|
180
|
+
return lines
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _architecture_summary(inferred: InferredConfig) -> list[str]:
|
|
184
|
+
lines = [
|
|
185
|
+
"boundary coverage: direct imports only; third-party packages allowed (review layers.*.third_party and imports.transitive)"
|
|
186
|
+
]
|
|
187
|
+
if inferred.features:
|
|
188
|
+
lines.append(f"features: {', '.join(inferred.features)}")
|
|
189
|
+
if inferred.layers:
|
|
190
|
+
lines.append(
|
|
191
|
+
"layers: "
|
|
192
|
+
+ ", ".join(f"{layer.name} ({layer.path})" for layer in inferred.layers)
|
|
193
|
+
)
|
|
194
|
+
else:
|
|
195
|
+
lines.append("layers: none detected (see the commented example)")
|
|
196
|
+
if inferred.shared:
|
|
197
|
+
lines.append(f"shared: {', '.join(inferred.shared)}")
|
|
198
|
+
lines.extend(_assembly_summary(inferred))
|
|
199
|
+
if inferred.modules:
|
|
200
|
+
lines.append(
|
|
201
|
+
"central modules: "
|
|
202
|
+
+ ", ".join(
|
|
203
|
+
f"{module} ({layer})" for module, layer in inferred.modules.items()
|
|
204
|
+
)
|
|
205
|
+
)
|
|
206
|
+
if inferred.unclassified_roots:
|
|
207
|
+
lines.append(
|
|
208
|
+
f"no layer yet: {', '.join(inferred.unclassified_roots)} "
|
|
209
|
+
"(see architecture.modules)"
|
|
210
|
+
)
|
|
211
|
+
return lines
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _assembly_summary(inferred: InferredConfig) -> list[str]:
|
|
215
|
+
lines: list[str] = []
|
|
216
|
+
if inferred.composition_root:
|
|
217
|
+
lines.append(f"composition root: {', '.join(inferred.composition_root)}")
|
|
218
|
+
if inferred.wiring:
|
|
219
|
+
lines.append(f"wiring: {', '.join(inferred.wiring)}")
|
|
220
|
+
lines.extend(
|
|
221
|
+
f" {module}: {why}"
|
|
222
|
+
for module, why in inferred.evidence.items()
|
|
223
|
+
if module in inferred.composition_root or module in inferred.wiring
|
|
224
|
+
)
|
|
225
|
+
if inferred.candidates:
|
|
226
|
+
lines.append(
|
|
227
|
+
"composition-root candidates (commented out in the config, review):"
|
|
228
|
+
)
|
|
229
|
+
lines.extend(
|
|
230
|
+
f" {c.module} ({c.confidence} confidence, {c.reason}): {' → '.join(c.chain)}"
|
|
231
|
+
for c in inferred.candidates
|
|
232
|
+
)
|
|
233
|
+
return lines
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _member_status(member: WorkspaceMember) -> str:
|
|
237
|
+
if member.skipped:
|
|
238
|
+
return f"{member.path}: skipped, {member.skipped}"
|
|
239
|
+
packages = ", ".join(
|
|
240
|
+
f"{name} (namespace package)" if name in member.namespace else name
|
|
241
|
+
for name in member.packages
|
|
242
|
+
)
|
|
243
|
+
return f"{member.path}: {packages} in {member.source_root}"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _violation_summary(path: Path) -> str:
|
|
247
|
+
try:
|
|
248
|
+
outcome = run_check(load_config(path), CheckOptions(use_debt=False))
|
|
249
|
+
except AnalysisError as exc:
|
|
250
|
+
return f"Could not check the inferred config: {exc}"
|
|
251
|
+
report = outcome.report
|
|
252
|
+
errors = report.count(Severity.ERROR)
|
|
253
|
+
warnings = report.count(Severity.WARNING)
|
|
254
|
+
if not errors and not warnings:
|
|
255
|
+
return "The inferred config yields no violations. Run `smelt check` any time."
|
|
256
|
+
return (
|
|
257
|
+
f"The inferred config yields {errors} error{'s' * (errors != 1)} and "
|
|
258
|
+
f"{warnings} warning{'s' * (warnings != 1)}. Review {path.name}, then run "
|
|
259
|
+
"`smelt check`, or `smelt debt` to adopt incrementally."
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _enable_debt(config: Path, relative: str) -> None:
|
|
264
|
+
"""Set the debt key, uncommenting the line `smelt init` leaves if it is there."""
|
|
265
|
+
text = config.read_text(encoding="utf-8")
|
|
266
|
+
line = f"debt: {relative}"
|
|
267
|
+
lines = text.splitlines()
|
|
268
|
+
for index, existing in enumerate(lines):
|
|
269
|
+
if existing.strip() in (f"# {line}", f"#{line}"):
|
|
270
|
+
lines[index] = line
|
|
271
|
+
config.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
|
|
272
|
+
return
|
|
273
|
+
separator = "" if not text or text.endswith("\n") else "\n"
|
|
274
|
+
config.write_text(f"{text}{separator}{line}\n", encoding="utf-8", newline="\n")
|