git-finalizer 2.0.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.
- git_finalizer/__init__.py +8 -0
- git_finalizer/delivery/__init__.py +3 -0
- git_finalizer/delivery/cli.py +166 -0
- git_finalizer/delivery/content_scan.py +524 -0
- git_finalizer/delivery/engine.py +2364 -0
- git_finalizer/delivery/integration_publish.py +547 -0
- git_finalizer/delivery/parser.py +552 -0
- git_finalizer/delivery/patch_check.py +165 -0
- git_finalizer/delivery/policy.py +311 -0
- git_finalizer/delivery/repo_bootstrap.py +588 -0
- git_finalizer/delivery/repo_state.py +612 -0
- git_finalizer/delivery/retirement_plan.py +740 -0
- git_finalizer/delivery/runtime.py +553 -0
- git_finalizer/delivery/scanners.py +329 -0
- git_finalizer/delivery/snapshot_verify.py +425 -0
- git_finalizer/delivery/source_review.py +374 -0
- git_finalizer/delivery/trailers.py +164 -0
- git_finalizer/delivery/validation.py +1095 -0
- git_finalizer/errors.py +105 -0
- git_finalizer/git_io.py +281 -0
- git_finalizer/json_io.py +55 -0
- git_finalizer/toolchain/__init__.py +3 -0
- git_finalizer/toolchain/tool_skill_sync.py +3044 -0
- git_finalizer/toolchain/tool_temp_dir.py +1057 -0
- git_finalizer/toolchain/workflow_health.py +504 -0
- git_finalizer-2.0.0.dist-info/METADATA +383 -0
- git_finalizer-2.0.0.dist-info/RECORD +30 -0
- git_finalizer-2.0.0.dist-info/WHEEL +4 -0
- git_finalizer-2.0.0.dist-info/entry_points.txt +5 -0
- git_finalizer-2.0.0.dist-info/licenses/LICENSE +202 -0
git_finalizer/errors.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Structured error codes and exception taxonomy across Git Finalizer CLIs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
VALID_ERROR_CODE = re.compile(r"^[A-Z][A-Z0-9_]{2,63}$")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ErrorCode:
|
|
11
|
+
"""Stable machine-readable error codes emitted on refusal or failure."""
|
|
12
|
+
|
|
13
|
+
CLI_INVALID_ARGS = "CLI_INVALID_ARGS"
|
|
14
|
+
EXECUTION_LOCK_UNAVAILABLE = "EXECUTION_LOCK_UNAVAILABLE"
|
|
15
|
+
EXECUTION_LOCK_TIMEOUT = "EXECUTION_LOCK_TIMEOUT"
|
|
16
|
+
RUNTIME_INTEGRITY_ERROR = "RUNTIME_INTEGRITY_ERROR"
|
|
17
|
+
REPO_INVALID = "REPO_INVALID"
|
|
18
|
+
BRANCH_PROTECTED = "BRANCH_PROTECTED"
|
|
19
|
+
DETACHED_HEAD = "DETACHED_HEAD"
|
|
20
|
+
UNBORN_REPO = "UNBORN_REPO"
|
|
21
|
+
UPSTREAM_CONFLICT = "UPSTREAM_CONFLICT"
|
|
22
|
+
REMOTE_UNAVAILABLE = "REMOTE_UNAVAILABLE"
|
|
23
|
+
REMOTE_DIVERGED = "REMOTE_DIVERGED"
|
|
24
|
+
REMOTE_BEHIND = "REMOTE_BEHIND"
|
|
25
|
+
REMOTE_MISSING = "REMOTE_MISSING"
|
|
26
|
+
SCOPE_INVALID = "SCOPE_INVALID"
|
|
27
|
+
INDEX_UNCLEAN = "INDEX_UNCLEAN"
|
|
28
|
+
WORKING_TREE_DIRTY = "WORKING_TREE_DIRTY"
|
|
29
|
+
WHITESPACE_VIOLATION = "WHITESPACE_VIOLATION"
|
|
30
|
+
BINARY_SIZE_EXCEEDED = "BINARY_SIZE_EXCEEDED"
|
|
31
|
+
CONTENT_SCAN_BLOCKED = "CONTENT_SCAN_BLOCKED"
|
|
32
|
+
EXTERNAL_SCANNER_FAILED = "EXTERNAL_SCANNER_FAILED"
|
|
33
|
+
EXTERNAL_SCANNER_BLOCKED = "EXTERNAL_SCANNER_BLOCKED"
|
|
34
|
+
SOURCE_REVIEW_BLOCKED = "SOURCE_REVIEW_BLOCKED"
|
|
35
|
+
FIXTURE_EXCEPTION_BLOCKED = "FIXTURE_EXCEPTION_BLOCKED"
|
|
36
|
+
SNAPSHOT_EVIDENCE_REJECTED = "SNAPSHOT_EVIDENCE_REJECTED"
|
|
37
|
+
POLICY_DENIED = "POLICY_DENIED"
|
|
38
|
+
HOOK_FAILED = "HOOK_FAILED"
|
|
39
|
+
COMMIT_FAILED = "COMMIT_FAILED"
|
|
40
|
+
PUSH_FAILED = "PUSH_FAILED"
|
|
41
|
+
POST_VERIFY_FAILED = "POST_VERIFY_FAILED"
|
|
42
|
+
RETIREMENT_BLOCKED = "RETIREMENT_BLOCKED"
|
|
43
|
+
CONTROLLER_UNAVAILABLE = "CONTROLLER_UNAVAILABLE"
|
|
44
|
+
BOOTSTRAP_BLOCKED = "BOOTSTRAP_BLOCKED"
|
|
45
|
+
BOOTSTRAP_FAILED = "BOOTSTRAP_FAILED"
|
|
46
|
+
INTEGRATION_PUBLISH_BLOCKED = "INTEGRATION_PUBLISH_BLOCKED"
|
|
47
|
+
INTEGRATION_PUBLISH_FAILED = "INTEGRATION_PUBLISH_FAILED"
|
|
48
|
+
SYNC_FAILED = "SYNC_FAILED"
|
|
49
|
+
TEMP_DIR_FAILED = "TEMP_DIR_FAILED"
|
|
50
|
+
SUMMARY_SERIALIZATION_ERROR = "SUMMARY_SERIALIZATION_ERROR"
|
|
51
|
+
INTERNAL_ERROR = "INTERNAL_ERROR"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class FinalizerError(RuntimeError):
|
|
55
|
+
"""Fail-closed operational blocker or terminal failure with a structured code."""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
code: str,
|
|
60
|
+
message: str,
|
|
61
|
+
*,
|
|
62
|
+
status: str = "blocked",
|
|
63
|
+
final_phase: str = "preflight",
|
|
64
|
+
next_action: str | None = None,
|
|
65
|
+
exit_code: int = 1,
|
|
66
|
+
commit_created: bool = False,
|
|
67
|
+
commit_sha: str | None = None,
|
|
68
|
+
push_executed: bool = False,
|
|
69
|
+
push_result: str = "not_run",
|
|
70
|
+
mode_result: dict[str, object] | None = None,
|
|
71
|
+
resume: dict[str, object] | None = None,
|
|
72
|
+
diagnostics: dict[str, object] | None = None,
|
|
73
|
+
scan_diagnostic: dict[str, object] | None = None,
|
|
74
|
+
reviewed_sensitive_sources: list[dict[str, object]] | None = None,
|
|
75
|
+
warnings: list[str] | None = None,
|
|
76
|
+
) -> None:
|
|
77
|
+
if VALID_ERROR_CODE.fullmatch(code) is None:
|
|
78
|
+
raise ValueError(f"invalid structured error_code: {code!r}")
|
|
79
|
+
if status not in {"blocked", "failed"}:
|
|
80
|
+
raise ValueError(f"invalid error status: {status!r}")
|
|
81
|
+
self.code = code
|
|
82
|
+
self.message = message
|
|
83
|
+
self.status = status
|
|
84
|
+
self.final_phase = final_phase
|
|
85
|
+
self.next_action = (
|
|
86
|
+
next_action
|
|
87
|
+
if next_action is not None
|
|
88
|
+
else ("inspect_failure" if status == "failed" else "resolve_blocker_and_retry")
|
|
89
|
+
)
|
|
90
|
+
self.exit_code = exit_code
|
|
91
|
+
self.commit_created = commit_created
|
|
92
|
+
self.commit_sha = commit_sha
|
|
93
|
+
self.push_executed = push_executed
|
|
94
|
+
self.push_result = push_result
|
|
95
|
+
self.mode_result = dict(mode_result) if mode_result is not None else {}
|
|
96
|
+
self.resume = dict(resume) if resume is not None else None
|
|
97
|
+
self.diagnostics = dict(diagnostics) if diagnostics is not None else None
|
|
98
|
+
self.scan_diagnostic = dict(scan_diagnostic) if scan_diagnostic is not None else None
|
|
99
|
+
self.reviewed_sensitive_sources = (
|
|
100
|
+
[dict(item) for item in reviewed_sensitive_sources]
|
|
101
|
+
if reviewed_sensitive_sources is not None
|
|
102
|
+
else None
|
|
103
|
+
)
|
|
104
|
+
self.warnings = list(warnings or [])
|
|
105
|
+
super().__init__(message)
|
git_finalizer/git_io.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Portable Git invocation, validation, binary detection, and isolated index helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import tempfile
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from git_finalizer.errors import ErrorCode, FinalizerError
|
|
16
|
+
|
|
17
|
+
FULL_OID_RE = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$")
|
|
18
|
+
SAFE_REMOTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/@:-]{0,127}$")
|
|
19
|
+
DEFAULT_LOCAL_GIT_TIMEOUT = 120.0
|
|
20
|
+
DEFAULT_REMOTE_GIT_TIMEOUT = 120.0
|
|
21
|
+
BINARY_CHUNK_SIZE = 1024 * 1024
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def remote_git_timeout() -> float:
|
|
25
|
+
"""Resolve remote git timeout, allowing bounded positive GF_REMOTE_GIT_TIMEOUT override."""
|
|
26
|
+
raw = os.environ.get("GF_REMOTE_GIT_TIMEOUT", "").strip()
|
|
27
|
+
if raw:
|
|
28
|
+
try:
|
|
29
|
+
val = float(raw)
|
|
30
|
+
except ValueError:
|
|
31
|
+
return DEFAULT_REMOTE_GIT_TIMEOUT
|
|
32
|
+
if 0.0 < val <= 300.0:
|
|
33
|
+
return val
|
|
34
|
+
return DEFAULT_REMOTE_GIT_TIMEOUT
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def find_git(path_env: str | None = None) -> str:
|
|
38
|
+
"""Resolve the git executable portably via PATH."""
|
|
39
|
+
resolved = shutil.which("git", path=path_env) if path_env is not None else shutil.which("git")
|
|
40
|
+
if not resolved:
|
|
41
|
+
raise FinalizerError(
|
|
42
|
+
ErrorCode.REPO_INVALID,
|
|
43
|
+
"PATH 中未找到可用的 git 可执行文件",
|
|
44
|
+
final_phase="cli",
|
|
45
|
+
)
|
|
46
|
+
return resolved
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def clean_git_env(extra: dict[str, str] | None = None) -> dict[str, str]:
|
|
50
|
+
"""Return a clean deterministic Git environment preserving caller PATH/HOME/TMPDIR."""
|
|
51
|
+
env = dict(os.environ)
|
|
52
|
+
env["LC_ALL"] = "C"
|
|
53
|
+
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
54
|
+
env["GIT_OPTIONAL_LOCKS"] = "0"
|
|
55
|
+
if extra:
|
|
56
|
+
env.update(extra)
|
|
57
|
+
return env
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def validate_oid(value: str, label: str = "OID") -> str:
|
|
61
|
+
if FULL_OID_RE.fullmatch(value) is None:
|
|
62
|
+
raise FinalizerError(
|
|
63
|
+
ErrorCode.CLI_INVALID_ARGS,
|
|
64
|
+
f"{label} 必须是完整小写十六进制 OID (40 或 64 位)",
|
|
65
|
+
final_phase="cli",
|
|
66
|
+
)
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def validate_remote_name(remote: str) -> str:
|
|
71
|
+
if (
|
|
72
|
+
not remote
|
|
73
|
+
or remote.startswith("-")
|
|
74
|
+
or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in remote)
|
|
75
|
+
or ".." in remote
|
|
76
|
+
or "\\" in remote
|
|
77
|
+
or "\0" in remote
|
|
78
|
+
or SAFE_REMOTE_RE.fullmatch(remote) is None
|
|
79
|
+
):
|
|
80
|
+
raise FinalizerError(
|
|
81
|
+
ErrorCode.CLI_INVALID_ARGS,
|
|
82
|
+
f"非法的 remote 名称: {remote!r}",
|
|
83
|
+
final_phase="cli",
|
|
84
|
+
)
|
|
85
|
+
return remote
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def validate_branch_name(branch: str) -> str:
|
|
89
|
+
if (
|
|
90
|
+
not branch
|
|
91
|
+
or branch.startswith("-")
|
|
92
|
+
or branch.startswith("/")
|
|
93
|
+
or branch.endswith("/")
|
|
94
|
+
or branch.endswith(".")
|
|
95
|
+
or branch.endswith(".lock")
|
|
96
|
+
or branch.startswith("refs/")
|
|
97
|
+
or ".." in branch
|
|
98
|
+
or "@{" in branch
|
|
99
|
+
or "//" in branch
|
|
100
|
+
or any(ch in branch for ch in (" ", "\t", "\n", "\r", "\0", "~", "^", ":", "?", "*", "[", "\\"))
|
|
101
|
+
):
|
|
102
|
+
raise FinalizerError(
|
|
103
|
+
ErrorCode.CLI_INVALID_ARGS,
|
|
104
|
+
f"非法的 branch 名称: {branch!r}",
|
|
105
|
+
final_phase="cli",
|
|
106
|
+
)
|
|
107
|
+
return branch
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def run_git(
|
|
111
|
+
repo: Path | None,
|
|
112
|
+
*arguments: str,
|
|
113
|
+
timeout: float = DEFAULT_LOCAL_GIT_TIMEOUT,
|
|
114
|
+
check: bool = False,
|
|
115
|
+
text: bool = False,
|
|
116
|
+
env: dict[str, str] | None = None,
|
|
117
|
+
input_data: bytes | str | None = None,
|
|
118
|
+
) -> subprocess.CompletedProcess[Any]:
|
|
119
|
+
"""Run git safely with clean env, close_fds=True, and explicit timeouts."""
|
|
120
|
+
resolved_git = find_git(env.get("PATH") if env else None)
|
|
121
|
+
command = [resolved_git]
|
|
122
|
+
if repo is not None:
|
|
123
|
+
command.extend(["-C", str(repo)])
|
|
124
|
+
command.extend(arguments)
|
|
125
|
+
run_env = clean_git_env(env) if env is None else {
|
|
126
|
+
**env,
|
|
127
|
+
"LC_ALL": "C",
|
|
128
|
+
"GIT_TERMINAL_PROMPT": "0",
|
|
129
|
+
"GIT_OPTIONAL_LOCKS": "0",
|
|
130
|
+
}
|
|
131
|
+
try:
|
|
132
|
+
completed = subprocess.run(
|
|
133
|
+
command,
|
|
134
|
+
input=input_data,
|
|
135
|
+
capture_output=True,
|
|
136
|
+
text=text,
|
|
137
|
+
timeout=timeout,
|
|
138
|
+
env=run_env,
|
|
139
|
+
close_fds=True,
|
|
140
|
+
check=False,
|
|
141
|
+
)
|
|
142
|
+
except subprocess.TimeoutExpired as exc:
|
|
143
|
+
raise FinalizerError(
|
|
144
|
+
ErrorCode.REMOTE_UNAVAILABLE if "ls-remote" in arguments or "fetch" in arguments or "push" in arguments else ErrorCode.INTERNAL_ERROR,
|
|
145
|
+
f"git 命令执行超时 ({arguments[0] if arguments else 'git'})",
|
|
146
|
+
status="failed",
|
|
147
|
+
) from exc
|
|
148
|
+
except OSError as exc:
|
|
149
|
+
raise FinalizerError(
|
|
150
|
+
ErrorCode.INTERNAL_ERROR,
|
|
151
|
+
f"无法执行 git 命令: {exc}",
|
|
152
|
+
status="failed",
|
|
153
|
+
) from exc
|
|
154
|
+
if check and completed.returncode != 0:
|
|
155
|
+
raise subprocess.CalledProcessError(
|
|
156
|
+
completed.returncode, command, output=completed.stdout, stderr=completed.stderr
|
|
157
|
+
)
|
|
158
|
+
return completed
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def parse_nul_records(raw: bytes) -> list[str]:
|
|
162
|
+
"""Decode strict UTF-8 NUL-delimited Git records, preserving empty middle elements."""
|
|
163
|
+
if not raw:
|
|
164
|
+
return []
|
|
165
|
+
if not raw.endswith(b"\0"):
|
|
166
|
+
raise ValueError("unterminated NUL record stream")
|
|
167
|
+
parts = raw.split(b"\0")
|
|
168
|
+
parts.pop()
|
|
169
|
+
return [part.decode("utf-8", errors="strict") for part in parts]
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def is_binary_bytes(data: bytes) -> bool:
|
|
173
|
+
"""Single canonical binary check across worktree, candidate, index, and history."""
|
|
174
|
+
return b"\x00" in data
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def inspect_file_stream(path: Path, max_bytes: int | None = None) -> tuple[bool, int]:
|
|
178
|
+
"""Stream-inspect a regular file for NUL bytes and byte size."""
|
|
179
|
+
binary = False
|
|
180
|
+
total = 0
|
|
181
|
+
with path.open("rb") as stream:
|
|
182
|
+
while True:
|
|
183
|
+
chunk = stream.read(BINARY_CHUNK_SIZE)
|
|
184
|
+
if not chunk:
|
|
185
|
+
break
|
|
186
|
+
total += len(chunk)
|
|
187
|
+
if max_bytes is not None and total > max_bytes:
|
|
188
|
+
raise ValueError(f"file exceeds scan byte budget ({max_bytes} bytes)")
|
|
189
|
+
if not binary and b"\x00" in chunk:
|
|
190
|
+
binary = True
|
|
191
|
+
return binary, total
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def read_blob_size(repo: Path, oid: str, *, env: dict[str, str] | None = None) -> int:
|
|
195
|
+
"""Check object existence/size cleanly via git cat-file -s before reading blob bytes."""
|
|
196
|
+
completed = run_git(repo, "cat-file", "-s", oid, env=env)
|
|
197
|
+
if completed.returncode != 0:
|
|
198
|
+
raise FinalizerError(
|
|
199
|
+
ErrorCode.INTERNAL_ERROR,
|
|
200
|
+
f"无法读取 Git 对象大小: {oid}",
|
|
201
|
+
status="failed",
|
|
202
|
+
)
|
|
203
|
+
return int(completed.stdout.decode("ascii").strip())
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def read_blob_bytes(
|
|
207
|
+
repo: Path,
|
|
208
|
+
oid: str,
|
|
209
|
+
*,
|
|
210
|
+
max_bytes: int,
|
|
211
|
+
env: dict[str, str] | None = None,
|
|
212
|
+
) -> bytes:
|
|
213
|
+
"""Verify blob byte size BEFORE materializing the blob in memory."""
|
|
214
|
+
size = read_blob_size(repo, oid, env=env)
|
|
215
|
+
if size > max_bytes:
|
|
216
|
+
raise ValueError(f"Git blob {oid} exceeds scan byte budget ({size} > {max_bytes})")
|
|
217
|
+
completed = run_git(repo, "cat-file", "blob", oid, env=env)
|
|
218
|
+
if completed.returncode != 0:
|
|
219
|
+
raise FinalizerError(
|
|
220
|
+
ErrorCode.INTERNAL_ERROR,
|
|
221
|
+
f"无法读取 Git blob 内容: {oid}",
|
|
222
|
+
status="failed",
|
|
223
|
+
)
|
|
224
|
+
return completed.stdout
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def read_baseline_blob(
|
|
228
|
+
repo: Path,
|
|
229
|
+
ref_expr: str,
|
|
230
|
+
path: str,
|
|
231
|
+
*,
|
|
232
|
+
max_bytes: int,
|
|
233
|
+
env: dict[str, str] | None = None,
|
|
234
|
+
) -> tuple[str | None, bytes | None]:
|
|
235
|
+
"""Read `path` blob oid and bytes from `ref_expr` if present as a regular blob."""
|
|
236
|
+
clean_env = clean_git_env(env)
|
|
237
|
+
ls = run_git(repo, "--literal-pathspecs", "ls-tree", "-z", ref_expr, "--", path, env=clean_env)
|
|
238
|
+
if ls.returncode != 0 or not ls.stdout:
|
|
239
|
+
return None, None
|
|
240
|
+
entries = parse_nul_records(ls.stdout)
|
|
241
|
+
if len(entries) != 1:
|
|
242
|
+
return None, None
|
|
243
|
+
meta, _, _ = entries[0].partition("\t")
|
|
244
|
+
parts = meta.split()
|
|
245
|
+
if len(parts) != 3 or parts[1] != "blob":
|
|
246
|
+
return None, None
|
|
247
|
+
oid = parts[2]
|
|
248
|
+
return oid, read_blob_bytes(repo, oid, max_bytes=max_bytes, env=clean_env)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
@contextmanager
|
|
252
|
+
def isolated_staging_env(
|
|
253
|
+
repo: Path,
|
|
254
|
+
git_dir: Path,
|
|
255
|
+
common_dir: Path,
|
|
256
|
+
*,
|
|
257
|
+
base_env: dict[str, str] | None = None,
|
|
258
|
+
) -> Iterator[tuple[dict[str, str], Path]]:
|
|
259
|
+
"""Build an isolated temporary GIT_INDEX_FILE + temp object store without touching .git/index or .git/objects."""
|
|
260
|
+
with tempfile.TemporaryDirectory(prefix="gf-isolated-stage-") as temporary:
|
|
261
|
+
tmp_path = Path(temporary)
|
|
262
|
+
temp_index = tmp_path / "index"
|
|
263
|
+
real_index = git_dir / "index"
|
|
264
|
+
if real_index.exists():
|
|
265
|
+
if real_index.is_symlink() or not real_index.is_file():
|
|
266
|
+
raise FinalizerError(
|
|
267
|
+
ErrorCode.REPO_INVALID,
|
|
268
|
+
"拒绝非普通文件类型的 Git index",
|
|
269
|
+
final_phase="preflight",
|
|
270
|
+
)
|
|
271
|
+
shutil.copy2(real_index, temp_index)
|
|
272
|
+
temp_objects = tmp_path / "objects"
|
|
273
|
+
temp_objects.mkdir(mode=0o700)
|
|
274
|
+
alt_objects = common_dir / "objects"
|
|
275
|
+
existing_alt = (base_env or os.environ).get("GIT_ALTERNATE_OBJECT_DIRECTORIES", "")
|
|
276
|
+
alts = os.pathsep.join(part for part in (str(alt_objects), existing_alt) if part)
|
|
277
|
+
env = clean_git_env(base_env)
|
|
278
|
+
env["GIT_INDEX_FILE"] = str(temp_index)
|
|
279
|
+
env["GIT_OBJECT_DIRECTORY"] = str(temp_objects)
|
|
280
|
+
env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = alts
|
|
281
|
+
yield env, temp_index
|
git_finalizer/json_io.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Strict JSON parsing, canonical serialization, and hashing helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DuplicateKeyError(ValueError):
|
|
12
|
+
"""Raised when a JSON object declares a duplicate key."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class NonFiniteConstantError(ValueError):
|
|
16
|
+
"""Raised when JSON contains NaN, Infinity, or -Infinity."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
20
|
+
"""Build a dict while rejecting duplicate JSON object keys."""
|
|
21
|
+
result: dict[str, Any] = {}
|
|
22
|
+
for key, value in pairs:
|
|
23
|
+
if key in result:
|
|
24
|
+
raise DuplicateKeyError(f"duplicate JSON key: {key!r}")
|
|
25
|
+
result[key] = value
|
|
26
|
+
return result
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _reject_constant(token: str) -> Any:
|
|
30
|
+
raise NonFiniteConstantError(f"non-finite JSON constant is not allowed: {token}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def loads_unique(raw: str | bytes, *, allow_nonfinite: bool = False) -> Any:
|
|
34
|
+
"""Decode strict UTF-8 JSON rejecting duplicate keys and optional non-finite numbers."""
|
|
35
|
+
text = raw.decode("utf-8", errors="strict") if isinstance(raw, bytes) else raw
|
|
36
|
+
kwargs: dict[str, Any] = {"object_pairs_hook": unique_object}
|
|
37
|
+
if not allow_nonfinite:
|
|
38
|
+
kwargs["parse_constant"] = _reject_constant
|
|
39
|
+
return json.loads(text, **kwargs)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def sha256_bytes(data: bytes) -> str:
|
|
43
|
+
return hashlib.sha256(data).hexdigest()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def sha256_file(path: Path) -> str:
|
|
47
|
+
digest = hashlib.sha256()
|
|
48
|
+
with path.open("rb") as stream:
|
|
49
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
50
|
+
digest.update(chunk)
|
|
51
|
+
return digest.hexdigest()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def canonical_json(value: Any) -> bytes:
|
|
55
|
+
return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode("utf-8")
|