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/git.py
ADDED
|
@@ -0,0 +1,1549 @@
|
|
|
1
|
+
"""Hardened Git intake for range, commit and staged reviews (SPEC 5.1, 5.2, 7.1).
|
|
2
|
+
|
|
3
|
+
Repository content is data. Git runs from a PATH entry outside the reviewed
|
|
4
|
+
repository with a scrubbed environment, and every read goes through a private
|
|
5
|
+
bare repository that borrows the target's object store as an alternate, so the
|
|
6
|
+
target's config, attributes, hooks, filters, grafts and replace refs never
|
|
7
|
+
apply. Only ref-name and Git-dir lookups touch the target itself, always with
|
|
8
|
+
the fixed ``-c`` overrides below.
|
|
9
|
+
|
|
10
|
+
Every commit, tree and blob that intake reads is hash-checked in Python
|
|
11
|
+
against its object ID, so a forged loose object, pack entry, multi-pack index
|
|
12
|
+
or commit-graph cannot change what is compared. Parents and ``~``/``^``
|
|
13
|
+
suffixes are taken from verified commit objects.
|
|
14
|
+
|
|
15
|
+
Limits never raise: a file over a limit is kept as ``skipped:<reason>`` with an
|
|
16
|
+
issue and no text. :class:`GitError` is raised only when the comparison itself
|
|
17
|
+
cannot be read (bad ref, Git failure, forged commit or tree, time budget spent
|
|
18
|
+
before the file list was read); its message is short and never contains Git's
|
|
19
|
+
stderr.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import contextlib
|
|
25
|
+
import dataclasses
|
|
26
|
+
import hashlib
|
|
27
|
+
import mmap
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
import shutil
|
|
31
|
+
import stat
|
|
32
|
+
import struct
|
|
33
|
+
import subprocess
|
|
34
|
+
import tempfile
|
|
35
|
+
import threading
|
|
36
|
+
import time
|
|
37
|
+
import unicodedata
|
|
38
|
+
from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
|
|
39
|
+
from dataclasses import dataclass, field
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
from typing import BinaryIO, Literal, get_args
|
|
42
|
+
|
|
43
|
+
from codeveto.model import AnchorSource, Changeset, FileChange, FileKind, FileStatus, Hunk
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"DEFAULT_LIMITS",
|
|
47
|
+
"EMPTY_TREE",
|
|
48
|
+
"FLAG_IMAGE_PREFIX",
|
|
49
|
+
"FLAG_INVALID_PATH",
|
|
50
|
+
"FLAG_MODE_CHANGE",
|
|
51
|
+
"FLAG_NON_UTF8",
|
|
52
|
+
"FLAG_NUL_BYTES",
|
|
53
|
+
"SKIPPED_PREFIX",
|
|
54
|
+
"Anchor",
|
|
55
|
+
"Git",
|
|
56
|
+
"GitError",
|
|
57
|
+
"Limits",
|
|
58
|
+
"read_anchor_file",
|
|
59
|
+
"read_commit",
|
|
60
|
+
"read_range",
|
|
61
|
+
"read_staged",
|
|
62
|
+
"repository_identities",
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
FLAG_NUL_BYTES = "nul-bytes"
|
|
66
|
+
FLAG_NON_UTF8 = "non-utf8"
|
|
67
|
+
FLAG_MODE_CHANGE = "mode-change"
|
|
68
|
+
FLAG_INVALID_PATH = "invalid-path"
|
|
69
|
+
FLAG_IMAGE_PREFIX = "image:"
|
|
70
|
+
"""``image:<format>`` marks a new-side binary whose magic bytes name an image format."""
|
|
71
|
+
SKIPPED_PREFIX = "skipped:"
|
|
72
|
+
|
|
73
|
+
#: Per-invocation timeout; the total budget is ``Limits.git_seconds``.
|
|
74
|
+
CALL_TIMEOUT_SECONDS = 20.0
|
|
75
|
+
#: Default output cap for small queries (rev-parse, merge-base, write-tree).
|
|
76
|
+
SMALL_OUTPUT_CAP = 64 * 1024
|
|
77
|
+
#: Output cap for the raw ``-z`` file listing and for all trees read together.
|
|
78
|
+
MAX_RAW_BYTES = 64 * 1024 * 1024
|
|
79
|
+
#: Largest commit object read.
|
|
80
|
+
MAX_COMMIT_BYTES = 16 * 1024 * 1024
|
|
81
|
+
#: Largest index file copied for staged mode.
|
|
82
|
+
MAX_INDEX_BYTES = 64 * 1024 * 1024
|
|
83
|
+
#: Most ``~``/``^`` steps in one revision.
|
|
84
|
+
MAX_REVISION_STEPS = 1000
|
|
85
|
+
#: Rename detection: fixed threshold and candidate limit, never from config.
|
|
86
|
+
RENAME_THRESHOLD = "-M50%"
|
|
87
|
+
RENAME_LIMIT = "-l1000"
|
|
88
|
+
|
|
89
|
+
#: ``-c`` overrides on every invocation (SPEC 5.1 and legacy). Commands that run
|
|
90
|
+
#: against the target also get ``safe.directory=<repo>``.
|
|
91
|
+
CONFIG_OVERRIDES: tuple[str, ...] = (
|
|
92
|
+
"core.fsmonitor=false",
|
|
93
|
+
f"core.hooksPath={os.devnull}",
|
|
94
|
+
"core.untrackedCache=false",
|
|
95
|
+
f"core.excludesFile={os.devnull}",
|
|
96
|
+
f"core.attributesFile={os.devnull}",
|
|
97
|
+
"core.commitGraph=false",
|
|
98
|
+
"core.multiPackIndex=false",
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
#: The empty tree per object format; a root commit is compared against it.
|
|
102
|
+
EMPTY_TREE: dict[str, str] = {
|
|
103
|
+
"sha1": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
|
|
104
|
+
"sha256": "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321",
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
_ABSENT = "000000"
|
|
108
|
+
_TREE = "040000"
|
|
109
|
+
_REGULAR = frozenset({"100644", "100755"})
|
|
110
|
+
_EXECUTABLE = "100755"
|
|
111
|
+
_SYMLINK = "120000"
|
|
112
|
+
_GITLINK = "160000"
|
|
113
|
+
_KNOWN_MODES = _REGULAR | {_ABSENT, _SYMLINK, _GITLINK}
|
|
114
|
+
_OID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
|
|
115
|
+
_HUNK = re.compile(rb"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: |$)")
|
|
116
|
+
_STATUS = {
|
|
117
|
+
b"A": FileStatus.ADDED,
|
|
118
|
+
b"M": FileStatus.MODIFIED,
|
|
119
|
+
b"D": FileStatus.DELETED,
|
|
120
|
+
b"R": FileStatus.RENAMED,
|
|
121
|
+
b"T": FileStatus.TYPE_CHANGED,
|
|
122
|
+
}
|
|
123
|
+
_REF_FORBIDDEN = frozenset(":{}\\*?[")
|
|
124
|
+
_REVISION = re.compile(r"(.*?)((?:[~^][0-9]{0,6})*)")
|
|
125
|
+
_LFS_POINTER = re.compile(
|
|
126
|
+
rb"version https://git-lfs\.github\.com/spec/v1\n"
|
|
127
|
+
rb"(?:ext-[0-9]-[a-z0-9-]+ sha256:[0-9a-f]{64}\n)*"
|
|
128
|
+
rb"oid sha256:[0-9a-f]{64}\n"
|
|
129
|
+
rb"size [0-9]{1,20}\n"
|
|
130
|
+
)
|
|
131
|
+
_LFS_MAX_BYTES = 1024
|
|
132
|
+
|
|
133
|
+
# Extensions and names reviewed as text even when they contain NUL bytes or
|
|
134
|
+
# start with a binary magic number (SPEC 5.1). Kept local until the language
|
|
135
|
+
# table (A3a) can supply it.
|
|
136
|
+
_SOURCE_EXTENSIONS = frozenset(
|
|
137
|
+
# A word list reads better than a 120-line literal.
|
|
138
|
+
"""
|
|
139
|
+
py pyi pyw pyx js mjs cjs jsx ts tsx mts cts go rs java kt kts scala groovy gradle
|
|
140
|
+
c h cc cpp cxx hpp hh hxx m mm cs fs vb swift dart rb php phtml pl pm lua r jl ex exs
|
|
141
|
+
erl hrl hs ml mli clj cljs elm nim zig v sol sh bash zsh fish ksh ps1 psm1 bat cmd
|
|
142
|
+
sql html htm xhtml css scss sass less vue svelte astro json jsonc json5 yaml yml
|
|
143
|
+
toml ini cfg conf properties env xml xsd xsl plist md markdown rst txt adoc tex
|
|
144
|
+
tf tfvars hcl nix proto graphql gql mk cmake dockerfile csv tsv svg lock
|
|
145
|
+
""".split() # noqa: SIM905
|
|
146
|
+
)
|
|
147
|
+
_SOURCE_NAMES = frozenset(
|
|
148
|
+
"""
|
|
149
|
+
dockerfile containerfile makefile gnumakefile gemfile rakefile jenkinsfile
|
|
150
|
+
procfile vagrantfile brewfile justfile codeowners license readme
|
|
151
|
+
.bashrc .zshrc .profile .bash_profile .gitignore .gitattributes .gitmodules
|
|
152
|
+
.editorconfig .npmrc .env .envrc .dockerignore .prettierrc .eslintrc .babelrc
|
|
153
|
+
.nvmrc .python-version .tool-versions .cursorrules .windsurfrules .clinerules
|
|
154
|
+
""".split() # noqa: SIM905
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class GitError(Exception):
|
|
159
|
+
"""The comparison could not be read. ``reason`` is a short machine code."""
|
|
160
|
+
|
|
161
|
+
def __init__(self, message: str, *, reason: str = "failed") -> None:
|
|
162
|
+
super().__init__(message)
|
|
163
|
+
self.reason = reason
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass(frozen=True, slots=True)
|
|
167
|
+
class Limits:
|
|
168
|
+
"""Intake limits (SPEC 5.1). Values may only ever be lowered.
|
|
169
|
+
|
|
170
|
+
The defaults are also the ceilings: constructing a ``Limits`` above them,
|
|
171
|
+
or calling :meth:`lowered` with a larger value, raises ``ValueError``.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
max_files: int = 2_000
|
|
175
|
+
max_file_bytes: int = 1024 * 1024
|
|
176
|
+
max_total_bytes: int = 32 * 1024 * 1024
|
|
177
|
+
max_file_lines: int = 50_000
|
|
178
|
+
max_total_lines: int = 300_000
|
|
179
|
+
git_seconds: float = 60.0
|
|
180
|
+
|
|
181
|
+
def __post_init__(self) -> None:
|
|
182
|
+
for spec in dataclasses.fields(self):
|
|
183
|
+
value = getattr(self, spec.name)
|
|
184
|
+
allowed = (int, float) if spec.name == "git_seconds" else (int,)
|
|
185
|
+
if isinstance(value, bool) or not isinstance(value, allowed):
|
|
186
|
+
raise TypeError(f"Limits.{spec.name} must be a number, got {value!r}")
|
|
187
|
+
ceiling = spec.default
|
|
188
|
+
if not 0 < value <= ceiling: # type: ignore[operator]
|
|
189
|
+
raise ValueError(f"Limits.{spec.name} must be > 0 and <= {ceiling}, got {value!r}")
|
|
190
|
+
|
|
191
|
+
def lowered(self, **values: float) -> Limits:
|
|
192
|
+
"""Return a copy with some limits lowered; raising any of them is rejected."""
|
|
193
|
+
names = {spec.name for spec in dataclasses.fields(self)}
|
|
194
|
+
for name, value in values.items():
|
|
195
|
+
if name not in names:
|
|
196
|
+
raise ValueError(f"unknown limit {name!r}")
|
|
197
|
+
current = getattr(self, name)
|
|
198
|
+
if isinstance(value, bool) or not isinstance(value, int | float):
|
|
199
|
+
raise TypeError(f"limit {name} must be a number, got {value!r}")
|
|
200
|
+
if value > current:
|
|
201
|
+
raise ValueError(f"limit {name} can only be lowered ({value!r} > {current!r})")
|
|
202
|
+
return dataclasses.replace(self, **values) # type: ignore[arg-type]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
DEFAULT_LIMITS = Limits()
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@dataclass(frozen=True, slots=True)
|
|
209
|
+
class Anchor:
|
|
210
|
+
"""A trust anchor resolved by the caller (SPEC 7.1): a full commit OID and its source.
|
|
211
|
+
|
|
212
|
+
Staged mode takes one from the anchor resolver (A2c); intake only checks
|
|
213
|
+
that the OID is well formed and names a commit in the repository.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
oid: str
|
|
217
|
+
source: AnchorSource
|
|
218
|
+
|
|
219
|
+
def __post_init__(self) -> None:
|
|
220
|
+
if not isinstance(self.oid, str) or not _OID.fullmatch(self.oid):
|
|
221
|
+
raise ValueError("Anchor.oid must be a full 40- or 64-hex commit ID")
|
|
222
|
+
if self.source not in get_args(AnchorSource):
|
|
223
|
+
raise ValueError(f"unknown Anchor.source {self.source!r}")
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# --- locating Git ------------------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _repository_identities(source: Path) -> set[tuple[int, int]]:
|
|
230
|
+
"""(st_dev, st_ino) of the reviewed directory and every enclosing repository."""
|
|
231
|
+
identities = set()
|
|
232
|
+
for path in (source, *source.parents):
|
|
233
|
+
if path == source or (path / ".git").exists():
|
|
234
|
+
info = path.stat()
|
|
235
|
+
identities.add((info.st_dev, info.st_ino))
|
|
236
|
+
return identities
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _inside(path: Path, identities: set[tuple[int, int]]) -> bool:
|
|
240
|
+
"""Whether ``path`` resolves to a location under one of ``identities``.
|
|
241
|
+
|
|
242
|
+
Identities, not strings, are compared, so case variants on case-insensitive
|
|
243
|
+
file systems and firmlinks (``/System/Volumes/Data/...``) are caught too.
|
|
244
|
+
"""
|
|
245
|
+
try:
|
|
246
|
+
resolved = path.resolve()
|
|
247
|
+
except (OSError, RuntimeError):
|
|
248
|
+
return True
|
|
249
|
+
for ancestor in (resolved, *resolved.parents):
|
|
250
|
+
try:
|
|
251
|
+
info = ancestor.stat()
|
|
252
|
+
except OSError:
|
|
253
|
+
continue
|
|
254
|
+
if (info.st_dev, info.st_ino) in identities:
|
|
255
|
+
return True
|
|
256
|
+
return False
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _git_program(source: Path) -> tuple[str, str]:
|
|
260
|
+
"""Return (git executable, PATH) using only PATH entries outside the repository."""
|
|
261
|
+
identities = _repository_identities(source)
|
|
262
|
+
search: list[str] = []
|
|
263
|
+
for entry in os.get_exec_path():
|
|
264
|
+
if os.path.isabs(entry) and not _inside(Path(entry), identities):
|
|
265
|
+
search.append(str(Path(entry).resolve()))
|
|
266
|
+
# An absolute executable name prevents Windows' lookup in the current
|
|
267
|
+
# directory, which may be a checkout unrelated to the reviewed repository.
|
|
268
|
+
executable = "git.exe" if os.name == "nt" else "git"
|
|
269
|
+
for entry in search:
|
|
270
|
+
candidate = shutil.which(str(Path(entry) / executable))
|
|
271
|
+
if candidate and not _inside(Path(candidate), identities):
|
|
272
|
+
return candidate, os.pathsep.join(search)
|
|
273
|
+
raise GitError("Git executable unavailable outside the reviewed repository", reason="no-git")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# --- running Git -------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class Git:
|
|
280
|
+
"""Run Git against ``source`` with a scrubbed environment and private state under ``temp``.
|
|
281
|
+
|
|
282
|
+
``temp`` must be a private directory owned by the caller; it holds the
|
|
283
|
+
private ``HOME``/``TMPDIR`` and the isolation repository. Commands run
|
|
284
|
+
against the isolation repository unless ``source=True`` (ref names and the
|
|
285
|
+
Git directory only).
|
|
286
|
+
"""
|
|
287
|
+
|
|
288
|
+
def __init__(
|
|
289
|
+
self,
|
|
290
|
+
source: Path,
|
|
291
|
+
temp: Path,
|
|
292
|
+
*,
|
|
293
|
+
time_budget: float = DEFAULT_LIMITS.git_seconds,
|
|
294
|
+
call_timeout: float = CALL_TIMEOUT_SECONDS,
|
|
295
|
+
) -> None:
|
|
296
|
+
self.source = source
|
|
297
|
+
self.temp = temp
|
|
298
|
+
self.home = temp / "home"
|
|
299
|
+
self.tmp = temp / "tmp"
|
|
300
|
+
self.home.mkdir(mode=0o700, exist_ok=True)
|
|
301
|
+
self.tmp.mkdir(mode=0o700, exist_ok=True)
|
|
302
|
+
self.bare = temp / "review.git"
|
|
303
|
+
self.program, path = _git_program(source)
|
|
304
|
+
# Drop inherited Git, loader, pager and shell options: build from scratch.
|
|
305
|
+
self.env = {
|
|
306
|
+
k: os.environ[k] for k in ("SYSTEMROOT", "WINDIR", "COMSPEC") if k in os.environ
|
|
307
|
+
}
|
|
308
|
+
self.env.update(
|
|
309
|
+
{
|
|
310
|
+
"PATH": path,
|
|
311
|
+
"HOME": str(self.home),
|
|
312
|
+
"USERPROFILE": str(self.home),
|
|
313
|
+
"XDG_CONFIG_HOME": str(self.home),
|
|
314
|
+
"TMPDIR": str(self.tmp),
|
|
315
|
+
"TEMP": str(self.tmp),
|
|
316
|
+
"TMP": str(self.tmp),
|
|
317
|
+
"LC_ALL": "C",
|
|
318
|
+
"GIT_CONFIG_NOSYSTEM": "1",
|
|
319
|
+
"GIT_CONFIG_GLOBAL": os.devnull,
|
|
320
|
+
"GIT_ATTR_NOSYSTEM": "1",
|
|
321
|
+
"GIT_NO_REPLACE_OBJECTS": "1",
|
|
322
|
+
"GIT_NO_LAZY_FETCH": "1",
|
|
323
|
+
"GIT_ALLOW_PROTOCOL": "",
|
|
324
|
+
"GIT_TERMINAL_PROMPT": "0",
|
|
325
|
+
"GIT_OPTIONAL_LOCKS": "0",
|
|
326
|
+
}
|
|
327
|
+
)
|
|
328
|
+
self.call_timeout = call_timeout
|
|
329
|
+
self.deadline = time.monotonic() + time_budget
|
|
330
|
+
self.object_format: str | None = None
|
|
331
|
+
#: Worktree mode counts lines that differ only by CR at EOL as unchanged.
|
|
332
|
+
self.ignore_cr_at_eol = False
|
|
333
|
+
|
|
334
|
+
@property
|
|
335
|
+
def empty_tree(self) -> str:
|
|
336
|
+
if self.object_format is None:
|
|
337
|
+
raise GitError("Git isolation repository not prepared", reason="not-isolated")
|
|
338
|
+
return EMPTY_TREE[self.object_format]
|
|
339
|
+
|
|
340
|
+
@property
|
|
341
|
+
def oid_length(self) -> int:
|
|
342
|
+
if self.object_format is None:
|
|
343
|
+
raise GitError("Git isolation repository not prepared", reason="not-isolated")
|
|
344
|
+
return 64 if self.object_format == "sha256" else 40
|
|
345
|
+
|
|
346
|
+
def argv(
|
|
347
|
+
self, args: list[str], *, source: bool = False, options: Sequence[str] = ()
|
|
348
|
+
) -> list[str]:
|
|
349
|
+
"""Full argv; ``options`` are extra global options placed before ``args``."""
|
|
350
|
+
overrides = [arg for option in CONFIG_OVERRIDES for arg in ("-c", option)]
|
|
351
|
+
if args[0] == "init":
|
|
352
|
+
prefix: list[str] = []
|
|
353
|
+
elif source:
|
|
354
|
+
# Repository config is already hostile input, so ownership checks
|
|
355
|
+
# add nothing; CI checkouts are often owned by another user.
|
|
356
|
+
prefix = ["-c", f"safe.directory={self.source}", "-C", str(self.source)]
|
|
357
|
+
else:
|
|
358
|
+
prefix = [f"--git-dir={self.bare}"]
|
|
359
|
+
return [self.program, "--no-pager", *overrides, *prefix, *options, *args]
|
|
360
|
+
|
|
361
|
+
def run_status(
|
|
362
|
+
self,
|
|
363
|
+
args: list[str],
|
|
364
|
+
*,
|
|
365
|
+
source: bool = False,
|
|
366
|
+
cap: int = SMALL_OUTPUT_CAP,
|
|
367
|
+
data: bytes = b"",
|
|
368
|
+
ok: Collection[int] = (0,),
|
|
369
|
+
options: Sequence[str] = (),
|
|
370
|
+
stderr: BinaryIO | None = None,
|
|
371
|
+
) -> tuple[int, bytes]:
|
|
372
|
+
"""Run Git; return (exit code, stdout). Exit codes outside ``ok`` raise.
|
|
373
|
+
|
|
374
|
+
Standard error is discarded unless ``stderr`` (a file the caller owns)
|
|
375
|
+
is given; its text must never reach output or messages.
|
|
376
|
+
"""
|
|
377
|
+
name = args[0]
|
|
378
|
+
remaining = self.deadline - time.monotonic()
|
|
379
|
+
if remaining <= 0:
|
|
380
|
+
raise GitError("Git exceeded the total time budget", reason="time-budget")
|
|
381
|
+
timeout = min(self.call_timeout, remaining)
|
|
382
|
+
fired = threading.Event()
|
|
383
|
+
# A hard byte limit protects the readers even when an input has far
|
|
384
|
+
# more paths or patch lines than a normal repository. Stdin is a file,
|
|
385
|
+
# so a large request can never deadlock against unread output.
|
|
386
|
+
with tempfile.TemporaryFile(dir=self.tmp) as stdin:
|
|
387
|
+
stdin.write(data)
|
|
388
|
+
stdin.seek(0)
|
|
389
|
+
# Fixed argv (no shell), Git resolved outside the repository.
|
|
390
|
+
with subprocess.Popen( # noqa: S603
|
|
391
|
+
self.argv(args, source=source, options=options),
|
|
392
|
+
stdin=stdin,
|
|
393
|
+
stdout=subprocess.PIPE,
|
|
394
|
+
stderr=subprocess.DEVNULL if stderr is None else stderr,
|
|
395
|
+
cwd=self.tmp,
|
|
396
|
+
env=self.env,
|
|
397
|
+
) as child:
|
|
398
|
+
|
|
399
|
+
def kill() -> None:
|
|
400
|
+
fired.set()
|
|
401
|
+
child.kill()
|
|
402
|
+
|
|
403
|
+
timer = threading.Timer(timeout, kill)
|
|
404
|
+
timer.daemon = True
|
|
405
|
+
timer.start()
|
|
406
|
+
try:
|
|
407
|
+
if child.stdout is None: # pragma: no cover - PIPE always gives one
|
|
408
|
+
raise GitError(f"Git {name} produced no output stream")
|
|
409
|
+
out = child.stdout.read(cap + 1)
|
|
410
|
+
if len(out) > cap:
|
|
411
|
+
child.kill()
|
|
412
|
+
raise GitError(f"Git {name} exceeded its output cap", reason="output-cap")
|
|
413
|
+
code = child.wait()
|
|
414
|
+
finally:
|
|
415
|
+
timer.cancel()
|
|
416
|
+
if fired.is_set():
|
|
417
|
+
if timeout < self.call_timeout:
|
|
418
|
+
raise GitError("Git exceeded the total time budget", reason="time-budget")
|
|
419
|
+
raise GitError(f"Git {name} timed out", reason="timeout")
|
|
420
|
+
if code not in ok:
|
|
421
|
+
raise GitError(
|
|
422
|
+
f"Git {name} failed; check refs, history and object availability",
|
|
423
|
+
reason="failed",
|
|
424
|
+
)
|
|
425
|
+
return code, out
|
|
426
|
+
|
|
427
|
+
def run(
|
|
428
|
+
self,
|
|
429
|
+
args: list[str],
|
|
430
|
+
*,
|
|
431
|
+
source: bool = False,
|
|
432
|
+
cap: int = SMALL_OUTPUT_CAP,
|
|
433
|
+
data: bytes = b"",
|
|
434
|
+
options: Sequence[str] = (),
|
|
435
|
+
) -> bytes:
|
|
436
|
+
return self.run_status(args, source=source, cap=cap, data=data, options=options)[1]
|
|
437
|
+
|
|
438
|
+
def _oid(self, raw: bytes) -> str:
|
|
439
|
+
oid = raw.decode("ascii", "replace")
|
|
440
|
+
if not _OID.fullmatch(oid) or len(oid) != self.oid_length:
|
|
441
|
+
raise GitError("Git returned an invalid object identifier", reason="bad-output")
|
|
442
|
+
return oid
|
|
443
|
+
|
|
444
|
+
# --- isolation ---------------------------------------------------------------
|
|
445
|
+
|
|
446
|
+
def isolate(self) -> str:
|
|
447
|
+
"""Create the private bare repository over the target's objects; return the format."""
|
|
448
|
+
raw = self.run(
|
|
449
|
+
["rev-parse", "--path-format=absolute", "--git-path", "objects"], source=True
|
|
450
|
+
)
|
|
451
|
+
store = raw.removesuffix(b"\n")
|
|
452
|
+
if b"\n" in store or b"\r" in store or store.startswith(b'"'):
|
|
453
|
+
raise GitError("Git object store path cannot be used", reason="bad-store")
|
|
454
|
+
if not Path(os.fsdecode(store)).is_absolute() or not Path(os.fsdecode(store)).is_dir():
|
|
455
|
+
raise GitError("Git object store unavailable", reason="bad-store")
|
|
456
|
+
fmt = self.run(["rev-parse", "--show-object-format"], source=True).strip()
|
|
457
|
+
if fmt not in (b"sha1", b"sha256"):
|
|
458
|
+
raise GitError("unsupported Git object format", reason="bad-format")
|
|
459
|
+
self.object_format = fmt.decode("ascii")
|
|
460
|
+
self.run(
|
|
461
|
+
[
|
|
462
|
+
"init",
|
|
463
|
+
"-q",
|
|
464
|
+
"--bare",
|
|
465
|
+
"--template=",
|
|
466
|
+
f"--object-format={self.object_format}",
|
|
467
|
+
str(self.bare),
|
|
468
|
+
]
|
|
469
|
+
)
|
|
470
|
+
# The scratch repository has no refs, config, index, attributes,
|
|
471
|
+
# grafts, replacements or hooks of the target; it only borrows its
|
|
472
|
+
# objects. Object reads also work on linked worktrees and packed clones.
|
|
473
|
+
info = self.bare / "objects" / "info"
|
|
474
|
+
info.mkdir(parents=True, exist_ok=True)
|
|
475
|
+
(info / "alternates").write_bytes(store + b"\n")
|
|
476
|
+
return self.object_format
|
|
477
|
+
|
|
478
|
+
def git_dir(self) -> Path:
|
|
479
|
+
"""The target's Git directory, as Git reports it (the index lives directly in it)."""
|
|
480
|
+
raw = self.run(["rev-parse", "--absolute-git-dir"], source=True)
|
|
481
|
+
path = Path(os.fsdecode(raw.removesuffix(b"\n")))
|
|
482
|
+
if not path.is_absolute():
|
|
483
|
+
raise GitError("Git directory unavailable", reason="bad-path")
|
|
484
|
+
return path
|
|
485
|
+
|
|
486
|
+
# --- verified objects ----------------------------------------------------------
|
|
487
|
+
|
|
488
|
+
def object_info(self, oids: Collection[str]) -> dict[str, tuple[str, int]]:
|
|
489
|
+
"""Type and size of each object; missing objects are left out."""
|
|
490
|
+
if not oids:
|
|
491
|
+
return {}
|
|
492
|
+
ordered = list(oids)
|
|
493
|
+
out = self.run(
|
|
494
|
+
["cat-file", "--batch-check"],
|
|
495
|
+
data="".join(oid + "\n" for oid in ordered).encode("ascii"),
|
|
496
|
+
cap=(self.oid_length + 32) * len(ordered),
|
|
497
|
+
)
|
|
498
|
+
records = out.splitlines()
|
|
499
|
+
if len(records) != len(ordered):
|
|
500
|
+
raise GitError("Git object list is incomplete", reason="bad-output")
|
|
501
|
+
info: dict[str, tuple[str, int]] = {}
|
|
502
|
+
for oid, record in zip(ordered, records, strict=True):
|
|
503
|
+
parts = record.split(b" ")
|
|
504
|
+
if (
|
|
505
|
+
len(parts) == 3
|
|
506
|
+
and parts[0] == oid.encode()
|
|
507
|
+
and parts[1] in (b"blob", b"tree", b"commit", b"tag")
|
|
508
|
+
and parts[2].isdigit()
|
|
509
|
+
):
|
|
510
|
+
info[oid] = (parts[1].decode("ascii"), int(parts[2]))
|
|
511
|
+
return info
|
|
512
|
+
|
|
513
|
+
def read_objects(self, wanted: dict[str, tuple[str, int]]) -> tuple[dict[str, bytes], set[str]]:
|
|
514
|
+
"""Read objects with ``cat-file --batch``; return (content, OIDs whose hash mismatches).
|
|
515
|
+
|
|
516
|
+
Each object is hashed as Git hashes it (``"<type> <size>\\0" + data``),
|
|
517
|
+
so a forged object stored under another object's ID is detected.
|
|
518
|
+
"""
|
|
519
|
+
if not wanted:
|
|
520
|
+
return {}, set()
|
|
521
|
+
if self.object_format is None:
|
|
522
|
+
raise GitError("Git isolation repository not prepared", reason="not-isolated")
|
|
523
|
+
data = self.run(
|
|
524
|
+
["cat-file", "--batch"],
|
|
525
|
+
data="".join(oid + "\n" for oid in wanted).encode("ascii"),
|
|
526
|
+
cap=sum(size for _, size in wanted.values()) + len(wanted) * (self.oid_length + 32),
|
|
527
|
+
)
|
|
528
|
+
pos = 0
|
|
529
|
+
contents: dict[str, bytes] = {}
|
|
530
|
+
mismatched: set[str] = set()
|
|
531
|
+
for oid, (kind, size) in wanted.items():
|
|
532
|
+
header = f"{oid} {kind} {size}\n".encode("ascii")
|
|
533
|
+
if not data.startswith(header, pos):
|
|
534
|
+
raise GitError("Git object metadata mismatch", reason="bad-output")
|
|
535
|
+
pos += len(header)
|
|
536
|
+
body = data[pos : pos + size]
|
|
537
|
+
pos += size
|
|
538
|
+
if len(body) != size or data[pos : pos + 1] != b"\n":
|
|
539
|
+
raise GitError("truncated Git object", reason="bad-output")
|
|
540
|
+
pos += 1
|
|
541
|
+
digest = hashlib.new(self.object_format, b"%s %d\0" % (kind.encode(), size) + body)
|
|
542
|
+
if digest.hexdigest() != oid:
|
|
543
|
+
mismatched.add(oid)
|
|
544
|
+
contents[oid] = body
|
|
545
|
+
if pos != len(data):
|
|
546
|
+
raise GitError("unexpected data after Git objects", reason="bad-output")
|
|
547
|
+
return contents, mismatched
|
|
548
|
+
|
|
549
|
+
def verified(self, oids: Collection[str], kind: str, cap: int) -> dict[str, bytes]:
|
|
550
|
+
"""Read and hash-check objects that must exist; any problem raises."""
|
|
551
|
+
info = self.object_info(oids)
|
|
552
|
+
for oid in oids:
|
|
553
|
+
if oid not in info:
|
|
554
|
+
raise GitError(f"Git {kind} object unavailable", reason="missing-object")
|
|
555
|
+
if info[oid][0] != kind:
|
|
556
|
+
raise GitError(f"Git object is not a {kind}", reason="object-mismatch")
|
|
557
|
+
if sum(size for _, size in info.values()) > cap:
|
|
558
|
+
raise GitError(f"Git {kind} objects exceed the size limit", reason="output-cap")
|
|
559
|
+
contents, mismatched = self.read_objects(info)
|
|
560
|
+
if mismatched:
|
|
561
|
+
raise GitError(f"Git {kind} object does not match its ID", reason="object-mismatch")
|
|
562
|
+
return contents
|
|
563
|
+
|
|
564
|
+
def commit(self, oid: str) -> tuple[str, list[str]]:
|
|
565
|
+
"""A hash-verified commit's (tree, parents)."""
|
|
566
|
+
body = self.verified([oid], "commit", MAX_COMMIT_BYTES)[oid]
|
|
567
|
+
tree: str | None = None
|
|
568
|
+
parents: list[str] = []
|
|
569
|
+
for line in body.split(b"\n"):
|
|
570
|
+
if not line:
|
|
571
|
+
break
|
|
572
|
+
if line.startswith(b"tree ") and tree is None and not parents:
|
|
573
|
+
tree = self._oid(line[5:])
|
|
574
|
+
elif line.startswith(b"parent ") and tree is not None:
|
|
575
|
+
parents.append(self._oid(line[7:]))
|
|
576
|
+
if tree is None:
|
|
577
|
+
raise GitError("Git commit has no tree", reason="bad-output")
|
|
578
|
+
return tree, parents
|
|
579
|
+
|
|
580
|
+
def verify_trees(self, oids: Iterable[str]) -> None:
|
|
581
|
+
"""Hash-check every tree a comparison reads; a forged tree raises."""
|
|
582
|
+
self.verified(sorted(set(oids)), "tree", MAX_RAW_BYTES)
|
|
583
|
+
|
|
584
|
+
# --- revisions -------------------------------------------------------------------
|
|
585
|
+
|
|
586
|
+
def resolve(self, ref: str) -> str:
|
|
587
|
+
"""Resolve a user-supplied revision to a full commit OID.
|
|
588
|
+
|
|
589
|
+
* Lower-case hex of 4 up to a full object ID is an object, looked up in
|
|
590
|
+
the private repository (which has no refs), so a branch named like a
|
|
591
|
+
hex prefix cannot shadow it.
|
|
592
|
+
* ``HEAD``/``@`` is the target's ``HEAD``. Any other name must resolve
|
|
593
|
+
unambiguously to a full ref (``refs/...``) in the target; a name that
|
|
594
|
+
is ambiguous or not a ref (``FETCH_HEAD``, a file at the top of the
|
|
595
|
+
Git directory) is rejected; pass a commit ID instead.
|
|
596
|
+
* A ``~n``/``^n`` suffix is walked here over hash-verified commits, so
|
|
597
|
+
target grafts, shallow files and forged parents never apply.
|
|
598
|
+
"""
|
|
599
|
+
if (
|
|
600
|
+
not isinstance(ref, str)
|
|
601
|
+
or not ref
|
|
602
|
+
or len(ref) > 1024
|
|
603
|
+
or ref.startswith(("-", "+"))
|
|
604
|
+
or ".." in ref
|
|
605
|
+
or any(ord(c) < 32 or ord(c) == 127 or c.isspace() or c in _REF_FORBIDDEN for c in ref)
|
|
606
|
+
):
|
|
607
|
+
raise GitError("invalid revision: supply a commit or ref name", reason="invalid-ref")
|
|
608
|
+
m = _REVISION.fullmatch(ref)
|
|
609
|
+
if m is None or not m[1] or "~" in m[1] or "^" in m[1]:
|
|
610
|
+
raise GitError("invalid revision: supply a commit or ref name", reason="invalid-ref")
|
|
611
|
+
name, suffix = m[1], m[2]
|
|
612
|
+
if re.fullmatch(rf"[0-9a-f]{{4,{self.oid_length}}}", name):
|
|
613
|
+
oid = self._object_commit(name)
|
|
614
|
+
else:
|
|
615
|
+
oid = self.target_commit(name)
|
|
616
|
+
return self._walk(oid, suffix)
|
|
617
|
+
|
|
618
|
+
def _object_commit(self, prefix: str) -> str:
|
|
619
|
+
code, out = self.run_status(
|
|
620
|
+
["rev-parse", "--verify", "--quiet", "--end-of-options", f"{prefix}^{{commit}}"],
|
|
621
|
+
ok=(0, 1),
|
|
622
|
+
)
|
|
623
|
+
if code != 0:
|
|
624
|
+
raise GitError("revision does not resolve to a commit", reason="unknown-ref")
|
|
625
|
+
return self._oid(out.rstrip(b"\n"))
|
|
626
|
+
|
|
627
|
+
def _target_rev(self, spec: str) -> tuple[int, bytes]:
|
|
628
|
+
return self.run_status(
|
|
629
|
+
["rev-parse", "--verify", "--quiet", "--end-of-options", spec],
|
|
630
|
+
source=True,
|
|
631
|
+
ok=(0, 1),
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
def target_commit(self, name: str) -> str:
|
|
635
|
+
"""Resolve a ref name (not a suffix) to a commit in the target."""
|
|
636
|
+
if name in ("HEAD", "@"):
|
|
637
|
+
code, out = self._target_rev("HEAD^{commit}")
|
|
638
|
+
if code != 0:
|
|
639
|
+
raise GitError("HEAD does not resolve to a commit", reason="unknown-ref")
|
|
640
|
+
return self._oid(out.rstrip(b"\n"))
|
|
641
|
+
code, out = self.run_status(
|
|
642
|
+
["rev-parse", "--verify", "--quiet", "--symbolic-full-name", "--end-of-options", name],
|
|
643
|
+
source=True,
|
|
644
|
+
ok=(0, 1),
|
|
645
|
+
)
|
|
646
|
+
full = out.rstrip(b"\n")
|
|
647
|
+
if code != 0 or not full.startswith(b"refs/") or b"\n" in full:
|
|
648
|
+
if self._target_rev(f"{name}^{{commit}}")[0] == 0:
|
|
649
|
+
raise GitError(
|
|
650
|
+
"revision name is ambiguous or not a ref; use a full ref name or commit ID",
|
|
651
|
+
reason="ambiguous-ref",
|
|
652
|
+
)
|
|
653
|
+
raise GitError("revision does not resolve to a commit", reason="unknown-ref")
|
|
654
|
+
try:
|
|
655
|
+
ref = full.decode("utf-8")
|
|
656
|
+
except UnicodeDecodeError as exc:
|
|
657
|
+
raise GitError("Git returned an invalid ref name", reason="bad-output") from exc
|
|
658
|
+
if any(ord(c) < 32 or ord(c) == 127 for c in ref):
|
|
659
|
+
raise GitError("Git returned an invalid ref name", reason="bad-output")
|
|
660
|
+
code, out = self._target_rev(f"{ref}^{{commit}}")
|
|
661
|
+
if code != 0:
|
|
662
|
+
raise GitError("revision does not resolve to a commit", reason="unknown-ref")
|
|
663
|
+
return self._oid(out.rstrip(b"\n"))
|
|
664
|
+
|
|
665
|
+
def _walk(self, oid: str, suffix: str) -> str:
|
|
666
|
+
steps = 0
|
|
667
|
+
for op, digits in re.findall(r"([~^])([0-9]*)", suffix):
|
|
668
|
+
count = int(digits) if digits else 1
|
|
669
|
+
steps += max(count, 1)
|
|
670
|
+
if steps > MAX_REVISION_STEPS:
|
|
671
|
+
raise GitError("revision suffix walks too far", reason="invalid-ref")
|
|
672
|
+
if op == "~":
|
|
673
|
+
for _ in range(count):
|
|
674
|
+
parents = self.commit(oid)[1]
|
|
675
|
+
if not parents:
|
|
676
|
+
raise GitError(
|
|
677
|
+
"revision does not resolve to a commit", reason="unknown-ref"
|
|
678
|
+
)
|
|
679
|
+
oid = parents[0]
|
|
680
|
+
elif count:
|
|
681
|
+
parents = self.commit(oid)[1]
|
|
682
|
+
if len(parents) < count:
|
|
683
|
+
raise GitError("revision does not resolve to a commit", reason="unknown-ref")
|
|
684
|
+
oid = parents[count - 1]
|
|
685
|
+
return oid
|
|
686
|
+
|
|
687
|
+
def resolve_anchor(self, oid: str) -> str:
|
|
688
|
+
"""Validate an explicit anchor: a full OID naming a commit."""
|
|
689
|
+
if not isinstance(oid, str) or not _OID.fullmatch(oid) or len(oid) != self.oid_length:
|
|
690
|
+
raise GitError("anchor must be a full commit object ID", reason="invalid-anchor")
|
|
691
|
+
if self.resolve(oid) != oid:
|
|
692
|
+
raise GitError("anchor does not name a commit", reason="invalid-anchor")
|
|
693
|
+
return oid
|
|
694
|
+
|
|
695
|
+
def head_or_none(self) -> str | None:
|
|
696
|
+
"""HEAD's commit, or ``None`` on an unborn branch (no commits yet)."""
|
|
697
|
+
code, out = self._target_rev("HEAD^{commit}")
|
|
698
|
+
if code == 0:
|
|
699
|
+
return self._oid(out.rstrip(b"\n"))
|
|
700
|
+
code, ref = self.run_status(["symbolic-ref", "--quiet", "HEAD"], source=True, ok=(0, 1))
|
|
701
|
+
ref = ref.rstrip(b"\n")
|
|
702
|
+
if code == 0 and re.fullmatch(rb"refs/heads/[\x21-\x7e]{1,1000}", ref):
|
|
703
|
+
code, _ = self._target_rev(ref.decode("ascii"))
|
|
704
|
+
if code == 1:
|
|
705
|
+
return None
|
|
706
|
+
raise GitError("HEAD does not resolve to a commit", reason="unknown-ref")
|
|
707
|
+
|
|
708
|
+
def merge_bases(self, a: str, b: str) -> list[str]:
|
|
709
|
+
code, out = self.run_status(["merge-base", "--all", a, b], ok=(0, 1))
|
|
710
|
+
return [] if code == 1 else [self._oid(line) for line in out.splitlines()]
|
|
711
|
+
|
|
712
|
+
# --- comparisons -----------------------------------------------------------------
|
|
713
|
+
|
|
714
|
+
def diff_trees(self, old: str, new: str) -> bytes:
|
|
715
|
+
"""Raw ``-z`` listing between two trees; ``-t`` also lists every changed tree."""
|
|
716
|
+
return self.run(
|
|
717
|
+
[
|
|
718
|
+
"diff-tree",
|
|
719
|
+
"-r",
|
|
720
|
+
"-t",
|
|
721
|
+
RENAME_THRESHOLD,
|
|
722
|
+
RENAME_LIMIT,
|
|
723
|
+
"--raw",
|
|
724
|
+
"-z",
|
|
725
|
+
"--no-abbrev",
|
|
726
|
+
"--no-commit-id",
|
|
727
|
+
"--no-ext-diff",
|
|
728
|
+
"--no-textconv",
|
|
729
|
+
"--ignore-submodules=none",
|
|
730
|
+
old,
|
|
731
|
+
new,
|
|
732
|
+
"--",
|
|
733
|
+
],
|
|
734
|
+
cap=MAX_RAW_BYTES,
|
|
735
|
+
)
|
|
736
|
+
|
|
737
|
+
def diff_index(self, old: str) -> bytes:
|
|
738
|
+
"""Raw listing of the private index against ``old`` (used to find unmerged paths)."""
|
|
739
|
+
return self.run(
|
|
740
|
+
[
|
|
741
|
+
"diff-index",
|
|
742
|
+
"--cached",
|
|
743
|
+
"--ita-invisible-in-index",
|
|
744
|
+
"-r",
|
|
745
|
+
"--raw",
|
|
746
|
+
"-z",
|
|
747
|
+
"--no-abbrev",
|
|
748
|
+
"--no-renames",
|
|
749
|
+
"--no-ext-diff",
|
|
750
|
+
"--no-textconv",
|
|
751
|
+
"--ignore-submodules=none",
|
|
752
|
+
old,
|
|
753
|
+
"--",
|
|
754
|
+
],
|
|
755
|
+
cap=MAX_RAW_BYTES,
|
|
756
|
+
)
|
|
757
|
+
|
|
758
|
+
def blob_hunks(self, old: str, new: str, cap: int) -> tuple[Hunk, ...]:
|
|
759
|
+
"""Hunks between two text blobs, numbered exactly as ``git diff -U0`` numbers them."""
|
|
760
|
+
# Only object IDs and fixed options reach Git. Git computes line matches
|
|
761
|
+
# without running configurable diff drivers or applying filters.
|
|
762
|
+
cr = ["--ignore-cr-at-eol"] if self.ignore_cr_at_eol else []
|
|
763
|
+
data = self.run(
|
|
764
|
+
[
|
|
765
|
+
"diff",
|
|
766
|
+
"--text",
|
|
767
|
+
"--unified=0",
|
|
768
|
+
"--inter-hunk-context=0",
|
|
769
|
+
"--no-ext-diff",
|
|
770
|
+
"--no-textconv",
|
|
771
|
+
"--no-color",
|
|
772
|
+
"--no-renames",
|
|
773
|
+
"--diff-algorithm=myers",
|
|
774
|
+
"--indent-heuristic",
|
|
775
|
+
*cr,
|
|
776
|
+
old,
|
|
777
|
+
new,
|
|
778
|
+
"--",
|
|
779
|
+
],
|
|
780
|
+
cap=cap,
|
|
781
|
+
)
|
|
782
|
+
# Blobs that differ only by CR at EOL have no hunks when CRs are ignored.
|
|
783
|
+
return _patch_hunks(data, allow_empty=self.ignore_cr_at_eol)
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def _patch_hunks(data: bytes, *, allow_empty: bool = False) -> tuple[Hunk, ...]:
|
|
787
|
+
hunks: list[Hunk] = []
|
|
788
|
+
for line in data.split(b"\n"):
|
|
789
|
+
# Content lines carry a +, - or space prefix, so only hunk headers
|
|
790
|
+
# start with "@@ ".
|
|
791
|
+
if line.startswith(b"@@ "):
|
|
792
|
+
m = _HUNK.match(line)
|
|
793
|
+
if not m:
|
|
794
|
+
raise GitError("malformed Git hunk header", reason="bad-output")
|
|
795
|
+
a, na, b, nb = (int(v) if v is not None else 1 for v in m.groups())
|
|
796
|
+
try:
|
|
797
|
+
hunks.append(Hunk(old_start=a, old_count=na, new_start=b, new_count=nb))
|
|
798
|
+
except ValueError as exc:
|
|
799
|
+
raise GitError("malformed Git hunk header", reason="bad-output") from exc
|
|
800
|
+
if not hunks and not allow_empty:
|
|
801
|
+
raise GitError("different text blobs yielded no hunks", reason="bad-output")
|
|
802
|
+
return tuple(hunks)
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def _safe_name(raw: bytes) -> tuple[str, bool]:
|
|
806
|
+
"""Decode a Git path; invalid ones become a placeholder (``ok`` False).
|
|
807
|
+
|
|
808
|
+
The placeholder starts with ``/``, which this check itself rejects, so it
|
|
809
|
+
can never equal a real path; it is derived from the raw bytes, so distinct
|
|
810
|
+
invalid paths keep distinct placeholders.
|
|
811
|
+
"""
|
|
812
|
+
try:
|
|
813
|
+
name = raw.decode("utf-8")
|
|
814
|
+
except UnicodeDecodeError:
|
|
815
|
+
name = ""
|
|
816
|
+
# Cc: controls (newline, ESC); Cf: format characters including every bidi
|
|
817
|
+
# control; Zl/Zp: U+2028/U+2029.
|
|
818
|
+
if (
|
|
819
|
+
not name
|
|
820
|
+
or "\\" in name
|
|
821
|
+
or any(part in ("", ".", "..") for part in name.split("/"))
|
|
822
|
+
or any(unicodedata.category(c) in ("Cc", "Cf", "Zl", "Zp") for c in name)
|
|
823
|
+
):
|
|
824
|
+
return f"/[unsupported path {hashlib.sha256(raw).hexdigest()[:32]}]", False
|
|
825
|
+
return name, True
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _copy_index(source: Path, dest: Path) -> None:
|
|
829
|
+
"""Copy one generation of a Git index into a trusted directory."""
|
|
830
|
+
# An index can be much larger than the subset of changed files. Copy into
|
|
831
|
+
# a trusted directory, preserving a single generation while git add races.
|
|
832
|
+
named = source.lstat()
|
|
833
|
+
if not stat.S_ISREG(named.st_mode):
|
|
834
|
+
raise GitError("expected a regular Git index", reason="bad-index")
|
|
835
|
+
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
|
|
836
|
+
flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
837
|
+
with os.fdopen(os.open(source, flags), "rb") as stream, dest.open("xb") as out:
|
|
838
|
+
opened = os.fstat(stream.fileno())
|
|
839
|
+
if not stat.S_ISREG(opened.st_mode) or not os.path.samestat(named, opened):
|
|
840
|
+
raise GitError("Git index changed while it was being opened", reason="bad-index")
|
|
841
|
+
size = opened.st_size
|
|
842
|
+
if size > MAX_INDEX_BYTES:
|
|
843
|
+
raise GitError(f"Git index exceeds {MAX_INDEX_BYTES}-byte limit", reason="bad-index")
|
|
844
|
+
remaining = size
|
|
845
|
+
while remaining:
|
|
846
|
+
block = stream.read(min(remaining, 256 * 1024))
|
|
847
|
+
if not block:
|
|
848
|
+
raise GitError("incomplete Git index", reason="bad-index")
|
|
849
|
+
out.write(block)
|
|
850
|
+
remaining -= len(block)
|
|
851
|
+
finished = os.fstat(stream.fileno())
|
|
852
|
+
if stream.read(1) or finished.st_size != size or finished.st_mtime_ns != opened.st_mtime_ns:
|
|
853
|
+
raise GitError("Git index changed while it was being read", reason="bad-index")
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _split_index_name(private_index: Path, hash_width: int) -> str | None:
|
|
857
|
+
"""Locate the split-index ``link`` extension in a private snapshot (gitformat-index)."""
|
|
858
|
+
with private_index.open("rb") as stream:
|
|
859
|
+
end = os.fstat(stream.fileno()).st_size - hash_width
|
|
860
|
+
if end < 12:
|
|
861
|
+
raise GitError("truncated Git index header", reason="bad-index")
|
|
862
|
+
with mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data:
|
|
863
|
+
magic, version, entries = struct.unpack_from(">4sII", data)
|
|
864
|
+
if magic != b"DIRC" or version not in {2, 3, 4}:
|
|
865
|
+
raise GitError("unsupported Git index header", reason="bad-index")
|
|
866
|
+
pos = 12
|
|
867
|
+
for _ in range(entries):
|
|
868
|
+
start = pos
|
|
869
|
+
pos += 40 + hash_width + 2 # stat fields, object ID, flags
|
|
870
|
+
if pos > end:
|
|
871
|
+
raise GitError("truncated Git index entry", reason="bad-index")
|
|
872
|
+
if data[pos - 2] & 0x40:
|
|
873
|
+
if version == 2:
|
|
874
|
+
raise GitError("invalid flags in Git index v2", reason="bad-index")
|
|
875
|
+
pos += 2
|
|
876
|
+
if version == 4:
|
|
877
|
+
# The prefix length is a variable-width integer. We only
|
|
878
|
+
# need its boundary to skip the NUL-terminated suffix.
|
|
879
|
+
for _ in range(10):
|
|
880
|
+
if pos >= end:
|
|
881
|
+
raise GitError("truncated Git index path prefix", reason="bad-index")
|
|
882
|
+
pos += 1
|
|
883
|
+
if not data[pos - 1] & 0x80:
|
|
884
|
+
break
|
|
885
|
+
else:
|
|
886
|
+
raise GitError("oversized Git index path prefix", reason="bad-index")
|
|
887
|
+
nul = data.find(b"\0", pos, end)
|
|
888
|
+
if nul < 0:
|
|
889
|
+
raise GitError("unterminated Git index path", reason="bad-index")
|
|
890
|
+
pos = nul + 1
|
|
891
|
+
if version < 4:
|
|
892
|
+
pos += -(pos - start) % 8
|
|
893
|
+
if pos > end:
|
|
894
|
+
raise GitError("truncated Git index padding", reason="bad-index")
|
|
895
|
+
link = None
|
|
896
|
+
while pos < end:
|
|
897
|
+
if end - pos < 8:
|
|
898
|
+
raise GitError("truncated Git index extension header", reason="bad-index")
|
|
899
|
+
kind, length = struct.unpack_from(">4sI", data, pos)
|
|
900
|
+
pos += 8
|
|
901
|
+
if length > end - pos:
|
|
902
|
+
raise GitError("truncated Git index extension", reason="bad-index")
|
|
903
|
+
if kind == b"link":
|
|
904
|
+
if link is not None or length < hash_width:
|
|
905
|
+
raise GitError("invalid split-index link", reason="bad-index")
|
|
906
|
+
link = data[pos : pos + hash_width]
|
|
907
|
+
pos += length
|
|
908
|
+
return "sharedindex." + link.hex() if link is not None and any(link) else None
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
# --- building FileChanges ------------------------------------------------------
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
@dataclass(frozen=True, slots=True)
|
|
915
|
+
class _Entry:
|
|
916
|
+
status: FileStatus
|
|
917
|
+
path: bytes
|
|
918
|
+
old_path: bytes | None # renames only
|
|
919
|
+
old_mode: str
|
|
920
|
+
new_mode: str
|
|
921
|
+
old_oid: str
|
|
922
|
+
new_oid: str
|
|
923
|
+
similarity: int | None
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
@dataclass(slots=True)
|
|
927
|
+
class _Listing:
|
|
928
|
+
entries: list[_Entry] = field(default_factory=list)
|
|
929
|
+
trees: set[str] = field(default_factory=set)
|
|
930
|
+
overflow: int = 0 # files beyond max_files, counted only
|
|
931
|
+
unmerged: int = 0
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
def _parse_raw(raw: bytes, oid_length: int, max_files: int) -> _Listing:
|
|
935
|
+
"""Parse ``--raw -z`` output without materialising more than ``max_files`` entries.
|
|
936
|
+
|
|
937
|
+
Tree records (``-t``) are collected for verification, not reviewed.
|
|
938
|
+
"""
|
|
939
|
+
listing = _Listing()
|
|
940
|
+
oid = rb"([0-9a-f]{%d})" % oid_length
|
|
941
|
+
header = re.compile(
|
|
942
|
+
rb":([0-7]{6}) ([0-7]{6}) " + oid + b" " + oid + rb" ([AMDRTU])([0-9]{0,3})"
|
|
943
|
+
)
|
|
944
|
+
pos, size = 0, len(raw)
|
|
945
|
+
|
|
946
|
+
def field_at(start: int) -> tuple[bytes, int]:
|
|
947
|
+
end = raw.find(b"\0", start)
|
|
948
|
+
if end < 0:
|
|
949
|
+
raise GitError("malformed Git diff listing", reason="bad-output")
|
|
950
|
+
return raw[start:end], end + 1
|
|
951
|
+
|
|
952
|
+
while pos < size:
|
|
953
|
+
record, pos = field_at(pos)
|
|
954
|
+
m = header.fullmatch(record)
|
|
955
|
+
if not m:
|
|
956
|
+
raise GitError("unsupported Git diff record", reason="bad-output")
|
|
957
|
+
letter, score = m[5], m[6]
|
|
958
|
+
names = []
|
|
959
|
+
for _ in range(2 if letter == b"R" else 1):
|
|
960
|
+
name, pos = field_at(pos)
|
|
961
|
+
names.append(name)
|
|
962
|
+
old_mode, new_mode, old_oid, new_oid = (v.decode("ascii") for v in m.groups()[:4])
|
|
963
|
+
if _TREE in (old_mode, new_mode):
|
|
964
|
+
if {old_mode, new_mode} - {_TREE, _ABSENT} or letter not in b"AMD":
|
|
965
|
+
raise GitError("unsupported Git diff record", reason="bad-output")
|
|
966
|
+
listing.trees.update(
|
|
967
|
+
o for mode, o in ((old_mode, old_oid), (new_mode, new_oid)) if mode == _TREE
|
|
968
|
+
)
|
|
969
|
+
continue
|
|
970
|
+
if letter == b"U":
|
|
971
|
+
listing.unmerged += 1
|
|
972
|
+
continue
|
|
973
|
+
if (letter == b"R") != bool(score) or not all(names) or (score and int(score) > 100):
|
|
974
|
+
raise GitError("unsupported Git diff record", reason="bad-output")
|
|
975
|
+
if len(listing.entries) >= max_files:
|
|
976
|
+
listing.overflow += 1
|
|
977
|
+
continue
|
|
978
|
+
listing.entries.append(
|
|
979
|
+
_Entry(
|
|
980
|
+
status=_STATUS[letter],
|
|
981
|
+
path=names[-1],
|
|
982
|
+
old_path=names[0] if letter == b"R" else None,
|
|
983
|
+
old_mode=old_mode,
|
|
984
|
+
new_mode=new_mode,
|
|
985
|
+
old_oid=old_oid,
|
|
986
|
+
new_oid=new_oid,
|
|
987
|
+
similarity=int(score) if score else None,
|
|
988
|
+
)
|
|
989
|
+
)
|
|
990
|
+
return listing
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def _line_count(raw: bytes) -> int:
|
|
994
|
+
return raw.count(b"\n") + (1 if raw and not raw.endswith(b"\n") else 0)
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
def _source_like(path: str) -> bool:
|
|
998
|
+
name = path.rsplit("/", 1)[-1].lower()
|
|
999
|
+
if name in _SOURCE_NAMES or name.startswith(".env."):
|
|
1000
|
+
return True
|
|
1001
|
+
return "." in name.lstrip(".") and name.rsplit(".", 1)[-1] in _SOURCE_EXTENSIONS
|
|
1002
|
+
|
|
1003
|
+
|
|
1004
|
+
def _is_binary(raw: bytes, mode: str, path: str) -> bool:
|
|
1005
|
+
"""SPEC 5.1 NUL policy, called only for content that contains a NUL byte.
|
|
1006
|
+
|
|
1007
|
+
A source-like name, a shebang or the executable bit keeps the file text even
|
|
1008
|
+
when it starts with a binary magic number, so a polyglot (PNG header plus
|
|
1009
|
+
PHP) is still reviewed.
|
|
1010
|
+
"""
|
|
1011
|
+
return not (_source_like(path) or raw.startswith(b"#!") or mode == _EXECUTABLE)
|
|
1012
|
+
|
|
1013
|
+
|
|
1014
|
+
_BMFF_BRANDS = {
|
|
1015
|
+
b"avif": "avif",
|
|
1016
|
+
b"avis": "avif",
|
|
1017
|
+
b"heic": "heic",
|
|
1018
|
+
b"heix": "heic",
|
|
1019
|
+
b"hevc": "heic",
|
|
1020
|
+
b"hevx": "heic",
|
|
1021
|
+
b"heim": "heic",
|
|
1022
|
+
b"heis": "heic",
|
|
1023
|
+
b"mif1": "heif",
|
|
1024
|
+
b"msf1": "heif",
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
def image_format(raw: bytes) -> str | None:
|
|
1029
|
+
"""The image format ``raw`` starts with (PNG, JPEG, GIF, WebP, ICO, BMP, TIFF, AVIF/HEIC)."""
|
|
1030
|
+
if raw.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
1031
|
+
return "png"
|
|
1032
|
+
if raw.startswith(b"\xff\xd8\xff"):
|
|
1033
|
+
return "jpeg"
|
|
1034
|
+
if raw[:6] in (b"GIF87a", b"GIF89a"):
|
|
1035
|
+
return "gif"
|
|
1036
|
+
if raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":
|
|
1037
|
+
return "webp"
|
|
1038
|
+
if raw[:4] == b"\x00\x00\x01\x00" and raw[4:6] not in (b"", b"\x00", b"\x00\x00"):
|
|
1039
|
+
return "ico"
|
|
1040
|
+
# "BM" alone is too weak: the header also states the file's exact size.
|
|
1041
|
+
if raw[:2] == b"BM" and len(raw) >= 14 and int.from_bytes(raw[2:6], "little") == len(raw):
|
|
1042
|
+
return "bmp"
|
|
1043
|
+
if raw[:4] in (b"II*\x00", b"MM\x00*"):
|
|
1044
|
+
return "tiff"
|
|
1045
|
+
if raw[4:8] == b"ftyp" and raw[8:12] in _BMFF_BRANDS:
|
|
1046
|
+
return _BMFF_BRANDS[raw[8:12]]
|
|
1047
|
+
return None
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
@dataclass(slots=True)
|
|
1051
|
+
class _Side:
|
|
1052
|
+
kind: FileKind
|
|
1053
|
+
text: str | None = None
|
|
1054
|
+
flags: frozenset[str] = frozenset()
|
|
1055
|
+
lines: int = 0
|
|
1056
|
+
target: str | None = None
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
def _classify(raw: bytes, mode: str, path: str) -> _Side:
|
|
1060
|
+
if mode == _SYMLINK:
|
|
1061
|
+
return _Side(FileKind.SYMLINK, target=raw.decode("utf-8", "surrogateescape"))
|
|
1062
|
+
flags: set[str] = set()
|
|
1063
|
+
if len(raw) <= _LFS_MAX_BYTES and _LFS_POINTER.fullmatch(raw):
|
|
1064
|
+
kind = FileKind.LFS_POINTER
|
|
1065
|
+
elif b"\0" in raw:
|
|
1066
|
+
if _is_binary(raw, mode, path):
|
|
1067
|
+
image = image_format(raw)
|
|
1068
|
+
return _Side(
|
|
1069
|
+
FileKind.BINARY, flags=frozenset({FLAG_IMAGE_PREFIX + image} if image else ())
|
|
1070
|
+
)
|
|
1071
|
+
kind = FileKind.TEXT
|
|
1072
|
+
flags.add(FLAG_NUL_BYTES)
|
|
1073
|
+
else:
|
|
1074
|
+
kind = FileKind.TEXT
|
|
1075
|
+
try:
|
|
1076
|
+
text = raw.decode("utf-8")
|
|
1077
|
+
except UnicodeDecodeError:
|
|
1078
|
+
text = raw.decode("utf-8", "surrogateescape")
|
|
1079
|
+
flags.add(FLAG_NON_UTF8)
|
|
1080
|
+
return _Side(kind, text=text, flags=frozenset(flags), lines=_line_count(raw))
|
|
1081
|
+
|
|
1082
|
+
|
|
1083
|
+
@dataclass(slots=True)
|
|
1084
|
+
class _Work:
|
|
1085
|
+
entry: _Entry
|
|
1086
|
+
path: str
|
|
1087
|
+
old_path: str | None
|
|
1088
|
+
flags: set[str] = field(default_factory=set)
|
|
1089
|
+
issues: list[str] = field(default_factory=list)
|
|
1090
|
+
skipped: str | None = None
|
|
1091
|
+
sizes: dict[str, int] = field(default_factory=dict) # "old"/"new" -> bytes
|
|
1092
|
+
|
|
1093
|
+
def skip(self, reason: str, message: str) -> None:
|
|
1094
|
+
if self.skipped is None:
|
|
1095
|
+
self.skipped = reason
|
|
1096
|
+
self.flags.add(SKIPPED_PREFIX + reason)
|
|
1097
|
+
self.issues.append(message)
|
|
1098
|
+
|
|
1099
|
+
def sides(self) -> list[tuple[str, str, str]]:
|
|
1100
|
+
"""(side, mode, oid) for the sides whose blob holds content to read."""
|
|
1101
|
+
e = self.entry
|
|
1102
|
+
return [
|
|
1103
|
+
(side, mode, oid)
|
|
1104
|
+
for side, mode, oid in (("old", e.old_mode, e.old_oid), ("new", e.new_mode, e.new_oid))
|
|
1105
|
+
if mode in _REGULAR or mode == _SYMLINK
|
|
1106
|
+
]
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def _plan(entries: list[_Entry]) -> list[_Work]:
|
|
1110
|
+
work: list[_Work] = []
|
|
1111
|
+
for e in entries:
|
|
1112
|
+
path, ok = _safe_name(e.path)
|
|
1113
|
+
old_path, old_ok = _safe_name(e.old_path) if e.old_path is not None else (None, True)
|
|
1114
|
+
item = _Work(e, path, old_path)
|
|
1115
|
+
if e.old_mode in _REGULAR and e.new_mode in _REGULAR and e.old_mode != e.new_mode:
|
|
1116
|
+
item.flags.add(FLAG_MODE_CHANGE)
|
|
1117
|
+
if not (ok and old_ok):
|
|
1118
|
+
item.flags.add(FLAG_INVALID_PATH)
|
|
1119
|
+
item.skip(
|
|
1120
|
+
"invalid-path",
|
|
1121
|
+
"path is not valid UTF-8 or contains control, format or separator "
|
|
1122
|
+
"characters; shown as a placeholder and not reviewed",
|
|
1123
|
+
)
|
|
1124
|
+
if e.old_mode not in _KNOWN_MODES or e.new_mode not in _KNOWN_MODES:
|
|
1125
|
+
item.skip("unsupported-mode", "unsupported Git entry mode")
|
|
1126
|
+
work.append(item)
|
|
1127
|
+
return work
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def _apply_byte_limits(git: Git, work: list[_Work], limits: Limits) -> dict[str, tuple[str, int]]:
|
|
1131
|
+
oids = sorted({oid for item in work if not item.skipped for _, _, oid in item.sides()})
|
|
1132
|
+
info = git.object_info(oids)
|
|
1133
|
+
wanted: dict[str, tuple[str, int]] = {}
|
|
1134
|
+
used = 0
|
|
1135
|
+
for item in work:
|
|
1136
|
+
if item.skipped:
|
|
1137
|
+
continue
|
|
1138
|
+
sides = item.sides()
|
|
1139
|
+
if any(info.get(oid, ("", 0))[0] != "blob" for _, _, oid in sides):
|
|
1140
|
+
item.skip("missing-object", "Git object unavailable")
|
|
1141
|
+
continue
|
|
1142
|
+
item.sizes = {side: info[oid][1] for side, _, oid in sides}
|
|
1143
|
+
total = sum(item.sizes.values())
|
|
1144
|
+
if any(size > limits.max_file_bytes for size in item.sizes.values()):
|
|
1145
|
+
item.skip("max-file-bytes", f"file exceeds the {limits.max_file_bytes}-byte limit")
|
|
1146
|
+
elif used + total > limits.max_total_bytes:
|
|
1147
|
+
item.skip(
|
|
1148
|
+
"max-total-bytes", f"change exceeds the {limits.max_total_bytes}-byte total limit"
|
|
1149
|
+
)
|
|
1150
|
+
else:
|
|
1151
|
+
used += total
|
|
1152
|
+
wanted.update((oid, info[oid]) for _, _, oid in sides)
|
|
1153
|
+
return wanted
|
|
1154
|
+
|
|
1155
|
+
|
|
1156
|
+
@dataclass(slots=True)
|
|
1157
|
+
class _State:
|
|
1158
|
+
max_file_lines: int
|
|
1159
|
+
max_total_lines: int
|
|
1160
|
+
lines: int = 0
|
|
1161
|
+
out_of_time: bool = False
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
def _build(git: Git, item: _Work, blobs: dict[str, bytes], state: _State) -> FileChange:
|
|
1165
|
+
"""Turn one planned entry into a FileChange."""
|
|
1166
|
+
e = item.entry
|
|
1167
|
+
old_mode = None if e.old_mode == _ABSENT else e.old_mode
|
|
1168
|
+
new_mode = None if e.new_mode == _ABSENT else e.new_mode
|
|
1169
|
+
primary = new_mode or old_mode or _ABSENT
|
|
1170
|
+
kind = {_SYMLINK: FileKind.SYMLINK, _GITLINK: FileKind.SUBMODULE}.get(primary, FileKind.TEXT)
|
|
1171
|
+
sides: dict[str, _Side] = {}
|
|
1172
|
+
hunks: tuple[Hunk, ...] = ()
|
|
1173
|
+
if not item.skipped:
|
|
1174
|
+
for side, mode, oid in item.sides():
|
|
1175
|
+
path = item.old_path if side == "old" and item.old_path else item.path
|
|
1176
|
+
sides[side] = _classify(blobs[oid], mode, path)
|
|
1177
|
+
lines = {s: v.lines for s, v in sides.items() if v.text is not None}
|
|
1178
|
+
if any(n > state.max_file_lines for n in lines.values()):
|
|
1179
|
+
item.skip("max-file-lines", f"file exceeds the {state.max_file_lines}-line limit")
|
|
1180
|
+
elif state.lines + sum(lines.values()) > state.max_total_lines:
|
|
1181
|
+
item.skip(
|
|
1182
|
+
"max-total-lines", f"change exceeds the {state.max_total_lines}-line total limit"
|
|
1183
|
+
)
|
|
1184
|
+
else:
|
|
1185
|
+
state.lines += sum(lines.values())
|
|
1186
|
+
if item.skipped:
|
|
1187
|
+
sides = {}
|
|
1188
|
+
old = sides.get("old")
|
|
1189
|
+
new = sides.get("new")
|
|
1190
|
+
main = new if new_mode is not None else old
|
|
1191
|
+
if main is not None:
|
|
1192
|
+
kind = main.kind
|
|
1193
|
+
item.flags.update(main.flags)
|
|
1194
|
+
for other in (old, new):
|
|
1195
|
+
if other is not None and other is not main:
|
|
1196
|
+
# An image flag describes the reviewed (main) side only.
|
|
1197
|
+
item.flags.update(f for f in other.flags if not f.startswith(FLAG_IMAGE_PREFIX))
|
|
1198
|
+
old_text = old.text if old else None
|
|
1199
|
+
new_text = new.text if new else None
|
|
1200
|
+
if not item.skipped:
|
|
1201
|
+
hunks = _hunks(git, item, old, new, state)
|
|
1202
|
+
if item.skipped: # a per-file Git failure inside _hunks drops the content
|
|
1203
|
+
old_text = new_text = None
|
|
1204
|
+
hunks = ()
|
|
1205
|
+
return FileChange(
|
|
1206
|
+
path=item.path,
|
|
1207
|
+
old_path=item.old_path,
|
|
1208
|
+
status=e.status,
|
|
1209
|
+
kind=kind,
|
|
1210
|
+
old_mode=old_mode,
|
|
1211
|
+
new_mode=new_mode,
|
|
1212
|
+
old_text=old_text,
|
|
1213
|
+
new_text=new_text,
|
|
1214
|
+
old_size=item.sizes.get("old"),
|
|
1215
|
+
new_size=item.sizes.get("new"),
|
|
1216
|
+
added_lines=frozenset(n for h in hunks for n in h.new_lines),
|
|
1217
|
+
removed_lines=frozenset(n for h in hunks for n in h.old_lines),
|
|
1218
|
+
hunks=hunks,
|
|
1219
|
+
similarity=e.similarity,
|
|
1220
|
+
symlink_target=main.target if main is not None else None,
|
|
1221
|
+
submodule_old=e.old_oid if e.old_mode == _GITLINK else None,
|
|
1222
|
+
submodule_new=e.new_oid if e.new_mode == _GITLINK else None,
|
|
1223
|
+
flags=frozenset(item.flags),
|
|
1224
|
+
issues=tuple(item.issues),
|
|
1225
|
+
)
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
_PER_FILE_FAILURES = {
|
|
1229
|
+
"output-cap": "Git diff output for this file exceeded its cap",
|
|
1230
|
+
"timeout": "Git diff for this file timed out",
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
|
|
1234
|
+
def _hunks(
|
|
1235
|
+
git: Git, item: _Work, old: _Side | None, new: _Side | None, state: _State
|
|
1236
|
+
) -> tuple[Hunk, ...]:
|
|
1237
|
+
e = item.entry
|
|
1238
|
+
old_text = old.text if old else None
|
|
1239
|
+
new_text = new.text if new else None
|
|
1240
|
+
if old is not None and new is not None and old_text is not None and new_text is not None:
|
|
1241
|
+
if e.old_oid == e.new_oid:
|
|
1242
|
+
return ()
|
|
1243
|
+
if state.out_of_time:
|
|
1244
|
+
item.skip("git-time", "Git time budget exhausted before this file was compared")
|
|
1245
|
+
return ()
|
|
1246
|
+
# Each -U0 hunk adds a header and each line a prefix; the overhead per
|
|
1247
|
+
# line bounds the output for any ordinary file.
|
|
1248
|
+
cap = item.sizes["old"] + item.sizes["new"] + 64 * (old.lines + new.lines) + 64 * 1024
|
|
1249
|
+
try:
|
|
1250
|
+
return git.blob_hunks(e.old_oid, e.new_oid, cap)
|
|
1251
|
+
except GitError as exc:
|
|
1252
|
+
if exc.reason == "time-budget":
|
|
1253
|
+
state.out_of_time = True
|
|
1254
|
+
item.skip("git-time", "Git time budget exhausted before this file was compared")
|
|
1255
|
+
return ()
|
|
1256
|
+
if exc.reason in _PER_FILE_FAILURES:
|
|
1257
|
+
item.skip(exc.reason, _PER_FILE_FAILURES[exc.reason])
|
|
1258
|
+
return ()
|
|
1259
|
+
raise
|
|
1260
|
+
# One side has no text (absent, binary, symlink or submodule): every line of
|
|
1261
|
+
# the text side is changed.
|
|
1262
|
+
if new_text is not None and new is not None and new.lines:
|
|
1263
|
+
return (Hunk(old_start=0, old_count=0, new_start=1, new_count=new.lines),)
|
|
1264
|
+
if old_text is not None and old is not None and old.lines:
|
|
1265
|
+
return (Hunk(old_start=1, old_count=old.lines, new_start=0, new_count=0),)
|
|
1266
|
+
return ()
|
|
1267
|
+
|
|
1268
|
+
|
|
1269
|
+
def _compare(
|
|
1270
|
+
git: Git,
|
|
1271
|
+
old_tree: str,
|
|
1272
|
+
new_tree: str,
|
|
1273
|
+
limits: Limits,
|
|
1274
|
+
prepare: Callable[[list[_Work]], None] | None = None,
|
|
1275
|
+
) -> tuple[tuple[FileChange, ...], list[str]]:
|
|
1276
|
+
"""Compare two hash-verified trees and build every FileChange.
|
|
1277
|
+
|
|
1278
|
+
``prepare`` sees the planned entries before any blob is read (worktree mode
|
|
1279
|
+
marks paths it could not snapshot as skipped and adds flags there).
|
|
1280
|
+
"""
|
|
1281
|
+
listing = _parse_raw(git.diff_trees(old_tree, new_tree), git.oid_length, limits.max_files)
|
|
1282
|
+
# Root trees plus every changed tree Git descended into: a forged tree
|
|
1283
|
+
# could otherwise hide or invent changes.
|
|
1284
|
+
git.verify_trees({old_tree, new_tree, *listing.trees})
|
|
1285
|
+
issues: list[str] = []
|
|
1286
|
+
if listing.overflow:
|
|
1287
|
+
issues.append(
|
|
1288
|
+
f"{listing.overflow} file(s) beyond the {limits.max_files}-file limit were not reviewed"
|
|
1289
|
+
)
|
|
1290
|
+
work = _plan(listing.entries)
|
|
1291
|
+
if prepare is not None:
|
|
1292
|
+
prepare(work)
|
|
1293
|
+
blobs, mismatched = git.read_objects(_apply_byte_limits(git, work, limits))
|
|
1294
|
+
for item in work:
|
|
1295
|
+
if not item.skipped and any(oid in mismatched for _, _, oid in item.sides()):
|
|
1296
|
+
item.skip("object-mismatch", "Git object content does not match its ID")
|
|
1297
|
+
state = _State(limits.max_file_lines, limits.max_total_lines)
|
|
1298
|
+
return tuple(_build(git, item, blobs, state) for item in work), issues
|
|
1299
|
+
|
|
1300
|
+
|
|
1301
|
+
# --- entry points ----------------------------------------------------------------
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
@contextlib.contextmanager
|
|
1305
|
+
def _session(repo: str | os.PathLike[str], limits: Limits) -> Iterator[Git]:
|
|
1306
|
+
if not isinstance(limits, Limits):
|
|
1307
|
+
raise TypeError("limits must be a Limits value")
|
|
1308
|
+
if "\0" in os.fsdecode(os.fspath(repo)):
|
|
1309
|
+
raise GitError("review repository path contains a NUL byte", reason="bad-repo")
|
|
1310
|
+
try:
|
|
1311
|
+
source = Path(repo).resolve(strict=True)
|
|
1312
|
+
if not source.is_dir():
|
|
1313
|
+
raise GitError("review repository must be a directory", reason="bad-repo")
|
|
1314
|
+
with tempfile.TemporaryDirectory(prefix="codeveto-git-") as tmp:
|
|
1315
|
+
git = Git(source, Path(tmp), time_budget=limits.git_seconds)
|
|
1316
|
+
git.isolate()
|
|
1317
|
+
yield git
|
|
1318
|
+
except OSError as exc:
|
|
1319
|
+
raise GitError(f"cannot read the repository ({type(exc).__name__})", reason="os") from exc
|
|
1320
|
+
|
|
1321
|
+
|
|
1322
|
+
def read_range(
|
|
1323
|
+
repo: str | os.PathLike[str],
|
|
1324
|
+
base: str,
|
|
1325
|
+
head: str = "HEAD",
|
|
1326
|
+
*,
|
|
1327
|
+
comparison: Literal["merge-base", "direct"] = "merge-base",
|
|
1328
|
+
anchor: str | None = None,
|
|
1329
|
+
limits: Limits = DEFAULT_LIMITS,
|
|
1330
|
+
) -> Changeset:
|
|
1331
|
+
"""Compare ``head`` with the merge base of ``base`` and ``head`` (or ``base`` itself).
|
|
1332
|
+
|
|
1333
|
+
The anchor is the merge base (``direct``: the base) with source ``"base"``;
|
|
1334
|
+
an explicit full-OID ``anchor`` overrides it with source ``"explicit"``.
|
|
1335
|
+
Without a unique merge base the result has no files and an issue.
|
|
1336
|
+
"""
|
|
1337
|
+
if comparison not in ("merge-base", "direct"):
|
|
1338
|
+
raise ValueError(f"unknown comparison {comparison!r}")
|
|
1339
|
+
with _session(repo, limits) as git:
|
|
1340
|
+
start, end = git.resolve(base), git.resolve(head)
|
|
1341
|
+
explicit = git.resolve_anchor(anchor) if anchor is not None else None
|
|
1342
|
+
source: AnchorSource = "explicit" if explicit else "base"
|
|
1343
|
+
merge_base: str | None = None
|
|
1344
|
+
compared = start
|
|
1345
|
+
if comparison == "merge-base":
|
|
1346
|
+
bases = git.merge_bases(start, end)
|
|
1347
|
+
if len(bases) != 1:
|
|
1348
|
+
problem = "no merge base" if not bases else f"{len(bases)} merge bases"
|
|
1349
|
+
return Changeset(
|
|
1350
|
+
mode="range",
|
|
1351
|
+
base=start,
|
|
1352
|
+
head=end,
|
|
1353
|
+
merge_base=None,
|
|
1354
|
+
anchor=explicit,
|
|
1355
|
+
anchor_source=source,
|
|
1356
|
+
issues=(
|
|
1357
|
+
f"base and head have {problem}; a unique merge base is required "
|
|
1358
|
+
"(use a direct comparison or a different base)",
|
|
1359
|
+
),
|
|
1360
|
+
)
|
|
1361
|
+
merge_base = compared = bases[0]
|
|
1362
|
+
old_tree, new_tree = git.commit(compared)[0], git.commit(end)[0]
|
|
1363
|
+
files, issues = _compare(git, old_tree, new_tree, limits)
|
|
1364
|
+
return Changeset(
|
|
1365
|
+
mode="range",
|
|
1366
|
+
base=start,
|
|
1367
|
+
head=end,
|
|
1368
|
+
merge_base=merge_base,
|
|
1369
|
+
anchor=explicit or compared,
|
|
1370
|
+
anchor_source=source,
|
|
1371
|
+
files=files,
|
|
1372
|
+
issues=tuple(issues),
|
|
1373
|
+
)
|
|
1374
|
+
|
|
1375
|
+
|
|
1376
|
+
def read_commit(
|
|
1377
|
+
repo: str | os.PathLike[str],
|
|
1378
|
+
commit: str,
|
|
1379
|
+
*,
|
|
1380
|
+
anchor: str | None = None,
|
|
1381
|
+
limits: Limits = DEFAULT_LIMITS,
|
|
1382
|
+
) -> Changeset:
|
|
1383
|
+
"""Compare ``commit`` with its first parent (a root commit: the empty tree).
|
|
1384
|
+
|
|
1385
|
+
The anchor is the first parent (or the empty tree OID) with source
|
|
1386
|
+
``"parent"``; an explicit full-OID ``anchor`` overrides it.
|
|
1387
|
+
"""
|
|
1388
|
+
with _session(repo, limits) as git:
|
|
1389
|
+
target = git.resolve(commit)
|
|
1390
|
+
explicit = git.resolve_anchor(anchor) if anchor is not None else None
|
|
1391
|
+
new_tree, parents = git.commit(target)
|
|
1392
|
+
parent = parents[0] if parents else None
|
|
1393
|
+
old_tree = git.commit(parent)[0] if parent else git.empty_tree
|
|
1394
|
+
files, issues = _compare(git, old_tree, new_tree, limits)
|
|
1395
|
+
return Changeset(
|
|
1396
|
+
mode="commit",
|
|
1397
|
+
base=parent,
|
|
1398
|
+
head=target,
|
|
1399
|
+
merge_base=None,
|
|
1400
|
+
anchor=explicit or parent or git.empty_tree,
|
|
1401
|
+
anchor_source="explicit" if explicit else "parent",
|
|
1402
|
+
files=files,
|
|
1403
|
+
issues=tuple(issues),
|
|
1404
|
+
)
|
|
1405
|
+
|
|
1406
|
+
|
|
1407
|
+
def _copy_target_index(git: Git) -> None:
|
|
1408
|
+
"""Copy the target's index (and its shared index when split) into the isolation repository.
|
|
1409
|
+
|
|
1410
|
+
The copy is taken once, so later ``git add`` races and an ``index.lock``
|
|
1411
|
+
do not matter, and the target's index is never written.
|
|
1412
|
+
"""
|
|
1413
|
+
# Built from the Git directory without resolving the final component,
|
|
1414
|
+
# so a symlinked index is refused rather than followed.
|
|
1415
|
+
index = git.git_dir() / "index"
|
|
1416
|
+
# No index file yet (nothing ever staged) reads as an empty index.
|
|
1417
|
+
if os.path.lexists(index):
|
|
1418
|
+
private = git.bare / "index"
|
|
1419
|
+
_copy_index(index, private)
|
|
1420
|
+
shared = _split_index_name(private, git.oid_length // 2)
|
|
1421
|
+
if shared:
|
|
1422
|
+
_copy_index(index.with_name(shared), git.bare / shared)
|
|
1423
|
+
|
|
1424
|
+
|
|
1425
|
+
def read_anchor_file(
|
|
1426
|
+
repo: str | os.PathLike[str],
|
|
1427
|
+
anchor: str,
|
|
1428
|
+
name: str = ".codeveto.toml",
|
|
1429
|
+
*,
|
|
1430
|
+
cap: int = 64 * 1024,
|
|
1431
|
+
limits: Limits = DEFAULT_LIMITS,
|
|
1432
|
+
) -> bytes | None:
|
|
1433
|
+
"""Bytes of the top-level file ``name`` in the trust anchor's tree (SPEC 7.2).
|
|
1434
|
+
|
|
1435
|
+
Only Git objects are read, through the isolation repository: the anchor
|
|
1436
|
+
commit, its root tree and the blob are each hash-verified, so the working
|
|
1437
|
+
tree, the index, the reviewed head and forged objects never apply.
|
|
1438
|
+
Returns ``None`` when the tree has no such entry or ``anchor`` is the
|
|
1439
|
+
empty tree (a root commit's anchor). A non-regular entry (symlink,
|
|
1440
|
+
directory, submodule), a duplicated entry or a blob over ``cap`` bytes
|
|
1441
|
+
raises :class:`GitError` (reasons ``not-regular``, ``bad-tree`` and
|
|
1442
|
+
``output-cap``).
|
|
1443
|
+
"""
|
|
1444
|
+
if not name or "/" in name or "\0" in name or name in (".", ".."):
|
|
1445
|
+
raise ValueError("name must be a top-level file name")
|
|
1446
|
+
with _session(repo, limits) as git:
|
|
1447
|
+
if anchor == git.empty_tree:
|
|
1448
|
+
return None
|
|
1449
|
+
tree = git.commit(git.resolve_anchor(anchor))[0]
|
|
1450
|
+
data = git.verified([tree], "tree", MAX_RAW_BYTES)[tree]
|
|
1451
|
+
wanted, width = name.encode("utf-8"), git.oid_length // 2
|
|
1452
|
+
found: list[tuple[bytes, str]] = []
|
|
1453
|
+
pos = 0
|
|
1454
|
+
while pos < len(data):
|
|
1455
|
+
space = data.find(b" ", pos)
|
|
1456
|
+
nul = data.find(b"\0", space + 1) if space >= 0 else -1
|
|
1457
|
+
if nul < 0 or nul + 1 + width > len(data):
|
|
1458
|
+
raise GitError("Git tree is malformed", reason="bad-tree")
|
|
1459
|
+
if data[space + 1 : nul] == wanted:
|
|
1460
|
+
found.append((data[pos:space], data[nul + 1 : nul + 1 + width].hex()))
|
|
1461
|
+
pos = nul + 1 + width
|
|
1462
|
+
if not found:
|
|
1463
|
+
return None
|
|
1464
|
+
if len(found) > 1:
|
|
1465
|
+
raise GitError(f"{name} appears twice in the anchor tree", reason="bad-tree")
|
|
1466
|
+
mode, oid = found[0]
|
|
1467
|
+
if mode not in (b"100644", b"100755"):
|
|
1468
|
+
raise GitError(f"{name} at the anchor is not a regular file", reason="not-regular")
|
|
1469
|
+
return git.verified([oid], "blob", cap)[oid]
|
|
1470
|
+
|
|
1471
|
+
|
|
1472
|
+
def repository_identities(repo: str | os.PathLike[str]) -> frozenset[tuple[int, int]]:
|
|
1473
|
+
"""(st_dev, st_ino) of ``repo``, its working tree top, Git directory and common Git directory.
|
|
1474
|
+
|
|
1475
|
+
These are the places the change under review can write. Unlike the PATH
|
|
1476
|
+
check, enclosing repositories are not included: a home directory kept in
|
|
1477
|
+
Git is not part of the reviewed repository. Test a path with ``_inside``.
|
|
1478
|
+
"""
|
|
1479
|
+
with _session(repo, DEFAULT_LIMITS) as git:
|
|
1480
|
+
places = [git.source]
|
|
1481
|
+
for args in (
|
|
1482
|
+
["rev-parse", "--show-toplevel"], # exits 128 in a bare repository
|
|
1483
|
+
["rev-parse", "--absolute-git-dir"],
|
|
1484
|
+
["rev-parse", "--path-format=absolute", "--git-common-dir"],
|
|
1485
|
+
):
|
|
1486
|
+
code, out = git.run_status(args, source=True, ok=(0, 128))
|
|
1487
|
+
raw = out.removesuffix(b"\n")
|
|
1488
|
+
if code != 0:
|
|
1489
|
+
continue
|
|
1490
|
+
path = Path(os.fsdecode(raw))
|
|
1491
|
+
if not raw or b"\n" in raw or not path.is_absolute():
|
|
1492
|
+
raise GitError("Git directory unavailable", reason="bad-path")
|
|
1493
|
+
places.append(path)
|
|
1494
|
+
identities = set()
|
|
1495
|
+
for place in places:
|
|
1496
|
+
info = place.stat()
|
|
1497
|
+
identities.add((info.st_dev, info.st_ino))
|
|
1498
|
+
return frozenset(identities)
|
|
1499
|
+
|
|
1500
|
+
|
|
1501
|
+
def read_staged(
|
|
1502
|
+
repo: str | os.PathLike[str],
|
|
1503
|
+
*,
|
|
1504
|
+
anchor: Anchor,
|
|
1505
|
+
limits: Limits = DEFAULT_LIMITS,
|
|
1506
|
+
) -> Changeset:
|
|
1507
|
+
"""Compare ``HEAD`` (the empty tree on an unborn branch) with a private copy of the index.
|
|
1508
|
+
|
|
1509
|
+
The index (and its shared index when split) is copied once into the
|
|
1510
|
+
isolation repository, so later ``git add`` races and an ``index.lock`` do
|
|
1511
|
+
not matter and the target's index is never written. The copy is written
|
|
1512
|
+
as a tree in the isolation repository (what ``git commit`` would record),
|
|
1513
|
+
and that tree is compared like a commit's. ``anchor`` is the caller's
|
|
1514
|
+
resolved trust anchor and is reported as given.
|
|
1515
|
+
"""
|
|
1516
|
+
if not isinstance(anchor, Anchor):
|
|
1517
|
+
raise TypeError("anchor must be an Anchor")
|
|
1518
|
+
with _session(repo, limits) as git:
|
|
1519
|
+
head = git.head_or_none()
|
|
1520
|
+
anchor_oid = git.resolve_anchor(anchor.oid)
|
|
1521
|
+
_copy_target_index(git)
|
|
1522
|
+
old_tree = git.commit(head)[0] if head else git.empty_tree
|
|
1523
|
+
code, out = git.run_status(["write-tree"], ok=(0, 128))
|
|
1524
|
+
|
|
1525
|
+
def staged(
|
|
1526
|
+
files: tuple[FileChange, ...], issues: Iterable[str], tree: str | None = None
|
|
1527
|
+
) -> Changeset:
|
|
1528
|
+
return Changeset(
|
|
1529
|
+
mode="staged",
|
|
1530
|
+
base=head,
|
|
1531
|
+
head=None,
|
|
1532
|
+
merge_base=None,
|
|
1533
|
+
anchor=anchor_oid,
|
|
1534
|
+
anchor_source=anchor.source,
|
|
1535
|
+
files=files,
|
|
1536
|
+
issues=tuple(issues),
|
|
1537
|
+
snapshot=tree,
|
|
1538
|
+
)
|
|
1539
|
+
|
|
1540
|
+
if code != 0:
|
|
1541
|
+
unmerged = _parse_raw(git.diff_index(old_tree), git.oid_length, 0).unmerged
|
|
1542
|
+
if not unmerged:
|
|
1543
|
+
raise GitError("Git index cannot be written as a tree", reason="bad-index")
|
|
1544
|
+
return staged(
|
|
1545
|
+
(), [f"{unmerged} unmerged index path(s); resolve conflicts before review"]
|
|
1546
|
+
)
|
|
1547
|
+
new_tree = git._oid(out.strip())
|
|
1548
|
+
files, issues = _compare(git, old_tree, new_tree, limits)
|
|
1549
|
+
return staged(files, issues, new_tree)
|