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/config.py
ADDED
|
@@ -0,0 +1,1229 @@
|
|
|
1
|
+
"""Trusted configuration: sources, precedence, strict schema and the trust model (SPEC 7).
|
|
2
|
+
|
|
3
|
+
Layers, lowest precedence first (SPEC 7.2):
|
|
4
|
+
|
|
5
|
+
1. built-in defaults;
|
|
6
|
+
2. the repository's ``.codeveto.toml``, read from Git objects at the trust
|
|
7
|
+
anchor (:func:`codeveto.git.read_anchor_file`), never from the working tree,
|
|
8
|
+
the index or the change under review; ``no_repo_config`` skips it;
|
|
9
|
+
3. the user config: ``$XDG_CONFIG_HOME/codeveto/config.toml``, on Windows
|
|
10
|
+
``%APPDATA%\\codeveto\\config.toml``, else ``~/.config/codeveto/config.toml``;
|
|
11
|
+
4. ``--config FILE``, then the command-line overrides (a mapping in the same
|
|
12
|
+
schema as a file).
|
|
13
|
+
|
|
14
|
+
Every layer is validated strictly: an unknown key, a wrong type, an unknown rule
|
|
15
|
+
ID, an invalid glob or malformed TOML raises :class:`ConfigError` naming the
|
|
16
|
+
source and the key path, and the CLI maps it to an ``incomplete`` review. The
|
|
17
|
+
repository layer is further restricted to what SPEC 7.2 says it may do; each
|
|
18
|
+
violation is a :class:`ConfigError` whose ``restriction`` names the broken
|
|
19
|
+
rule. User and command-line layers are unrestricted (SPEC 6.3).
|
|
20
|
+
|
|
21
|
+
Merging: later layers override earlier ones key by key (``fail_on``, each rule
|
|
22
|
+
ID in ``[rules]``, each ``[ai]`` key, each ``[classes]`` list); ``[[ignore]]``
|
|
23
|
+
entries accumulate; limits and AI budgets take the minimum of the repository
|
|
24
|
+
value and the trusted value. Environment variables are read only to locate the
|
|
25
|
+
user config.
|
|
26
|
+
|
|
27
|
+
The engine sees the result only through :meth:`Config.policy`, which satisfies
|
|
28
|
+
the ``Policy`` protocol of SPEC 5.6. :func:`weakened` compares the anchor's
|
|
29
|
+
repository config with the one in a change for ``agent/reviewer-config-weakened``.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import dataclasses
|
|
35
|
+
import difflib
|
|
36
|
+
import json
|
|
37
|
+
import math
|
|
38
|
+
import os
|
|
39
|
+
import re
|
|
40
|
+
import stat
|
|
41
|
+
import sys
|
|
42
|
+
import tomllib
|
|
43
|
+
import unicodedata
|
|
44
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
45
|
+
from dataclasses import dataclass, field
|
|
46
|
+
from pathlib import Path, PurePosixPath, PureWindowsPath
|
|
47
|
+
from types import MappingProxyType
|
|
48
|
+
from typing import Literal
|
|
49
|
+
from urllib.parse import urlsplit
|
|
50
|
+
|
|
51
|
+
from codeveto import git as _git
|
|
52
|
+
from codeveto.globs import Glob, GlobError, compile_glob
|
|
53
|
+
from codeveto.rules.base import NON_WAIVABLE_RULES, Registry, RuleMeta, Severity
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
"AI_PROVIDERS",
|
|
57
|
+
"EFFORT_LEVELS",
|
|
58
|
+
"FAIL_ON_LEVELS",
|
|
59
|
+
"MAX_CONFIG_BYTES",
|
|
60
|
+
"MAX_PACKETS_CEILING",
|
|
61
|
+
"MAX_REASON_LENGTH",
|
|
62
|
+
"NETWORK_PROVIDERS",
|
|
63
|
+
"NON_WAIVABLE_RULES",
|
|
64
|
+
"PROTECTED_PROBES",
|
|
65
|
+
"REPO_CONFIG_NAME",
|
|
66
|
+
"AISettings",
|
|
67
|
+
"Config",
|
|
68
|
+
"ConfigError",
|
|
69
|
+
"ConfigPolicy",
|
|
70
|
+
"FailOn",
|
|
71
|
+
"Ignore",
|
|
72
|
+
"Layer",
|
|
73
|
+
"LayerKind",
|
|
74
|
+
"Weakening",
|
|
75
|
+
"build_config",
|
|
76
|
+
"load_config",
|
|
77
|
+
"parse_layer",
|
|
78
|
+
"parse_toml",
|
|
79
|
+
"user_config_path",
|
|
80
|
+
"weakened",
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
REPO_CONFIG_NAME = ".codeveto.toml"
|
|
84
|
+
MAX_CONFIG_BYTES = 64 * 1024
|
|
85
|
+
"""Cap for every config file, repository or local."""
|
|
86
|
+
|
|
87
|
+
FailOn = Literal["error", "warning", "note", "never"]
|
|
88
|
+
FAIL_ON_LEVELS: tuple[str, ...] = ("note", "warning", "error", "never")
|
|
89
|
+
"""Strictest first: a later level blocks on fewer findings."""
|
|
90
|
+
|
|
91
|
+
# NON_WAIVABLE_RULES (SPEC 6.3) comes from rules/base.py, the single source;
|
|
92
|
+
# a rule is also non-waivable when its metadata says so.
|
|
93
|
+
|
|
94
|
+
AI_PROVIDERS: tuple[str, ...] = ("claude", "openai", "none")
|
|
95
|
+
NETWORK_PROVIDERS: frozenset[str] = frozenset({"claude", "openai"})
|
|
96
|
+
EFFORT_LEVELS: tuple[str, ...] = ("low", "medium", "high", "xhigh", "max")
|
|
97
|
+
MAX_PACKETS_CEILING = 100
|
|
98
|
+
|
|
99
|
+
LayerKind = Literal["repository", "user", "file", "cli"]
|
|
100
|
+
_KIND_ORDER: dict[str, int] = {"repository": 0, "user": 1, "file": 2, "cli": 3}
|
|
101
|
+
|
|
102
|
+
_TOP_KEYS = ("fail_on", "allow_inline_ignores", "rules", "ignore", "classes", "limits", "ai")
|
|
103
|
+
_RULES_KEYS = ("enable", "disable", "severity")
|
|
104
|
+
_IGNORE_KEYS = ("paths", "rules", "reason")
|
|
105
|
+
_CLASS_KEYS = ("vendored", "generated", "minified") # SPEC 5.4 table order
|
|
106
|
+
_LIMIT_KEYS = tuple(spec.name for spec in dataclasses.fields(_git.Limits))
|
|
107
|
+
_AI_FLAGS = ("enabled", "required", "blocking")
|
|
108
|
+
_AI_BUDGETS = (
|
|
109
|
+
"max_packets",
|
|
110
|
+
"max_output_tokens",
|
|
111
|
+
"max_total_input_tokens",
|
|
112
|
+
"max_total_output_tokens",
|
|
113
|
+
"deadline_s",
|
|
114
|
+
"concurrency",
|
|
115
|
+
"effort",
|
|
116
|
+
)
|
|
117
|
+
_AI_KEYS = (*_AI_FLAGS, "provider", "model", "effort", "base_url", *_AI_BUDGETS[:-1])
|
|
118
|
+
_SEVERITIES = ("error", "warning", "note")
|
|
119
|
+
_MODEL_ID = re.compile(r"[\x21-\x7e]{1,200}")
|
|
120
|
+
_BARE_KEY = re.compile(r"[A-Za-z0-9_-]+")
|
|
121
|
+
_OID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
|
|
122
|
+
_MAX_KEY_PART = 120
|
|
123
|
+
_MAX_SHOWN = 80
|
|
124
|
+
MAX_REASON_LENGTH = 500
|
|
125
|
+
|
|
126
|
+
_PROTECTED = (
|
|
127
|
+
".codeveto.toml",
|
|
128
|
+
"CODEOWNERS",
|
|
129
|
+
".github/CODEOWNERS",
|
|
130
|
+
# workflow class (SPEC 5.4)
|
|
131
|
+
".github/workflows/x.yml",
|
|
132
|
+
".forgejo/workflows/x.yaml",
|
|
133
|
+
".gitea/workflows/x.yml",
|
|
134
|
+
"action.yml",
|
|
135
|
+
"action.yaml",
|
|
136
|
+
# agent-config class (SPEC 5.4)
|
|
137
|
+
"AGENTS.md",
|
|
138
|
+
"CLAUDE.md",
|
|
139
|
+
"GEMINI.md",
|
|
140
|
+
".github/copilot-instructions.md",
|
|
141
|
+
".cursorrules",
|
|
142
|
+
".cursor/rules/x.mdc",
|
|
143
|
+
".windsurfrules",
|
|
144
|
+
".clinerules",
|
|
145
|
+
".mcp.json",
|
|
146
|
+
".claude/settings.json",
|
|
147
|
+
".codex/config.toml",
|
|
148
|
+
".vscode/settings.json",
|
|
149
|
+
".vscode/tasks.json",
|
|
150
|
+
".devcontainer/devcontainer.json",
|
|
151
|
+
)
|
|
152
|
+
PROTECTED_PROBES: tuple[str, ...] = tuple(
|
|
153
|
+
prefix + path
|
|
154
|
+
for path in _PROTECTED
|
|
155
|
+
for prefix in ("", "codeveto-probe/", "codeveto-probe/codeveto-probe/")
|
|
156
|
+
)
|
|
157
|
+
"""Paths no repository ignore of a non-waivable rule may match (SPEC 6.3)."""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# --- errors --------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class ConfigError(Exception):
|
|
164
|
+
"""An invalid or forbidden configuration; the review is ``incomplete``.
|
|
165
|
+
|
|
166
|
+
``source`` names the layer, ``key`` the TOML key path (``None`` for the
|
|
167
|
+
whole file) and ``restriction`` the repository-layer rule that was broken
|
|
168
|
+
(``None`` for schema errors).
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
def __init__(
|
|
172
|
+
self, source: str, key: str | None, problem: str, *, restriction: str | None = None
|
|
173
|
+
) -> None:
|
|
174
|
+
super().__init__(f"{source}: {key}: {problem}" if key else f"{source}: {problem}")
|
|
175
|
+
self.source = source
|
|
176
|
+
self.key = key
|
|
177
|
+
self.problem = problem
|
|
178
|
+
self.restriction = restriction
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _part(name: str) -> str:
|
|
182
|
+
# json.dumps escapes every non-ASCII and control character in odd key names.
|
|
183
|
+
shown = name if _BARE_KEY.fullmatch(name) else json.dumps(name)
|
|
184
|
+
return shown if len(shown) <= _MAX_KEY_PART else shown[: _MAX_KEY_PART - 3] + "..."
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _join(prefix: str, name: str) -> str:
|
|
188
|
+
return f"{prefix}.{_part(name)}" if prefix else _part(name)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _show(value: object) -> str:
|
|
192
|
+
"""A bounded, ASCII-only rendering of a (possibly repository-derived) value."""
|
|
193
|
+
text = ascii(value)
|
|
194
|
+
return text if len(text) <= _MAX_SHOWN else text[: _MAX_SHOWN - 3] + "..."
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _escape(text: str, limit: int = 300) -> str:
|
|
198
|
+
"""``text`` with every character outside printable ASCII escaped, bounded."""
|
|
199
|
+
shown = ascii(text)[1:-1]
|
|
200
|
+
return shown if len(shown) <= limit else shown[: limit - 3] + "..."
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _type_name(value: object) -> str:
|
|
204
|
+
if isinstance(value, bool):
|
|
205
|
+
return "a boolean"
|
|
206
|
+
if isinstance(value, int):
|
|
207
|
+
return "an integer"
|
|
208
|
+
if isinstance(value, float):
|
|
209
|
+
return "a float"
|
|
210
|
+
if isinstance(value, str):
|
|
211
|
+
return "a string"
|
|
212
|
+
if isinstance(value, list | tuple):
|
|
213
|
+
return "an array"
|
|
214
|
+
if isinstance(value, Mapping):
|
|
215
|
+
return "a table"
|
|
216
|
+
return f"a {type(value).__name__}"
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _hint(name: str, choices: Iterable[str]) -> str:
|
|
220
|
+
close = difflib.get_close_matches(name, list(choices), n=1)
|
|
221
|
+
return f"; did you mean {close[0]!r}?" if close else ""
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _is_int(value: object) -> bool:
|
|
225
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _non_waivable(registry: Registry, rule_id: str) -> bool:
|
|
229
|
+
entry = registry.get(rule_id)
|
|
230
|
+
return rule_id in NON_WAIVABLE_RULES or (entry is not None and entry.meta.non_waivable)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _selects(selector: str, rule_id: str) -> bool:
|
|
234
|
+
if selector == "*":
|
|
235
|
+
return True
|
|
236
|
+
if selector.endswith("/*"):
|
|
237
|
+
return rule_id.startswith(selector[:-1])
|
|
238
|
+
return selector == rule_id
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _is_catch_all(pattern: str) -> bool:
|
|
242
|
+
"""No literal character other than ``/`` and ``.`` (SPEC 7.2).
|
|
243
|
+
|
|
244
|
+
``*``, ``?`` and whole character classes count as wildcards, and ``\\.``
|
|
245
|
+
or ``\\/`` as the literal they escape; any other escaped or plain
|
|
246
|
+
character makes the pattern specific. So ``**``, ``*.*``, ``**/.*``,
|
|
247
|
+
``**/[!.]*`` and ``*[!q]*`` are catch-alls and ``tests/**`` is not.
|
|
248
|
+
"""
|
|
249
|
+
i, n = 0, len(pattern)
|
|
250
|
+
while i < n:
|
|
251
|
+
ch = pattern[i]
|
|
252
|
+
if ch == "\\" and i + 1 < n:
|
|
253
|
+
if pattern[i + 1] not in "./":
|
|
254
|
+
return False
|
|
255
|
+
i += 2
|
|
256
|
+
elif ch == "[":
|
|
257
|
+
j = i + 1
|
|
258
|
+
if j < n and pattern[j] == "!":
|
|
259
|
+
j += 1
|
|
260
|
+
if j < n and pattern[j] == "]":
|
|
261
|
+
j += 1
|
|
262
|
+
while j < n and pattern[j] != "]":
|
|
263
|
+
j += 2 if pattern[j] == "\\" else 1
|
|
264
|
+
i = j + 1
|
|
265
|
+
elif ch in "*?/.":
|
|
266
|
+
i += 1
|
|
267
|
+
else:
|
|
268
|
+
return False
|
|
269
|
+
return True
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _literal_first_segment(pattern: str) -> bool:
|
|
273
|
+
first = pattern.split("/", 1)[0]
|
|
274
|
+
return bool(first) and not set(first) & set("*?[\\")
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# --- layers --------------------------------------------------------------------
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@dataclass(frozen=True, slots=True)
|
|
281
|
+
class Ignore:
|
|
282
|
+
"""One ``[[ignore]]`` entry: ``rules`` selectors (IDs, ``pack/*`` or ``*``) on ``paths``."""
|
|
283
|
+
|
|
284
|
+
paths: tuple[str, ...]
|
|
285
|
+
rules: tuple[str, ...]
|
|
286
|
+
reason: str
|
|
287
|
+
source: str
|
|
288
|
+
globs: tuple[Glob, ...] = field(repr=False, compare=False, default=())
|
|
289
|
+
|
|
290
|
+
def covers(self, rule_id: str) -> bool:
|
|
291
|
+
return any(_selects(selector, rule_id) for selector in self.rules)
|
|
292
|
+
|
|
293
|
+
def matches(self, rule_id: str, path: str) -> bool:
|
|
294
|
+
return self.covers(rule_id) and any(glob.match(path) for glob in self.globs)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _frozen(mapping: Mapping[str, object] | None = None) -> Mapping[str, object]:
|
|
298
|
+
return MappingProxyType(dict(mapping or {}))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@dataclass(frozen=True, slots=True)
|
|
302
|
+
class Layer:
|
|
303
|
+
"""One validated configuration source; ``None``/empty means "not set here"."""
|
|
304
|
+
|
|
305
|
+
source: str
|
|
306
|
+
kind: LayerKind
|
|
307
|
+
fail_on: FailOn | None = None
|
|
308
|
+
allow_inline_ignores: bool | None = None
|
|
309
|
+
enable: tuple[str, ...] = ()
|
|
310
|
+
disable: tuple[str, ...] = ()
|
|
311
|
+
severity: Mapping[str, Severity] = field(default_factory=_frozen)
|
|
312
|
+
ignores: tuple[Ignore, ...] = ()
|
|
313
|
+
classes: Mapping[str, tuple[str, ...]] = field(default_factory=_frozen)
|
|
314
|
+
limits: Mapping[str, int | float] = field(default_factory=_frozen)
|
|
315
|
+
ai: Mapping[str, object] = field(default_factory=_frozen)
|
|
316
|
+
|
|
317
|
+
@property
|
|
318
|
+
def trusted(self) -> bool:
|
|
319
|
+
return self.kind != "repository"
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
class _Parser:
|
|
323
|
+
"""Validates one layer's data; ``repo`` turns on the SPEC 7.2 restrictions."""
|
|
324
|
+
|
|
325
|
+
def __init__(self, source: str, kind: LayerKind, registry: Registry) -> None:
|
|
326
|
+
if kind not in _KIND_ORDER:
|
|
327
|
+
raise ValueError(f"unknown layer kind {kind!r}")
|
|
328
|
+
self.source = source
|
|
329
|
+
self.kind = kind
|
|
330
|
+
self.repo = kind == "repository"
|
|
331
|
+
self.registry = registry
|
|
332
|
+
self.packs = tuple(sorted({entry.meta.pack for entry in registry.all()}))
|
|
333
|
+
self.non_waivable = tuple(
|
|
334
|
+
sorted(
|
|
335
|
+
{e.id for e in registry.all() if _non_waivable(registry, e.id)} | NON_WAIVABLE_RULES
|
|
336
|
+
)
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
def error(self, key: str | None, problem: str) -> ConfigError:
|
|
340
|
+
return ConfigError(self.source, key, problem)
|
|
341
|
+
|
|
342
|
+
def forbid(self, key: str, problem: str, restriction: str) -> ConfigError:
|
|
343
|
+
return ConfigError(
|
|
344
|
+
self.source, key, f"repository config may not {problem}", restriction=restriction
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
# --- shapes ----------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
def table(self, value: object, key: str, allowed: Sequence[str]) -> Mapping[str, object]:
|
|
350
|
+
if not isinstance(value, Mapping):
|
|
351
|
+
raise self.error(key or None, f"must be a table, not {_type_name(value)}")
|
|
352
|
+
for name in value:
|
|
353
|
+
if not isinstance(name, str):
|
|
354
|
+
raise self.error(key or None, f"keys must be strings, not {_show(name)}")
|
|
355
|
+
if name not in allowed:
|
|
356
|
+
raise self.error(_join(key, name), "unknown key" + _hint(name, allowed))
|
|
357
|
+
return value
|
|
358
|
+
|
|
359
|
+
def array(self, value: object, key: str, *, nonempty: bool = False) -> list[object]:
|
|
360
|
+
if not isinstance(value, list | tuple):
|
|
361
|
+
raise self.error(key, f"must be an array, not {_type_name(value)}")
|
|
362
|
+
if nonempty and not value:
|
|
363
|
+
raise self.error(key, "must not be empty")
|
|
364
|
+
return list(value)
|
|
365
|
+
|
|
366
|
+
def text(self, value: object, key: str) -> str:
|
|
367
|
+
if not isinstance(value, str):
|
|
368
|
+
raise self.error(key, f"must be a string, not {_type_name(value)}")
|
|
369
|
+
return value
|
|
370
|
+
|
|
371
|
+
def flag(self, value: object, key: str) -> bool:
|
|
372
|
+
if not isinstance(value, bool):
|
|
373
|
+
raise self.error(key, f"must be a boolean, not {_type_name(value)}")
|
|
374
|
+
return value
|
|
375
|
+
|
|
376
|
+
def choice(self, value: object, key: str, choices: Sequence[str]) -> str:
|
|
377
|
+
options = ", ".join(repr(c) for c in choices)
|
|
378
|
+
if not isinstance(value, str) or value not in choices:
|
|
379
|
+
got = _show(value) if isinstance(value, str) else _type_name(value)
|
|
380
|
+
raise self.error(key, f"must be one of {options}, not {got}")
|
|
381
|
+
return value
|
|
382
|
+
|
|
383
|
+
def number(self, value: object, key: str, *, integer: bool) -> int | float:
|
|
384
|
+
if integer and not _is_int(value):
|
|
385
|
+
raise self.error(key, f"must be an integer, not {_type_name(value)}")
|
|
386
|
+
if not integer and not (_is_int(value) or isinstance(value, float)):
|
|
387
|
+
raise self.error(key, f"must be a number, not {_type_name(value)}")
|
|
388
|
+
number: int | float = value # type: ignore[assignment]
|
|
389
|
+
if isinstance(number, float) and not math.isfinite(number):
|
|
390
|
+
raise self.error(key, f"must be a finite number, not {_show(number)}")
|
|
391
|
+
if number <= 0:
|
|
392
|
+
raise self.error(key, f"must be greater than 0, not {_show(number)}")
|
|
393
|
+
return number
|
|
394
|
+
|
|
395
|
+
def rule_id(self, value: object, key: str) -> str:
|
|
396
|
+
rule_id = self.text(value, key)
|
|
397
|
+
if rule_id not in self.registry:
|
|
398
|
+
known = [entry.id for entry in self.registry.all()]
|
|
399
|
+
raise self.error(key, f"unknown rule ID {_show(rule_id)}" + _hint(rule_id, known))
|
|
400
|
+
return rule_id
|
|
401
|
+
|
|
402
|
+
def selector(self, value: object, key: str) -> str:
|
|
403
|
+
selector = self.text(value, key)
|
|
404
|
+
if selector == "*":
|
|
405
|
+
return selector
|
|
406
|
+
if selector.endswith("/*"):
|
|
407
|
+
pack = selector[:-2]
|
|
408
|
+
if pack not in self.packs:
|
|
409
|
+
raise self.error(key, f"unknown rule pack {_show(pack)}" + _hint(pack, self.packs))
|
|
410
|
+
return selector
|
|
411
|
+
return self.rule_id(selector, key)
|
|
412
|
+
|
|
413
|
+
def glob(self, value: object, key: str) -> Glob:
|
|
414
|
+
pattern = self.text(value, key)
|
|
415
|
+
try:
|
|
416
|
+
return compile_glob(pattern)
|
|
417
|
+
except GlobError as exc:
|
|
418
|
+
raise self.error(key, f"invalid glob {_show(pattern)}: {_escape(exc.reason)}") from None
|
|
419
|
+
|
|
420
|
+
# --- sections ----------------------------------------------------------------
|
|
421
|
+
|
|
422
|
+
def parse(self, data: object) -> Layer:
|
|
423
|
+
top = self.table(data, "", _TOP_KEYS)
|
|
424
|
+
fail_on = self.fail_on(top["fail_on"]) if "fail_on" in top else None
|
|
425
|
+
inline = None
|
|
426
|
+
if "allow_inline_ignores" in top:
|
|
427
|
+
if self.repo:
|
|
428
|
+
raise self.forbid(
|
|
429
|
+
"allow_inline_ignores",
|
|
430
|
+
"set allow_inline_ignores; enable it in user config or on the command line",
|
|
431
|
+
"inline-ignores",
|
|
432
|
+
)
|
|
433
|
+
inline = self.flag(top["allow_inline_ignores"], "allow_inline_ignores")
|
|
434
|
+
enable, disable, severity = self.rules(top.get("rules", {}))
|
|
435
|
+
if "classes" in top and self.repo:
|
|
436
|
+
raise self.forbid(
|
|
437
|
+
"classes",
|
|
438
|
+
"set [classes]; generated and vendored patterns come only from trusted config",
|
|
439
|
+
"classes",
|
|
440
|
+
)
|
|
441
|
+
return Layer(
|
|
442
|
+
source=self.source,
|
|
443
|
+
kind=self.kind,
|
|
444
|
+
fail_on=fail_on, # type: ignore[arg-type]
|
|
445
|
+
allow_inline_ignores=inline,
|
|
446
|
+
enable=enable,
|
|
447
|
+
disable=disable,
|
|
448
|
+
severity=MappingProxyType(severity),
|
|
449
|
+
ignores=self.ignores(top["ignore"]) if "ignore" in top else (),
|
|
450
|
+
classes=_frozen(self.classes(top.get("classes", {}))),
|
|
451
|
+
limits=_frozen(self.limits(top.get("limits", {}))),
|
|
452
|
+
ai=_frozen(self.ai(top.get("ai", {}))),
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
def fail_on(self, value: object) -> str:
|
|
456
|
+
level = self.choice(value, "fail_on", ("error", "warning", "note", "never"))
|
|
457
|
+
if self.repo and level == "never":
|
|
458
|
+
raise self.forbid(
|
|
459
|
+
"fail_on",
|
|
460
|
+
'set fail_on = "never"; use --fail-on or user config',
|
|
461
|
+
"fail-on-never",
|
|
462
|
+
)
|
|
463
|
+
return level
|
|
464
|
+
|
|
465
|
+
def rules(self, value: object) -> tuple[tuple[str, ...], tuple[str, ...], dict[str, Severity]]:
|
|
466
|
+
rules = self.table(value, "rules", _RULES_KEYS)
|
|
467
|
+
lists: dict[str, tuple[str, ...]] = {}
|
|
468
|
+
for name in ("enable", "disable"):
|
|
469
|
+
key = f"rules.{name}"
|
|
470
|
+
items = self.array(rules.get(name, []), key)
|
|
471
|
+
lists[name] = tuple(self.rule_id(item, f"{key}[{i}]") for i, item in enumerate(items))
|
|
472
|
+
for i, rule_id in enumerate(lists["disable"]):
|
|
473
|
+
if rule_id in lists["enable"]:
|
|
474
|
+
raise self.error(f"rules.disable[{i}]", f"{rule_id} is also in rules.enable")
|
|
475
|
+
if self.repo and _non_waivable(self.registry, rule_id):
|
|
476
|
+
raise self.forbid(
|
|
477
|
+
f"rules.disable[{i}]", f"disable non-waivable rule {rule_id}", "non-waivable"
|
|
478
|
+
)
|
|
479
|
+
severity: dict[str, Severity] = {}
|
|
480
|
+
table = rules.get("severity", {})
|
|
481
|
+
if not isinstance(table, Mapping):
|
|
482
|
+
raise self.error("rules.severity", f"must be a table, not {_type_name(table)}")
|
|
483
|
+
for rule_id, level in table.items():
|
|
484
|
+
if not isinstance(rule_id, str):
|
|
485
|
+
raise self.error("rules.severity", f"keys must be strings, not {_show(rule_id)}")
|
|
486
|
+
key = _join("rules.severity", rule_id)
|
|
487
|
+
self.rule_id(rule_id, key)
|
|
488
|
+
chosen = Severity(self.choice(level, key, _SEVERITIES))
|
|
489
|
+
entry = self.registry.get(rule_id)
|
|
490
|
+
default = entry.meta.severity if entry is not None else chosen
|
|
491
|
+
if self.repo and _non_waivable(self.registry, rule_id) and chosen < default:
|
|
492
|
+
raise self.forbid(
|
|
493
|
+
key,
|
|
494
|
+
f"downgrade non-waivable rule {rule_id} below {default.value}",
|
|
495
|
+
"non-waivable",
|
|
496
|
+
)
|
|
497
|
+
severity[rule_id] = chosen
|
|
498
|
+
return lists["enable"], lists["disable"], severity
|
|
499
|
+
|
|
500
|
+
def ignores(self, value: object) -> tuple[Ignore, ...]:
|
|
501
|
+
entries = self.array(value, "ignore")
|
|
502
|
+
result: list[Ignore] = []
|
|
503
|
+
for i, item in enumerate(entries):
|
|
504
|
+
key = f"ignore[{i}]"
|
|
505
|
+
entry = self.table(item, key, _IGNORE_KEYS)
|
|
506
|
+
for name in _IGNORE_KEYS:
|
|
507
|
+
if name not in entry:
|
|
508
|
+
raise self.error(key, f"missing required key {name!r}")
|
|
509
|
+
paths = self.array(entry["paths"], f"{key}.paths", nonempty=True)
|
|
510
|
+
globs = tuple(self.glob(p, f"{key}.paths[{j}]") for j, p in enumerate(paths))
|
|
511
|
+
if self.repo:
|
|
512
|
+
for j, glob in enumerate(globs):
|
|
513
|
+
if _is_catch_all(glob.pattern):
|
|
514
|
+
raise self.forbid(
|
|
515
|
+
f"{key}.paths[{j}]",
|
|
516
|
+
f"ignore with the catch-all path {_show(glob.pattern)}; "
|
|
517
|
+
"name specific paths such as fixture directories",
|
|
518
|
+
"catch-all-ignore",
|
|
519
|
+
)
|
|
520
|
+
selectors = self.array(entry["rules"], f"{key}.rules", nonempty=True)
|
|
521
|
+
rules = tuple(self.selector(s, f"{key}.rules[{j}]") for j, s in enumerate(selectors))
|
|
522
|
+
if self.repo:
|
|
523
|
+
self.non_waivable_paths(key, globs, rules)
|
|
524
|
+
reason = self.reason(entry["reason"], f"{key}.reason")
|
|
525
|
+
result.append(
|
|
526
|
+
Ignore(
|
|
527
|
+
paths=tuple(g.pattern for g in globs),
|
|
528
|
+
rules=rules,
|
|
529
|
+
reason=reason,
|
|
530
|
+
source=self.source,
|
|
531
|
+
globs=globs,
|
|
532
|
+
)
|
|
533
|
+
)
|
|
534
|
+
return tuple(result)
|
|
535
|
+
|
|
536
|
+
def non_waivable_paths(
|
|
537
|
+
self, key: str, globs: tuple[Glob, ...], selectors: tuple[str, ...]
|
|
538
|
+
) -> None:
|
|
539
|
+
"""SPEC 6.3: non-waivable rules may only be path-ignored on specific fixture paths."""
|
|
540
|
+
covered = [r for r in self.non_waivable if any(_selects(s, r) for s in selectors)]
|
|
541
|
+
if not covered:
|
|
542
|
+
return
|
|
543
|
+
what = f"ignore non-waivable {covered[0]}" + (
|
|
544
|
+
f" (and {len(covered) - 1} more)" if len(covered) > 1 else ""
|
|
545
|
+
)
|
|
546
|
+
for j, glob in enumerate(globs):
|
|
547
|
+
if not _literal_first_segment(glob.pattern):
|
|
548
|
+
raise self.forbid(
|
|
549
|
+
f"{key}.paths[{j}]",
|
|
550
|
+
f"{what} on {_show(glob.pattern)}; such patterns must start with a "
|
|
551
|
+
"literal directory or file name (no glob character before the first '/')",
|
|
552
|
+
"non-waivable-path",
|
|
553
|
+
)
|
|
554
|
+
for probe in PROTECTED_PROBES:
|
|
555
|
+
if glob.match(probe):
|
|
556
|
+
raise self.forbid(
|
|
557
|
+
f"{key}.paths[{j}]",
|
|
558
|
+
f"{what} on {_show(glob.pattern)}: it matches the protected path {probe!r}",
|
|
559
|
+
"non-waivable-path",
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
def reason(self, value: object, key: str) -> str:
|
|
563
|
+
raw = self.text(value, key)
|
|
564
|
+
# Checked before stripping: str.strip() would silently drop a trailing NEL.
|
|
565
|
+
for index, ch in enumerate(raw):
|
|
566
|
+
if unicodedata.category(ch) in ("Cc", "Cf", "Zl", "Zp"):
|
|
567
|
+
raise self.error(
|
|
568
|
+
key,
|
|
569
|
+
"must not contain control, format or line separator characters "
|
|
570
|
+
f"(U+{ord(ch):04X} at {index})",
|
|
571
|
+
)
|
|
572
|
+
reason = raw.strip()
|
|
573
|
+
if not reason:
|
|
574
|
+
raise self.error(key, "must not be empty")
|
|
575
|
+
if len(reason) > MAX_REASON_LENGTH:
|
|
576
|
+
raise self.error(key, f"must be at most {MAX_REASON_LENGTH} characters")
|
|
577
|
+
return reason
|
|
578
|
+
|
|
579
|
+
def classes(self, value: object) -> dict[str, tuple[str, ...]]:
|
|
580
|
+
table = self.table(value, "classes", _CLASS_KEYS)
|
|
581
|
+
result: dict[str, tuple[str, ...]] = {}
|
|
582
|
+
for name, items in table.items():
|
|
583
|
+
key = f"classes.{name}"
|
|
584
|
+
patterns = self.array(items, key)
|
|
585
|
+
result[name] = tuple(
|
|
586
|
+
self.glob(p, f"{key}[{j}]").pattern for j, p in enumerate(patterns)
|
|
587
|
+
)
|
|
588
|
+
return result
|
|
589
|
+
|
|
590
|
+
def limits(self, value: object) -> dict[str, int | float]:
|
|
591
|
+
table = self.table(value, "limits", _LIMIT_KEYS)
|
|
592
|
+
result: dict[str, int | float] = {}
|
|
593
|
+
for name, raw in table.items():
|
|
594
|
+
key = f"limits.{name}"
|
|
595
|
+
number = self.number(raw, key, integer=name != "git_seconds")
|
|
596
|
+
ceiling = getattr(_git.DEFAULT_LIMITS, name)
|
|
597
|
+
if number > ceiling:
|
|
598
|
+
if self.repo:
|
|
599
|
+
raise self.forbid(
|
|
600
|
+
key, f"raise limits ({_show(number)} > built-in {ceiling})", "limit-raised"
|
|
601
|
+
)
|
|
602
|
+
raise self.error(key, f"must be at most {ceiling}; limits can only be lowered")
|
|
603
|
+
result[name] = number
|
|
604
|
+
return result
|
|
605
|
+
|
|
606
|
+
def ai(self, value: object) -> dict[str, object]:
|
|
607
|
+
table = self.table(value, "ai", _AI_KEYS)
|
|
608
|
+
result: dict[str, object] = {}
|
|
609
|
+
for name, raw in table.items():
|
|
610
|
+
key = f"ai.{name}"
|
|
611
|
+
if name in _AI_FLAGS:
|
|
612
|
+
result[name] = self.flag(raw, key)
|
|
613
|
+
if self.repo and name == "enabled" and raw is True:
|
|
614
|
+
raise self.forbid(
|
|
615
|
+
key, "enable the AI pass; use --ai or user config", "ai-enable"
|
|
616
|
+
)
|
|
617
|
+
elif name == "provider":
|
|
618
|
+
result[name] = self.choice(raw, key, AI_PROVIDERS)
|
|
619
|
+
if self.repo and raw in NETWORK_PROVIDERS:
|
|
620
|
+
raise self.forbid(
|
|
621
|
+
key,
|
|
622
|
+
f"enable the network AI provider {raw!r}; use --ai or user config",
|
|
623
|
+
"ai-provider",
|
|
624
|
+
)
|
|
625
|
+
elif name == "base_url":
|
|
626
|
+
if self.repo:
|
|
627
|
+
raise self.forbid(
|
|
628
|
+
key, "set AI endpoints; use --ai-base-url or user config", "ai-endpoint"
|
|
629
|
+
)
|
|
630
|
+
result[name] = self.url(raw, key)
|
|
631
|
+
elif name == "model":
|
|
632
|
+
if self.repo:
|
|
633
|
+
raise self.forbid(
|
|
634
|
+
key, "choose the AI model; use --ai-model or user config", "ai-model"
|
|
635
|
+
)
|
|
636
|
+
model = self.text(raw, key)
|
|
637
|
+
if not _MODEL_ID.fullmatch(model):
|
|
638
|
+
raise self.error(key, f"is not a model ID: {_show(model)}")
|
|
639
|
+
result[name] = model
|
|
640
|
+
elif name == "effort":
|
|
641
|
+
effort = self.choice(raw, key, EFFORT_LEVELS)
|
|
642
|
+
default = _AI_DEFAULTS.effort
|
|
643
|
+
if self.repo and EFFORT_LEVELS.index(effort) > EFFORT_LEVELS.index(default):
|
|
644
|
+
raise self.forbid(
|
|
645
|
+
key, f"raise the AI effort above {default!r}", "budget-raised"
|
|
646
|
+
)
|
|
647
|
+
result[name] = effort
|
|
648
|
+
else:
|
|
649
|
+
number = self.number(raw, key, integer=name != "deadline_s")
|
|
650
|
+
default_value = getattr(_AI_DEFAULTS, name)
|
|
651
|
+
if self.repo and default_value is not None and number > default_value:
|
|
652
|
+
raise self.forbid(
|
|
653
|
+
key,
|
|
654
|
+
f"raise AI budgets ({_show(number)} > built-in {default_value})",
|
|
655
|
+
"budget-raised",
|
|
656
|
+
)
|
|
657
|
+
if name == "max_packets" and number > MAX_PACKETS_CEILING:
|
|
658
|
+
raise self.error(key, f"must be at most {MAX_PACKETS_CEILING}")
|
|
659
|
+
result[name] = number
|
|
660
|
+
return result
|
|
661
|
+
|
|
662
|
+
def url(self, value: object, key: str) -> str:
|
|
663
|
+
url = self.text(value, key)
|
|
664
|
+
if any(ord(c) <= 0x20 or ord(c) == 0x7F for c in url):
|
|
665
|
+
raise self.error(key, "must not contain spaces or control characters")
|
|
666
|
+
try:
|
|
667
|
+
parts = urlsplit(url)
|
|
668
|
+
except ValueError:
|
|
669
|
+
raise self.error(key, f"is not a URL: {_show(url)}") from None
|
|
670
|
+
if parts.scheme not in ("https", "http") or not parts.hostname:
|
|
671
|
+
raise self.error(key, f"must be an http(s) URL with a host, not {_show(url)}")
|
|
672
|
+
return url
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def parse_toml(data: bytes | str, source: str) -> dict[str, object]:
|
|
676
|
+
"""Decode (UTF-8, optional BOM) and parse one config file; problems raise ConfigError."""
|
|
677
|
+
raw = data.encode("utf-8", "surrogatepass") if isinstance(data, str) else data
|
|
678
|
+
if len(raw) > MAX_CONFIG_BYTES:
|
|
679
|
+
raise ConfigError(source, None, f"larger than {MAX_CONFIG_BYTES // 1024} KiB")
|
|
680
|
+
try:
|
|
681
|
+
text = raw.decode("utf-8")
|
|
682
|
+
except UnicodeDecodeError as exc:
|
|
683
|
+
raise ConfigError(source, None, f"not valid UTF-8 (byte {exc.start})") from None
|
|
684
|
+
try:
|
|
685
|
+
return tomllib.loads(text.removeprefix("\ufeff"))
|
|
686
|
+
except tomllib.TOMLDecodeError as exc:
|
|
687
|
+
raise ConfigError(source, None, f"invalid TOML: {_escape(str(exc))}") from None
|
|
688
|
+
except RecursionError:
|
|
689
|
+
raise ConfigError(source, None, "invalid TOML: nested too deeply") from None
|
|
690
|
+
except ValueError as exc: # e.g. an integer beyond Python's digit limit
|
|
691
|
+
problem = (
|
|
692
|
+
"an integer has too many digits"
|
|
693
|
+
if "integer string conversion" in str(exc)
|
|
694
|
+
else _escape(str(exc), 120)
|
|
695
|
+
)
|
|
696
|
+
raise ConfigError(source, None, f"invalid TOML: {problem}") from None
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def parse_layer(
|
|
700
|
+
data: Mapping[str, object], *, source: str, kind: LayerKind, registry: Registry
|
|
701
|
+
) -> Layer:
|
|
702
|
+
"""Validate one layer's parsed data (a TOML table or the CLI override mapping)."""
|
|
703
|
+
return _Parser(source, kind, registry).parse(data)
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
# --- the merged configuration -----------------------------------------------------
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
@dataclass(frozen=True, slots=True)
|
|
710
|
+
class AISettings:
|
|
711
|
+
"""Effective ``[ai]`` settings (SPEC 9.4-9.6); the defaults are the built-in layer.
|
|
712
|
+
|
|
713
|
+
The pass runs only when ``enabled`` is on and ``provider`` is not ``"none"``;
|
|
714
|
+
``None`` budgets are unlimited.
|
|
715
|
+
"""
|
|
716
|
+
|
|
717
|
+
enabled: bool = False
|
|
718
|
+
required: bool = False
|
|
719
|
+
blocking: bool = False
|
|
720
|
+
provider: str = "none"
|
|
721
|
+
model: str | None = None
|
|
722
|
+
effort: str = "high"
|
|
723
|
+
base_url: str | None = None
|
|
724
|
+
max_packets: int = 40
|
|
725
|
+
max_output_tokens: int = 32_000
|
|
726
|
+
max_total_input_tokens: int | None = None
|
|
727
|
+
max_total_output_tokens: int | None = None
|
|
728
|
+
deadline_s: float = 600.0
|
|
729
|
+
concurrency: int = 4
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
_AI_DEFAULTS = AISettings()
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def _lower(name: str, trusted: object, repo: object) -> object:
|
|
736
|
+
if repo is None:
|
|
737
|
+
return trusted
|
|
738
|
+
if trusted is None:
|
|
739
|
+
return repo
|
|
740
|
+
if name == "effort":
|
|
741
|
+
return min(trusted, repo, key=EFFORT_LEVELS.index) # type: ignore[call-overload]
|
|
742
|
+
return min(trusted, repo) # type: ignore[type-var]
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
class ConfigPolicy:
|
|
746
|
+
"""The engine's view of a :class:`Config`: implements SPEC 5.6 ``Policy``."""
|
|
747
|
+
|
|
748
|
+
__slots__ = ("_classes", "_enabled", "_ignores", "_severity", "allow_inline_ignores", "fail_on")
|
|
749
|
+
|
|
750
|
+
fail_on: FailOn
|
|
751
|
+
allow_inline_ignores: bool
|
|
752
|
+
|
|
753
|
+
def __init__(self, config: Config) -> None:
|
|
754
|
+
self.fail_on = config.fail_on
|
|
755
|
+
self.allow_inline_ignores = config.allow_inline_ignores
|
|
756
|
+
self._enabled = config.rules_enabled
|
|
757
|
+
self._severity = config.rules_severity
|
|
758
|
+
self._ignores = config.ignores
|
|
759
|
+
self._classes = tuple(
|
|
760
|
+
(name, tuple(compile_glob(p) for p in config.classes.get(name, ())))
|
|
761
|
+
for name in _CLASS_KEYS
|
|
762
|
+
)
|
|
763
|
+
|
|
764
|
+
def enabled(self, meta: RuleMeta) -> bool:
|
|
765
|
+
return self._enabled.get(meta.id, meta.default_enabled)
|
|
766
|
+
|
|
767
|
+
def severity(self, meta: RuleMeta) -> Severity:
|
|
768
|
+
return self._severity.get(meta.id, meta.severity)
|
|
769
|
+
|
|
770
|
+
def ignore_reason(self, rule_id: str, path: str) -> str | None:
|
|
771
|
+
for entry in self._ignores:
|
|
772
|
+
if entry.matches(rule_id, path):
|
|
773
|
+
return entry.reason
|
|
774
|
+
return None
|
|
775
|
+
|
|
776
|
+
def file_class(self, path: str) -> str | None:
|
|
777
|
+
for name, globs in self._classes:
|
|
778
|
+
if any(glob.match(path) for glob in globs):
|
|
779
|
+
return name
|
|
780
|
+
return None
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
@dataclass(frozen=True, slots=True)
|
|
784
|
+
class Config:
|
|
785
|
+
"""The merged configuration of one review."""
|
|
786
|
+
|
|
787
|
+
fail_on: FailOn
|
|
788
|
+
allow_inline_ignores: bool
|
|
789
|
+
rules_enabled: Mapping[str, bool]
|
|
790
|
+
rules_severity: Mapping[str, Severity]
|
|
791
|
+
ignores: tuple[Ignore, ...]
|
|
792
|
+
classes: Mapping[str, tuple[str, ...]]
|
|
793
|
+
limits: _git.Limits
|
|
794
|
+
ai: AISettings
|
|
795
|
+
config_notes: tuple[str, ...]
|
|
796
|
+
layers: tuple[Layer, ...]
|
|
797
|
+
|
|
798
|
+
def policy(self) -> ConfigPolicy:
|
|
799
|
+
return ConfigPolicy(self)
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def build_config(
|
|
803
|
+
layers: Iterable[Layer], registry: Registry, *, notes: Iterable[str] = ()
|
|
804
|
+
) -> Config:
|
|
805
|
+
"""Merge validated layers over the built-in defaults (SPEC 7.2, 6.3).
|
|
806
|
+
|
|
807
|
+
Layers are applied in precedence order (repository, user, file, CLI)
|
|
808
|
+
whatever order they are passed in; layers of one kind keep their order.
|
|
809
|
+
``notes`` are extra ``config_notes`` placed first (for example, that the
|
|
810
|
+
anchor holds no repository config).
|
|
811
|
+
"""
|
|
812
|
+
ordered = tuple(sorted(layers, key=lambda layer: _KIND_ORDER[layer.kind]))
|
|
813
|
+
fail_on: str = "error"
|
|
814
|
+
inline = False
|
|
815
|
+
enabled: dict[str, bool] = {}
|
|
816
|
+
severity: dict[str, Severity] = {}
|
|
817
|
+
ignores: list[Ignore] = []
|
|
818
|
+
classes: dict[str, tuple[str, ...]] = {}
|
|
819
|
+
limits: dict[str, dict[str, int | float]] = {"trusted": {}, "repository": {}}
|
|
820
|
+
budgets: dict[str, dict[str, object]] = {"trusted": {}, "repository": {}}
|
|
821
|
+
ai: dict[str, object] = {}
|
|
822
|
+
for layer in ordered:
|
|
823
|
+
side = "trusted" if layer.trusted else "repository"
|
|
824
|
+
if layer.fail_on is not None:
|
|
825
|
+
fail_on = layer.fail_on
|
|
826
|
+
if layer.allow_inline_ignores is not None:
|
|
827
|
+
inline = layer.allow_inline_ignores
|
|
828
|
+
enabled.update(dict.fromkeys(layer.enable, True))
|
|
829
|
+
enabled.update(dict.fromkeys(layer.disable, False))
|
|
830
|
+
severity.update(layer.severity)
|
|
831
|
+
ignores.extend(layer.ignores)
|
|
832
|
+
classes.update(layer.classes)
|
|
833
|
+
limits[side].update(layer.limits)
|
|
834
|
+
for name, value in layer.ai.items():
|
|
835
|
+
(budgets[side] if name in _AI_BUDGETS else ai)[name] = value
|
|
836
|
+
limit_values = {
|
|
837
|
+
name: _lower(
|
|
838
|
+
name,
|
|
839
|
+
limits["trusted"].get(name, getattr(_git.DEFAULT_LIMITS, name)),
|
|
840
|
+
limits["repository"].get(name),
|
|
841
|
+
)
|
|
842
|
+
for name in _LIMIT_KEYS
|
|
843
|
+
}
|
|
844
|
+
for name in _AI_BUDGETS:
|
|
845
|
+
ai[name] = _lower(
|
|
846
|
+
name,
|
|
847
|
+
budgets["trusted"].get(name, getattr(_AI_DEFAULTS, name)),
|
|
848
|
+
budgets["repository"].get(name),
|
|
849
|
+
)
|
|
850
|
+
rule_ids = tuple(sorted({entry.id for entry in registry.all()} | NON_WAIVABLE_RULES))
|
|
851
|
+
config_notes = list(notes)
|
|
852
|
+
for layer in ordered:
|
|
853
|
+
for i, entry in enumerate(layer.ignores):
|
|
854
|
+
covered = [r for r in rule_ids if _non_waivable(registry, r) and entry.covers(r)]
|
|
855
|
+
if covered:
|
|
856
|
+
paths = ", ".join(_escape(p, 120) for p in entry.paths)
|
|
857
|
+
config_notes.append(
|
|
858
|
+
f"{layer.source}: ignore[{i}] ignores non-waivable "
|
|
859
|
+
f"{', '.join(covered)} in {paths} ({_escape(entry.reason, 520)})"
|
|
860
|
+
)
|
|
861
|
+
return Config(
|
|
862
|
+
fail_on=fail_on, # type: ignore[arg-type]
|
|
863
|
+
allow_inline_ignores=inline,
|
|
864
|
+
rules_enabled=MappingProxyType(enabled),
|
|
865
|
+
rules_severity=MappingProxyType(severity),
|
|
866
|
+
ignores=tuple(ignores),
|
|
867
|
+
classes=MappingProxyType(classes),
|
|
868
|
+
limits=_git.Limits(**limit_values), # type: ignore[arg-type]
|
|
869
|
+
ai=AISettings(**ai), # type: ignore[arg-type]
|
|
870
|
+
config_notes=tuple(config_notes),
|
|
871
|
+
layers=ordered,
|
|
872
|
+
)
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
# --- sources ---------------------------------------------------------------------
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def user_config_path(
|
|
879
|
+
environ: Mapping[str, str] | None = None, platform: str | None = None
|
|
880
|
+
) -> Path | None:
|
|
881
|
+
"""Where the user config lives; ``None`` when no home directory is known.
|
|
882
|
+
|
|
883
|
+
Windows: ``%APPDATA%\\codeveto\\config.toml``; elsewhere
|
|
884
|
+
``$XDG_CONFIG_HOME/codeveto/config.toml``. A missing or relative variable
|
|
885
|
+
falls back to ``~/.config/codeveto/config.toml`` (``HOME``, or
|
|
886
|
+
``USERPROFILE`` on Windows).
|
|
887
|
+
"""
|
|
888
|
+
env = os.environ if environ is None else environ
|
|
889
|
+
windows = (sys.platform if platform is None else platform) == "win32"
|
|
890
|
+
flavour = PureWindowsPath if windows else PurePosixPath
|
|
891
|
+
base = env.get("APPDATA" if windows else "XDG_CONFIG_HOME", "")
|
|
892
|
+
if base and flavour(base).is_absolute():
|
|
893
|
+
return Path(base) / "codeveto" / "config.toml"
|
|
894
|
+
home = env.get("USERPROFILE" if windows else "HOME", "")
|
|
895
|
+
if home and flavour(home).is_absolute():
|
|
896
|
+
return Path(home) / ".config" / "codeveto" / "config.toml"
|
|
897
|
+
return None
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def _read_file(path: Path, source: str, *, required: bool) -> bytes | None:
|
|
901
|
+
"""Read a local config file: regular files only, never blocking, capped."""
|
|
902
|
+
flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
|
|
903
|
+
try:
|
|
904
|
+
fd = os.open(path, flags | getattr(os, "O_CLOEXEC", 0))
|
|
905
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
906
|
+
if required:
|
|
907
|
+
raise ConfigError(source, None, "file not found") from None
|
|
908
|
+
return None
|
|
909
|
+
except OSError as exc:
|
|
910
|
+
# Windows does not open a directory as a file (PermissionError).
|
|
911
|
+
if os.path.isdir(path):
|
|
912
|
+
raise ConfigError(source, None, "not a regular file") from None
|
|
913
|
+
raise ConfigError(source, None, f"cannot be read ({type(exc).__name__})") from None
|
|
914
|
+
try:
|
|
915
|
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
916
|
+
raise ConfigError(source, None, "not a regular file")
|
|
917
|
+
chunks: list[bytes] = []
|
|
918
|
+
size = 0
|
|
919
|
+
while size <= MAX_CONFIG_BYTES:
|
|
920
|
+
chunk = os.read(fd, MAX_CONFIG_BYTES + 1 - size)
|
|
921
|
+
if not chunk:
|
|
922
|
+
break
|
|
923
|
+
chunks.append(chunk)
|
|
924
|
+
size += len(chunk)
|
|
925
|
+
except OSError as exc:
|
|
926
|
+
raise ConfigError(source, None, f"cannot be read ({type(exc).__name__})") from None
|
|
927
|
+
finally:
|
|
928
|
+
os.close(fd)
|
|
929
|
+
return b"".join(chunks)
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def _repository_layer(
|
|
933
|
+
repo: str | os.PathLike[str], anchor: str, registry: Registry
|
|
934
|
+
) -> tuple[Layer | None, str | None]:
|
|
935
|
+
"""The anchor's repository layer (or ``None``) and a config note, if any."""
|
|
936
|
+
if not isinstance(anchor, str) or not _OID.fullmatch(anchor):
|
|
937
|
+
raise ConfigError("repository config", None, "the anchor must be a full commit object ID")
|
|
938
|
+
source = f"repository config ({REPO_CONFIG_NAME} at anchor {anchor[:12]})"
|
|
939
|
+
try:
|
|
940
|
+
raw = _git.read_anchor_file(repo, anchor, REPO_CONFIG_NAME, cap=MAX_CONFIG_BYTES)
|
|
941
|
+
except _git.GitError as exc:
|
|
942
|
+
problem = {
|
|
943
|
+
"output-cap": f"larger than {MAX_CONFIG_BYTES // 1024} KiB",
|
|
944
|
+
"not-regular": "not a regular file at the anchor",
|
|
945
|
+
}.get(exc.reason, f"cannot be read from the anchor ({exc})")
|
|
946
|
+
raise ConfigError(source, None, problem) from None
|
|
947
|
+
if raw is None:
|
|
948
|
+
if anchor in _git.EMPTY_TREE.values():
|
|
949
|
+
return None, (
|
|
950
|
+
f"{source}: the anchor is the empty tree (a root commit), "
|
|
951
|
+
"so no repository config exists at the anchor"
|
|
952
|
+
)
|
|
953
|
+
return None, None
|
|
954
|
+
layer = parse_layer(
|
|
955
|
+
parse_toml(raw, source), source=source, kind="repository", registry=registry
|
|
956
|
+
)
|
|
957
|
+
return layer, None
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
class _RepositoryGuard:
|
|
961
|
+
"""Refuses local config files the change under review could have written (SPEC 7.2)."""
|
|
962
|
+
|
|
963
|
+
def __init__(self, repo: str | os.PathLike[str] | None) -> None:
|
|
964
|
+
self.repo = repo
|
|
965
|
+
self._identities: frozenset[tuple[int, int]] | None = None
|
|
966
|
+
|
|
967
|
+
def check(self, path: Path, source: str) -> None:
|
|
968
|
+
if self.repo is None:
|
|
969
|
+
return
|
|
970
|
+
if self._identities is None:
|
|
971
|
+
try:
|
|
972
|
+
self._identities = _git.repository_identities(self.repo)
|
|
973
|
+
except _git.GitError as exc:
|
|
974
|
+
raise ConfigError(
|
|
975
|
+
source, None, f"cannot locate the reviewed repository to check it ({exc})"
|
|
976
|
+
) from None
|
|
977
|
+
if _git._inside(path, set(self._identities)):
|
|
978
|
+
raise ConfigError(
|
|
979
|
+
source,
|
|
980
|
+
None,
|
|
981
|
+
"lies inside the reviewed repository's working tree or Git directory, "
|
|
982
|
+
"where the change under review could have written it",
|
|
983
|
+
)
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
def load_config(
|
|
987
|
+
registry: Registry,
|
|
988
|
+
*,
|
|
989
|
+
repo: str | os.PathLike[str] | None = None,
|
|
990
|
+
anchor: str | None = None,
|
|
991
|
+
no_repo_config: bool = False,
|
|
992
|
+
user_config: bool | str | os.PathLike[str] = True,
|
|
993
|
+
config_file: str | os.PathLike[str] | None = None,
|
|
994
|
+
cli: Mapping[str, object] | None = None,
|
|
995
|
+
environ: Mapping[str, str] | None = None,
|
|
996
|
+
platform: str | None = None,
|
|
997
|
+
) -> Config:
|
|
998
|
+
"""Load, validate and merge every layer (SPEC 7.2); any problem raises ConfigError.
|
|
999
|
+
|
|
1000
|
+
The repository layer is read from ``repo`` at ``anchor`` (a full commit
|
|
1001
|
+
OID, or the empty tree OID of a root commit) unless ``no_repo_config``;
|
|
1002
|
+
pass neither for a review-less command (with ``no_repo_config``, ``repo``
|
|
1003
|
+
alone still guards the local files). ``user_config`` is ``True`` to use
|
|
1004
|
+
:func:`user_config_path`, ``False`` to skip it, or a path; a missing user
|
|
1005
|
+
config is fine, a missing ``config_file`` is not. An existing user config
|
|
1006
|
+
or a ``config_file`` inside ``repo``'s working tree or Git directory is
|
|
1007
|
+
refused. ``cli`` holds the command-line overrides in file schema.
|
|
1008
|
+
"""
|
|
1009
|
+
layers: list[Layer] = []
|
|
1010
|
+
notes: list[str] = []
|
|
1011
|
+
if anchor is not None and repo is None:
|
|
1012
|
+
raise ValueError("the repository layer needs both repo and anchor")
|
|
1013
|
+
if not no_repo_config and repo is not None:
|
|
1014
|
+
if anchor is None:
|
|
1015
|
+
raise ValueError("the repository layer needs both repo and anchor")
|
|
1016
|
+
layer, note = _repository_layer(repo, anchor, registry)
|
|
1017
|
+
if layer is not None:
|
|
1018
|
+
layers.append(layer)
|
|
1019
|
+
if note is not None:
|
|
1020
|
+
notes.append(note)
|
|
1021
|
+
guard = _RepositoryGuard(repo)
|
|
1022
|
+
if user_config is True:
|
|
1023
|
+
user_path = user_config_path(environ, platform)
|
|
1024
|
+
elif user_config is False:
|
|
1025
|
+
user_path = None
|
|
1026
|
+
else:
|
|
1027
|
+
user_path = Path(user_config)
|
|
1028
|
+
if user_path is not None:
|
|
1029
|
+
source = f"user config ({user_path})"
|
|
1030
|
+
if os.path.lexists(user_path):
|
|
1031
|
+
guard.check(user_path, source)
|
|
1032
|
+
raw = _read_file(user_path, source, required=False)
|
|
1033
|
+
if raw is not None:
|
|
1034
|
+
layers.append(
|
|
1035
|
+
parse_layer(parse_toml(raw, source), source=source, kind="user", registry=registry)
|
|
1036
|
+
)
|
|
1037
|
+
if config_file is not None:
|
|
1038
|
+
source = f"--config {os.fspath(config_file)}"
|
|
1039
|
+
guard.check(Path(config_file), source)
|
|
1040
|
+
raw = _read_file(Path(config_file), source, required=True) or b""
|
|
1041
|
+
layers.append(
|
|
1042
|
+
parse_layer(parse_toml(raw, source), source=source, kind="file", registry=registry)
|
|
1043
|
+
)
|
|
1044
|
+
if cli:
|
|
1045
|
+
layers.append(parse_layer(cli, source="command line", kind="cli", registry=registry))
|
|
1046
|
+
return build_config(layers, registry, notes=notes)
|
|
1047
|
+
|
|
1048
|
+
|
|
1049
|
+
# --- weakened-config comparison -------------------------------------------------------
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
@dataclass(frozen=True, slots=True)
|
|
1053
|
+
class Weakening:
|
|
1054
|
+
"""One way a changed repository config is less strict than the anchor's (SPEC 7.2).
|
|
1055
|
+
|
|
1056
|
+
``kind`` is one of ``invalid``, ``rule-disabled``, ``severity-lowered``,
|
|
1057
|
+
``ignore-added``, ``ignore-widened-rules``, ``ignore-widened-paths``,
|
|
1058
|
+
``fail-on-raised``, ``ai-blocking-off``, ``ai-required-off``,
|
|
1059
|
+
``ai-disabled``, ``ai-budget-lowered``, ``ai-budget-removed``,
|
|
1060
|
+
``limit-raised`` and ``limit-removed``; ``key`` is the key path in the new
|
|
1061
|
+
config (``""`` for the whole file).
|
|
1062
|
+
"""
|
|
1063
|
+
|
|
1064
|
+
kind: str
|
|
1065
|
+
key: str
|
|
1066
|
+
detail: str
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
_META = frozenset("*?[\\")
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def _glob_within(inner: str, outer: str) -> bool:
|
|
1073
|
+
"""Conservatively, whether every path ``inner`` matches is matched by ``outer``."""
|
|
1074
|
+
if inner == outer:
|
|
1075
|
+
return True
|
|
1076
|
+
if not _META & set(inner) and not inner.endswith("/"):
|
|
1077
|
+
# A literal pattern matches exactly one path.
|
|
1078
|
+
return compile_glob(outer).match(inner)
|
|
1079
|
+
for suffix in ("/**", "/"):
|
|
1080
|
+
prefix = outer.removesuffix(suffix)
|
|
1081
|
+
if prefix == outer or not prefix or _META & set(prefix):
|
|
1082
|
+
continue
|
|
1083
|
+
if inner.startswith(prefix + "/") and len(inner) > len(prefix) + 1:
|
|
1084
|
+
return True
|
|
1085
|
+
if suffix == "/" and inner == prefix:
|
|
1086
|
+
return True
|
|
1087
|
+
return False
|
|
1088
|
+
|
|
1089
|
+
|
|
1090
|
+
def _repo_text_layer(text: bytes | str | None, source: str, registry: Registry) -> Layer:
|
|
1091
|
+
if text is None:
|
|
1092
|
+
return Layer(source=source, kind="repository")
|
|
1093
|
+
return parse_layer(
|
|
1094
|
+
parse_toml(text, source), source=source, kind="repository", registry=registry
|
|
1095
|
+
)
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
def _listed(rule_ids: Sequence[str]) -> str:
|
|
1099
|
+
shown = ", ".join(rule_ids[:5])
|
|
1100
|
+
return shown if len(rule_ids) <= 5 else f"{shown} and {len(rule_ids) - 5} more"
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
def _budget_rank(name: str, value: object) -> float:
|
|
1104
|
+
if value is None:
|
|
1105
|
+
return math.inf # unlimited
|
|
1106
|
+
if name == "effort":
|
|
1107
|
+
return float(EFFORT_LEVELS.index(value)) # type: ignore[arg-type]
|
|
1108
|
+
return float(value) # type: ignore[arg-type]
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
def weakened(
|
|
1112
|
+
anchor_cfg_text: bytes | str | None, new_cfg_text: bytes | str | None, registry: Registry
|
|
1113
|
+
) -> list[Weakening]:
|
|
1114
|
+
"""Every way ``new_cfg_text`` is less strict than ``anchor_cfg_text`` (SPEC 7.2).
|
|
1115
|
+
|
|
1116
|
+
Both are repository configs (``None``: no file). A new config that fails to
|
|
1117
|
+
parse or breaks a repository restriction is one ``invalid`` weakening and
|
|
1118
|
+
never an exception; an anchor config that fails to parse is compared as if
|
|
1119
|
+
absent. Reordering keys, entries or list items, rewording reasons and
|
|
1120
|
+
narrowing ignores are not weakenings.
|
|
1121
|
+
"""
|
|
1122
|
+
try:
|
|
1123
|
+
old = _repo_text_layer(anchor_cfg_text, "anchor .codeveto.toml", registry)
|
|
1124
|
+
except Exception: # an unreadable anchor config is reported by the review itself
|
|
1125
|
+
old = Layer(source="anchor .codeveto.toml", kind="repository")
|
|
1126
|
+
try:
|
|
1127
|
+
new = _repo_text_layer(new_cfg_text, "changed .codeveto.toml", registry)
|
|
1128
|
+
except ConfigError as exc:
|
|
1129
|
+
return [Weakening("invalid", exc.key or "", str(exc))]
|
|
1130
|
+
except Exception as exc:
|
|
1131
|
+
problem = f"changed .codeveto.toml: cannot be parsed ({type(exc).__name__})"
|
|
1132
|
+
return [Weakening("invalid", "", problem)]
|
|
1133
|
+
found: list[Weakening] = []
|
|
1134
|
+
|
|
1135
|
+
def on(layer: Layer, meta: RuleMeta) -> bool:
|
|
1136
|
+
if meta.id in layer.disable:
|
|
1137
|
+
return False
|
|
1138
|
+
return meta.id in layer.enable or meta.default_enabled
|
|
1139
|
+
|
|
1140
|
+
metas = [entry.meta for entry in registry.all()]
|
|
1141
|
+
for meta in metas:
|
|
1142
|
+
was, now = on(old, meta), on(new, meta)
|
|
1143
|
+
if was and not now:
|
|
1144
|
+
key = (
|
|
1145
|
+
f"rules.disable[{new.disable.index(meta.id)}]"
|
|
1146
|
+
if meta.id in new.disable
|
|
1147
|
+
else "rules.enable"
|
|
1148
|
+
)
|
|
1149
|
+
found.append(Weakening("rule-disabled", key, f"{meta.id} is no longer enabled"))
|
|
1150
|
+
elif was and now:
|
|
1151
|
+
before = old.severity.get(meta.id, meta.severity)
|
|
1152
|
+
after = new.severity.get(meta.id, meta.severity)
|
|
1153
|
+
if after < before:
|
|
1154
|
+
key = (
|
|
1155
|
+
_join("rules.severity", meta.id)
|
|
1156
|
+
if meta.id in new.severity
|
|
1157
|
+
else "rules.severity"
|
|
1158
|
+
)
|
|
1159
|
+
found.append(
|
|
1160
|
+
Weakening(
|
|
1161
|
+
"severity-lowered",
|
|
1162
|
+
key,
|
|
1163
|
+
f"{meta.id} lowered from {before.value} to {after.value}",
|
|
1164
|
+
)
|
|
1165
|
+
)
|
|
1166
|
+
enabled_before = {meta.id for meta in metas if on(old, meta)}
|
|
1167
|
+
known = sorted({meta.id for meta in metas} | NON_WAIVABLE_RULES)
|
|
1168
|
+
for i, entry in enumerate(new.ignores):
|
|
1169
|
+
covered = [
|
|
1170
|
+
r for r in known if entry.covers(r) and (r in enabled_before or r not in registry)
|
|
1171
|
+
]
|
|
1172
|
+
for j, pattern in enumerate(entry.paths):
|
|
1173
|
+
uncovered = [
|
|
1174
|
+
r
|
|
1175
|
+
for r in covered
|
|
1176
|
+
if not any(
|
|
1177
|
+
o.covers(r) and any(_glob_within(pattern, p) for p in o.paths)
|
|
1178
|
+
for o in old.ignores
|
|
1179
|
+
)
|
|
1180
|
+
]
|
|
1181
|
+
if not uncovered:
|
|
1182
|
+
continue
|
|
1183
|
+
if any(any(_glob_within(pattern, p) for p in o.paths) for o in old.ignores):
|
|
1184
|
+
kind, what = "ignore-widened-rules", "now also ignores"
|
|
1185
|
+
elif any(o.covers(r) for o in old.ignores for r in uncovered):
|
|
1186
|
+
kind, what = "ignore-widened-paths", "widened to a new path for"
|
|
1187
|
+
else:
|
|
1188
|
+
kind, what = "ignore-added", "newly ignores"
|
|
1189
|
+
detail = f"{_escape(pattern, 120)}: {what} {_listed(uncovered)}"
|
|
1190
|
+
found.append(Weakening(kind, f"ignore[{i}].paths[{j}]", detail))
|
|
1191
|
+
before_fail, after_fail = old.fail_on or "error", new.fail_on or "error"
|
|
1192
|
+
if FAIL_ON_LEVELS.index(after_fail) > FAIL_ON_LEVELS.index(before_fail):
|
|
1193
|
+
found.append(
|
|
1194
|
+
Weakening(
|
|
1195
|
+
"fail-on-raised", "fail_on", f"fail_on raised from {before_fail} to {after_fail}"
|
|
1196
|
+
)
|
|
1197
|
+
)
|
|
1198
|
+
for name, kind in (("blocking", "ai-blocking-off"), ("required", "ai-required-off")):
|
|
1199
|
+
if old.ai.get(name) is True and new.ai.get(name) is not True:
|
|
1200
|
+
found.append(Weakening(kind, f"ai.{name}", f"ai.{name} is no longer true"))
|
|
1201
|
+
|
|
1202
|
+
def ai_off(layer: Layer) -> str | None:
|
|
1203
|
+
if layer.ai.get("enabled") is False:
|
|
1204
|
+
return "ai.enabled"
|
|
1205
|
+
return "ai.provider" if layer.ai.get("provider") == "none" else None
|
|
1206
|
+
|
|
1207
|
+
switched = ai_off(new)
|
|
1208
|
+
if switched and not ai_off(old):
|
|
1209
|
+
found.append(Weakening("ai-disabled", switched, "the AI pass is turned off"))
|
|
1210
|
+
for name in _AI_BUDGETS:
|
|
1211
|
+
key = f"ai.{name}"
|
|
1212
|
+
default = getattr(_AI_DEFAULTS, name)
|
|
1213
|
+
before_budget, after_budget = old.ai.get(name, default), new.ai.get(name, default)
|
|
1214
|
+
if name in old.ai and name not in new.ai:
|
|
1215
|
+
detail = f"{key} = {before_budget} removed"
|
|
1216
|
+
found.append(Weakening("ai-budget-removed", key, detail))
|
|
1217
|
+
elif _budget_rank(name, after_budget) < _budget_rank(name, before_budget):
|
|
1218
|
+
detail = f"{key} lowered from {before_budget} to {after_budget}"
|
|
1219
|
+
found.append(Weakening("ai-budget-lowered", key, detail))
|
|
1220
|
+
for name in _LIMIT_KEYS:
|
|
1221
|
+
key = f"limits.{name}"
|
|
1222
|
+
default = getattr(_git.DEFAULT_LIMITS, name)
|
|
1223
|
+
before_limit, after_limit = old.limits.get(name, default), new.limits.get(name, default)
|
|
1224
|
+
if name in old.limits and name not in new.limits:
|
|
1225
|
+
found.append(Weakening("limit-removed", key, f"{key} = {before_limit} removed"))
|
|
1226
|
+
elif after_limit > before_limit:
|
|
1227
|
+
detail = f"{key} raised from {before_limit} to {after_limit}"
|
|
1228
|
+
found.append(Weakening("limit-raised", key, detail))
|
|
1229
|
+
return found
|