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
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Exact staged CLI results, checked before loading config and analysis schemas."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import sqlite3
|
|
9
|
+
from contextlib import closing, suppress
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import TYPE_CHECKING, TextIO
|
|
12
|
+
|
|
13
|
+
from smelt.analysis.identity import analyzer_identity
|
|
14
|
+
from smelt.engine.changes import (
|
|
15
|
+
GitIndex,
|
|
16
|
+
capture_index,
|
|
17
|
+
capture_repository,
|
|
18
|
+
lexical_path,
|
|
19
|
+
resolve_comparison,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
import argparse
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
_RESULT_FIELDS = 5
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RecordingStream(io.TextIOBase):
|
|
30
|
+
def __init__(self, destination: TextIO) -> None:
|
|
31
|
+
self.destination = destination
|
|
32
|
+
self.parts: list[str] = []
|
|
33
|
+
|
|
34
|
+
def write(self, text: str) -> int:
|
|
35
|
+
self.parts.append(text)
|
|
36
|
+
return self.destination.write(text)
|
|
37
|
+
|
|
38
|
+
def isatty(self) -> bool:
|
|
39
|
+
return self.destination.isatty()
|
|
40
|
+
|
|
41
|
+
def flush(self) -> None:
|
|
42
|
+
with suppress(ValueError):
|
|
43
|
+
self.destination.flush()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class ResultCache:
|
|
48
|
+
path: Path
|
|
49
|
+
key: str
|
|
50
|
+
family: str
|
|
51
|
+
index: GitIndex
|
|
52
|
+
format: str
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def prepare(
|
|
56
|
+
cls, args: argparse.Namespace, cwd: Path, *, color: bool
|
|
57
|
+
) -> ResultCache | None:
|
|
58
|
+
if args.command != "check" or not args.staged or args.no_cache or args.fix:
|
|
59
|
+
return None
|
|
60
|
+
requested = lexical_path(cwd / args.config) if args.config is not None else None
|
|
61
|
+
captured = capture_repository(cwd, requested)
|
|
62
|
+
repository = captured.path
|
|
63
|
+
if requested is not None and not requested.is_relative_to(repository):
|
|
64
|
+
return None
|
|
65
|
+
index = capture_index(repository)
|
|
66
|
+
args._staged_index = index
|
|
67
|
+
_, comparison = resolve_comparison(repository, args.base, captured=captured)
|
|
68
|
+
args._comparison = comparison
|
|
69
|
+
config = requested
|
|
70
|
+
if config is None:
|
|
71
|
+
for directory in (cwd.resolve(), *cwd.resolve().parents):
|
|
72
|
+
if not directory.is_relative_to(repository):
|
|
73
|
+
break
|
|
74
|
+
config = next(
|
|
75
|
+
(
|
|
76
|
+
directory / name
|
|
77
|
+
for name in ("smelt.yaml", "smelt.yml")
|
|
78
|
+
if (directory / name).relative_to(repository).as_posix()
|
|
79
|
+
in index.blobs
|
|
80
|
+
),
|
|
81
|
+
None,
|
|
82
|
+
)
|
|
83
|
+
if config is not None:
|
|
84
|
+
break
|
|
85
|
+
if (
|
|
86
|
+
config is None
|
|
87
|
+
or config.relative_to(repository).as_posix() not in index.blobs
|
|
88
|
+
):
|
|
89
|
+
return None
|
|
90
|
+
options = {
|
|
91
|
+
key: value
|
|
92
|
+
for key, value in vars(args).items()
|
|
93
|
+
if key != "handler" and not key.startswith("_")
|
|
94
|
+
}
|
|
95
|
+
inputs = [
|
|
96
|
+
2,
|
|
97
|
+
str(cwd.resolve()),
|
|
98
|
+
str(config),
|
|
99
|
+
comparison.to_json(),
|
|
100
|
+
options,
|
|
101
|
+
color,
|
|
102
|
+
]
|
|
103
|
+
key = hashlib.sha256(
|
|
104
|
+
json.dumps([inputs, index.identity], sort_keys=True).encode()
|
|
105
|
+
).hexdigest()
|
|
106
|
+
# Inventory protects negative existence queries, package/namespace discovery
|
|
107
|
+
# and workspace globbing. Contents only need to match observed inputs.
|
|
108
|
+
family = hashlib.sha256(
|
|
109
|
+
json.dumps([inputs, sorted(index.blobs)], sort_keys=True).encode()
|
|
110
|
+
).hexdigest()
|
|
111
|
+
return cls(
|
|
112
|
+
config.parent
|
|
113
|
+
/ ".smelt_cache"
|
|
114
|
+
/ "v1"
|
|
115
|
+
/ analyzer_identity()
|
|
116
|
+
/ "results.sqlite3",
|
|
117
|
+
key,
|
|
118
|
+
family,
|
|
119
|
+
index,
|
|
120
|
+
args.format,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
def read(self) -> tuple[int, str, str] | None:
|
|
124
|
+
if not self.path.is_file():
|
|
125
|
+
return None
|
|
126
|
+
try:
|
|
127
|
+
with closing(
|
|
128
|
+
sqlite3.connect(f"{self.path.as_uri()}?mode=ro", uri=True, timeout=0.02)
|
|
129
|
+
) as connection:
|
|
130
|
+
for key in (self.key, self.family):
|
|
131
|
+
row = connection.execute(
|
|
132
|
+
"SELECT payload, digest FROM results WHERE key = ?", (key,)
|
|
133
|
+
).fetchone()
|
|
134
|
+
if row is None or hashlib.sha256(row[0]).hexdigest() != row[1]:
|
|
135
|
+
continue
|
|
136
|
+
data = json.loads(row[0])
|
|
137
|
+
if not self._valid(data):
|
|
138
|
+
continue
|
|
139
|
+
code, out, err, previous, dependencies = data
|
|
140
|
+
if previous != self.index.identity:
|
|
141
|
+
if not dependencies or any(
|
|
142
|
+
self.index.blobs.get(path) != oid
|
|
143
|
+
for path, oid in dependencies.items()
|
|
144
|
+
):
|
|
145
|
+
continue
|
|
146
|
+
out = self._refresh(out)
|
|
147
|
+
return code, out, err
|
|
148
|
+
except (OSError, ValueError, TypeError, KeyError, IndexError, sqlite3.Error):
|
|
149
|
+
return None
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
def write(
|
|
153
|
+
self,
|
|
154
|
+
code: int,
|
|
155
|
+
out: str,
|
|
156
|
+
err: str,
|
|
157
|
+
*,
|
|
158
|
+
dependencies: dict[str, str] | None = None,
|
|
159
|
+
) -> None:
|
|
160
|
+
if code not in {0, 1}:
|
|
161
|
+
return
|
|
162
|
+
payload = json.dumps(
|
|
163
|
+
[code, out, err, self.index.identity, dependencies or {}]
|
|
164
|
+
).encode()
|
|
165
|
+
rows = [(self.key, payload, hashlib.sha256(payload).hexdigest())]
|
|
166
|
+
if dependencies:
|
|
167
|
+
rows.append((self.family, payload, rows[0][2]))
|
|
168
|
+
try:
|
|
169
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
with (
|
|
171
|
+
closing(sqlite3.connect(self.path, timeout=0.02)) as connection,
|
|
172
|
+
connection,
|
|
173
|
+
):
|
|
174
|
+
connection.execute(
|
|
175
|
+
"CREATE TABLE IF NOT EXISTS results (key TEXT PRIMARY KEY, payload BLOB NOT NULL, digest TEXT NOT NULL)"
|
|
176
|
+
)
|
|
177
|
+
connection.executemany(
|
|
178
|
+
"INSERT OR REPLACE INTO results VALUES (?, ?, ?)",
|
|
179
|
+
rows,
|
|
180
|
+
)
|
|
181
|
+
except (OSError, sqlite3.Error):
|
|
182
|
+
return
|
|
183
|
+
|
|
184
|
+
def _valid(self, data: object) -> bool:
|
|
185
|
+
return (
|
|
186
|
+
isinstance(data, list)
|
|
187
|
+
and len(data) == _RESULT_FIELDS
|
|
188
|
+
and type(data[0]) is int
|
|
189
|
+
and data[0] in {0, 1}
|
|
190
|
+
and all(isinstance(data[index], str) for index in (1, 2, 3))
|
|
191
|
+
and isinstance(data[4], dict)
|
|
192
|
+
and all(
|
|
193
|
+
isinstance(path, str) and isinstance(oid, str)
|
|
194
|
+
for path, oid in data[4].items()
|
|
195
|
+
)
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
def _refresh(self, output: str) -> str:
|
|
199
|
+
if self.format not in {"json", "sarif"}:
|
|
200
|
+
return output
|
|
201
|
+
report = json.loads(output)
|
|
202
|
+
comparison = (
|
|
203
|
+
report["comparison"]
|
|
204
|
+
if self.format == "json"
|
|
205
|
+
else report["runs"][0]["properties"]["comparison"]
|
|
206
|
+
)
|
|
207
|
+
comparison["index_hash"] = self.index.identity
|
|
208
|
+
return json.dumps(report, indent=2, ensure_ascii=False) + "\n"
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Resolve the same rule names for project and package settings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
from smelt.config.errors import ConfigError, ConfigIssue, did_you_mean
|
|
8
|
+
from smelt.diagnostics.violation import Severity
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
|
|
13
|
+
from smelt.analysis.context import AnalysisContext
|
|
14
|
+
from smelt.config.loader import LoadedConfig
|
|
15
|
+
from smelt.rules.base import Rule, RuleSet
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RuleSettings:
|
|
19
|
+
def __init__(self, rules: RuleSet, loaded: LoadedConfig) -> None:
|
|
20
|
+
self.config = loaded.config
|
|
21
|
+
self.source = loaded.path.name
|
|
22
|
+
self.codes = {rule.code: rule.code for rule in rules.rules}
|
|
23
|
+
self.codes.update({rule.name: rule.code for rule in rules.rules})
|
|
24
|
+
project_rules = {
|
|
25
|
+
rule.code
|
|
26
|
+
for rule in rules.rules
|
|
27
|
+
if getattr(rule, "scope", "source") != "source"
|
|
28
|
+
}
|
|
29
|
+
self.global_rules = self._normalize(loaded.config.rules, "rules")
|
|
30
|
+
self.packages = {
|
|
31
|
+
name: self._normalize(contract.rules, f"structure.contracts.{name}.rules")
|
|
32
|
+
for name, contract in loaded.config.structure.contracts.items()
|
|
33
|
+
}
|
|
34
|
+
for index, entry in enumerate(loaded.config.ignore):
|
|
35
|
+
selector = self.codes.get(entry.rule, entry.rule)
|
|
36
|
+
if selector != "ALL" and not any(
|
|
37
|
+
code.startswith(selector) for code in self.codes.values()
|
|
38
|
+
):
|
|
39
|
+
raise ConfigError(
|
|
40
|
+
[
|
|
41
|
+
ConfigIssue(
|
|
42
|
+
f"ignore[{index}].rule",
|
|
43
|
+
f'unknown rule "{entry.rule}"{did_you_mean(entry.rule, self.codes)}',
|
|
44
|
+
)
|
|
45
|
+
],
|
|
46
|
+
self.source,
|
|
47
|
+
)
|
|
48
|
+
for name, settings in self.packages.items():
|
|
49
|
+
if project_rules & settings.keys():
|
|
50
|
+
raise ConfigError(
|
|
51
|
+
[
|
|
52
|
+
ConfigIssue(
|
|
53
|
+
f"structure.contracts.{name}.rules",
|
|
54
|
+
"test-file and project rules must be configured at project level; use ignore.paths for individual test files",
|
|
55
|
+
)
|
|
56
|
+
],
|
|
57
|
+
self.source,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def validate_packages(self, ctx: AnalysisContext) -> None:
|
|
61
|
+
seen: dict[tuple[str, str], str] = {}
|
|
62
|
+
issues: list[ConfigIssue] = []
|
|
63
|
+
for contract in ctx.contracts.resolved:
|
|
64
|
+
for code, value in self.packages[contract.name].items():
|
|
65
|
+
previous = seen.setdefault((contract.package, code), value)
|
|
66
|
+
if previous != value:
|
|
67
|
+
issues.append(
|
|
68
|
+
ConfigIssue(
|
|
69
|
+
f"structure.contracts.{contract.name}.rules",
|
|
70
|
+
f"conflicting {code} settings for {contract.package}",
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
if issues:
|
|
74
|
+
raise ConfigError(issues, self.source)
|
|
75
|
+
|
|
76
|
+
def globally_enabled(self, rule: Rule, *, selected: bool = False) -> bool:
|
|
77
|
+
setting = self.global_rules.get(rule.code)
|
|
78
|
+
if setting is not None:
|
|
79
|
+
return setting != "off"
|
|
80
|
+
activation = getattr(rule, "activation", None)
|
|
81
|
+
return bool(
|
|
82
|
+
selected
|
|
83
|
+
or getattr(rule, "enabled_by_default", False)
|
|
84
|
+
or (activation is not None and activation.matches(self.config))
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def has_package_activation(self, code: str) -> bool:
|
|
88
|
+
return any(
|
|
89
|
+
settings.get(code, "off") != "off" for settings in self.packages.values()
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def severity(
|
|
93
|
+
self,
|
|
94
|
+
rule: Rule,
|
|
95
|
+
ctx: AnalysisContext,
|
|
96
|
+
module: str | None,
|
|
97
|
+
*,
|
|
98
|
+
selected: bool = False,
|
|
99
|
+
) -> Severity | None:
|
|
100
|
+
value = self.global_rules.get(rule.code)
|
|
101
|
+
if value is None:
|
|
102
|
+
value = (
|
|
103
|
+
rule.default_severity.value
|
|
104
|
+
if self.globally_enabled(rule, selected=selected)
|
|
105
|
+
else "off"
|
|
106
|
+
)
|
|
107
|
+
if module:
|
|
108
|
+
applicable = sorted(
|
|
109
|
+
(
|
|
110
|
+
contract
|
|
111
|
+
for contract in ctx.contracts.resolved
|
|
112
|
+
if module == contract.package
|
|
113
|
+
or module.startswith(contract.package + ".")
|
|
114
|
+
),
|
|
115
|
+
key=lambda contract: len(contract.package),
|
|
116
|
+
)
|
|
117
|
+
for contract in applicable:
|
|
118
|
+
value = self.packages[contract.name].get(rule.code, value)
|
|
119
|
+
return None if value == "off" else Severity(value)
|
|
120
|
+
|
|
121
|
+
def severity_for_path(
|
|
122
|
+
self,
|
|
123
|
+
rule: Rule,
|
|
124
|
+
ctx: AnalysisContext,
|
|
125
|
+
path: str | None,
|
|
126
|
+
*,
|
|
127
|
+
selected: bool = False,
|
|
128
|
+
) -> Severity | None:
|
|
129
|
+
source = ctx.files.source_for_path(path) if path else None
|
|
130
|
+
module = source.module if source else None
|
|
131
|
+
if module is None and path:
|
|
132
|
+
absolute = ctx.files.resolve_path(ctx.root / path)
|
|
133
|
+
for source_root in self.config.project.source_roots:
|
|
134
|
+
base = ctx.files.resolve_path(ctx.root / source_root)
|
|
135
|
+
if absolute.is_relative_to(base):
|
|
136
|
+
parts = list(absolute.relative_to(base).with_suffix("").parts)
|
|
137
|
+
if parts and parts[0] in self.config.project.root_packages:
|
|
138
|
+
if parts[-1] == "__init__":
|
|
139
|
+
parts.pop()
|
|
140
|
+
module = ".".join(parts)
|
|
141
|
+
break
|
|
142
|
+
return self.severity(rule, ctx, module, selected=selected)
|
|
143
|
+
|
|
144
|
+
def _normalize(self, raw: Mapping[str, str], location: str) -> dict[str, str]:
|
|
145
|
+
result: dict[str, str] = {}
|
|
146
|
+
issues: list[ConfigIssue] = []
|
|
147
|
+
for key, value in raw.items():
|
|
148
|
+
code = self.codes.get(key)
|
|
149
|
+
if code is None:
|
|
150
|
+
issues.append(
|
|
151
|
+
ConfigIssue(
|
|
152
|
+
f"{location}.{key}",
|
|
153
|
+
f'unknown rule "{key}"{did_you_mean(key, self.codes)}',
|
|
154
|
+
)
|
|
155
|
+
)
|
|
156
|
+
elif code in result:
|
|
157
|
+
issues.append(
|
|
158
|
+
ConfigIssue(f"{location}.{key}", f"{code} is already configured")
|
|
159
|
+
)
|
|
160
|
+
else:
|
|
161
|
+
result[code] = value
|
|
162
|
+
if issues:
|
|
163
|
+
raise ConfigError(issues, self.source)
|
|
164
|
+
return result
|
smelt/engine/schema.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Editor documentation derived from the same catalog used by checks."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from smelt.config.schema import config_json_schema as model_json_schema
|
|
6
|
+
from smelt.rules.registry import build_rule_set
|
|
7
|
+
|
|
8
|
+
SCHEMA_COMMENT = (
|
|
9
|
+
"Generated by Smelt. Refresh with `smelt config schema`; not used by the checker."
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def config_json_schema() -> dict[str, Any]:
|
|
14
|
+
schema = model_json_schema()
|
|
15
|
+
schema["$comment"] = SCHEMA_COMMENT
|
|
16
|
+
properties: dict[str, Any] = {}
|
|
17
|
+
codes: dict[str, Any] = {}
|
|
18
|
+
source_properties: dict[str, Any] = {}
|
|
19
|
+
source_codes: dict[str, Any] = {}
|
|
20
|
+
for rule in build_rule_set().rules:
|
|
21
|
+
doc = rule.explain()
|
|
22
|
+
definition = {
|
|
23
|
+
"type": "string",
|
|
24
|
+
"enum": ["error", "warning", "hint", "off"],
|
|
25
|
+
"title": f"{rule.code}: {doc.summary}",
|
|
26
|
+
"description": f"{doc.summary} {doc.rationale} Repair: {doc.fix}",
|
|
27
|
+
"markdownDescription": (
|
|
28
|
+
f"**{rule.code} — {rule.name}**\n\n{doc.summary}\n\n{doc.rationale}"
|
|
29
|
+
f"\n\n**Problem**\n```{doc.example_language}\n{doc.bad}\n```"
|
|
30
|
+
f"\n\n**Preferred**\n```{doc.example_language}\n{doc.good}\n```"
|
|
31
|
+
f"\n\n{doc.fix}\n\nRun `smelt explain {rule.name}` for details."
|
|
32
|
+
),
|
|
33
|
+
"examples": [rule.default_severity.value],
|
|
34
|
+
}
|
|
35
|
+
properties[rule.name] = definition
|
|
36
|
+
codes[f"^{rule.code}$"] = definition
|
|
37
|
+
if getattr(rule, "scope", "source") == "source":
|
|
38
|
+
source_properties[rule.name] = definition
|
|
39
|
+
source_codes[f"^{rule.code}$"] = definition
|
|
40
|
+
rule_settings = {
|
|
41
|
+
"type": "object",
|
|
42
|
+
"description": "Explicit checks by problem name or stable SMT code. Each value both enables the check and sets severity; off disables it.",
|
|
43
|
+
"properties": properties,
|
|
44
|
+
"patternProperties": codes,
|
|
45
|
+
"additionalProperties": False,
|
|
46
|
+
}
|
|
47
|
+
schema["$defs"]["RuleSettings"] = rule_settings
|
|
48
|
+
schema["$defs"]["SourceRuleSettings"] = {
|
|
49
|
+
**rule_settings,
|
|
50
|
+
"description": "Source rules use the same names and severities. Test-file and project checks belong in the project rules map.",
|
|
51
|
+
"properties": source_properties,
|
|
52
|
+
"patternProperties": source_codes,
|
|
53
|
+
}
|
|
54
|
+
schema["properties"]["rules"] = {"$ref": "#/$defs/RuleSettings"}
|
|
55
|
+
schema["$defs"]["PackageContract"]["properties"]["rules"] = {
|
|
56
|
+
"$ref": "#/$defs/SourceRuleSettings"
|
|
57
|
+
}
|
|
58
|
+
return schema
|
smelt/engine/staged.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""A staged project view whose source and policy both come from the Git index."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from smelt.analysis.cache import FactCache
|
|
10
|
+
from smelt.analysis.errors import AnalysisError
|
|
11
|
+
from smelt.config import discover_config, load_config
|
|
12
|
+
from smelt.config.errors import ConfigError, ConfigIssue
|
|
13
|
+
from smelt.engine.changes import capture_index, git_repository, lexical_path
|
|
14
|
+
from smelt.engine.git_source import GitSourceStore
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from smelt.config import LoadedConfig
|
|
21
|
+
from smelt.engine.changes import GitIndex
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class StagedProject:
|
|
26
|
+
loaded: LoadedConfig
|
|
27
|
+
original_config: Path
|
|
28
|
+
repository: Path
|
|
29
|
+
index_hash: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@contextmanager
|
|
33
|
+
def staged_project(
|
|
34
|
+
cwd: Path,
|
|
35
|
+
config: str | None,
|
|
36
|
+
*,
|
|
37
|
+
index: GitIndex | None = None,
|
|
38
|
+
use_cache: bool = False,
|
|
39
|
+
) -> Iterator[StagedProject]:
|
|
40
|
+
requested = lexical_path(cwd / config) if config is not None else None
|
|
41
|
+
repository = index.repository if index else git_repository(cwd, requested)
|
|
42
|
+
if requested is not None and not requested.is_relative_to(repository):
|
|
43
|
+
raise AnalysisError("--staged config must be inside the Git repository")
|
|
44
|
+
index = index or capture_index(repository)
|
|
45
|
+
store = GitSourceStore.from_index(index)
|
|
46
|
+
path = requested if requested is not None else discover_config(cwd, store=store)
|
|
47
|
+
if path is None or not store.is_file(path) or not path.is_relative_to(repository):
|
|
48
|
+
raise ConfigError(
|
|
49
|
+
[ConfigIssue("", "no smelt.yaml found in the staged Git index")]
|
|
50
|
+
)
|
|
51
|
+
# Policy is read before run_check creates the analysis cache. Reuse verified
|
|
52
|
+
# immutable blobs here too, instead of starting cat-file for the same config
|
|
53
|
+
# after every source edit. Close this transaction before analysis opens its
|
|
54
|
+
# own cache connection, including when policy validation fails.
|
|
55
|
+
cache = FactCache(path.parent / ".smelt_cache") if use_cache else None
|
|
56
|
+
store.cache = cache
|
|
57
|
+
try:
|
|
58
|
+
loaded = load_config(path, store=store)
|
|
59
|
+
finally:
|
|
60
|
+
if cache is not None:
|
|
61
|
+
cache.close()
|
|
62
|
+
store.cache = None
|
|
63
|
+
for directory in [
|
|
64
|
+
*loaded.config.project.source_roots,
|
|
65
|
+
*loaded.config.project.test_roots,
|
|
66
|
+
]:
|
|
67
|
+
if not store.resolve(loaded.root / directory).is_relative_to(repository):
|
|
68
|
+
raise AnalysisError(
|
|
69
|
+
"--staged source/test roots must be inside the Git repository"
|
|
70
|
+
)
|
|
71
|
+
if loaded.config.debt and not store.resolve(
|
|
72
|
+
loaded.root / loaded.config.debt
|
|
73
|
+
).is_relative_to(repository):
|
|
74
|
+
raise AnalysisError("--staged debt file must be inside the Git repository")
|
|
75
|
+
yield StagedProject(loaded, path, repository, index.identity)
|