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
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""The MCP server's door to the harness AI layer (SPEC 9.4 harness, 10.1).
|
|
2
|
+
|
|
3
|
+
``get_ai_packets`` and ``submit_ai_review`` call
|
|
4
|
+
``codeveto.ai.harness.build_packets`` and ``verify_responses`` through this
|
|
5
|
+
module only, so the server does not depend on the AI layer's internals and
|
|
6
|
+
works in a build without it: when ``codeveto.ai.harness`` (or one of the two
|
|
7
|
+
functions) cannot be imported, :class:`AIUnavailable` carries
|
|
8
|
+
:data:`AI_UNAVAILABLE` and the tool answers with that error.
|
|
9
|
+
|
|
10
|
+
Both functions receive the revision bound at server launch as keyword
|
|
11
|
+
arguments (see :meth:`codeveto.integrations.mcp.Binding.revision`), never
|
|
12
|
+
anything taken from a tool call except the responses document itself.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import importlib
|
|
18
|
+
from collections.abc import Callable, Mapping
|
|
19
|
+
from types import ModuleType
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
__all__ = ["AI_UNAVAILABLE", "AIUnavailable", "build_packets", "verify_responses"]
|
|
23
|
+
|
|
24
|
+
AI_UNAVAILABLE = "AI layer not available in this build"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AIUnavailable(Exception):
|
|
28
|
+
"""The harness AI layer is not part of this build."""
|
|
29
|
+
|
|
30
|
+
def __init__(self) -> None:
|
|
31
|
+
super().__init__(AI_UNAVAILABLE)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _harness() -> ModuleType:
|
|
35
|
+
try:
|
|
36
|
+
return importlib.import_module("codeveto.ai.harness")
|
|
37
|
+
except ImportError as exc:
|
|
38
|
+
raise AIUnavailable() from exc
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _function(name: str) -> Callable[..., Any]:
|
|
42
|
+
function = getattr(_harness(), name, None)
|
|
43
|
+
if not callable(function):
|
|
44
|
+
raise AIUnavailable()
|
|
45
|
+
return function # type: ignore[no-any-return]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _harness_kwargs(revision: Mapping[str, Any]) -> dict[str, Any]:
|
|
49
|
+
"""The server's bound revision as ``codeveto.ai.harness`` keyword arguments.
|
|
50
|
+
|
|
51
|
+
The harness selects the mode like ``codeveto review`` does: ``base``/``head``
|
|
52
|
+
for a range, ``commit`` for one commit, ``staged=True`` for the index, and
|
|
53
|
+
none of them for the working tree.
|
|
54
|
+
"""
|
|
55
|
+
mode = revision.get("mode")
|
|
56
|
+
kwargs: dict[str, Any] = {"anchor": revision.get("anchor")}
|
|
57
|
+
if mode == "range":
|
|
58
|
+
kwargs.update(
|
|
59
|
+
base=revision.get("base"),
|
|
60
|
+
head=revision.get("head"),
|
|
61
|
+
comparison=revision.get("comparison"),
|
|
62
|
+
)
|
|
63
|
+
elif mode == "commit":
|
|
64
|
+
kwargs["commit"] = revision.get("commit")
|
|
65
|
+
elif mode == "staged":
|
|
66
|
+
kwargs["staged"] = True
|
|
67
|
+
return kwargs
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def build_packets(revision: Mapping[str, Any]) -> Any:
|
|
71
|
+
"""Packets for the bound revision (harness step 1)."""
|
|
72
|
+
return _function("build_packets")(revision["repo"], **_harness_kwargs(revision))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def verify_responses(revision: Mapping[str, Any], responses: Mapping[str, Any]) -> Any:
|
|
76
|
+
"""Verify the harness's responses against freshly built packets (harness step 2)."""
|
|
77
|
+
return _function("verify_responses")(revision["repo"], responses, **_harness_kwargs(revision))
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""The pre-push hook (SPEC 10.2): review every update Git is about to push.
|
|
2
|
+
|
|
3
|
+
Run by the installed hook as ``<python> -I -m codeveto.integrations.prepush
|
|
4
|
+
<remote name> <remote URL>`` with Git's records on stdin, one per line:
|
|
5
|
+
``<local ref> <local oid> <remote ref> <remote oid>``. The whole input is
|
|
6
|
+
read (at most :data:`MAX_INPUT` bytes and :data:`MAX_UPDATES` records) and
|
|
7
|
+
validated before anything is reviewed, as in the legacy ``pre_push.py``:
|
|
8
|
+
four space-separated fields, a well-formed remote ref, full lower-case object
|
|
9
|
+
IDs of one width, a deletion exactly when the local side is ``(delete)``, and
|
|
10
|
+
no remote ref twice. Any problem ends the hook with exit 2 (incomplete).
|
|
11
|
+
|
|
12
|
+
For each update of a branch or tag (other refs, such as notes, are skipped
|
|
13
|
+
with a message; deletions are not reviewed):
|
|
14
|
+
|
|
15
|
+
- an existing remote ref: ``codeveto review --base <remote oid> --head <local
|
|
16
|
+
oid> --comparison direct --anchor <remote oid>``;
|
|
17
|
+
- a new remote ref: the same with the unique merge base of the local commit
|
|
18
|
+
and ``refs/remotes/<remote>/HEAD`` as base and anchor; without one (no such
|
|
19
|
+
ref, a URL instead of a remote name, no unique merge base) that update is
|
|
20
|
+
incomplete (exit 2).
|
|
21
|
+
|
|
22
|
+
Every update is reviewed even after one is vetoed; the exit code is the worst
|
|
23
|
+
of them (0 clear, 1 vetoed, 2 incomplete). Review output goes to stderr.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import subprocess
|
|
32
|
+
import sys
|
|
33
|
+
import time
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
from typing import BinaryIO
|
|
36
|
+
|
|
37
|
+
from codeveto import engine
|
|
38
|
+
from codeveto import git as gitmod
|
|
39
|
+
from codeveto.git import DEFAULT_LIMITS, GitError
|
|
40
|
+
|
|
41
|
+
__all__ = ["MAX_INPUT", "MAX_UPDATES", "TOTAL_SECONDS", "Update", "main", "parse", "valid_ref"]
|
|
42
|
+
|
|
43
|
+
OID = re.compile(rb"[0-9a-f]{40}|[0-9a-f]{64}")
|
|
44
|
+
MAX_INPUT = 128 * 1024
|
|
45
|
+
MAX_UPDATES = 256
|
|
46
|
+
TOTAL_SECONDS = 900.0
|
|
47
|
+
_PREFIX = "codeveto pre-push"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class Update:
|
|
52
|
+
"""One validated pre-push record."""
|
|
53
|
+
|
|
54
|
+
remote_ref: bytes
|
|
55
|
+
local_oid: str
|
|
56
|
+
remote_oid: str
|
|
57
|
+
deleted: bool
|
|
58
|
+
created: bool
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def valid_ref(ref: bytes) -> bool:
|
|
62
|
+
"""A full ref name Git would accept (the legacy check, kept byte for byte)."""
|
|
63
|
+
return (
|
|
64
|
+
ref.startswith(b"refs/")
|
|
65
|
+
and not ref.endswith(b".")
|
|
66
|
+
and not any(b in ref for b in (b"..", b"@{"))
|
|
67
|
+
and not any(c <= 32 or c == 127 or c in b"~^:?*[\\" for c in ref)
|
|
68
|
+
and all(
|
|
69
|
+
part and not part.startswith(b".") and not part.endswith(b".lock")
|
|
70
|
+
for part in ref.split(b"/")
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse(stream: BinaryIO) -> list[Update]:
|
|
76
|
+
"""Read and validate every record on ``stream``; raise ``ValueError`` on any problem."""
|
|
77
|
+
data = stream.read(MAX_INPUT + 1)
|
|
78
|
+
if len(data) > MAX_INPUT:
|
|
79
|
+
raise ValueError("pre-push input exceeds the byte limit")
|
|
80
|
+
if not data:
|
|
81
|
+
return []
|
|
82
|
+
if not data.endswith(b"\n"):
|
|
83
|
+
raise ValueError("incomplete pre-push record")
|
|
84
|
+
lines = data[:-1].split(b"\n")
|
|
85
|
+
if len(lines) > MAX_UPDATES:
|
|
86
|
+
raise ValueError("pre-push input exceeds the ref limit")
|
|
87
|
+
parsed: list[Update] = []
|
|
88
|
+
seen: set[bytes] = set()
|
|
89
|
+
width: int | None = None
|
|
90
|
+
for n, row in enumerate(lines, 1):
|
|
91
|
+
fields = row.removesuffix(b"\r").split(b" ")
|
|
92
|
+
if len(fields) != 4:
|
|
93
|
+
raise ValueError(f"invalid pre-push record {n}")
|
|
94
|
+
source, new, target, old = fields
|
|
95
|
+
if (
|
|
96
|
+
not source
|
|
97
|
+
or any(c <= 32 or c == 127 for c in source)
|
|
98
|
+
or not valid_ref(target)
|
|
99
|
+
or not OID.fullmatch(new)
|
|
100
|
+
or not OID.fullmatch(old)
|
|
101
|
+
or len(new) != len(old)
|
|
102
|
+
or (width is not None and len(new) != width)
|
|
103
|
+
):
|
|
104
|
+
raise ValueError(f"invalid ref or object ID in record {n}")
|
|
105
|
+
deleted = new == b"0" * len(new)
|
|
106
|
+
created = old == b"0" * len(old)
|
|
107
|
+
if deleted != (source == b"(delete)") or (deleted and created):
|
|
108
|
+
raise ValueError(f"inconsistent pre-push object IDs in record {n}")
|
|
109
|
+
if target in seen:
|
|
110
|
+
raise ValueError(f"duplicate remote ref in record {n}")
|
|
111
|
+
seen.add(target)
|
|
112
|
+
width = len(new)
|
|
113
|
+
parsed.append(Update(target, new.decode("ascii"), old.decode("ascii"), deleted, created))
|
|
114
|
+
return parsed
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _display(raw: bytes) -> str:
|
|
118
|
+
return json.dumps(raw.decode("utf-8", "backslashreplace"), ensure_ascii=True)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _say(message: str) -> None:
|
|
122
|
+
print(f"{_PREFIX}: {message}", file=sys.stderr, flush=True)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _new_branch_base(remote: str, local: str) -> str | None:
|
|
126
|
+
"""The unique merge base of ``local`` and ``refs/remotes/<remote>/HEAD``, if any."""
|
|
127
|
+
ref = f"refs/remotes/{remote}/HEAD"
|
|
128
|
+
if not remote or not valid_ref(os.fsencode(ref)) or not remote.isascii():
|
|
129
|
+
return None
|
|
130
|
+
try:
|
|
131
|
+
with gitmod._session(".", DEFAULT_LIMITS) as git:
|
|
132
|
+
head = git.resolve(ref)
|
|
133
|
+
commit = git.resolve(local)
|
|
134
|
+
bases = git.merge_bases(commit, head)
|
|
135
|
+
if len(bases) != 1:
|
|
136
|
+
return None
|
|
137
|
+
git.commit(bases[0]) # hash-verified
|
|
138
|
+
return bases[0]
|
|
139
|
+
except GitError:
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _review(base: str, head: str, timeout: float) -> int:
|
|
144
|
+
argv = [
|
|
145
|
+
sys.executable,
|
|
146
|
+
"-I",
|
|
147
|
+
"-m",
|
|
148
|
+
"codeveto",
|
|
149
|
+
"review",
|
|
150
|
+
f"--base={base}",
|
|
151
|
+
f"--head={head}",
|
|
152
|
+
"--comparison=direct",
|
|
153
|
+
f"--anchor={base}",
|
|
154
|
+
"--ai=none",
|
|
155
|
+
]
|
|
156
|
+
try:
|
|
157
|
+
# Fixed argv: this interpreter, codeveto and validated object IDs.
|
|
158
|
+
done = subprocess.run( # noqa: S603
|
|
159
|
+
argv, stdin=subprocess.DEVNULL, stdout=sys.stderr, timeout=timeout, check=False
|
|
160
|
+
)
|
|
161
|
+
except subprocess.TimeoutExpired:
|
|
162
|
+
_say("the review exceeded its time limit; incomplete")
|
|
163
|
+
return 2
|
|
164
|
+
return done.returncode if done.returncode in (0, 1) else 2
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def run(remote: str, updates: list[Update]) -> int:
|
|
168
|
+
"""Review each update; return the worst exit code."""
|
|
169
|
+
deadline = time.monotonic() + TOTAL_SECONDS
|
|
170
|
+
per_review = engine.hard_deadline_s() + DEFAULT_LIMITS.git_seconds + 30.0
|
|
171
|
+
result = 0
|
|
172
|
+
for update in updates:
|
|
173
|
+
ref = update.remote_ref
|
|
174
|
+
if update.deleted:
|
|
175
|
+
_say(f"skip deletion of {_display(ref)}")
|
|
176
|
+
continue
|
|
177
|
+
if not ref.startswith((b"refs/heads/", b"refs/tags/")):
|
|
178
|
+
_say(f"skip non-branch ref {_display(ref)}")
|
|
179
|
+
continue
|
|
180
|
+
if update.created:
|
|
181
|
+
base = _new_branch_base(remote, update.local_oid)
|
|
182
|
+
if base is None:
|
|
183
|
+
_say(
|
|
184
|
+
f"new ref {_display(ref)}: no unique merge base with the HEAD of remote "
|
|
185
|
+
f"{_display(os.fsencode(remote))}; incomplete (run git remote set-head "
|
|
186
|
+
"<remote> --auto, or review it with codeveto review --base)"
|
|
187
|
+
)
|
|
188
|
+
result = 2
|
|
189
|
+
continue
|
|
190
|
+
how = "new, from its merge base with the remote HEAD"
|
|
191
|
+
else:
|
|
192
|
+
base, how = update.remote_oid, "direct"
|
|
193
|
+
remaining = deadline - time.monotonic()
|
|
194
|
+
if remaining <= 0:
|
|
195
|
+
_say("the reviews exceeded the hook's time budget; incomplete")
|
|
196
|
+
return 2
|
|
197
|
+
_say(f"{_display(ref)} at {update.local_oid} ({how})")
|
|
198
|
+
result = max(result, _review(base, update.local_oid, min(per_review, remaining)))
|
|
199
|
+
return result
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def main(argv: list[str] | None = None) -> int:
|
|
203
|
+
args = sys.argv[1:] if argv is None else argv
|
|
204
|
+
remote = args[0] if args else ""
|
|
205
|
+
if not remote.isprintable():
|
|
206
|
+
remote = ""
|
|
207
|
+
stdin = sys.stdin
|
|
208
|
+
if stdin is None or stdin.isatty():
|
|
209
|
+
_say("expected Git's pre-push records on standard input; incomplete")
|
|
210
|
+
return 2
|
|
211
|
+
try:
|
|
212
|
+
return run(remote, parse(stdin.buffer))
|
|
213
|
+
except (ValueError, OSError, subprocess.SubprocessError) as exc:
|
|
214
|
+
_say(f"incomplete: {str(exc)!a}")
|
|
215
|
+
return 2
|
|
216
|
+
except Exception as exc: # never exit 1 (vetoed) or with a traceback for a failure
|
|
217
|
+
_say(f"internal error ({type(exc).__name__}); incomplete")
|
|
218
|
+
return 2
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
if __name__ == "__main__":
|
|
222
|
+
sys.exit(main())
|
codeveto/jsonsafe.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""``json.loads`` with a nesting limit, for text CodeVeto does not trust.
|
|
2
|
+
|
|
3
|
+
Up to Python 3.14 the C decoder raised ``RecursionError`` on deeply nested
|
|
4
|
+
input; from 3.15 it returns the structure, which then breaks recursive code
|
|
5
|
+
later on (``repr``, ``json.dumps``, tree walks) outside any handler. :func:`loads`
|
|
6
|
+
first counts ``[`` and ``{`` outside strings in one linear pass and refuses a
|
|
7
|
+
document nested deeper than :data:`MAX_DEPTH` with a
|
|
8
|
+
:class:`json.JSONDecodeError` (a ``ValueError``), the error invalid JSON
|
|
9
|
+
raises, so every caller keeps its invalid-JSON path on every Python version.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
__all__ = ["MAX_DEPTH", "check_depth", "loads"]
|
|
19
|
+
|
|
20
|
+
MAX_DEPTH = 512
|
|
21
|
+
|
|
22
|
+
_STRUCTURAL = re.compile(r'["\[\]{}]')
|
|
23
|
+
# The rest of a string after its opening quote, up to (not including) the closing one.
|
|
24
|
+
_STRING_BODY = re.compile(r'[^"\\]*(?:\\.[^"\\]*)*', re.DOTALL)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def check_depth(text: str, limit: int = MAX_DEPTH) -> None:
|
|
28
|
+
"""Raise :class:`json.JSONDecodeError` when ``text`` nests deeper than ``limit``.
|
|
29
|
+
|
|
30
|
+
Brackets inside strings (escaped quotes included) do not count. Malformed
|
|
31
|
+
input (an unterminated string, unbalanced brackets) is left to the parser.
|
|
32
|
+
"""
|
|
33
|
+
depth = 0
|
|
34
|
+
pos = 0
|
|
35
|
+
end = len(text)
|
|
36
|
+
while pos < end:
|
|
37
|
+
m = _STRUCTURAL.search(text, pos)
|
|
38
|
+
if m is None:
|
|
39
|
+
return
|
|
40
|
+
c, at = m.group(), m.start()
|
|
41
|
+
if c == '"':
|
|
42
|
+
body = _STRING_BODY.match(text, at + 1) # always matches (possibly empty)
|
|
43
|
+
close = body.end() if body else at + 1
|
|
44
|
+
if close >= end or text[close] != '"':
|
|
45
|
+
return # unterminated: the parser reports it
|
|
46
|
+
pos = close + 1
|
|
47
|
+
continue
|
|
48
|
+
if c in "[{":
|
|
49
|
+
depth += 1
|
|
50
|
+
if depth > limit:
|
|
51
|
+
raise json.JSONDecodeError(f"nested deeper than {limit} levels", text, at)
|
|
52
|
+
elif depth:
|
|
53
|
+
depth -= 1
|
|
54
|
+
pos = at + 1
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def loads(text: str, **kwargs: Any) -> Any:
|
|
58
|
+
""":func:`json.loads` of ``text`` (with the caller's hooks) after :func:`check_depth`."""
|
|
59
|
+
check_depth(text)
|
|
60
|
+
return json.loads(text, **kwargs)
|