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/worktree.py
ADDED
|
@@ -0,0 +1,1176 @@
|
|
|
1
|
+
"""Worktree review: the trust anchor compared with the working tree (SPEC 5.1, 7.1).
|
|
2
|
+
|
|
3
|
+
This is the default local mode. It covers commits since the anchor plus staged,
|
|
4
|
+
unstaged and untracked changes, and it never writes the target's index, refs or
|
|
5
|
+
working tree. The one write that reaches the target's ``.git`` is Git's own
|
|
6
|
+
object freshening: storing a blob that already exists in the target's object
|
|
7
|
+
store (through the isolation repository's alternate) may update that loose
|
|
8
|
+
object's or pack's modification time. No object, ref or file content changes.
|
|
9
|
+
|
|
10
|
+
How the snapshot is built
|
|
11
|
+
-------------------------
|
|
12
|
+
|
|
13
|
+
1. **Tracked paths** come from a private copy of the target's index (with its
|
|
14
|
+
shared index when split), listed in the isolation repository. Index flags
|
|
15
|
+
are not trusted: assume-unchanged entries are read like any other, and a
|
|
16
|
+
skip-worktree entry is kept from the index only when its file is absent.
|
|
17
|
+
2. **Untracked paths** come from ``git ls-files --others`` run with the private
|
|
18
|
+
Git directory and ``--work-tree``. The working tree's ``.gitignore`` files,
|
|
19
|
+
``info/exclude`` and global excludes are never used for exclusion: the only
|
|
20
|
+
rules are the anchor revision's ``.gitignore`` blobs (read from hash-verified
|
|
21
|
+
trees), combined by :func:`anchor_excludes` into one exclude file passed with
|
|
22
|
+
``--exclude-from``. At most ``max_files`` untracked paths are taken. Any
|
|
23
|
+
warning Git prints while listing (an unreadable directory, a path too long
|
|
24
|
+
to open) becomes an issue with a count; its text is never shown.
|
|
25
|
+
3. **Every path is read safely** below a directory descriptor of the top-level
|
|
26
|
+
directory, one component at a time: directories with
|
|
27
|
+
``O_DIRECTORY|O_NOFOLLOW|O_NONBLOCK``, files after an ``lstat`` with
|
|
28
|
+
``O_NOFOLLOW|O_NONBLOCK`` and an ``fstat`` that must show the same regular
|
|
29
|
+
file. Symlinks are recorded with their ``readlinkat`` target and never
|
|
30
|
+
followed; a symlinked parent directory is never traversed; a tracked path
|
|
31
|
+
that became a FIFO, socket or device is reported and never opened. Git does
|
|
32
|
+
not list special files as untracked (nor can it commit them), so untracked
|
|
33
|
+
FIFOs and sockets are not reported. A file is read up to
|
|
34
|
+
``max_file_bytes + 1`` bytes. A larger untracked file is not read at all;
|
|
35
|
+
a larger tracked file is compared with the index by size first and hashed
|
|
36
|
+
in fixed-size chunks (nothing kept) only when the sizes are equal, at most
|
|
37
|
+
:data:`HASH_BUDGET_FACTOR` times ``max_total_bytes`` in all; past that it
|
|
38
|
+
is skipped as ``max-file-bytes``. A file that changes while it is read is
|
|
39
|
+
reported.
|
|
40
|
+
4. **Changed content is stored** as blobs in the private repository only
|
|
41
|
+
(``hash-object -w --no-filters`` over private copies, so the target's
|
|
42
|
+
attributes, filters and ``core.autocrlf`` never apply). A private index of
|
|
43
|
+
every path is written as a tree, with modes from ``fstat`` (``100755`` when
|
|
44
|
+
the owner may execute, ``120000`` for symlinks, gitlinks kept from the
|
|
45
|
+
index). Content that differs from the index only by one CR before each LF
|
|
46
|
+
(where ``--ignore-cr-at-eol`` sees no change) keeps the index blob.
|
|
47
|
+
5. **The anchor tree and the private tree are compared** with the range-mode
|
|
48
|
+
machinery (renames, kinds, flags, limits, verification), with
|
|
49
|
+
``--ignore-cr-at-eol`` for hunks; line numbers still follow Git.
|
|
50
|
+
|
|
51
|
+
Paths that could not be snapshotted (special files, unreadable or racing files,
|
|
52
|
+
symlinked parents, unsupported names, content over a limit) are marked
|
|
53
|
+
``skipped:<reason>`` on their FileChange, or become a changeset issue when the
|
|
54
|
+
comparison has no FileChange for them. Untracked files that the target's
|
|
55
|
+
current ignore rules (working-tree ``.gitignore`` files and ``info/exclude``)
|
|
56
|
+
would hide but the anchor's rules do not are reviewed and flagged
|
|
57
|
+
``ignored-locally``; when one of those ``.gitignore`` files is not a regular
|
|
58
|
+
file (a FIFO would stall Git), the flags are not computed and an issue says so.
|
|
59
|
+
|
|
60
|
+
Content the working tree does not show (SPEC 5.1)
|
|
61
|
+
-------------------------------------------------
|
|
62
|
+
|
|
63
|
+
* **Staged content**: the review covers the working-tree version of each path.
|
|
64
|
+
When a path's staged blob has lines that are in neither the anchor's nor the
|
|
65
|
+
working-tree version (staged, then edited or reverted on disk, or hidden by
|
|
66
|
+
skip-worktree or assume-unchanged), ``git commit`` would record content this
|
|
67
|
+
review did not see, so an issue asks for a ``--staged`` review as well.
|
|
68
|
+
Lines are compared as a set after removing one CR before LF; ordinary
|
|
69
|
+
partial staging (staged lines that are all on disk) raises nothing.
|
|
70
|
+
* **Submodules**: a gitlink is kept from the index and its files are never
|
|
71
|
+
reviewed. An issue says so when the directory holds files and has no
|
|
72
|
+
``.git`` entry, when the gitlink is new or changed since the anchor and the
|
|
73
|
+
directory holds files, or when something other than a directory stands at
|
|
74
|
+
the path. An empty directory (a submodule that is not checked out) or an
|
|
75
|
+
absent one is fine.
|
|
76
|
+
|
|
77
|
+
Combined exclude file
|
|
78
|
+
---------------------
|
|
79
|
+
|
|
80
|
+
Git applies a ``.gitignore`` in directory ``D`` to paths below ``D``: a
|
|
81
|
+
pattern without a slash (other than a trailing one) matches a name at any depth
|
|
82
|
+
below ``D``, a pattern with a slash is relative to ``D``. Deeper files take
|
|
83
|
+
precedence over shallower ones and, within a file, the last matching pattern
|
|
84
|
+
wins. Excluded directories are not descended into, so nothing below them can be
|
|
85
|
+
re-included. :func:`anchor_excludes` reproduces this in one root-level file:
|
|
86
|
+
|
|
87
|
+
* Each blob is parsed as Git parses it (UTF-8 BOM skipped, lines split on LF,
|
|
88
|
+
comments and blank lines dropped, one CR before LF removed, the line cut at a
|
|
89
|
+
NUL, unescaped trailing spaces trimmed).
|
|
90
|
+
* The root file's patterns are kept as they are. For ``D/.gitignore`` the
|
|
91
|
+
directory is glob-escaped and prepended: ``/x`` becomes ``/D/x``, ``a/b``
|
|
92
|
+
becomes ``/D/a/b`` and ``name`` becomes ``/D/**/name``; ``!`` and a trailing
|
|
93
|
+
``/`` are kept. Patterns that match nothing (``!``, ``/``) are dropped.
|
|
94
|
+
* Files are emitted shallowest first, so a later (deeper) pattern overrides an
|
|
95
|
+
earlier one exactly where Git's per-directory precedence would. Git's own
|
|
96
|
+
traversal still refuses to descend into excluded directories.
|
|
97
|
+
* Every pattern line ends in CR LF, so Git strips exactly that CR and a pattern
|
|
98
|
+
ending in a literal CR survives. Directory names with control, format or
|
|
99
|
+
non-UTF-8 bytes are applied like any other; only a name containing LF cannot
|
|
100
|
+
be written as a pattern line, and its ignore file raises an issue instead
|
|
101
|
+
(dropping it could hide files its ``!`` patterns re-include).
|
|
102
|
+
|
|
103
|
+
``core.ignorecase`` is forced off for listing and checking, so patterns match
|
|
104
|
+
case-sensitively on every platform (SPEC 5.4).
|
|
105
|
+
|
|
106
|
+
The top level must be the nearest directory, at or above the reviewed path,
|
|
107
|
+
that holds the repository's ``.git`` entry: repository config such as
|
|
108
|
+
``core.worktree`` can never widen the review to another directory.
|
|
109
|
+
|
|
110
|
+
Windows: descriptor-relative opens are POSIX only, so :func:`read_worktree`
|
|
111
|
+
raises :class:`GitError` (reason ``unsupported-platform``) there; staged and
|
|
112
|
+
range reviews are unaffected.
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
from __future__ import annotations
|
|
116
|
+
|
|
117
|
+
import errno
|
|
118
|
+
import hashlib
|
|
119
|
+
import os
|
|
120
|
+
import re
|
|
121
|
+
import secrets
|
|
122
|
+
import stat
|
|
123
|
+
import tempfile
|
|
124
|
+
import time
|
|
125
|
+
from collections.abc import Iterable, Iterator
|
|
126
|
+
from dataclasses import dataclass, field
|
|
127
|
+
from pathlib import Path
|
|
128
|
+
from typing import BinaryIO
|
|
129
|
+
|
|
130
|
+
from codeveto import git as gitmod
|
|
131
|
+
from codeveto.anchor import anchor_commit
|
|
132
|
+
from codeveto.git import DEFAULT_LIMITS, MAX_RAW_BYTES, Anchor, Git, GitError, Limits
|
|
133
|
+
from codeveto.model import Changeset
|
|
134
|
+
|
|
135
|
+
__all__ = ["FLAG_IGNORED_LOCALLY", "HASH_BUDGET_FACTOR", "anchor_excludes", "read_worktree"]
|
|
136
|
+
|
|
137
|
+
FLAG_IGNORED_LOCALLY = "ignored-locally"
|
|
138
|
+
#: Large tracked files are hashed (to compare with the index) up to this many
|
|
139
|
+
#: times ``max_total_bytes`` in all: 1 GiB with the default limits.
|
|
140
|
+
HASH_BUDGET_FACTOR = 32
|
|
141
|
+
|
|
142
|
+
_O_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
|
143
|
+
_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
|
|
144
|
+
_O_NONBLOCK = getattr(os, "O_NONBLOCK", 0)
|
|
145
|
+
_O_DIRECTORY = getattr(os, "O_DIRECTORY", 0)
|
|
146
|
+
_O_FILE = os.O_RDONLY | _O_NOFOLLOW | _O_NONBLOCK | _O_CLOEXEC
|
|
147
|
+
_O_DIR = _O_FILE | _O_DIRECTORY
|
|
148
|
+
|
|
149
|
+
#: Reading below a directory descriptor needs POSIX openat/fstatat/readlinkat.
|
|
150
|
+
_SUPPORTED = (
|
|
151
|
+
os.name == "posix"
|
|
152
|
+
and bool(_O_NOFOLLOW and _O_DIRECTORY)
|
|
153
|
+
and {os.open, os.stat, os.readlink} <= os.supports_dir_fd
|
|
154
|
+
and os.scandir in os.supports_fd
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
_CHUNK = 256 * 1024
|
|
158
|
+
#: Most paths named in issues before the rest are summarised.
|
|
159
|
+
_MAX_PATH_ISSUES = 100
|
|
160
|
+
#: Options for commands that read the working tree or write the private index:
|
|
161
|
+
#: case-sensitive matching everywhere, and no checkout-time path protections
|
|
162
|
+
#: (the private index is never checked out; a name Git cannot record is
|
|
163
|
+
#: detected and reported instead of silently dropped).
|
|
164
|
+
_CASE = ("-c", "core.ignorecase=false")
|
|
165
|
+
_INDEX_OPTIONS = (*_CASE, "-c", "core.protectNTFS=false", "-c", "core.protectHFS=false")
|
|
166
|
+
|
|
167
|
+
# Indirections so tests can simulate a file growing mid-read and a slow read.
|
|
168
|
+
_read = os.read
|
|
169
|
+
_now = time.monotonic
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# --- the anchor's tree and ignore rules ------------------------------------------------
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def anchor_excludes(files: Iterable[tuple[bytes, bytes]]) -> bytes:
|
|
176
|
+
"""Combine ``.gitignore`` blobs into one root-level exclude file.
|
|
177
|
+
|
|
178
|
+
``files`` holds ``(directory, content)`` pairs; ``directory`` is ``b""``
|
|
179
|
+
for the top level or a path ending in ``/`` without LF. See the module
|
|
180
|
+
docstring for the rewriting rules.
|
|
181
|
+
"""
|
|
182
|
+
out = bytearray()
|
|
183
|
+
for directory, content in sorted(files, key=lambda f: (f[0].count(b"/"), f[0])):
|
|
184
|
+
if b"\n" in directory:
|
|
185
|
+
raise ValueError("an ignore file's directory cannot contain LF")
|
|
186
|
+
prefix = _glob_escape(directory.removesuffix(b"/"))
|
|
187
|
+
for pattern in _patterns(content):
|
|
188
|
+
rebased = _rebase(pattern, prefix)
|
|
189
|
+
if rebased:
|
|
190
|
+
out += rebased + b"\r\n"
|
|
191
|
+
return bytes(out)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _patterns(content: bytes) -> Iterator[bytes]:
|
|
195
|
+
"""Patterns of one ignore file, parsed as Git's ``add_patterns_from_buffer`` does."""
|
|
196
|
+
content = content.removeprefix(b"\xef\xbb\xbf")
|
|
197
|
+
lines = content.split(b"\n")
|
|
198
|
+
if lines and not lines[-1]:
|
|
199
|
+
lines.pop()
|
|
200
|
+
for line in lines:
|
|
201
|
+
if not line or line.startswith(b"#"):
|
|
202
|
+
continue
|
|
203
|
+
line = line.removesuffix(b"\r")
|
|
204
|
+
nul = line.find(b"\0")
|
|
205
|
+
if nul >= 0:
|
|
206
|
+
line = line[:nul]
|
|
207
|
+
line = _trim_trailing_spaces(line)
|
|
208
|
+
if line:
|
|
209
|
+
yield line
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _trim_trailing_spaces(text: bytes) -> bytes:
|
|
213
|
+
"""Drop trailing spaces unless the last one is escaped (Git's ``trim_trailing_spaces``)."""
|
|
214
|
+
last_space: int | None = None
|
|
215
|
+
i = 0
|
|
216
|
+
while i < len(text):
|
|
217
|
+
c = text[i]
|
|
218
|
+
if c == 0x20:
|
|
219
|
+
if last_space is None:
|
|
220
|
+
last_space = i
|
|
221
|
+
elif c == 0x5C: # a backslash escapes the next byte
|
|
222
|
+
i += 1
|
|
223
|
+
if i >= len(text):
|
|
224
|
+
return text
|
|
225
|
+
last_space = None
|
|
226
|
+
else:
|
|
227
|
+
last_space = None
|
|
228
|
+
i += 1
|
|
229
|
+
return text if last_space is None else text[:last_space]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _glob_escape(text: bytes) -> bytes:
|
|
233
|
+
return re.sub(rb"([\\*?\[])", rb"\\\1", text)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _rebase(pattern: bytes, prefix: bytes) -> bytes | None:
|
|
237
|
+
"""Rewrite one pattern of ``<prefix>/.gitignore`` for a top-level exclude file."""
|
|
238
|
+
if not prefix:
|
|
239
|
+
return pattern
|
|
240
|
+
negative = pattern.startswith(b"!")
|
|
241
|
+
body = pattern[1:] if negative else pattern
|
|
242
|
+
core = body.removesuffix(b"/")
|
|
243
|
+
if not core.strip(b"/"):
|
|
244
|
+
return None
|
|
245
|
+
if core.startswith(b"/"):
|
|
246
|
+
rebased = b"/" + prefix + body
|
|
247
|
+
elif b"/" in core:
|
|
248
|
+
rebased = b"/" + prefix + b"/" + body
|
|
249
|
+
else:
|
|
250
|
+
rebased = b"/" + prefix + b"/**/" + body
|
|
251
|
+
return b"!" + rebased if negative else rebased
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _tree_entries(body: bytes, width: int) -> Iterator[tuple[bytes, bytes, str]]:
|
|
255
|
+
"""(mode, name, oid) of each entry of a raw tree object."""
|
|
256
|
+
pos = 0
|
|
257
|
+
while pos < len(body):
|
|
258
|
+
space = body.find(b" ", pos)
|
|
259
|
+
nul = body.find(b"\0", space + 1) if space >= 0 else -1
|
|
260
|
+
if space < 0 or nul < 0 or nul + 1 + width > len(body):
|
|
261
|
+
raise GitError("malformed Git tree object", reason="bad-output")
|
|
262
|
+
yield body[pos:space], body[space + 1 : nul], body[nul + 1 : nul + 1 + width].hex()
|
|
263
|
+
pos = nul + 1 + width
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@dataclass(slots=True)
|
|
267
|
+
class _AnchorTree:
|
|
268
|
+
#: Every non-tree entry: path -> (mode, oid).
|
|
269
|
+
entries: dict[bytes, tuple[str, str]] = field(default_factory=dict)
|
|
270
|
+
#: (directory, blob oid) of each regular ``.gitignore``.
|
|
271
|
+
ignores: list[tuple[bytes, str]] = field(default_factory=list)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _anchor_listing(git: Git, tree: str) -> _AnchorTree:
|
|
275
|
+
"""Walk the anchor's trees, each one hash-verified, breadth first."""
|
|
276
|
+
width = git.oid_length // 2
|
|
277
|
+
listing = _AnchorTree()
|
|
278
|
+
level: list[tuple[bytes, str]] = [(b"", tree)]
|
|
279
|
+
budget = MAX_RAW_BYTES
|
|
280
|
+
while level:
|
|
281
|
+
trees = git.verified(sorted({oid for _, oid in level}), "tree", budget)
|
|
282
|
+
budget -= sum(len(body) for body in trees.values())
|
|
283
|
+
below: list[tuple[bytes, str]] = []
|
|
284
|
+
for prefix, oid in level:
|
|
285
|
+
for mode, name, child in _tree_entries(trees[oid], width):
|
|
286
|
+
if mode == b"40000":
|
|
287
|
+
below.append((prefix + name + b"/", child))
|
|
288
|
+
continue
|
|
289
|
+
listing.entries[prefix + name] = (mode.decode("ascii", "replace"), child)
|
|
290
|
+
if name == b".gitignore" and mode in (b"100644", b"100755"):
|
|
291
|
+
listing.ignores.append((prefix, child))
|
|
292
|
+
level = below
|
|
293
|
+
return listing
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _anchor_ignore_files(
|
|
297
|
+
git: Git, found: list[tuple[bytes, str]], limits: Limits
|
|
298
|
+
) -> tuple[list[tuple[bytes, bytes]], list[str]]:
|
|
299
|
+
"""The anchor's ``.gitignore`` blobs as (directory, content), hash-verified."""
|
|
300
|
+
issues: list[str] = []
|
|
301
|
+
info = git.object_info({oid for _, oid in found})
|
|
302
|
+
wanted: dict[str, tuple[str, int]] = {}
|
|
303
|
+
used = 0
|
|
304
|
+
kept: list[tuple[bytes, str]] = []
|
|
305
|
+
for prefix, oid in found:
|
|
306
|
+
name = gitmod._safe_name(prefix + b".gitignore")[0]
|
|
307
|
+
kind, size = info.get(oid, ("", 0))
|
|
308
|
+
if b"\n" in prefix:
|
|
309
|
+
issues.append(
|
|
310
|
+
f"{name}: anchor ignore file in a directory whose name cannot be "
|
|
311
|
+
"written as a pattern; its rules were not applied"
|
|
312
|
+
)
|
|
313
|
+
elif kind != "blob":
|
|
314
|
+
issues.append(f"{name}: anchor ignore file unavailable; its rules were not applied")
|
|
315
|
+
elif size > limits.max_file_bytes or used + size > limits.max_total_bytes:
|
|
316
|
+
issues.append(f"{name}: anchor ignore file exceeds a size limit; not applied")
|
|
317
|
+
else:
|
|
318
|
+
used += size if oid not in wanted else 0
|
|
319
|
+
wanted[oid] = (kind, size)
|
|
320
|
+
kept.append((prefix, oid))
|
|
321
|
+
contents, mismatched = git.read_objects(wanted)
|
|
322
|
+
result: list[tuple[bytes, bytes]] = []
|
|
323
|
+
for prefix, oid in kept:
|
|
324
|
+
if oid in mismatched:
|
|
325
|
+
name = gitmod._safe_name(prefix + b".gitignore")[0]
|
|
326
|
+
issues.append(f"{name}: anchor ignore file does not match its ID; not applied")
|
|
327
|
+
else:
|
|
328
|
+
result.append((prefix, contents[oid]))
|
|
329
|
+
return result, issues
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
# --- Git listings ------------------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
@dataclass(frozen=True, slots=True)
|
|
336
|
+
class _Indexed:
|
|
337
|
+
mode: str
|
|
338
|
+
oid: str
|
|
339
|
+
skip_worktree: bool
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _index_entries(git: Git) -> dict[bytes, _Indexed]:
|
|
343
|
+
"""Entries of the private index copy; for unmerged paths stage 2, then 3, then 1."""
|
|
344
|
+
out = git.run(["ls-files", "-z", "--stage", "-t"], cap=MAX_RAW_BYTES)
|
|
345
|
+
if out and not out.endswith(b"\0"):
|
|
346
|
+
raise GitError("malformed Git index listing", reason="bad-output")
|
|
347
|
+
header = re.compile(rb"([A-Z?]) ([0-7]{6}) ([0-9a-f]{%d}) ([0-3])\t" % git.oid_length)
|
|
348
|
+
entries: dict[bytes, _Indexed] = {}
|
|
349
|
+
ranks: dict[bytes, int] = {}
|
|
350
|
+
for record in out.split(b"\0")[:-1]:
|
|
351
|
+
m = header.match(record)
|
|
352
|
+
path = record[m.end() :] if m else b""
|
|
353
|
+
if m is None or not path:
|
|
354
|
+
raise GitError("malformed Git index listing", reason="bad-output")
|
|
355
|
+
rank = (0, 2, 3, 1).index(int(m[4]))
|
|
356
|
+
if ranks.get(path, 4) > rank:
|
|
357
|
+
entries[path] = _Indexed(m[2].decode(), m[3].decode(), m[1] == b"S")
|
|
358
|
+
ranks[path] = rank
|
|
359
|
+
return entries
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
@dataclass(slots=True)
|
|
363
|
+
class _Untracked:
|
|
364
|
+
paths: list[bytes] = field(default_factory=list)
|
|
365
|
+
nested: list[bytes] = field(default_factory=list)
|
|
366
|
+
overflow: int = 0
|
|
367
|
+
warnings: int = 0
|
|
368
|
+
failed: bool = False
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _count_lines(stream: BinaryIO) -> int:
|
|
372
|
+
"""Lines written to a captured stderr file, counted in fixed-size chunks."""
|
|
373
|
+
stream.seek(0)
|
|
374
|
+
count = 0
|
|
375
|
+
last = b"\n"
|
|
376
|
+
while chunk := stream.read(64 * 1024):
|
|
377
|
+
count += chunk.count(b"\n")
|
|
378
|
+
last = chunk[-1:]
|
|
379
|
+
return count + (last != b"\n")
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _untracked(git: Git, top: str, excludes: Path, max_files: int) -> _Untracked:
|
|
383
|
+
result = _Untracked()
|
|
384
|
+
with tempfile.TemporaryFile(dir=git.tmp) as errors:
|
|
385
|
+
try:
|
|
386
|
+
_, out = git.run_status(
|
|
387
|
+
["ls-files", "-z", "--others", f"--exclude-from={excludes}"],
|
|
388
|
+
options=(f"--work-tree={top}", *_CASE),
|
|
389
|
+
cap=MAX_RAW_BYTES,
|
|
390
|
+
stderr=errors,
|
|
391
|
+
)
|
|
392
|
+
except GitError as exc:
|
|
393
|
+
if exc.reason not in ("timeout", "output-cap"):
|
|
394
|
+
raise
|
|
395
|
+
result.failed = True
|
|
396
|
+
return result
|
|
397
|
+
# Each warning is a directory Git could not open or a path it could not
|
|
398
|
+
# access; the files there are missing from the listing.
|
|
399
|
+
result.warnings = _count_lines(errors)
|
|
400
|
+
if out and not out.endswith(b"\0"):
|
|
401
|
+
raise GitError("malformed Git file listing", reason="bad-output")
|
|
402
|
+
for raw in out.split(b"\0")[:-1]:
|
|
403
|
+
if raw.endswith(b"/"): # an untracked nested repository
|
|
404
|
+
result.nested.append(raw[:-1])
|
|
405
|
+
elif len(result.paths) >= max_files:
|
|
406
|
+
result.overflow += 1
|
|
407
|
+
else:
|
|
408
|
+
result.paths.append(raw)
|
|
409
|
+
return result
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _read_regular(path: Path, cap: int) -> bytes | None:
|
|
413
|
+
"""A small regular file outside the working tree, never through a symlink; None if absent."""
|
|
414
|
+
try:
|
|
415
|
+
named = path.lstat()
|
|
416
|
+
except FileNotFoundError:
|
|
417
|
+
return None
|
|
418
|
+
if not stat.S_ISREG(named.st_mode):
|
|
419
|
+
raise OSError(errno.EINVAL, "not a regular file")
|
|
420
|
+
fd = os.open(path, _O_FILE)
|
|
421
|
+
try:
|
|
422
|
+
opened = os.fstat(fd)
|
|
423
|
+
if not stat.S_ISREG(opened.st_mode) or not os.path.samestat(named, opened):
|
|
424
|
+
raise OSError(errno.EINVAL, "file changed while it was opened")
|
|
425
|
+
data = b""
|
|
426
|
+
while len(data) <= cap:
|
|
427
|
+
chunk = _read(fd, cap + 1 - len(data))
|
|
428
|
+
if not chunk:
|
|
429
|
+
return data
|
|
430
|
+
data += chunk
|
|
431
|
+
raise OSError(errno.EFBIG, "file too large")
|
|
432
|
+
finally:
|
|
433
|
+
os.close(fd)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _ignored_locally(
|
|
437
|
+
git: Git, top: str, paths: list[bytes], limits: Limits
|
|
438
|
+
) -> tuple[set[bytes], list[str]]:
|
|
439
|
+
"""Which ``paths`` the working tree's own ignore rules and ``info/exclude`` would hide."""
|
|
440
|
+
if not paths:
|
|
441
|
+
return set(), []
|
|
442
|
+
failed = "local ignore rules could not be evaluated; files they hide are not flagged"
|
|
443
|
+
try:
|
|
444
|
+
raw = git.run(
|
|
445
|
+
["rev-parse", "--path-format=absolute", "--git-path", "info/exclude"], source=True
|
|
446
|
+
).removesuffix(b"\n")
|
|
447
|
+
except GitError as exc:
|
|
448
|
+
if exc.reason == "time-budget":
|
|
449
|
+
raise
|
|
450
|
+
return set(), [failed]
|
|
451
|
+
exclude = Path(os.fsdecode(raw))
|
|
452
|
+
if b"\n" in raw or b"\r" in raw or not exclude.is_absolute():
|
|
453
|
+
return set(), [failed]
|
|
454
|
+
try:
|
|
455
|
+
content = _read_regular(exclude, limits.max_file_bytes)
|
|
456
|
+
except OSError:
|
|
457
|
+
return set(), ["info/exclude could not be read; files it hides are not flagged"]
|
|
458
|
+
copy = Path(os.devnull)
|
|
459
|
+
if content is not None:
|
|
460
|
+
copy = git.tmp / "local-exclude"
|
|
461
|
+
copy.write_bytes(content)
|
|
462
|
+
data = b"".join(path + b"\0" for path in paths)
|
|
463
|
+
try:
|
|
464
|
+
code, out = git.run_status(
|
|
465
|
+
["check-ignore", "-z", "--stdin", "--no-index"],
|
|
466
|
+
options=(f"--work-tree={top}", *_CASE, "-c", f"core.excludesFile={copy}"),
|
|
467
|
+
data=data,
|
|
468
|
+
cap=len(data) + 1024,
|
|
469
|
+
ok=(0, 1),
|
|
470
|
+
)
|
|
471
|
+
except GitError as exc:
|
|
472
|
+
if exc.reason == "time-budget":
|
|
473
|
+
raise
|
|
474
|
+
return set(), [failed]
|
|
475
|
+
return (set(out.split(b"\0")[:-1]) if code == 0 else set()), []
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
# --- reading the working tree ------------------------------------------------------
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _blob_oid(object_format: str, data: bytes) -> str:
|
|
482
|
+
return hashlib.new(object_format, b"blob %d\0" % len(data) + data).hexdigest()
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _components(raw: bytes) -> tuple[bytes, ...] | None:
|
|
486
|
+
"""Path components, or None for a path that could leave the tree or enter ``.git``."""
|
|
487
|
+
parts = tuple(raw.split(b"/"))
|
|
488
|
+
for part in parts:
|
|
489
|
+
if part in (b"", b".", b"..") or part.lower() == b".git":
|
|
490
|
+
return None
|
|
491
|
+
return parts
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _lines(data: bytes) -> set[bytes]:
|
|
495
|
+
"""Distinct lines, numbered as Git numbers them, without one CR before LF."""
|
|
496
|
+
rows = data.split(b"\n")
|
|
497
|
+
if rows and not rows[-1]:
|
|
498
|
+
rows.pop()
|
|
499
|
+
return {row.removesuffix(b"\r") for row in rows}
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
@dataclass(slots=True)
|
|
503
|
+
class _State:
|
|
504
|
+
"""What one path is in the working tree."""
|
|
505
|
+
|
|
506
|
+
#: file | symlink | absent | directory | symlinked-parent | special | error | changed
|
|
507
|
+
kind: str
|
|
508
|
+
data: bytes | None = None # file content (None when over the limit) or symlink target
|
|
509
|
+
oid: str | None = None # blob ID of the full content, when it was read or hashed
|
|
510
|
+
size: int = 0
|
|
511
|
+
executable: bool = False
|
|
512
|
+
unhashed: bool = False # over the limit, same size as the index, hashing budget spent
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
class _Walker:
|
|
516
|
+
"""Inspect paths below the top-level directory, one component at a time.
|
|
517
|
+
|
|
518
|
+
Paths are visited in sorted order, so only the current directory chain is
|
|
519
|
+
kept open (a stack of descriptors); failed directories are remembered.
|
|
520
|
+
"""
|
|
521
|
+
|
|
522
|
+
def __init__(
|
|
523
|
+
self, root: int, object_format: str, limit: int, hash_budget: int, deadline: float
|
|
524
|
+
) -> None:
|
|
525
|
+
self.root = root
|
|
526
|
+
self.object_format = object_format
|
|
527
|
+
self.limit = limit
|
|
528
|
+
self.hash_budget = hash_budget
|
|
529
|
+
self.deadline = deadline
|
|
530
|
+
self.stack: list[tuple[bytes, int]] = []
|
|
531
|
+
self.failed: dict[tuple[bytes, ...], str] = {}
|
|
532
|
+
self.ignore_files: dict[tuple[bytes, ...], bool] = {}
|
|
533
|
+
|
|
534
|
+
def close(self) -> None:
|
|
535
|
+
while self.stack:
|
|
536
|
+
os.close(self.stack.pop()[1])
|
|
537
|
+
os.close(self.root)
|
|
538
|
+
|
|
539
|
+
def _directory(self, parts: tuple[bytes, ...]) -> int | str:
|
|
540
|
+
"""A descriptor for directory ``parts``, or the state that stopped the walk."""
|
|
541
|
+
keep = 0
|
|
542
|
+
while keep < min(len(self.stack), len(parts)) and self.stack[keep][0] == parts[keep]:
|
|
543
|
+
keep += 1
|
|
544
|
+
while len(self.stack) > keep:
|
|
545
|
+
os.close(self.stack.pop()[1])
|
|
546
|
+
fd = self.stack[-1][1] if self.stack else self.root
|
|
547
|
+
for depth in range(keep, len(parts)):
|
|
548
|
+
prefix = parts[: depth + 1]
|
|
549
|
+
if prefix in self.failed:
|
|
550
|
+
return self.failed[prefix]
|
|
551
|
+
try:
|
|
552
|
+
child = os.open(parts[depth], _O_DIR, dir_fd=fd)
|
|
553
|
+
except OSError:
|
|
554
|
+
self.failed[prefix] = state = self._why(fd, parts[depth])
|
|
555
|
+
return state
|
|
556
|
+
self.stack.append((parts[depth], child))
|
|
557
|
+
fd = child
|
|
558
|
+
return fd
|
|
559
|
+
|
|
560
|
+
@staticmethod
|
|
561
|
+
def _why(fd: int, name: bytes) -> str:
|
|
562
|
+
try:
|
|
563
|
+
info = os.stat(name, dir_fd=fd, follow_symlinks=False)
|
|
564
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
565
|
+
return "absent"
|
|
566
|
+
except OSError:
|
|
567
|
+
return "error"
|
|
568
|
+
if stat.S_ISLNK(info.st_mode):
|
|
569
|
+
return "symlinked-parent"
|
|
570
|
+
# A file or special file where a directory was: nothing below it exists.
|
|
571
|
+
return "error" if stat.S_ISDIR(info.st_mode) else "absent"
|
|
572
|
+
|
|
573
|
+
def inspect(self, parts: tuple[bytes, ...], *, index_size: int | None = None) -> _State:
|
|
574
|
+
"""The working-tree state of ``parts``; ``index_size`` is set for tracked paths."""
|
|
575
|
+
where = self._directory(parts[:-1])
|
|
576
|
+
if isinstance(where, str):
|
|
577
|
+
return _State(where)
|
|
578
|
+
name = parts[-1]
|
|
579
|
+
try:
|
|
580
|
+
info = os.stat(name, dir_fd=where, follow_symlinks=False)
|
|
581
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
582
|
+
return _State("absent")
|
|
583
|
+
except OSError:
|
|
584
|
+
return _State("error")
|
|
585
|
+
if stat.S_ISLNK(info.st_mode):
|
|
586
|
+
try:
|
|
587
|
+
target = os.readlink(name, dir_fd=where)
|
|
588
|
+
except FileNotFoundError:
|
|
589
|
+
return _State("absent")
|
|
590
|
+
except OSError:
|
|
591
|
+
return _State("error")
|
|
592
|
+
oid = _blob_oid(self.object_format, target)
|
|
593
|
+
return _State("symlink", data=target, oid=oid, size=len(target))
|
|
594
|
+
if stat.S_ISDIR(info.st_mode):
|
|
595
|
+
return _State("directory")
|
|
596
|
+
if not stat.S_ISREG(info.st_mode):
|
|
597
|
+
return _State("special") # FIFO, socket or device: never opened
|
|
598
|
+
try:
|
|
599
|
+
fd = os.open(name, _O_FILE, dir_fd=where)
|
|
600
|
+
except FileNotFoundError:
|
|
601
|
+
return _State("absent")
|
|
602
|
+
except OSError as exc:
|
|
603
|
+
# ELOOP: replaced by a symlink after the lstat.
|
|
604
|
+
return _State("changed" if exc.errno == errno.ELOOP else "error")
|
|
605
|
+
try:
|
|
606
|
+
return self._read(fd, info, index_size)
|
|
607
|
+
except OSError:
|
|
608
|
+
return _State("error")
|
|
609
|
+
finally:
|
|
610
|
+
os.close(fd)
|
|
611
|
+
|
|
612
|
+
def _read(self, fd: int, named: os.stat_result, index_size: int | None) -> _State:
|
|
613
|
+
opened = os.fstat(fd)
|
|
614
|
+
if not stat.S_ISREG(opened.st_mode) or not os.path.samestat(named, opened):
|
|
615
|
+
return _State("changed")
|
|
616
|
+
size = opened.st_size
|
|
617
|
+
executable = bool(opened.st_mode & stat.S_IXUSR)
|
|
618
|
+
keep = size <= self.limit
|
|
619
|
+
if not keep:
|
|
620
|
+
# Over the limit, the content is never kept. An untracked file, or
|
|
621
|
+
# one whose size differs from the index blob, has changed: nothing
|
|
622
|
+
# of it is read. Only an equal size is worth hashing, within budget.
|
|
623
|
+
if index_size is None or index_size != size:
|
|
624
|
+
return _State("file", size=size, executable=executable)
|
|
625
|
+
if size > self.hash_budget:
|
|
626
|
+
return _State("file", size=size, executable=executable, unhashed=True)
|
|
627
|
+
self.hash_budget -= size
|
|
628
|
+
digest = hashlib.new(self.object_format, b"blob %d\0" % size)
|
|
629
|
+
chunks: list[bytes] = []
|
|
630
|
+
total = 0
|
|
631
|
+
while total <= size:
|
|
632
|
+
if _now() > self.deadline:
|
|
633
|
+
raise GitError("working tree read exceeded the time budget", reason="time-budget")
|
|
634
|
+
chunk = _read(fd, min(_CHUNK, size + 1 - total))
|
|
635
|
+
if not chunk:
|
|
636
|
+
break
|
|
637
|
+
total += len(chunk)
|
|
638
|
+
digest.update(chunk)
|
|
639
|
+
if keep:
|
|
640
|
+
chunks.append(chunk)
|
|
641
|
+
after = os.fstat(fd)
|
|
642
|
+
before = (opened.st_size, opened.st_mtime_ns, opened.st_ctime_ns)
|
|
643
|
+
if total != size or (after.st_size, after.st_mtime_ns, after.st_ctime_ns) != before:
|
|
644
|
+
return _State("changed")
|
|
645
|
+
data = b"".join(chunks) if keep else None
|
|
646
|
+
return _State("file", data=data, oid=digest.hexdigest(), size=size, executable=executable)
|
|
647
|
+
|
|
648
|
+
def submodule(self, parts: tuple[bytes, ...]) -> tuple[str, bool, bool]:
|
|
649
|
+
"""(kind, has a ``.git`` entry, holds other entries) of a gitlink's directory."""
|
|
650
|
+
where = self._directory(parts[:-1])
|
|
651
|
+
if isinstance(where, str):
|
|
652
|
+
return where, False, False
|
|
653
|
+
try:
|
|
654
|
+
info = os.stat(parts[-1], dir_fd=where, follow_symlinks=False)
|
|
655
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
656
|
+
return "absent", False, False
|
|
657
|
+
except OSError:
|
|
658
|
+
return "error", False, False
|
|
659
|
+
if not stat.S_ISDIR(info.st_mode):
|
|
660
|
+
return "other", False, False
|
|
661
|
+
try:
|
|
662
|
+
fd = os.open(parts[-1], _O_DIR, dir_fd=where)
|
|
663
|
+
except OSError:
|
|
664
|
+
return "error", False, False
|
|
665
|
+
try:
|
|
666
|
+
try:
|
|
667
|
+
os.stat(b".git", dir_fd=fd, follow_symlinks=False)
|
|
668
|
+
has_git = True
|
|
669
|
+
except FileNotFoundError:
|
|
670
|
+
has_git = False
|
|
671
|
+
with os.scandir(fd) as entries:
|
|
672
|
+
holds = any(entry.name != ".git" for entry in entries)
|
|
673
|
+
except OSError:
|
|
674
|
+
return "error", False, False
|
|
675
|
+
finally:
|
|
676
|
+
os.close(fd)
|
|
677
|
+
return "directory", has_git, holds
|
|
678
|
+
|
|
679
|
+
def ignore_files_regular(self, dirs: tuple[bytes, ...]) -> bool:
|
|
680
|
+
"""Whether every ``.gitignore`` from the top level down to ``dirs`` is safe to read.
|
|
681
|
+
|
|
682
|
+
``git check-ignore`` reads these working-tree files; a FIFO would stall
|
|
683
|
+
it until its timeout. Absent files, regular files and symlinks (which
|
|
684
|
+
Git refuses to follow) are fine.
|
|
685
|
+
"""
|
|
686
|
+
if isinstance(self._directory(dirs), str):
|
|
687
|
+
return True # nothing below was read
|
|
688
|
+
fds = [self.root, *(fd for _, fd in self.stack)]
|
|
689
|
+
safe = True
|
|
690
|
+
for depth, fd in enumerate(fds):
|
|
691
|
+
key = dirs[:depth]
|
|
692
|
+
if key not in self.ignore_files:
|
|
693
|
+
try:
|
|
694
|
+
info = os.stat(b".gitignore", dir_fd=fd, follow_symlinks=False)
|
|
695
|
+
except FileNotFoundError:
|
|
696
|
+
ok = True
|
|
697
|
+
except OSError:
|
|
698
|
+
ok = False
|
|
699
|
+
else:
|
|
700
|
+
ok = stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
|
|
701
|
+
self.ignore_files[key] = ok
|
|
702
|
+
safe = safe and self.ignore_files[key]
|
|
703
|
+
return safe
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
# --- the private snapshot ---------------------------------------------------------
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
@dataclass(slots=True)
|
|
710
|
+
class _Mark:
|
|
711
|
+
"""What the comparison must know about a path it cannot learn from the blobs."""
|
|
712
|
+
|
|
713
|
+
reason: str | None = None
|
|
714
|
+
message: str = ""
|
|
715
|
+
size: int | None = None
|
|
716
|
+
flags: set[str] = field(default_factory=set)
|
|
717
|
+
used: bool = False
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
@dataclass(frozen=True, slots=True)
|
|
721
|
+
class _StagedCheck:
|
|
722
|
+
"""A path whose staged blob differs from both the anchor and the working tree."""
|
|
723
|
+
|
|
724
|
+
raw: bytes
|
|
725
|
+
staged: str
|
|
726
|
+
anchor: str | None
|
|
727
|
+
disk: frozenset[bytes]
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
_MESSAGES = {
|
|
731
|
+
"special-file": "path is a FIFO, socket or device; it was not read",
|
|
732
|
+
"symlinked-parent": "a parent directory is a symbolic link; it was not followed",
|
|
733
|
+
"unreadable": "file could not be read",
|
|
734
|
+
"changed-during-read": "file changed while it was being read",
|
|
735
|
+
"unsafe-path": "path has an unsafe component; it was not read",
|
|
736
|
+
"unsupported-path": "Git cannot record this path; it was not reviewed",
|
|
737
|
+
"unsupported-mode": "index entry has an unsupported mode; it was not read",
|
|
738
|
+
}
|
|
739
|
+
_PROBLEMS = {"special": "special-file", "error": "unreadable", "changed": "changed-during-read"}
|
|
740
|
+
_INDEX_MODES = frozenset({"100644", "100755", "120000"})
|
|
741
|
+
_PLACEHOLDER_REASONS = frozenset({"max-file-bytes", "max-total-bytes"})
|
|
742
|
+
_STAGED_HINT = "run a --staged review as well"
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
class _Snapshot:
|
|
746
|
+
"""Collects the private tree's entries, the blobs to store and per-path marks."""
|
|
747
|
+
|
|
748
|
+
def __init__(
|
|
749
|
+
self,
|
|
750
|
+
git: Git,
|
|
751
|
+
limits: Limits,
|
|
752
|
+
anchor: _AnchorTree,
|
|
753
|
+
index_sizes: dict[str, tuple[str, int]],
|
|
754
|
+
) -> None:
|
|
755
|
+
self.git = git
|
|
756
|
+
self.limits = limits
|
|
757
|
+
self.anchor = anchor
|
|
758
|
+
self.index_sizes = index_sizes
|
|
759
|
+
self.format = git.object_format or "sha1"
|
|
760
|
+
self.entries: dict[bytes, tuple[str, str]] = {}
|
|
761
|
+
self.marks: dict[bytes, _Mark] = {}
|
|
762
|
+
self.issues: list[str] = []
|
|
763
|
+
self.read_untracked: list[bytes] = []
|
|
764
|
+
self.local_rules_safe = True
|
|
765
|
+
self.staged: list[_StagedCheck] = []
|
|
766
|
+
self.staged_bytes = 0
|
|
767
|
+
self.spool = git.temp / "worktree"
|
|
768
|
+
self.spool.mkdir(mode=0o700)
|
|
769
|
+
if b"\n" in os.fsencode(self.spool):
|
|
770
|
+
raise GitError("temporary directory path cannot be used", reason="bad-path")
|
|
771
|
+
self.spooled: dict[str, Path] = {}
|
|
772
|
+
self.stored_bytes = 0
|
|
773
|
+
# Placeholders for content that is not stored are unique and unguessable,
|
|
774
|
+
# so no anchor blob can equal one.
|
|
775
|
+
self.nonce = secrets.token_hex(16).encode()
|
|
776
|
+
|
|
777
|
+
def mark(self, raw: bytes, reason: str, message: str | None = None) -> _Mark:
|
|
778
|
+
mark = self.marks.setdefault(raw, _Mark())
|
|
779
|
+
if mark.reason is None:
|
|
780
|
+
mark.reason = reason
|
|
781
|
+
mark.message = message or _MESSAGES[reason]
|
|
782
|
+
return mark
|
|
783
|
+
|
|
784
|
+
def path_issue(self, raw: bytes, message: str) -> None:
|
|
785
|
+
self.issues.append(f"{gitmod._safe_name(raw)[0]}: {message}")
|
|
786
|
+
|
|
787
|
+
def _store(self, data: bytes) -> str:
|
|
788
|
+
oid = _blob_oid(self.format, data)
|
|
789
|
+
if oid not in self.spooled:
|
|
790
|
+
path = self.spool / str(len(self.spooled))
|
|
791
|
+
path.write_bytes(data)
|
|
792
|
+
self.spooled[oid] = path
|
|
793
|
+
return oid
|
|
794
|
+
|
|
795
|
+
def _changed(self, raw: bytes, mode: str, state: _State) -> None:
|
|
796
|
+
"""Record changed content: store it, or a placeholder when it is over a limit."""
|
|
797
|
+
limits = self.limits
|
|
798
|
+
size = state.size
|
|
799
|
+
if state.data is None or size > limits.max_file_bytes:
|
|
800
|
+
reason = "max-file-bytes"
|
|
801
|
+
message = f"file exceeds the {limits.max_file_bytes}-byte limit"
|
|
802
|
+
if state.unhashed:
|
|
803
|
+
message += " and the budget for comparing large files with the index"
|
|
804
|
+
elif self.stored_bytes + size > limits.max_total_bytes:
|
|
805
|
+
reason = "max-total-bytes"
|
|
806
|
+
message = f"change exceeds the {limits.max_total_bytes}-byte total limit"
|
|
807
|
+
else:
|
|
808
|
+
self.stored_bytes += size
|
|
809
|
+
self.entries[raw] = (mode, self._store(state.data))
|
|
810
|
+
return
|
|
811
|
+
# A unique stand-in blob keeps the path in the tree (so the comparison
|
|
812
|
+
# lists it, and rename detection never reads a missing object); the
|
|
813
|
+
# mark makes the comparison skip it before anything is read.
|
|
814
|
+
placeholder = b"codeveto placeholder " + self.nonce + b" " + raw
|
|
815
|
+
self.entries[raw] = (mode, self._store(placeholder))
|
|
816
|
+
self.mark(raw, reason, message).size = size
|
|
817
|
+
|
|
818
|
+
def tracked(self, raw: bytes, entry: _Indexed, walker: _Walker) -> None:
|
|
819
|
+
if entry.mode == gitmod._GITLINK:
|
|
820
|
+
self.entries[raw] = (entry.mode, entry.oid)
|
|
821
|
+
self._submodule(raw, entry, walker)
|
|
822
|
+
return
|
|
823
|
+
parts = _components(raw)
|
|
824
|
+
if parts is None:
|
|
825
|
+
self.mark(raw, "unsafe-path")
|
|
826
|
+
return
|
|
827
|
+
if entry.mode not in _INDEX_MODES:
|
|
828
|
+
self.mark(raw, "unsupported-mode")
|
|
829
|
+
return
|
|
830
|
+
size = self.index_sizes.get(entry.oid, ("", None))[1]
|
|
831
|
+
disk = self._record(raw, entry, walker.inspect(parts, index_size=size))
|
|
832
|
+
anchored = self.anchor.entries.get(raw)
|
|
833
|
+
anchor_oid = anchored[1] if anchored else None
|
|
834
|
+
recorded = self.entries.get(raw, ("", None))[1]
|
|
835
|
+
if disk is not None and entry.oid != anchor_oid and recorded != entry.oid:
|
|
836
|
+
self._check_staged(raw, entry.oid, anchor_oid, disk)
|
|
837
|
+
|
|
838
|
+
def _record(self, raw: bytes, entry: _Indexed, state: _State) -> bytes | None:
|
|
839
|
+
"""Record one tracked path; return its working-tree bytes (None when unknown)."""
|
|
840
|
+
kind = state.kind
|
|
841
|
+
if kind == "absent":
|
|
842
|
+
if entry.skip_worktree: # sparse checkout: absent is not deleted
|
|
843
|
+
self.entries[raw] = (entry.mode, entry.oid)
|
|
844
|
+
return b""
|
|
845
|
+
if kind == "directory":
|
|
846
|
+
return b"" # deleted; anything inside is untracked
|
|
847
|
+
if kind == "symlinked-parent":
|
|
848
|
+
self.mark(raw, kind)
|
|
849
|
+
return b""
|
|
850
|
+
if kind in _PROBLEMS:
|
|
851
|
+
self.entries[raw] = (entry.mode, entry.oid)
|
|
852
|
+
self.mark(raw, _PROBLEMS[kind])
|
|
853
|
+
return None
|
|
854
|
+
mode = self._mode(state)
|
|
855
|
+
if state.oid == entry.oid or self._crlf_of(state, entry.oid):
|
|
856
|
+
# Unchanged, or only one CR before each LF differs: the index blob stands.
|
|
857
|
+
self.entries[raw] = (mode, entry.oid)
|
|
858
|
+
else:
|
|
859
|
+
self._changed(raw, mode, state)
|
|
860
|
+
return state.data
|
|
861
|
+
|
|
862
|
+
def _check_staged(self, raw: bytes, staged: str, anchor: str | None, disk: bytes) -> None:
|
|
863
|
+
if self.staged_bytes + len(disk) > self.limits.max_total_bytes:
|
|
864
|
+
self.path_issue(raw, f"the staged version could not be compared; {_STAGED_HINT}")
|
|
865
|
+
return
|
|
866
|
+
self.staged_bytes += len(disk)
|
|
867
|
+
self.staged.append(_StagedCheck(raw, staged, anchor, frozenset(_lines(disk))))
|
|
868
|
+
|
|
869
|
+
def staged_issues(self) -> None:
|
|
870
|
+
"""Flag staged blobs with lines that neither the anchor nor the working tree has."""
|
|
871
|
+
if not self.staged:
|
|
872
|
+
return
|
|
873
|
+
limits = self.limits
|
|
874
|
+
oids = {c.staged for c in self.staged} | {c.anchor for c in self.staged if c.anchor}
|
|
875
|
+
info = self.git.object_info(oids)
|
|
876
|
+
wanted: dict[str, tuple[str, int]] = {}
|
|
877
|
+
used = 0
|
|
878
|
+
for oid in sorted(oids):
|
|
879
|
+
kind, size = info.get(oid, ("", 0))
|
|
880
|
+
if kind == "blob" and size <= limits.max_file_bytes:
|
|
881
|
+
if used + size > limits.max_total_bytes:
|
|
882
|
+
break
|
|
883
|
+
used += size
|
|
884
|
+
wanted[oid] = (kind, size)
|
|
885
|
+
contents, mismatched = self.git.read_objects(wanted)
|
|
886
|
+
for check in self.staged:
|
|
887
|
+
needed = [check.staged, *([check.anchor] if check.anchor else [])]
|
|
888
|
+
if any(oid not in contents or oid in mismatched for oid in needed):
|
|
889
|
+
message = f"the staged version could not be compared; {_STAGED_HINT}"
|
|
890
|
+
else:
|
|
891
|
+
old = _lines(contents[check.anchor]) if check.anchor else set()
|
|
892
|
+
if not _lines(contents[check.staged]) - old - check.disk:
|
|
893
|
+
continue
|
|
894
|
+
message = (
|
|
895
|
+
"the staged version has lines that are not in the working tree, "
|
|
896
|
+
f"so committed or staged content was not reviewed; {_STAGED_HINT}"
|
|
897
|
+
)
|
|
898
|
+
self.path_issue(check.raw, message)
|
|
899
|
+
|
|
900
|
+
def _submodule(self, raw: bytes, entry: _Indexed, walker: _Walker) -> None:
|
|
901
|
+
parts = _components(raw)
|
|
902
|
+
if parts is None:
|
|
903
|
+
return # the private index refuses it; reported as unsupported
|
|
904
|
+
kind, has_git, holds = walker.submodule(parts)
|
|
905
|
+
if kind == "absent" or (kind == "directory" and not holds):
|
|
906
|
+
return # not checked out: nothing on disk to review
|
|
907
|
+
if kind != "directory":
|
|
908
|
+
self.path_issue(raw, "the index has a submodule here, but the path is not a directory")
|
|
909
|
+
elif not has_git:
|
|
910
|
+
self.path_issue(
|
|
911
|
+
raw, "submodule directory has files but no .git entry; they were not reviewed"
|
|
912
|
+
)
|
|
913
|
+
elif self.anchor.entries.get(raw) != (gitmod._GITLINK, entry.oid):
|
|
914
|
+
self.path_issue(
|
|
915
|
+
raw, "submodule is new or changed since the anchor; its files were not reviewed"
|
|
916
|
+
)
|
|
917
|
+
|
|
918
|
+
def untracked(self, raw: bytes, walker: _Walker) -> None:
|
|
919
|
+
parts = _components(raw)
|
|
920
|
+
if parts is None:
|
|
921
|
+
self.mark(raw, "unsafe-path")
|
|
922
|
+
return
|
|
923
|
+
state = walker.inspect(parts)
|
|
924
|
+
kind = state.kind
|
|
925
|
+
if kind == "absent":
|
|
926
|
+
return # removed after it was listed
|
|
927
|
+
if kind == "directory":
|
|
928
|
+
self.mark(raw, "changed-during-read")
|
|
929
|
+
elif kind == "symlinked-parent":
|
|
930
|
+
self.mark(raw, kind)
|
|
931
|
+
elif kind in _PROBLEMS:
|
|
932
|
+
self.mark(raw, _PROBLEMS[kind])
|
|
933
|
+
else:
|
|
934
|
+
self.read_untracked.append(raw)
|
|
935
|
+
self._changed(raw, self._mode(state), state)
|
|
936
|
+
if not walker.ignore_files_regular(parts[:-1]):
|
|
937
|
+
self.local_rules_safe = False
|
|
938
|
+
|
|
939
|
+
def _mode(self, state: _State) -> str:
|
|
940
|
+
if state.kind == "symlink":
|
|
941
|
+
return gitmod._SYMLINK
|
|
942
|
+
return gitmod._EXECUTABLE if state.executable else "100644"
|
|
943
|
+
|
|
944
|
+
def _crlf_of(self, state: _State, oid: str) -> bool:
|
|
945
|
+
"""Whether the content equals blob ``oid`` once one CR before each LF is removed.
|
|
946
|
+
|
|
947
|
+
That is exactly when ``--ignore-cr-at-eol`` sees no change: the index
|
|
948
|
+
side must then hold no CR LF itself.
|
|
949
|
+
"""
|
|
950
|
+
data = state.data
|
|
951
|
+
if state.kind != "file" or data is None or b"\0" in data or b"\r\n" not in data:
|
|
952
|
+
return False
|
|
953
|
+
normalised = data.replace(b"\r\n", b"\n")
|
|
954
|
+
return b"\r\n" not in normalised and _blob_oid(self.format, normalised) == oid
|
|
955
|
+
|
|
956
|
+
def write_tree(self) -> str:
|
|
957
|
+
"""Store the blobs and write every entry as a tree in the isolation repository."""
|
|
958
|
+
git = self.git
|
|
959
|
+
if self.spooled:
|
|
960
|
+
listing = b"".join(os.fsencode(path) + b"\n" for path in self.spooled.values())
|
|
961
|
+
out = git.run(
|
|
962
|
+
["hash-object", "-w", "--no-filters", "--stdin-paths"],
|
|
963
|
+
data=listing,
|
|
964
|
+
cap=(git.oid_length + 1) * len(self.spooled),
|
|
965
|
+
)
|
|
966
|
+
if out.split() != [oid.encode() for oid in self.spooled]:
|
|
967
|
+
raise GitError(
|
|
968
|
+
"Git stored working-tree content under another ID", reason="bad-output"
|
|
969
|
+
)
|
|
970
|
+
(git.bare / "index").unlink(missing_ok=True)
|
|
971
|
+
records = b"".join(
|
|
972
|
+
f"{mode} {oid}\t".encode() + raw + b"\0"
|
|
973
|
+
for raw, (mode, oid) in sorted(self.entries.items())
|
|
974
|
+
)
|
|
975
|
+
if records:
|
|
976
|
+
git.run(
|
|
977
|
+
["update-index", "-z", "--add", "--index-info"],
|
|
978
|
+
data=records,
|
|
979
|
+
options=_INDEX_OPTIONS,
|
|
980
|
+
)
|
|
981
|
+
# update-index skips names it refuses (".git" variants, a symlinked
|
|
982
|
+
# .gitmodules) with only a warning: compare what it recorded.
|
|
983
|
+
out = git.run(["ls-files", "-z"], cap=MAX_RAW_BYTES, options=_INDEX_OPTIONS)
|
|
984
|
+
recorded = set(out.split(b"\0")[:-1])
|
|
985
|
+
for raw in sorted(self.entries.keys() - recorded):
|
|
986
|
+
mark = self.marks.setdefault(raw, _Mark())
|
|
987
|
+
mark.reason, mark.message = "unsupported-path", _MESSAGES["unsupported-path"]
|
|
988
|
+
tree = git.run(["write-tree", "--missing-ok"], options=_INDEX_OPTIONS)
|
|
989
|
+
return git._oid(tree.strip())
|
|
990
|
+
|
|
991
|
+
def prepare(self, work: list[gitmod._Work]) -> None:
|
|
992
|
+
"""``_compare`` hook: skip and flag planned entries before any blob is read."""
|
|
993
|
+
skipped: list[gitmod._Work] = []
|
|
994
|
+
for item in work:
|
|
995
|
+
mark = self.marks.get(item.entry.path)
|
|
996
|
+
if mark is None:
|
|
997
|
+
continue
|
|
998
|
+
mark.used = True
|
|
999
|
+
item.flags.update(mark.flags)
|
|
1000
|
+
if mark.reason is not None:
|
|
1001
|
+
item.skip(mark.reason, mark.message)
|
|
1002
|
+
item.sizes = {} if mark.size is None else {"new": mark.size}
|
|
1003
|
+
skipped.append(item)
|
|
1004
|
+
# The comparison only sizes entries it reads; report the anchor side too.
|
|
1005
|
+
readable = {*gitmod._REGULAR, gitmod._SYMLINK}
|
|
1006
|
+
old = {i.entry.old_oid for i in skipped if i.entry.old_mode in readable}
|
|
1007
|
+
info = self.git.object_info(old)
|
|
1008
|
+
for item in skipped:
|
|
1009
|
+
if item.entry.old_mode in readable and item.entry.old_oid in info:
|
|
1010
|
+
item.sizes["old"] = info[item.entry.old_oid][1]
|
|
1011
|
+
|
|
1012
|
+
def unmatched_issues(self) -> list[str]:
|
|
1013
|
+
"""Marked paths the comparison had no FileChange for.
|
|
1014
|
+
|
|
1015
|
+
A path held by a placeholder blob always differs from the anchor, so it
|
|
1016
|
+
only lacks a FileChange when the comparison stopped at ``max_files``,
|
|
1017
|
+
which the comparison already reports.
|
|
1018
|
+
"""
|
|
1019
|
+
issues = []
|
|
1020
|
+
left = [
|
|
1021
|
+
raw
|
|
1022
|
+
for raw, mark in sorted(self.marks.items())
|
|
1023
|
+
if mark.reason and not mark.used and mark.reason not in _PLACEHOLDER_REASONS
|
|
1024
|
+
]
|
|
1025
|
+
for raw in left[:_MAX_PATH_ISSUES]:
|
|
1026
|
+
issues.append(f"{gitmod._safe_name(raw)[0]}: {self.marks[raw].message}")
|
|
1027
|
+
if len(left) > _MAX_PATH_ISSUES:
|
|
1028
|
+
issues.append(f"{len(left) - _MAX_PATH_ISSUES} more path(s) could not be reviewed")
|
|
1029
|
+
return issues
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
# --- entry point --------------------------------------------------------------------
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
def _anchor_tree(git: Git, anchor: Anchor) -> tuple[str | None, str]:
|
|
1036
|
+
"""(anchor commit or None for the empty tree, its hash-verified tree)."""
|
|
1037
|
+
if anchor.oid == git.empty_tree:
|
|
1038
|
+
return None, git.empty_tree
|
|
1039
|
+
oid = anchor_commit(git, anchor.oid)
|
|
1040
|
+
return oid, git.commit(oid)[0]
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def _open_top(git: Git) -> tuple[str, int]:
|
|
1044
|
+
"""The top-level directory as Git reports it, opened and checked.
|
|
1045
|
+
|
|
1046
|
+
It must be the nearest directory at or above the reviewed path that holds
|
|
1047
|
+
a ``.git`` entry, so repository config (``core.worktree``) cannot point the
|
|
1048
|
+
review at a parent or any other directory.
|
|
1049
|
+
"""
|
|
1050
|
+
code, out = git.run_status(["rev-parse", "--show-toplevel"], source=True, ok=(0, 128))
|
|
1051
|
+
raw = out.removesuffix(b"\n")
|
|
1052
|
+
if code != 0 or not raw:
|
|
1053
|
+
raise GitError(
|
|
1054
|
+
"worktree review needs a repository with a working tree", reason="no-worktree"
|
|
1055
|
+
)
|
|
1056
|
+
top = os.fsdecode(raw)
|
|
1057
|
+
if b"\n" in raw or b"\r" in raw or not os.path.isabs(top):
|
|
1058
|
+
raise GitError("Git working tree path cannot be used", reason="bad-path")
|
|
1059
|
+
holder = next(
|
|
1060
|
+
(p for p in (git.source, *git.source.parents) if os.path.lexists(p / ".git")), None
|
|
1061
|
+
)
|
|
1062
|
+
outside = GitError(
|
|
1063
|
+
"Git reports a working tree other than the directory that holds the repository",
|
|
1064
|
+
reason="bad-path",
|
|
1065
|
+
)
|
|
1066
|
+
if holder is None:
|
|
1067
|
+
raise outside
|
|
1068
|
+
expected = holder.stat()
|
|
1069
|
+
fd = os.open(top, os.O_RDONLY | _O_DIRECTORY | _O_CLOEXEC)
|
|
1070
|
+
if not os.path.samestat(os.fstat(fd), expected):
|
|
1071
|
+
os.close(fd)
|
|
1072
|
+
raise outside
|
|
1073
|
+
return top, fd
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
def read_worktree(
|
|
1077
|
+
repo: str | os.PathLike[str],
|
|
1078
|
+
*,
|
|
1079
|
+
anchor: Anchor,
|
|
1080
|
+
limits: Limits = DEFAULT_LIMITS,
|
|
1081
|
+
) -> Changeset:
|
|
1082
|
+
"""Compare the trust anchor's tree with the working tree (SPEC 5.1 ``worktree``).
|
|
1083
|
+
|
|
1084
|
+
``anchor`` is the resolved trust anchor (see :mod:`codeveto.anchor`); an
|
|
1085
|
+
anchor equal to the empty tree compares against nothing (unborn ``HEAD``).
|
|
1086
|
+
The result has mode ``"worktree"``, ``base`` the anchor commit (``None``
|
|
1087
|
+
for the empty tree) and no ``head``.
|
|
1088
|
+
"""
|
|
1089
|
+
if not isinstance(anchor, Anchor):
|
|
1090
|
+
raise TypeError("anchor must be an Anchor")
|
|
1091
|
+
if not _SUPPORTED:
|
|
1092
|
+
raise GitError(
|
|
1093
|
+
"worktree review needs a POSIX system; review staged changes or a range instead",
|
|
1094
|
+
reason="unsupported-platform",
|
|
1095
|
+
)
|
|
1096
|
+
with gitmod._session(repo, limits) as git:
|
|
1097
|
+
git.ignore_cr_at_eol = True
|
|
1098
|
+
base, anchor_tree = _anchor_tree(git, anchor)
|
|
1099
|
+
top, root = _open_top(git)
|
|
1100
|
+
walker = _Walker(
|
|
1101
|
+
root,
|
|
1102
|
+
git.object_format or "sha1",
|
|
1103
|
+
limits.max_file_bytes,
|
|
1104
|
+
HASH_BUDGET_FACTOR * limits.max_total_bytes,
|
|
1105
|
+
git.deadline,
|
|
1106
|
+
)
|
|
1107
|
+
try:
|
|
1108
|
+
gitmod._copy_target_index(git)
|
|
1109
|
+
indexed = _index_entries(git)
|
|
1110
|
+
listing = _anchor_listing(git, anchor_tree)
|
|
1111
|
+
ignore_files, issues = _anchor_ignore_files(git, listing.ignores, limits)
|
|
1112
|
+
excludes = git.tmp / "anchor-excludes"
|
|
1113
|
+
excludes.write_bytes(anchor_excludes(ignore_files))
|
|
1114
|
+
untracked = _untracked(git, top, excludes, limits.max_files)
|
|
1115
|
+
if untracked.failed:
|
|
1116
|
+
issues.append(
|
|
1117
|
+
"untracked files could not be listed within the Git limits; "
|
|
1118
|
+
"they were not reviewed"
|
|
1119
|
+
)
|
|
1120
|
+
if untracked.warnings:
|
|
1121
|
+
issues.append(
|
|
1122
|
+
f"Git could not read {untracked.warnings} location(s) while listing "
|
|
1123
|
+
"untracked files (an unreadable directory or a path too long to "
|
|
1124
|
+
"open); files there were not reviewed"
|
|
1125
|
+
)
|
|
1126
|
+
for raw in untracked.nested[:_MAX_PATH_ISSUES]:
|
|
1127
|
+
issues.append(
|
|
1128
|
+
f"{gitmod._safe_name(raw)[0]}: untracked nested Git repository; "
|
|
1129
|
+
"its files were not reviewed"
|
|
1130
|
+
)
|
|
1131
|
+
if untracked.overflow:
|
|
1132
|
+
issues.append(
|
|
1133
|
+
f"{untracked.overflow} untracked file(s) beyond the "
|
|
1134
|
+
f"{limits.max_files}-file limit were not reviewed"
|
|
1135
|
+
)
|
|
1136
|
+
sizes = git.object_info({e.oid for e in indexed.values() if e.mode in _INDEX_MODES})
|
|
1137
|
+
snapshot = _Snapshot(git, limits, listing, sizes)
|
|
1138
|
+
listed = set(untracked.paths)
|
|
1139
|
+
for raw in sorted(listed | indexed.keys()):
|
|
1140
|
+
if _now() > git.deadline:
|
|
1141
|
+
raise GitError(
|
|
1142
|
+
"working tree read exceeded the time budget", reason="time-budget"
|
|
1143
|
+
)
|
|
1144
|
+
if raw in listed:
|
|
1145
|
+
snapshot.untracked(raw, walker)
|
|
1146
|
+
else:
|
|
1147
|
+
snapshot.tracked(raw, indexed[raw], walker)
|
|
1148
|
+
finally:
|
|
1149
|
+
walker.close()
|
|
1150
|
+
snapshot.staged_issues()
|
|
1151
|
+
issues += snapshot.issues
|
|
1152
|
+
if snapshot.local_rules_safe:
|
|
1153
|
+
flagged, flag_issues = _ignored_locally(git, top, snapshot.read_untracked, limits)
|
|
1154
|
+
issues += flag_issues
|
|
1155
|
+
for raw in flagged:
|
|
1156
|
+
snapshot.marks.setdefault(raw, _Mark()).flags.add(FLAG_IGNORED_LOCALLY)
|
|
1157
|
+
else:
|
|
1158
|
+
issues.append(
|
|
1159
|
+
"a working-tree .gitignore is not a regular file, so local ignore rules "
|
|
1160
|
+
"were not evaluated; files they hide are not flagged"
|
|
1161
|
+
)
|
|
1162
|
+
new_tree = snapshot.write_tree()
|
|
1163
|
+
files, compare_issues = gitmod._compare(
|
|
1164
|
+
git, anchor_tree, new_tree, limits, prepare=snapshot.prepare
|
|
1165
|
+
)
|
|
1166
|
+
return Changeset(
|
|
1167
|
+
mode="worktree",
|
|
1168
|
+
base=base,
|
|
1169
|
+
head=None,
|
|
1170
|
+
merge_base=None,
|
|
1171
|
+
anchor=anchor.oid,
|
|
1172
|
+
anchor_source=anchor.source,
|
|
1173
|
+
files=files,
|
|
1174
|
+
issues=(*issues, *compare_issues, *snapshot.unmatched_issues()),
|
|
1175
|
+
snapshot=new_tree,
|
|
1176
|
+
)
|