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,237 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import posixpath
5
+ from typing import TYPE_CHECKING, Any
6
+ from urllib.parse import quote
7
+
8
+ from smelt.diagnostics.groups import group_findings
9
+ from smelt.diagnostics.violation import Severity, Violation
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Mapping
13
+
14
+ from smelt.diagnostics.report import Report
15
+
16
+ JSON_SCHEMA_VERSION = 1
17
+ SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json"
18
+ TOOL_URI = "https://github.com/mathisarends/smelt"
19
+
20
+
21
+ def render_json(report: Report) -> str:
22
+ document = {
23
+ "schema_version": JSON_SCHEMA_VERSION,
24
+ "status": report.status,
25
+ "summary": report.summary_json(),
26
+ "scope": {
27
+ "mode": report.comparison.get("mode", "changed")
28
+ if report.comparison
29
+ else "full",
30
+ "paths": list(report.scope),
31
+ "files": report.checked_files,
32
+ "rules": [rule.code for rule in report.rules],
33
+ },
34
+ "comparison": dict(report.comparison) if report.comparison else None,
35
+ "coverage": dict(report.coverage) if report.coverage else None,
36
+ "project": dict(report.project) if report.project else None,
37
+ "violations": [v.to_json() for v in report.violations],
38
+ "configuration_diagnostics": [
39
+ diagnostic.to_json() for diagnostic in report.configuration_diagnostics
40
+ ],
41
+ "groups": group_findings(report.violations),
42
+ }
43
+ if report.fixes is not None:
44
+ document["fixes"] = dict(report.fixes)
45
+ return json.dumps(document, indent=2, ensure_ascii=False) + "\n"
46
+
47
+
48
+ def render_error_json(
49
+ kind: str,
50
+ message: str,
51
+ *,
52
+ invalid_input: Mapping[str, str] | None = None,
53
+ config: Mapping[str, Any] | None = None,
54
+ ) -> str:
55
+ """The document ``--format json`` prints instead of a report when it exits with 2."""
56
+ document = {
57
+ "schema_version": JSON_SCHEMA_VERSION,
58
+ "status": "error",
59
+ "error": {
60
+ "kind": kind,
61
+ "message": message,
62
+ "input": dict(invalid_input) if invalid_input is not None else None,
63
+ "config": dict(config) if config is not None else None,
64
+ },
65
+ }
66
+ return json.dumps(document, indent=2, ensure_ascii=False) + "\n"
67
+
68
+
69
+ _SARIF_LEVEL = {
70
+ Severity.ERROR: "error",
71
+ Severity.WARNING: "warning",
72
+ Severity.HINT: "note",
73
+ }
74
+
75
+
76
+ def render_sarif(report: Report, version: str) -> str:
77
+ rules = [
78
+ {
79
+ "id": meta.code,
80
+ "name": meta.name,
81
+ "shortDescription": {"text": meta.summary},
82
+ "helpUri": meta.docs_url,
83
+ "defaultConfiguration": {"level": _SARIF_LEVEL[meta.default_severity]},
84
+ "properties": {"category": meta.category.value},
85
+ }
86
+ for meta in report.rules
87
+ ]
88
+ index = {meta.code: i for i, meta in enumerate(report.rules)}
89
+ prefix = (report.project or {}).get("repository_prefix", "")
90
+ results = [_sarif_result(v, index, prefix) for v in report.violations]
91
+ document = {
92
+ "$schema": SARIF_SCHEMA,
93
+ "version": "2.1.0",
94
+ "runs": [
95
+ {
96
+ "tool": {
97
+ "driver": {
98
+ "name": "smelt",
99
+ "version": version,
100
+ "informationUri": TOOL_URI,
101
+ "rules": rules,
102
+ }
103
+ },
104
+ "results": results,
105
+ "invocations": [
106
+ {
107
+ "executionSuccessful": True,
108
+ "toolConfigurationNotifications": [
109
+ {
110
+ "level": _SARIF_LEVEL[diagnostic.severity],
111
+ "message": {
112
+ "text": f"{diagnostic.key}: {diagnostic.message}"
113
+ },
114
+ "locations": [
115
+ {
116
+ "physicalLocation": {
117
+ "artifactLocation": {
118
+ "uri": quote(
119
+ posixpath.join(
120
+ prefix, diagnostic.path
121
+ ),
122
+ safe="/",
123
+ )
124
+ }
125
+ }
126
+ }
127
+ ],
128
+ }
129
+ for diagnostic in report.configuration_diagnostics
130
+ ],
131
+ }
132
+ ],
133
+ "properties": _sarif_properties(report),
134
+ }
135
+ ],
136
+ }
137
+ return json.dumps(document, indent=2, ensure_ascii=False) + "\n"
138
+
139
+
140
+ def _sarif_properties(report: Report) -> dict[str, Any]:
141
+ """Provenance a SARIF consumer can keep with the results."""
142
+ coverage = report.coverage or {}
143
+ return {
144
+ "mode": report.comparison.get("mode", "changed")
145
+ if report.comparison
146
+ else "full",
147
+ "comparison": dict(report.comparison) if report.comparison else None,
148
+ "policyHash": coverage.get("policy_hash"),
149
+ **({"fixes": dict(report.fixes)} if report.fixes is not None else {}),
150
+ "project": dict(report.project) if report.project else None,
151
+ }
152
+
153
+
154
+ def _sarif_result(
155
+ violation: Violation, index: dict[str, int], prefix: str = ""
156
+ ) -> dict[str, Any]:
157
+ text = violation.message
158
+ if violation.hint:
159
+ text += f"\n{violation.hint}"
160
+ result: dict[str, Any] = {
161
+ "ruleId": violation.code,
162
+ "level": _SARIF_LEVEL[violation.severity],
163
+ "message": {"text": text},
164
+ }
165
+ if violation.code in index:
166
+ result["ruleIndex"] = index[violation.code]
167
+ if violation.path:
168
+ region: dict[str, int] = {}
169
+ if violation.line:
170
+ region["startLine"] = violation.line
171
+ if violation.column:
172
+ region["startColumn"] = violation.column
173
+ if violation.end_line:
174
+ region["endLine"] = violation.end_line
175
+ if violation.end_column:
176
+ region["endColumn"] = violation.end_column
177
+ location: dict[str, Any] = {
178
+ "artifactLocation": {
179
+ "uri": quote(posixpath.join(prefix, violation.path), safe="/")
180
+ }
181
+ }
182
+ if region:
183
+ location["region"] = region
184
+ result["locations"] = [{"physicalLocation": location}]
185
+ return result
186
+
187
+
188
+ _GITHUB_LEVEL = {
189
+ Severity.ERROR: "error",
190
+ Severity.WARNING: "warning",
191
+ Severity.HINT: "notice",
192
+ }
193
+
194
+
195
+ def render_github(report: Report) -> str:
196
+ prefix = (report.project or {}).get("repository_prefix", "")
197
+ lines = [_github_line(v, prefix) for v in report.violations]
198
+ lines.extend(
199
+ f"::{_GITHUB_LEVEL[diagnostic.severity]} file={_escape_property(posixpath.join(prefix, diagnostic.path))},title=Smelt configuration::{_escape_data(f'{diagnostic.key}: {diagnostic.message}')}"
200
+ for diagnostic in report.configuration_diagnostics
201
+ )
202
+ summary = report.summary_json()
203
+ lines.append(
204
+ f"smelt: {summary['errors']} errors, {summary['warnings']} warnings, "
205
+ f"{summary['hints']} hints, {summary['modules']} modules"
206
+ )
207
+ return "\n".join(lines) + "\n"
208
+
209
+
210
+ def _github_line(violation: Violation, prefix: str = "") -> str:
211
+ properties: list[str] = []
212
+ if violation.path:
213
+ properties.append(
214
+ f"file={_escape_property(posixpath.join(prefix, violation.path))}"
215
+ )
216
+ if violation.line:
217
+ properties.append(f"line={violation.line}")
218
+ if violation.column:
219
+ properties.append(f"col={violation.column}")
220
+ if violation.end_line:
221
+ properties.append(f"endLine={violation.end_line}")
222
+ if violation.end_column:
223
+ properties.append(f"endColumn={violation.end_column}")
224
+ properties.append(f"title={_escape_property(f'{violation.code} {violation.rule}')}")
225
+ message = violation.message
226
+ if violation.hint:
227
+ message += f"\nHint: {violation.hint}"
228
+ level = _GITHUB_LEVEL[violation.severity]
229
+ return f"::{level} {','.join(properties)}::{_escape_data(message)}"
230
+
231
+
232
+ def _escape_data(value: str) -> str:
233
+ return value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
234
+
235
+
236
+ def _escape_property(value: str) -> str:
237
+ return _escape_data(value).replace(":", "%3A").replace(",", "%2C")
@@ -0,0 +1,321 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import posixpath
5
+ import textwrap
6
+ from collections import Counter
7
+ from collections.abc import Mapping
8
+ from dataclasses import replace
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from smelt.diagnostics.groups import group_findings
12
+ from smelt.diagnostics.violation import Severity, Violation
13
+
14
+ if TYPE_CHECKING:
15
+ from smelt.diagnostics.report import LineReader, Report
16
+
17
+ _WIDTH = 88
18
+ _TOP_EDGES = 5
19
+ # Keys of "expected" that only machine readers need; the message says the same.
20
+ _MACHINE_ONLY = frozenset({"cycle", "members", "cyclic_edges", "subject", "evidence"})
21
+ _COLORS = {
22
+ Severity.ERROR: "\x1b[31m",
23
+ Severity.WARNING: "\x1b[33m",
24
+ Severity.HINT: "\x1b[36m",
25
+ }
26
+
27
+
28
+ def render_text(
29
+ report: Report,
30
+ read_line: LineReader,
31
+ *,
32
+ color: bool = False,
33
+ show_hints: bool = False,
34
+ statistics: bool = False,
35
+ ) -> str:
36
+ style = _Style(color)
37
+ shown = [
38
+ violation
39
+ for violation in report.violations
40
+ if show_hints or violation.severity is not Severity.HINT
41
+ ]
42
+ blocks: list[str] = [
43
+ f"warning: {diagnostic.path}: {diagnostic.key}: {diagnostic.message}"
44
+ for diagnostic in report.configuration_diagnostics
45
+ ]
46
+ if not statistics:
47
+ blocks.extend(
48
+ _render_violation(v, read_line, style) for v in _group_unclassified(shown)
49
+ )
50
+ lines = ["\n\n".join(blocks)] if blocks else []
51
+ if blocks:
52
+ lines.append("")
53
+ edges = _repeated_edges(shown)
54
+ if edges:
55
+ lines.extend([*edges, ""])
56
+ facades = _facades(shown)
57
+ if facades:
58
+ lines.extend([*facades, ""])
59
+ many_rules = len({violation.code for violation in shown}) > 1
60
+ if shown and (statistics or (len(shown) > _STATISTICS_THRESHOLD and many_rules)):
61
+ lines.extend([_statistics(shown, style), ""])
62
+ if report.scope:
63
+ lines.append(
64
+ f"Scope: {', '.join(report.scope)} ({report.checked_files} analyzed source/test files)"
65
+ )
66
+ if report.comparison and report.comparison.get("mode") == "staged":
67
+ lines.append("Scope: staged Git index; new findings since the compared commit.")
68
+ if report.coverage is not None and "complete" in report.coverage:
69
+ coverage = report.coverage
70
+ counts = coverage.get("counts", {})
71
+ state = "complete" if coverage["complete"] else "incomplete"
72
+ lines.append(
73
+ f"Policy coverage: {state} ({coverage.get('mode', 'configured')}); "
74
+ f"{counts.get('uncovered', 0)} uncovered, {counts.get('unclassified', 0)} unclassified sources"
75
+ )
76
+ lines.extend(
77
+ f"Coverage discovery: {error}"
78
+ for error in coverage.get("discovery_errors", [])
79
+ )
80
+ lines.append(_summary(report, style, show_hints=show_hints))
81
+ return "\n".join(lines) + "\n"
82
+
83
+
84
+ _BOLD = "\x1b[1m"
85
+ _DIM = "\x1b[2m"
86
+ _GREEN = "\x1b[32m"
87
+ _RED = "\x1b[31m"
88
+ _YELLOW = "\x1b[33m"
89
+ _RESET = "\x1b[0m"
90
+ # Longer listings end with a per-rule breakdown so the overview survives scrolling.
91
+ _STATISTICS_THRESHOLD = 10
92
+
93
+
94
+ class _Style:
95
+ def __init__(self, color: bool) -> None:
96
+ self.color = color
97
+
98
+ def __call__(self, text: str, *codes: str) -> str:
99
+ if not self.color or not codes:
100
+ return text
101
+ return "".join(codes) + text + _RESET
102
+
103
+
104
+ def _group_unclassified(violations: list[Violation]) -> list[Violation]:
105
+ groups: dict[tuple[str, Severity, str | None], list[Violation]] = {}
106
+ for violation in violations:
107
+ if violation.code in ("SMT305", "SMT306") and violation.path:
108
+ groups.setdefault(
109
+ (violation.code, violation.severity, violation.hint), []
110
+ ).append(violation)
111
+ result: list[Violation] = []
112
+ for violation in violations:
113
+ if violation.code not in ("SMT305", "SMT306") or not violation.path:
114
+ result.append(violation)
115
+ continue
116
+ group = groups[(violation.code, violation.severity, violation.hint)]
117
+ if violation is not group[0]:
118
+ continue
119
+ if len(group) > 1:
120
+ directory = posixpath.commonpath([v.path for v in group if v.path])
121
+ grouped = replace(
122
+ violation,
123
+ path=directory,
124
+ message=f"{len(group)} source files have incomplete policy coverage; --format json lists individual paths"
125
+ if violation.code == "SMT306"
126
+ else f"{len(group)} modules have no architecture classification; --format json lists individual paths",
127
+ )
128
+ result.append(grouped)
129
+ else:
130
+ result.append(violation)
131
+ return result
132
+
133
+
134
+ def _repeated_edges(violations: list[Violation]) -> list[str]:
135
+ """The dependency edges behind several findings, most frequent first.
136
+
137
+ 81 findings are rarely 81 problems: one facade or one missing allowance
138
+ often explains a dozen of them.
139
+ """
140
+ counts = Counter((v.code, v.edge) for v in violations if v.edge)
141
+ repeated = sorted(
142
+ ((count, code, edge) for (code, edge), count in counts.items() if count > 1),
143
+ key=lambda item: (-item[0], item[1], item[2]),
144
+ )
145
+ if not repeated:
146
+ return []
147
+ width = len(str(repeated[0][0]))
148
+ lines = ['Repeated dependency edges (often one decision or fix each; JSON "edge"):']
149
+ lines.extend(
150
+ f" {count:>{width}}x {code} {edge}"
151
+ for count, code, edge in repeated[:_TOP_EDGES]
152
+ )
153
+ if len(repeated) > _TOP_EDGES:
154
+ lines.append(f" … {len(repeated) - _TOP_EDGES} more")
155
+ return lines
156
+
157
+
158
+ def _facades(violations: list[Violation]) -> list[str]:
159
+ """Modules relaying indirect findings: narrowing one addresses all of its findings."""
160
+ groups = [g for g in group_findings(violations) if g["kind"] == "facade"]
161
+ if not groups:
162
+ return []
163
+ width = len(str(groups[0]["count"]))
164
+ lines = ['Indirect findings by the module relaying them (JSON "groups"):']
165
+ lines.extend(
166
+ f" {g['count']:>{width}}x {g['key']} ({', '.join(g['edges'])})"
167
+ for g in groups[:_TOP_EDGES]
168
+ )
169
+ if len(groups) > _TOP_EDGES:
170
+ lines.append(f" … {len(groups) - _TOP_EDGES} more")
171
+ return lines
172
+
173
+
174
+ def _statistics(violations: list[Violation], style: _Style) -> str:
175
+ counts = Counter((v.code, v.rule, v.severity) for v in violations)
176
+ ordered = sorted(counts.items(), key=lambda item: (-item[1], item[0][0]))
177
+ width = len(str(ordered[0][1]))
178
+ name_width = max(len(rule) for (_, rule, _), _ in ordered)
179
+ return "\n".join(
180
+ f"{count:>{width}} {style(code, _BOLD)} {rule:<{name_width}} "
181
+ + style(f"[{severity.value}]", _COLORS[severity])
182
+ for (code, rule, severity), count in ordered
183
+ )
184
+
185
+
186
+ def _render_violation(
187
+ violation: Violation, read_line: LineReader, style: _Style
188
+ ) -> str:
189
+ location = violation.path or "<project>"
190
+ if violation.line:
191
+ location += f":{violation.line}"
192
+ if violation.column:
193
+ location += f":{violation.column}"
194
+ severity = style(f"[{violation.severity.value}]", _COLORS[violation.severity])
195
+ header = f"{style(location, _BOLD)} {style(violation.code, _BOLD)} {violation.rule} {severity}"
196
+ out = [header, f" {violation.message}"]
197
+ out.extend(_snippet(violation, read_line, style))
198
+ out.extend(_chain(violation))
199
+ if violation.expected:
200
+ out.extend(_expected(violation, violation.expected))
201
+ if violation.hint:
202
+ out.append(_wrap("Hint: ", violation.hint))
203
+ return "\n".join(out)
204
+
205
+
206
+ def _chain(violation: Violation) -> list[str]:
207
+ links = violation.import_chain
208
+ if not links:
209
+ return []
210
+ connected = all(a.imported == b.importer for a, b in itertools.pairwise(links))
211
+ if connected:
212
+ modules = [links[0].importer, *(link.imported for link in links)]
213
+ return [_wrap("Chain: ", " → ".join(modules))]
214
+ lines = [" Imports:"]
215
+ for link in links:
216
+ where = f" (line {link.line})" if link.line else ""
217
+ lines.append(f" {link.importer} → {link.imported}{where}")
218
+ return lines
219
+
220
+
221
+ def _snippet(violation: Violation, read_line: LineReader, style: _Style) -> list[str]:
222
+ if not violation.path or not violation.line:
223
+ return []
224
+ raw = read_line(violation.path, violation.line)
225
+ if not raw.strip():
226
+ return []
227
+ stripped = raw.lstrip()
228
+ indent = len(raw) - len(stripped)
229
+ lines = [f" {stripped.rstrip()}"]
230
+ if (
231
+ violation.column
232
+ and violation.end_column
233
+ and violation.end_line in (None, violation.line)
234
+ ):
235
+ start = max(violation.column - 1 - indent, 0)
236
+ width = max(violation.end_column - violation.column, 1)
237
+ carets = style("^" * width, _COLORS[violation.severity])
238
+ lines.append(" " + " " * start + carets)
239
+ return lines
240
+
241
+
242
+ def _expected(violation: Violation, expected: Mapping[str, Any]) -> list[str]:
243
+ lines: list[str] = []
244
+ for key, value in expected.items():
245
+ if key == "may_depend_on" and violation.layer:
246
+ targets = ", ".join(value) if value else "(nothing)"
247
+ lines.append(f" Allowed: {violation.layer} → {targets}")
248
+ elif key in _MACHINE_ONLY:
249
+ continue
250
+ elif key == "candidates":
251
+ lines.extend(_candidate_lines(value))
252
+ elif key in ("path", "expected_path"):
253
+ lines.append(f" Expected: {value}")
254
+ else:
255
+ lines.append(
256
+ _wrap(f"Expected {key.replace('_', ' ')}: ", _format_value(value))
257
+ )
258
+ return lines
259
+
260
+
261
+ def _candidate_lines(candidates: list[Mapping[str, Any]]) -> list[str]:
262
+ """``application/commands/ (ChannelCommands, HelpCommand via ...application)``."""
263
+ lines = [" Candidates:"]
264
+ for candidate in candidates:
265
+ names = ", ".join(candidate.get("imports", ()))
266
+ via = ", ".join(candidate.get("via", ()))
267
+ detail = f"{names} via {via}" if via else names
268
+ lines.append(
269
+ f" {candidate['source']} ({detail}) → {candidate['test_path']}"
270
+ if detail
271
+ else f" {candidate['source']} → {candidate['test_path']}"
272
+ )
273
+ return lines
274
+
275
+
276
+ def _format_value(value: object) -> str:
277
+ if isinstance(value, list | tuple):
278
+ return ", ".join(str(v) for v in value) if value else "(none)"
279
+ if isinstance(value, Mapping):
280
+ return "; ".join(f"{k}: {_format_value(v)}" for k, v in value.items())
281
+ return str(value)
282
+
283
+
284
+ def _wrap(label: str, text: str) -> str:
285
+ return textwrap.fill(
286
+ text,
287
+ width=_WIDTH,
288
+ initial_indent=f" {label}",
289
+ subsequent_indent=" " * (len(label) + 2),
290
+ break_on_hyphens=False,
291
+ break_long_words=False,
292
+ )
293
+
294
+
295
+ def _plural(count: int, word: str) -> str:
296
+ return f"{count} {word}" if count == 1 else f"{count} {word}s"
297
+
298
+
299
+ def _summary(report: Report, style: _Style, *, show_hints: bool) -> str:
300
+ errors = report.count(Severity.ERROR)
301
+ warnings = report.count(Severity.WARNING)
302
+ hints = report.count(Severity.HINT)
303
+ hint_text = _plural(hints, "hint")
304
+ if hints and not show_hints:
305
+ hint_text += " (use --show-hints)"
306
+ tail: list[str] = []
307
+ if report.suppressed:
308
+ tail.append(f"{report.suppressed} suppressed")
309
+ if report.in_debt:
310
+ tail.append(f"{report.in_debt} in debt")
311
+ tail.append(_plural(report.modules, "module"))
312
+
313
+ if errors == 0 and warnings == 0:
314
+ checks = " ".join(style(f"✓ {c.value}", _GREEN) for c in report.categories)
315
+ parts = [checks or style("✓ nothing to check", _GREEN)]
316
+ if hints:
317
+ parts.append(hint_text)
318
+ return " · ".join([*parts, *tail])
319
+ mark = style("✗", _RED) if report.failed else style("!", _YELLOW)
320
+ counts = [_plural(errors, "error"), _plural(warnings, "warning"), hint_text]
321
+ return f"{mark} " + " · ".join([*counts, *tail])
@@ -0,0 +1,104 @@
1
+ from collections.abc import Callable, Mapping
2
+ from dataclasses import dataclass, field
3
+ from typing import Any
4
+
5
+ from smelt.diagnostics.violation import Category, Severity, Violation
6
+
7
+ type LineReader = Callable[[str, int], str]
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class ConfigurationDiagnostic:
12
+ path: str
13
+ key: str
14
+ message: str
15
+ severity: Severity = Severity.WARNING
16
+
17
+ def to_json(self) -> dict[str, str]:
18
+ return {
19
+ "path": self.path,
20
+ "key": self.key,
21
+ "message": self.message,
22
+ "severity": self.severity.value,
23
+ }
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class RuleMeta:
28
+ code: str
29
+ name: str
30
+ category: Category
31
+ default_severity: Severity
32
+ enabled_by_default: bool
33
+ summary: str
34
+ docs_url: str
35
+ requires: tuple[str, ...] = ()
36
+ config: tuple[str, ...] = ()
37
+ activation: dict[str, str] = field(default_factory=dict)
38
+ scope: str = "source"
39
+
40
+ def to_json(self) -> dict[str, Any]:
41
+ return {
42
+ "code": self.code,
43
+ "name": self.name,
44
+ "category": self.category.value,
45
+ "default_severity": self.default_severity.value,
46
+ "enabled_by_default": self.enabled_by_default,
47
+ "summary": self.summary,
48
+ "docs_url": self.docs_url,
49
+ "requires": list(self.requires),
50
+ "config": list(self.config),
51
+ "activation": self.activation,
52
+ "scope": self.scope,
53
+ }
54
+
55
+
56
+ @dataclass
57
+ class Report:
58
+ violations: list[Violation]
59
+ modules: int
60
+ categories: list[Category]
61
+ rules: list[RuleMeta] = field(default_factory=list)
62
+ fail_on: Severity = Severity.ERROR
63
+ suppressed: int = 0
64
+ in_debt: int = 0
65
+ scope: tuple[str, ...] = ()
66
+ checked_files: int = 0
67
+ # what --changed compared with; None for a full inventory
68
+ comparison: Mapping[str, Any] | None = None
69
+ # roots, classification and policy the check ran under
70
+ coverage: Mapping[str, Any] | None = None
71
+ # Origin of config-relative paths and their prefix in repository CI reports.
72
+ project: Mapping[str, str] | None = None
73
+ fixes: Mapping[str, Any] | None = None
74
+ configuration_diagnostics: list[ConfigurationDiagnostic] = field(
75
+ default_factory=list
76
+ )
77
+
78
+ def count(self, severity: Severity) -> int:
79
+ return sum(1 for v in self.violations if v.severity is severity) + sum(
80
+ 1
81
+ for diagnostic in self.configuration_diagnostics
82
+ if diagnostic.severity is severity
83
+ )
84
+
85
+ @property
86
+ def failed(self) -> bool:
87
+ return any(v.severity.at_least(self.fail_on) for v in self.violations) or any(
88
+ diagnostic.severity.at_least(self.fail_on)
89
+ for diagnostic in self.configuration_diagnostics
90
+ )
91
+
92
+ @property
93
+ def status(self) -> str:
94
+ return "failed" if self.failed else "passed"
95
+
96
+ def summary_json(self) -> dict[str, int]:
97
+ return {
98
+ "errors": self.count(Severity.ERROR),
99
+ "warnings": self.count(Severity.WARNING),
100
+ "hints": self.count(Severity.HINT),
101
+ "modules": self.modules,
102
+ "suppressed": self.suppressed,
103
+ "in_debt": self.in_debt,
104
+ }