codeveto 0.1.0__py3-none-any.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.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/rules/config.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"""Config pack (SPEC 6.1): JSON/JSONC, TOML and YAML syntax and duplicate keys.
|
|
2
|
+
|
|
3
|
+
Parse errors are introduced-only by comparing sides: a file whose old side
|
|
4
|
+
already failed to parse reports nothing (the breakage is not this change's).
|
|
5
|
+
A new error is reported at the first changed line at or after the error
|
|
6
|
+
position, else at the nearest changed line before it; the message names the
|
|
7
|
+
line the parser stopped at. Test fixtures and vendored files are skipped:
|
|
8
|
+
broken samples are what parser tests keep there. Fixtures are files of the
|
|
9
|
+
``test`` class and files below a ``testdata``, ``_testdata``, ``test-data``,
|
|
10
|
+
``test_data`` or ``__fixtures__`` directory (Go keeps every
|
|
11
|
+
test input in ``testdata``).
|
|
12
|
+
|
|
13
|
+
JSON with comments: files the language table calls ``jsonc`` (``*.jsonc``,
|
|
14
|
+
``tsconfig*.json``, ``jsconfig*.json``, ``.vscode/**``, dev container files)
|
|
15
|
+
and a few tools that read their ``.json`` config as JSON with comments
|
|
16
|
+
(:data:`JSONC_NAMES`) may hold ``//`` and ``/* */`` comments and trailing
|
|
17
|
+
commas. Everything else must be strict JSON, except that a TypeScript
|
|
18
|
+
config under another name (a strict-JSON failure that parses as JSONC and
|
|
19
|
+
has ``compilerOptions``, such as a shared ``tsconfigs/base.json``) is left
|
|
20
|
+
alone, and a file that holds several complete JSON values one after the
|
|
21
|
+
other (JSON Lines or a JSON stream named ``.json``) is a warning, not an
|
|
22
|
+
error, unless it is a manifest, lockfile or agent configuration.
|
|
23
|
+
|
|
24
|
+
YAML is read with :mod:`codeveto.yamlish`, whose errors are only the hard
|
|
25
|
+
syntax errors a YAML parser certainly rejects. Templated YAML (Helm charts,
|
|
26
|
+
Jinja, Go templates: an unquoted ``{{`` or a ``{%``) is a template, not YAML,
|
|
27
|
+
and is not checked.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import json
|
|
33
|
+
import re
|
|
34
|
+
from collections.abc import Iterator
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
|
|
37
|
+
from codeveto import jsonsafe, languages, lexers
|
|
38
|
+
from codeveto.lexers import LineIndex
|
|
39
|
+
from codeveto.rules.base import FileContext, Hit, Severity, rule
|
|
40
|
+
from codeveto.yamlish import YamlError, YamlResult
|
|
41
|
+
|
|
42
|
+
__all__ = ["JSONC_NAMES", "JsonKey", "is_jsonc", "json_keys", "parse_json", "strip_jsonc"]
|
|
43
|
+
|
|
44
|
+
JSONC_NAMES = frozenset(
|
|
45
|
+
{
|
|
46
|
+
".eslintrc.json",
|
|
47
|
+
"turbo.json",
|
|
48
|
+
"deno.json",
|
|
49
|
+
"biome.json",
|
|
50
|
+
".swcrc",
|
|
51
|
+
"api-extractor.json",
|
|
52
|
+
"tsdoc-metadata.json",
|
|
53
|
+
"tslint.json",
|
|
54
|
+
}
|
|
55
|
+
)
|
|
56
|
+
"""``.json`` files whose tools accept comments and trailing commas."""
|
|
57
|
+
|
|
58
|
+
_PARSE_CLASSES = frozenset(languages.FILE_CLASSES) - {"test", "vendored"}
|
|
59
|
+
_FIXTURE_DIRS = frozenset({"testdata", "_testdata", "test-data", "test_data", "__fixtures__"})
|
|
60
|
+
_SINGLE_DOCUMENT_CLASSES = frozenset({"manifest", "lockfile", "agent-config"})
|
|
61
|
+
_DUPLICATE_JSON_CLASSES = _PARSE_CLASSES - {"lockfile"}
|
|
62
|
+
|
|
63
|
+
_TRAILING_COMMA = re.compile(r'"(?:[^"\\\n]|\\.)*"|,(?=[ \t\r\n]*[\]}])')
|
|
64
|
+
_JSON_TOKEN = re.compile(r'"(?:[^"\\\n]|\\.)*"|[{}\[\]:,]')
|
|
65
|
+
_TOML_POSITION = re.compile(r"\(at line (\d{1,9}), column \d{1,9}\)")
|
|
66
|
+
_TEMPLATE = re.compile(r"(?<![$\\])\{\{|\{%")
|
|
67
|
+
_BLOCK_START = re.compile(
|
|
68
|
+
r"[-?:](?:[ \t]|$)"
|
|
69
|
+
r"|(?:\"(?:[^\"\\]|\\.){0,512}\"|'(?:[^']|''){0,512}'|[^\s#'\"\[\]{},:|>%@`][^#]{0,512}?)"
|
|
70
|
+
r"[ \t]*:(?:[ \t]|$)"
|
|
71
|
+
)
|
|
72
|
+
_MAX_PATH = 64
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# --- JSON helpers (also used by the hygiene pack) --------------------------------------
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def is_jsonc(path: str, language: str) -> bool:
|
|
79
|
+
"""Does ``path`` hold JSON with comments (by the language table or :data:`JSONC_NAMES`)?"""
|
|
80
|
+
return language == "jsonc" or path.rsplit("/", 1)[-1] in JSONC_NAMES
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def strip_jsonc(text: str) -> str:
|
|
84
|
+
"""``text`` with JSONC comments and trailing commas blanked; offsets and lines kept."""
|
|
85
|
+
result = lexers.lex(text, "jsonc")
|
|
86
|
+
chars = list(text)
|
|
87
|
+
for span in lexers.flatten(result)[1]:
|
|
88
|
+
for i in range(span.start, span.end):
|
|
89
|
+
if chars[i] not in "\r\n":
|
|
90
|
+
chars[i] = " "
|
|
91
|
+
blanked = "".join(chars)
|
|
92
|
+
for m in _TRAILING_COMMA.finditer(blanked):
|
|
93
|
+
if m.group() == ",":
|
|
94
|
+
chars[m.start()] = " "
|
|
95
|
+
return "".join(chars)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True, slots=True)
|
|
99
|
+
class JsonError:
|
|
100
|
+
line: int
|
|
101
|
+
message: str
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def parse_json(text: str, *, jsonc: bool) -> tuple[object, JsonError | None]:
|
|
105
|
+
"""Parse JSON (or JSONC); the error carries the 1-based line where parsing stopped."""
|
|
106
|
+
body = text.removeprefix("")
|
|
107
|
+
if jsonc:
|
|
108
|
+
body = strip_jsonc(body)
|
|
109
|
+
try:
|
|
110
|
+
return jsonsafe.loads(body), None
|
|
111
|
+
except json.JSONDecodeError as exc:
|
|
112
|
+
return None, JsonError(max(exc.lineno, 1), exc.msg)
|
|
113
|
+
except (ValueError, RecursionError, MemoryError) as exc:
|
|
114
|
+
return None, JsonError(1, type(exc).__name__)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(slots=True)
|
|
118
|
+
class _Frame:
|
|
119
|
+
"""One open object (``obj`` is its id) or array (``obj == 0``) while scanning."""
|
|
120
|
+
|
|
121
|
+
obj: int
|
|
122
|
+
expecting: bool
|
|
123
|
+
key: str
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass(frozen=True, slots=True)
|
|
127
|
+
class JsonKey:
|
|
128
|
+
"""One object key: the object it belongs to, its parents' keys, and its line."""
|
|
129
|
+
|
|
130
|
+
obj: int
|
|
131
|
+
path: tuple[str, ...]
|
|
132
|
+
key: str
|
|
133
|
+
line: int
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def json_keys(text: str, *, jsonc: bool) -> Iterator[JsonKey]:
|
|
137
|
+
"""Every object key of a JSON document that parses, in order.
|
|
138
|
+
|
|
139
|
+
``path`` holds the keys of the enclosing objects (``"[]"`` for an array
|
|
140
|
+
level), so ``("compilerOptions",)`` is the path of ``strict`` in a
|
|
141
|
+
tsconfig. Bounded: one regex pass, an explicit stack, depth capped.
|
|
142
|
+
"""
|
|
143
|
+
body = text.removeprefix("")
|
|
144
|
+
offset = len(text) - len(body)
|
|
145
|
+
if jsonc:
|
|
146
|
+
body = strip_jsonc(body)
|
|
147
|
+
index = LineIndex(text)
|
|
148
|
+
stack: list[_Frame] = []
|
|
149
|
+
counter = 0
|
|
150
|
+
for m in _JSON_TOKEN.finditer(body):
|
|
151
|
+
tok = m.group()
|
|
152
|
+
top = stack[-1] if stack else None
|
|
153
|
+
if tok == "{":
|
|
154
|
+
counter += 1
|
|
155
|
+
stack.append(_Frame(counter, True, ""))
|
|
156
|
+
elif tok == "[":
|
|
157
|
+
stack.append(_Frame(0, False, "[]"))
|
|
158
|
+
elif tok in "}]":
|
|
159
|
+
if stack:
|
|
160
|
+
stack.pop()
|
|
161
|
+
elif tok == ",":
|
|
162
|
+
if top is not None and top.obj:
|
|
163
|
+
top.expecting = True
|
|
164
|
+
elif tok == ":":
|
|
165
|
+
continue
|
|
166
|
+
elif top is not None and top.obj and top.expecting:
|
|
167
|
+
top.expecting = False
|
|
168
|
+
try:
|
|
169
|
+
key = json.loads(tok)
|
|
170
|
+
except ValueError:
|
|
171
|
+
key = tok[1:-1]
|
|
172
|
+
top.key = key if isinstance(key, str) else tok[1:-1]
|
|
173
|
+
if len(stack) <= _MAX_PATH:
|
|
174
|
+
path = tuple(f.key for f in stack[:-1])
|
|
175
|
+
yield JsonKey(top.obj, path, top.key, index.line_of(offset + m.start()))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def json_duplicates(text: str, *, jsonc: bool) -> Iterator[tuple[JsonKey, JsonKey]]:
|
|
179
|
+
"""``(first, again)`` for each key that repeats in the same object."""
|
|
180
|
+
seen: dict[tuple[int, str], JsonKey] = {}
|
|
181
|
+
for key in json_keys(text, jsonc=jsonc):
|
|
182
|
+
first = seen.get((key.obj, key.key))
|
|
183
|
+
if first is None:
|
|
184
|
+
seen[(key.obj, key.key)] = key
|
|
185
|
+
elif not key.key.startswith("//"): # npm's "//" comment keys repeat by design
|
|
186
|
+
yield first, key
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# --- Anchoring ---------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _anchor(ctx: FileContext, target: int) -> int | None:
|
|
193
|
+
"""First changed line at or after ``target``, else the last one before it."""
|
|
194
|
+
changed = sorted(ctx.added_lines | ctx.deletion_points)
|
|
195
|
+
if not changed:
|
|
196
|
+
return None
|
|
197
|
+
for line in changed:
|
|
198
|
+
if line >= target:
|
|
199
|
+
return line
|
|
200
|
+
return changed[-1]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _old_language(ctx: FileContext) -> str:
|
|
204
|
+
return languages.language_of(ctx.old_path or ctx.path, text=ctx.old_text)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _fixture(path: str) -> bool:
|
|
208
|
+
"""Is ``path`` below a test-data directory (``testdata/``, ``fixtures/`` and the like)?"""
|
|
209
|
+
return any(part in _FIXTURE_DIRS for part in path.split("/")[:-1])
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _json_stream(text: str) -> bool:
|
|
213
|
+
"""Does ``text`` hold two or more complete JSON values and nothing else (JSON Lines)?"""
|
|
214
|
+
decoder = json.JSONDecoder()
|
|
215
|
+
body = text.removeprefix("\ufeff")
|
|
216
|
+
end, count = len(body), 0
|
|
217
|
+
i = len(body) - len(body.lstrip())
|
|
218
|
+
try:
|
|
219
|
+
while i < end:
|
|
220
|
+
_, i = decoder.raw_decode(body, i)
|
|
221
|
+
count += 1
|
|
222
|
+
while i < end and body[i] in " \t\r\n":
|
|
223
|
+
i += 1
|
|
224
|
+
except (ValueError, RecursionError):
|
|
225
|
+
return False
|
|
226
|
+
return count > 1
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _typescript_config(text: str) -> bool:
|
|
230
|
+
"""Strict JSON that fails but parses as JSONC with ``compilerOptions``: a tsconfig."""
|
|
231
|
+
if '"compilerOptions"' not in text:
|
|
232
|
+
return False # skip the JSONC lexer on large data files
|
|
233
|
+
value, error = parse_json(text, jsonc=True)
|
|
234
|
+
return error is None and isinstance(value, dict) and "compilerOptions" in value
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _templated(text: str) -> bool:
|
|
238
|
+
return any(_TEMPLATE.search(line) for line in text.splitlines())
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _pick(ctx: FileContext, first: int, again: int) -> int:
|
|
242
|
+
"""The line to report a duplicate at: the repeat, or the first one when only it changed."""
|
|
243
|
+
if again in ctx.added_lines or first not in ctx.added_lines:
|
|
244
|
+
return again
|
|
245
|
+
return first
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# --- JSON --------------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
@rule(
|
|
252
|
+
id="config/invalid-json",
|
|
253
|
+
severity="error",
|
|
254
|
+
title="Invalid JSON",
|
|
255
|
+
languages={"json", "jsonc"},
|
|
256
|
+
classes=_PARSE_CLASSES,
|
|
257
|
+
scope="file",
|
|
258
|
+
rationale=(
|
|
259
|
+
"The change leaves a JSON file that does not parse, so every tool that reads it "
|
|
260
|
+
"fails or silently falls back to defaults."
|
|
261
|
+
),
|
|
262
|
+
hint="Fix the syntax near the reported line (a missing comma, quote or bracket).",
|
|
263
|
+
tags={"config", "correctness"},
|
|
264
|
+
)
|
|
265
|
+
def invalid_json(ctx: FileContext) -> Iterator[Hit]:
|
|
266
|
+
"""The new side fails to parse while the old side parsed (or did not exist).
|
|
267
|
+
|
|
268
|
+
JSONC files may hold comments and trailing commas; other JSON is strict.
|
|
269
|
+
An empty or whitespace-only file and test fixtures are left alone, and so
|
|
270
|
+
is a TypeScript config under another name; a JSON stream (several
|
|
271
|
+
complete values) is a warning outside manifests, lockfiles and agent
|
|
272
|
+
configuration.
|
|
273
|
+
"""
|
|
274
|
+
new = ctx.new_text
|
|
275
|
+
if new is None or not new.strip() or _fixture(ctx.path):
|
|
276
|
+
return
|
|
277
|
+
jsonc = is_jsonc(ctx.path, ctx.language)
|
|
278
|
+
_, error = parse_json(new, jsonc=jsonc)
|
|
279
|
+
if error is None or (not jsonc and _typescript_config(new)):
|
|
280
|
+
return
|
|
281
|
+
old = ctx.old_text
|
|
282
|
+
if old is not None and old.strip():
|
|
283
|
+
old_path = ctx.old_path or ctx.path
|
|
284
|
+
if parse_json(old, jsonc=is_jsonc(old_path, _old_language(ctx)))[1] is not None:
|
|
285
|
+
return
|
|
286
|
+
line = _anchor(ctx, error.line)
|
|
287
|
+
if line is None:
|
|
288
|
+
return
|
|
289
|
+
if ctx.file_class not in _SINGLE_DOCUMENT_CLASSES and not jsonc and _json_stream(new):
|
|
290
|
+
message = f"Several JSON values, not one JSON document (line {error.line})"
|
|
291
|
+
yield Hit(line, message=message, severity=Severity.WARNING)
|
|
292
|
+
return
|
|
293
|
+
yield Hit(line, message=f"Invalid JSON: {error.message} (line {error.line})")
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@rule(
|
|
297
|
+
id="config/duplicate-json-key",
|
|
298
|
+
severity="error",
|
|
299
|
+
title="Duplicate JSON key",
|
|
300
|
+
languages={"json", "jsonc"},
|
|
301
|
+
classes=_DUPLICATE_JSON_CLASSES,
|
|
302
|
+
scope="line",
|
|
303
|
+
rationale=(
|
|
304
|
+
"Most JSON readers keep only the last of two equal keys in an object, so one of the "
|
|
305
|
+
"two values is silently ignored."
|
|
306
|
+
),
|
|
307
|
+
hint="Keep one entry for the key and merge the values.",
|
|
308
|
+
tags={"config", "correctness"},
|
|
309
|
+
)
|
|
310
|
+
def duplicate_json_key(ctx: FileContext) -> Iterator[Hit]:
|
|
311
|
+
"""A key repeated in the same object of a file that parses.
|
|
312
|
+
|
|
313
|
+
Reported at the repeat (or at the first occurrence when only that line
|
|
314
|
+
changed). npm's ``"//"`` comment keys are allowed to repeat; lockfiles
|
|
315
|
+
are written by tools and skipped.
|
|
316
|
+
"""
|
|
317
|
+
new = ctx.new_text
|
|
318
|
+
if not new or not ctx.added_lines or _fixture(ctx.path):
|
|
319
|
+
return
|
|
320
|
+
jsonc = is_jsonc(ctx.path, ctx.language)
|
|
321
|
+
if parse_json(new, jsonc=jsonc)[1] is not None:
|
|
322
|
+
return
|
|
323
|
+
for first, again in json_duplicates(new, jsonc=jsonc):
|
|
324
|
+
where = ".".join((*first.path, first.key))
|
|
325
|
+
yield Hit(
|
|
326
|
+
_pick(ctx, first.line, again.line),
|
|
327
|
+
message=f"Duplicate key {first.key!r} (lines {first.line} and {again.line})",
|
|
328
|
+
evidence=where,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
# --- TOML --------------------------------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _toml_line(error: BaseException, lines: int) -> int:
|
|
336
|
+
lineno = getattr(error, "lineno", None)
|
|
337
|
+
if isinstance(lineno, int) and lineno > 0:
|
|
338
|
+
return lineno
|
|
339
|
+
m = _TOML_POSITION.search(str(error))
|
|
340
|
+
if m:
|
|
341
|
+
return int(m.group(1))
|
|
342
|
+
return max(lines, 1) if "end of document" in str(error) else 1
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _toml_message(error: BaseException) -> str:
|
|
346
|
+
text = getattr(error, "msg", None)
|
|
347
|
+
if not isinstance(text, str) or not text:
|
|
348
|
+
text = _TOML_POSITION.sub("", str(error)).strip() or type(error).__name__
|
|
349
|
+
return text[:120]
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@rule(
|
|
353
|
+
id="config/invalid-toml",
|
|
354
|
+
severity="error",
|
|
355
|
+
title="Invalid TOML",
|
|
356
|
+
languages={"toml"},
|
|
357
|
+
classes=_PARSE_CLASSES,
|
|
358
|
+
scope="file",
|
|
359
|
+
rationale=(
|
|
360
|
+
"The change leaves a TOML file that does not parse, so the tools that read it "
|
|
361
|
+
"(build backends, linters, Cargo, uv) fail."
|
|
362
|
+
),
|
|
363
|
+
hint="Fix the syntax near the reported line (quotes, brackets, a repeated table or key).",
|
|
364
|
+
tags={"config", "correctness"},
|
|
365
|
+
)
|
|
366
|
+
def invalid_toml(ctx: FileContext) -> Iterator[Hit]:
|
|
367
|
+
"""The new side fails ``tomllib`` while the old side parsed (or did not exist).
|
|
368
|
+
|
|
369
|
+
TOML forbids repeated keys and tables, so duplicates are parse errors
|
|
370
|
+
here.
|
|
371
|
+
"""
|
|
372
|
+
if ctx.new_text is None or _fixture(ctx.path):
|
|
373
|
+
return
|
|
374
|
+
error = ctx.toml_error
|
|
375
|
+
if error is None:
|
|
376
|
+
return
|
|
377
|
+
if ctx.old_text is not None and ctx.old_toml_error is not None:
|
|
378
|
+
return
|
|
379
|
+
target = _toml_line(error, len(ctx.lines))
|
|
380
|
+
line = _anchor(ctx, target)
|
|
381
|
+
if line is not None:
|
|
382
|
+
yield Hit(line, message=f"Invalid TOML: {_toml_message(error)} (line {target})")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
# --- YAML --------------------------------------------------------------------------------
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _yaml_errors(ctx: FileContext, *, tabs: bool) -> Iterator[YamlError]:
|
|
389
|
+
"""New hard YAML errors of one kind (tab indentation or the rest), introduced-only."""
|
|
390
|
+
new = ctx.new_text
|
|
391
|
+
result: YamlResult | None = ctx.yaml
|
|
392
|
+
if new is None or result is None or not result.errors or _templated(new):
|
|
393
|
+
return
|
|
394
|
+
if _fixture(ctx.path):
|
|
395
|
+
return
|
|
396
|
+
old = ctx.old_yaml
|
|
397
|
+
if ctx.old_text is not None and old is not None and old.errors:
|
|
398
|
+
return
|
|
399
|
+
for error in result.errors:
|
|
400
|
+
if (error.code == "tab-indent") is not tabs:
|
|
401
|
+
continue
|
|
402
|
+
if tabs and not _tab_starts_block(ctx.lines, error.line):
|
|
403
|
+
continue
|
|
404
|
+
yield error
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _tab_starts_block(lines: tuple[str, ...], number: int) -> bool:
|
|
408
|
+
"""Does the tab-indented line start a block node (a ``key:``, a ``- `` entry, ``?``)?
|
|
409
|
+
|
|
410
|
+
YAML forbids tabs only as indentation of block structure. After the
|
|
411
|
+
indentation a tab may lead the continuation of a plain multi-line scalar
|
|
412
|
+
or a flow collection (``\t[``, ``\t{}``), which parsers accept.
|
|
413
|
+
"""
|
|
414
|
+
if not 1 <= number <= len(lines):
|
|
415
|
+
return True
|
|
416
|
+
content = lines[number - 1].lstrip(" \t")
|
|
417
|
+
return _BLOCK_START.match(content) is not None
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
@rule(
|
|
421
|
+
id="config/invalid-yaml",
|
|
422
|
+
severity="error",
|
|
423
|
+
title="Invalid YAML",
|
|
424
|
+
languages={"yaml"},
|
|
425
|
+
classes=_PARSE_CLASSES,
|
|
426
|
+
scope="file",
|
|
427
|
+
rationale=(
|
|
428
|
+
"The change leaves a YAML file with a syntax error that every YAML parser rejects, so "
|
|
429
|
+
"the tool that reads it (CI, deployment, the application) fails."
|
|
430
|
+
),
|
|
431
|
+
hint="Fix the indentation, quote or bracket near the reported line.",
|
|
432
|
+
tags={"config", "correctness"},
|
|
433
|
+
)
|
|
434
|
+
def invalid_yaml(ctx: FileContext) -> Iterator[Hit]:
|
|
435
|
+
"""A hard syntax error other than tab indentation (see :mod:`codeveto.yamlish`).
|
|
436
|
+
|
|
437
|
+
Unterminated quotes and flow collections, inconsistent indentation and a
|
|
438
|
+
mapping where a value is required; constructs the reader does not
|
|
439
|
+
support are partial coverage, never errors.
|
|
440
|
+
"""
|
|
441
|
+
for error in _yaml_errors(ctx, tabs=False):
|
|
442
|
+
line = _anchor(ctx, error.line)
|
|
443
|
+
if line is not None:
|
|
444
|
+
yield Hit(line, message=f"Invalid YAML: {error.message} (line {error.line})")
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
@rule(
|
|
448
|
+
id="config/yaml-tab-indent",
|
|
449
|
+
severity="error",
|
|
450
|
+
title="Tab used for YAML indentation",
|
|
451
|
+
languages={"yaml"},
|
|
452
|
+
classes=_PARSE_CLASSES,
|
|
453
|
+
scope="file",
|
|
454
|
+
rationale="YAML forbids tabs in indentation; parsers reject the file.",
|
|
455
|
+
hint="Indent with spaces.",
|
|
456
|
+
tags={"config", "correctness"},
|
|
457
|
+
)
|
|
458
|
+
def yaml_tab_indent(ctx: FileContext) -> Iterator[Hit]:
|
|
459
|
+
"""A tab in indentation outside block scalars (whose bodies may hold tabs)."""
|
|
460
|
+
for error in _yaml_errors(ctx, tabs=True):
|
|
461
|
+
line = _anchor(ctx, error.line)
|
|
462
|
+
if line is not None:
|
|
463
|
+
yield Hit(line, message=f"Tab in YAML indentation (line {error.line})")
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
@rule(
|
|
467
|
+
id="config/duplicate-yaml-key",
|
|
468
|
+
severity="warning",
|
|
469
|
+
title="Duplicate YAML key",
|
|
470
|
+
languages={"yaml"},
|
|
471
|
+
classes=_PARSE_CLASSES,
|
|
472
|
+
scope="line",
|
|
473
|
+
rationale=(
|
|
474
|
+
"Most YAML loaders keep only the last of two equal keys in a mapping (strict ones "
|
|
475
|
+
"reject the file), so one value is silently ignored."
|
|
476
|
+
),
|
|
477
|
+
hint="Keep one entry for the key and merge the values.",
|
|
478
|
+
tags={"config", "correctness"},
|
|
479
|
+
)
|
|
480
|
+
def duplicate_yaml_key(ctx: FileContext) -> Iterator[Hit]:
|
|
481
|
+
"""A key repeated in one mapping; reported at the repeat (or the changed first one)."""
|
|
482
|
+
new = ctx.new_text
|
|
483
|
+
result = ctx.yaml
|
|
484
|
+
if not new or result is None or not result.duplicates or _templated(new):
|
|
485
|
+
return
|
|
486
|
+
if _fixture(ctx.path):
|
|
487
|
+
return
|
|
488
|
+
for dup in result.duplicates:
|
|
489
|
+
yield Hit(
|
|
490
|
+
_pick(ctx, dup.first_line, dup.line),
|
|
491
|
+
message=f"Duplicate key {dup.key!r} (lines {dup.first_line} and {dup.line})",
|
|
492
|
+
evidence=dup.key,
|
|
493
|
+
)
|