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.
@@ -0,0 +1,612 @@
1
+ """Repository topology, branch state, protected refs, and remote endpoint verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ from pathlib import Path, PurePosixPath
7
+ import posixpath
8
+ from urllib.parse import urlparse
9
+
10
+ from git_finalizer.delivery.policy import DeliveryPolicy
11
+ from git_finalizer.errors import ErrorCode, FinalizerError
12
+ from git_finalizer.git_io import (
13
+ DEFAULT_REMOTE_GIT_TIMEOUT,
14
+ parse_nul_records,
15
+ run_git,
16
+ validate_oid,
17
+ validate_remote_name,
18
+ )
19
+
20
+ STATIC_PROTECTED_EXACT = frozenset(
21
+ {"main", "master", "trunk", "production", "HEAD", "rescue", "archive", "recovery"}
22
+ )
23
+ STATIC_PROTECTED_PREFIXES = ("rescue/", "archive/", "recovery/")
24
+
25
+
26
+ @dataclasses.dataclass
27
+ class RepoInfo:
28
+ repo: Path
29
+ git_dir: Path
30
+ common_dir: Path
31
+ is_unborn: bool
32
+ head_oid: str | None
33
+ branch: str | None
34
+ upstream: str | None
35
+ merge_parent: str | None
36
+
37
+
38
+ def is_protected_branch(branch: str, policy: DeliveryPolicy | None = None) -> bool:
39
+ if branch in STATIC_PROTECTED_EXACT or branch.startswith(STATIC_PROTECTED_PREFIXES):
40
+ return True
41
+ if policy is not None:
42
+ import fnmatch
43
+
44
+ for pattern in policy.extra_protected_branches:
45
+ if fnmatch.fnmatchcase(branch, pattern):
46
+ return True
47
+ return False
48
+
49
+
50
+ def redact_endpoint(url: str) -> str:
51
+ if "@" not in url:
52
+ return url
53
+ parsed = urlparse(url)
54
+ if parsed.scheme and (parsed.username is not None or parsed.password is not None):
55
+ host = parsed.hostname or ""
56
+ port = f":{parsed.port}" if parsed.port else ""
57
+ return parsed._replace(netloc=f"<redacted>@{host}{port}").geturl()
58
+ if "://" not in url and ":" in url and "@" in url:
59
+ _, _, rest = url.partition("@")
60
+ return f"<redacted>@{rest}"
61
+ return url
62
+
63
+
64
+ def _pending_operation_check(
65
+ repo: Path,
66
+ git_dir: Path,
67
+ merge_parent_arg: str | None,
68
+ mode: str,
69
+ head_oid: str | None = None,
70
+ ) -> str | None:
71
+ for marker in ("CHERRY_PICK_HEAD", "REVERT_HEAD", "REBASE_HEAD", "BISECT_START", "BISECT_LOG"):
72
+ p = git_dir / marker
73
+ if p.exists() or p.is_symlink():
74
+ raise FinalizerError(
75
+ ErrorCode.REPO_INVALID,
76
+ f"仓库存在未完成的 Git 操作({marker})",
77
+ final_phase="preflight",
78
+ )
79
+ for directory in ("rebase-merge", "rebase-apply", "sequencer"):
80
+ p = git_dir / directory
81
+ if p.exists() or p.is_symlink():
82
+ raise FinalizerError(
83
+ ErrorCode.REPO_INVALID,
84
+ f"仓库存在未完成的 Git 操作({directory})",
85
+ final_phase="preflight",
86
+ )
87
+ merge_head_file = git_dir / "MERGE_HEAD"
88
+ if merge_parent_arg is None:
89
+ if merge_head_file.exists() or merge_head_file.is_symlink():
90
+ raise FinalizerError(
91
+ ErrorCode.REPO_INVALID,
92
+ "仓库存在未完成的 Git 操作(MERGE_HEAD);请先完成或中止合并,或仅在 verify-only/commit-only 下传 --merge-parent",
93
+ final_phase="preflight",
94
+ )
95
+ return None
96
+
97
+ if mode not in {"verify-only", "commit-only"}:
98
+ raise FinalizerError(
99
+ ErrorCode.CLI_INVALID_ARGS,
100
+ "--merge-parent 仅允许配合 --mode verify-only 或 --mode commit-only 使用",
101
+ final_phase="cli",
102
+ )
103
+ merge_parent_oid = validate_oid(merge_parent_arg, "--merge-parent")
104
+ if head_oid and merge_parent_oid == head_oid:
105
+ raise FinalizerError(
106
+ ErrorCode.REPO_INVALID,
107
+ "--merge-parent 不能与 HEAD 相同",
108
+ final_phase="preflight",
109
+ )
110
+ if merge_head_file.is_symlink() or not merge_head_file.is_file():
111
+ raise FinalizerError(
112
+ ErrorCode.REPO_INVALID,
113
+ "使用 --merge-parent 要求仓库处于有效的普通 MERGE_HEAD 状态",
114
+ final_phase="preflight",
115
+ )
116
+ raw_merge = merge_head_file.read_bytes()
117
+ if len(raw_merge) > 256 or raw_merge != f"{merge_parent_oid}\n".encode("ascii"):
118
+ raise FinalizerError(
119
+ ErrorCode.REPO_INVALID,
120
+ "MERGE_HEAD 与传入的 --merge-parent 不一致或格式非法",
121
+ final_phase="preflight",
122
+ )
123
+ parent_chk = run_git(repo, "cat-file", "-e", f"{merge_parent_oid}^{{commit}}")
124
+ if parent_chk.returncode != 0:
125
+ raise FinalizerError(
126
+ ErrorCode.REPO_INVALID,
127
+ "--merge-parent 不是有效 commit 对象",
128
+ final_phase="preflight",
129
+ )
130
+ unmerged = run_git(repo, "ls-files", "--unmerged", "-z")
131
+ if unmerged.returncode != 0 or unmerged.stdout:
132
+ raise FinalizerError(
133
+ ErrorCode.INDEX_UNCLEAN,
134
+ "仓库仍存在未解决的冲突 unmerged index entries",
135
+ final_phase="preflight",
136
+ )
137
+ return merge_parent_oid
138
+
139
+
140
+ def inspect_repository(
141
+ repo_arg: str | None,
142
+ *,
143
+ merge_parent_arg: str | None = None,
144
+ mode: str = "normal",
145
+ require_attached: bool = True,
146
+ ) -> RepoInfo:
147
+ if not repo_arg:
148
+ raise FinalizerError(
149
+ ErrorCode.CLI_INVALID_ARGS,
150
+ "必须通过 --repo 指定 Git worktree 根目录",
151
+ final_phase="cli",
152
+ )
153
+ raw_repo = Path(repo_arg)
154
+ if not raw_repo.exists():
155
+ raise FinalizerError(
156
+ ErrorCode.REPO_INVALID,
157
+ f"--repo 不是 Git worktree: {repo_arg}",
158
+ final_phase="preflight",
159
+ )
160
+ resolved_repo = raw_repo.resolve()
161
+ inside = run_git(resolved_repo, "rev-parse", "--is-inside-work-tree")
162
+ if inside.returncode != 0 or inside.stdout.decode("ascii", errors="replace").strip() != "true":
163
+ raise FinalizerError(
164
+ ErrorCode.REPO_INVALID,
165
+ f"--repo 不是 Git worktree: {repo_arg}",
166
+ final_phase="preflight",
167
+ )
168
+ top_res = run_git(resolved_repo, "rev-parse", "--show-toplevel")
169
+ if top_res.returncode != 0:
170
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法解析 --show-toplevel", final_phase="preflight")
171
+ top_resolved = Path(top_res.stdout.decode("utf-8", errors="strict").strip()).resolve()
172
+ if top_resolved != resolved_repo:
173
+ raise FinalizerError(
174
+ ErrorCode.REPO_INVALID,
175
+ f"--repo 必须是 Git worktree 根目录(实际根目录为 {top_resolved})",
176
+ final_phase="preflight",
177
+ )
178
+ dirs_res = run_git(resolved_repo, "rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir")
179
+ if dirs_res.returncode != 0:
180
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法解析 .git 目录", final_phase="preflight")
181
+ dir_lines = dirs_res.stdout.decode("utf-8", errors="strict").splitlines()
182
+ if len(dir_lines) != 2:
183
+ raise FinalizerError(ErrorCode.REPO_INVALID, "git-dir / git-common-dir 输出异常", final_phase="preflight")
184
+ git_dir = Path(dir_lines[0]).resolve()
185
+ common_dir = Path(dir_lines[1]).resolve()
186
+
187
+ sym = run_git(resolved_repo, "symbolic-ref", "--quiet", "--short", "HEAD")
188
+ branch: str | None = sym.stdout.decode("utf-8", errors="strict").strip() if sym.returncode == 0 else None
189
+ if require_attached and not branch:
190
+ raise FinalizerError(
191
+ ErrorCode.DETACHED_HEAD,
192
+ "要求 symbolic attached branch(当前处于 detached HEAD)",
193
+ final_phase="preflight",
194
+ )
195
+
196
+ head_res = run_git(resolved_repo, "rev-parse", "--verify", "--quiet", "HEAD")
197
+ if head_res.returncode == 0:
198
+ is_unborn = False
199
+ head_oid: str | None = head_res.stdout.decode("ascii").strip()
200
+ elif head_res.returncode == 1 or head_res.returncode == 128:
201
+ # Distinguish unborn HEAD from corrupt objects cleanly (`show-ref --verify --quiet` exits 1 when missing).
202
+ ref_chk = run_git(resolved_repo, "show-ref", "--verify", "--quiet", "--", f"refs/heads/{branch}") if branch else None
203
+ if ref_chk is not None and ref_chk.returncode == 0:
204
+ raise FinalizerError(
205
+ ErrorCode.REPO_INVALID,
206
+ "HEAD 引用存在但对象已损坏",
207
+ status="failed",
208
+ final_phase="preflight",
209
+ )
210
+ if ref_chk is not None and ref_chk.returncode not in (0, 1):
211
+ raise FinalizerError(
212
+ ErrorCode.REPO_INVALID,
213
+ "无法读取分支引用状态",
214
+ status="failed",
215
+ final_phase="preflight",
216
+ )
217
+ is_unborn = True
218
+ head_oid = None
219
+ else:
220
+ raise FinalizerError(
221
+ ErrorCode.REPO_INVALID,
222
+ "读取 HEAD 失败",
223
+ status="failed",
224
+ final_phase="preflight",
225
+ )
226
+
227
+ merge_parent = _pending_operation_check(resolved_repo, git_dir, merge_parent_arg, mode, head_oid=head_oid)
228
+ upstream = None
229
+ if not is_unborn and branch:
230
+ up_res = run_git(resolved_repo, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
231
+ if up_res.returncode == 0:
232
+ upstream = up_res.stdout.decode("utf-8", errors="strict").strip() or None
233
+
234
+ return RepoInfo(
235
+ repo=resolved_repo,
236
+ git_dir=git_dir,
237
+ common_dir=common_dir,
238
+ is_unborn=is_unborn,
239
+ head_oid=head_oid,
240
+ branch=branch,
241
+ upstream=upstream,
242
+ merge_parent=merge_parent,
243
+ )
244
+
245
+
246
+ def resolve_configured_upstream(repo: Path, branch: str) -> tuple[str, str]:
247
+ """Fail-closed upstream remote and branch resolution (fixes `git config || true` bugs)."""
248
+ rem_cfg = run_git(repo, "config", "--get-all", f"branch.{branch}.remote")
249
+ if rem_cfg.returncode == 1:
250
+ raise FinalizerError(
251
+ ErrorCode.UPSTREAM_CONFLICT,
252
+ f"当前分支 {branch} 未配置 upstream remote",
253
+ final_phase="preflight",
254
+ )
255
+ if rem_cfg.returncode != 0:
256
+ raise FinalizerError(
257
+ ErrorCode.REPO_INVALID,
258
+ f"读取 branch.{branch}.remote 配置失败 (exit {rem_cfg.returncode})",
259
+ status="failed",
260
+ final_phase="preflight",
261
+ )
262
+ remotes = [ln.strip() for ln in rem_cfg.stdout.decode("utf-8").splitlines() if ln.strip()]
263
+ if len(remotes) != 1 or remotes[0] == ".":
264
+ raise FinalizerError(
265
+ ErrorCode.UPSTREAM_CONFLICT,
266
+ f"当前分支 {branch} 的 upstream remote 配置含糊或无效",
267
+ final_phase="preflight",
268
+ )
269
+ remote = validate_remote_name(remotes[0])
270
+
271
+ merge_cfg = run_git(repo, "config", "--get-all", f"branch.{branch}.merge")
272
+ if merge_cfg.returncode == 1:
273
+ raise FinalizerError(
274
+ ErrorCode.UPSTREAM_CONFLICT,
275
+ f"当前分支 {branch} 未配置 upstream merge ref",
276
+ final_phase="preflight",
277
+ )
278
+ if merge_cfg.returncode != 0:
279
+ raise FinalizerError(
280
+ ErrorCode.REPO_INVALID,
281
+ f"读取 branch.{branch}.merge 配置失败 (exit {merge_cfg.returncode})",
282
+ status="failed",
283
+ final_phase="preflight",
284
+ )
285
+ merges = [ln.strip() for ln in merge_cfg.stdout.decode("utf-8").splitlines() if ln.strip()]
286
+ if len(merges) != 1 or not merges[0].startswith("refs/heads/"):
287
+ raise FinalizerError(
288
+ ErrorCode.UPSTREAM_CONFLICT,
289
+ f"当前分支 {branch} 的 upstream merge ref 配置无效",
290
+ final_phase="preflight",
291
+ )
292
+ target_branch = merges[0].removeprefix("refs/heads/")
293
+
294
+ # Fail closed on conflicting pushRemote / pushDefault configuration.
295
+ branch_push_remote: str | None = None
296
+ bpr_res = run_git(repo, "config", "--null", "--get-all", f"branch.{branch}.pushRemote")
297
+ if bpr_res.returncode not in (0, 1):
298
+ raise FinalizerError(
299
+ ErrorCode.REPO_INVALID,
300
+ f"读取 branch.{branch}.pushRemote 配置失败 (exit {bpr_res.returncode})",
301
+ status="failed",
302
+ final_phase="preflight",
303
+ )
304
+ if bpr_res.returncode == 0:
305
+ bpr_vals = parse_nul_records(bpr_res.stdout)
306
+ if len(bpr_vals) != 1 or not bpr_vals[0].strip():
307
+ raise FinalizerError(
308
+ ErrorCode.UPSTREAM_CONFLICT,
309
+ f"branch.{branch}.pushRemote 配置含糊,无法证明唯一 push 目标",
310
+ final_phase="preflight",
311
+ )
312
+ branch_push_remote = bpr_vals[0].strip()
313
+
314
+ default_push_remote: str | None = None
315
+ dpr_res = run_git(repo, "config", "--null", "--get-all", "remote.pushDefault")
316
+ if dpr_res.returncode not in (0, 1):
317
+ raise FinalizerError(
318
+ ErrorCode.REPO_INVALID,
319
+ f"读取 remote.pushDefault 配置失败 (exit {dpr_res.returncode})",
320
+ status="failed",
321
+ final_phase="preflight",
322
+ )
323
+ if dpr_res.returncode == 0:
324
+ dpr_vals = parse_nul_records(dpr_res.stdout)
325
+ if len(dpr_vals) != 1 or not dpr_vals[0].strip():
326
+ raise FinalizerError(
327
+ ErrorCode.UPSTREAM_CONFLICT,
328
+ "remote.pushDefault 配置含糊,无法证明唯一 push 目标",
329
+ final_phase="preflight",
330
+ )
331
+ default_push_remote = dpr_vals[0].strip()
332
+
333
+ effective_push_remote = branch_push_remote or default_push_remote or remote
334
+ if effective_push_remote != remote:
335
+ raise FinalizerError(
336
+ ErrorCode.UPSTREAM_CONFLICT,
337
+ f"实际 push remote 与 upstream remote 不一致 ({effective_push_remote} != {remote})",
338
+ final_phase="preflight",
339
+ )
340
+
341
+ validate_remote_endpoints(repo, remote)
342
+ return remote, target_branch
343
+
344
+
345
+ def resolve_upstream_for_resume(repo: Path, branch: str) -> tuple[str, str]:
346
+ """Resolve existing upstream cleanly via `for-each-ref` + `rev-parse` without invoking `git config`."""
347
+ head_ref = f"refs/heads/{branch}"
348
+ fer = run_git(
349
+ repo,
350
+ "for-each-ref",
351
+ "--format=%(upstream:short)\t%(upstream:remotename)\t%(upstream:remoteref)",
352
+ head_ref,
353
+ )
354
+ if fer.returncode != 0:
355
+ raise FinalizerError(
356
+ ErrorCode.UPSTREAM_CONFLICT,
357
+ "无法解析当前分支 configured upstream",
358
+ final_phase="preflight",
359
+ )
360
+ lines = [ln for ln in fer.stdout.decode("utf-8", errors="replace").splitlines() if ln]
361
+ if len(lines) != 1:
362
+ raise FinalizerError(
363
+ ErrorCode.UPSTREAM_CONFLICT,
364
+ f"当前分支 {branch} 不存在唯一可解析的 upstream",
365
+ final_phase="preflight",
366
+ )
367
+ parts = lines[0].split("\t")
368
+ if len(parts) != 3:
369
+ raise FinalizerError(ErrorCode.UPSTREAM_CONFLICT, "configured upstream 格式异常", final_phase="preflight")
370
+ short_name, remote_raw, merge_ref = parts
371
+ if not short_name or not remote_raw or remote_raw == "." or not merge_ref.startswith("refs/heads/"):
372
+ raise FinalizerError(
373
+ ErrorCode.UPSTREAM_CONFLICT,
374
+ "configured upstream 不是可验证的远端 branch",
375
+ final_phase="preflight",
376
+ )
377
+ remote = validate_remote_name(remote_raw)
378
+ target_branch = merge_ref.removeprefix("refs/heads/")
379
+ up_oid_res = run_git(repo, "rev-parse", "--verify", "@{upstream}^{commit}")
380
+ full_ref = f"refs/remotes/{remote}/{target_branch}"
381
+ tr_oid_res = run_git(repo, "rev-parse", "--verify", f"{full_ref}^{{commit}}")
382
+ if (
383
+ up_oid_res.returncode != 0
384
+ or tr_oid_res.returncode != 0
385
+ or up_oid_res.stdout.strip() != tr_oid_res.stdout.strip()
386
+ ):
387
+ raise FinalizerError(
388
+ ErrorCode.UPSTREAM_CONFLICT,
389
+ "configured upstream 无法解析或 tracking ref 不一致",
390
+ final_phase="preflight",
391
+ )
392
+ validate_remote_endpoints(repo, remote)
393
+ return remote, target_branch
394
+
395
+
396
+ def validate_remote_endpoints(repo: Path, remote: str) -> str:
397
+ """Ensure `remote` exists with a single identical fetch/push URL."""
398
+ validate_remote_name(remote)
399
+ fetch = run_git(repo, "remote", "get-url", "--all", remote)
400
+ if fetch.returncode != 0:
401
+ raise FinalizerError(
402
+ ErrorCode.REMOTE_MISSING,
403
+ f"未配置指定 remote: {remote}",
404
+ final_phase="preflight",
405
+ )
406
+ fetch_urls = [ln for ln in fetch.stdout.decode("utf-8").splitlines() if ln]
407
+ if len(fetch_urls) != 1:
408
+ raise FinalizerError(
409
+ ErrorCode.REMOTE_MISSING,
410
+ f"remote {remote} 包含多个 fetch endpoint 或未配置 URL",
411
+ final_phase="preflight",
412
+ )
413
+ push = run_git(repo, "remote", "get-url", "--push", "--all", remote)
414
+ if push.returncode != 0:
415
+ raise FinalizerError(
416
+ ErrorCode.REMOTE_MISSING,
417
+ f"无法读取 remote {remote} 的 push endpoint",
418
+ final_phase="preflight",
419
+ )
420
+ push_urls = [ln for ln in push.stdout.decode("utf-8").splitlines() if ln]
421
+ if len(push_urls) != 1:
422
+ raise FinalizerError(
423
+ ErrorCode.REMOTE_MISSING,
424
+ f"remote {remote} 包含多个 push endpoint",
425
+ final_phase="preflight",
426
+ )
427
+ if fetch_urls[0] != push_urls[0]:
428
+ raise FinalizerError(
429
+ ErrorCode.UPSTREAM_CONFLICT,
430
+ f"remote {remote} 的 fetch 与 push endpoint 不一致",
431
+ final_phase="preflight",
432
+ )
433
+ return fetch_urls[0]
434
+
435
+
436
+ def list_remote_refs(repo: Path, remote: str) -> dict[str, str]:
437
+ """Query `git ls-remote` safely with timeout and `--` separator."""
438
+ validate_remote_name(remote)
439
+ completed = run_git(repo, "ls-remote", "--", remote, timeout=DEFAULT_REMOTE_GIT_TIMEOUT)
440
+ if completed.returncode != 0:
441
+ raise FinalizerError(
442
+ ErrorCode.REMOTE_UNAVAILABLE,
443
+ f"无法访问远端 {remote}",
444
+ final_phase="remote_verify",
445
+ )
446
+ refs: dict[str, str] = {}
447
+ for line in completed.stdout.decode("utf-8", errors="replace").splitlines():
448
+ line = line.strip()
449
+ if not line:
450
+ continue
451
+ oid, sep, ref = line.partition("\t")
452
+ if not sep:
453
+ parts = line.split(None, 1)
454
+ if len(parts) != 2:
455
+ continue
456
+ oid, ref = parts
457
+ refs[ref] = oid
458
+ return refs
459
+
460
+
461
+ def _is_staged_deletion(
462
+ repo: Path, rel_path: str, *, is_unborn: bool, env: dict[str, str] | None = None
463
+ ) -> bool:
464
+ if is_unborn:
465
+ return False
466
+ return (
467
+ run_git(
468
+ repo,
469
+ "--literal-pathspecs",
470
+ "diff",
471
+ "--cached",
472
+ "--no-renames",
473
+ "--no-ext-diff",
474
+ "--no-textconv",
475
+ "--quiet",
476
+ "--diff-filter=D",
477
+ "HEAD",
478
+ "--",
479
+ rel_path,
480
+ env=env,
481
+ ).returncode
482
+ == 1
483
+ )
484
+
485
+
486
+ def validate_explicit_paths(
487
+ repo: Path,
488
+ raw_paths: list[str],
489
+ *,
490
+ is_unborn: bool,
491
+ env: dict[str, str] | None = None,
492
+ ) -> list[str]:
493
+ """Validate explicit repository-relative paths, deduplicating against duplicates/symlinks/out-of-scope index."""
494
+ if not raw_paths:
495
+ raise FinalizerError(
496
+ ErrorCode.SCOPE_INVALID,
497
+ "必须在 `--` 后显式列出至少一个 repository-relative 文件路径",
498
+ final_phase="cli",
499
+ )
500
+
501
+ repo_str = str(repo)
502
+ cleaned: list[str] = []
503
+ seen: set[str] = set()
504
+ for raw in raw_paths:
505
+ if not raw or raw in {".", ".."} or "\0" in raw or any(ch in raw for ch in ("\n", "\r", "\t")):
506
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"非法文件路径: {raw!r}", final_phase="preflight")
507
+
508
+ # Support both repository-relative paths (`./a`, `dir/a`) and absolute paths inside `repo`.
509
+ candidate_raw = raw if raw.startswith("/") else f"{repo_str}/{raw}"
510
+ lexical = Path(posixpath.normpath(candidate_raw))
511
+ if lexical == repo:
512
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, "不能把 repo 根目录作为提交文件", final_phase="preflight")
513
+ try:
514
+ rel_path = lexical.relative_to(repo).as_posix()
515
+ except ValueError as exc:
516
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"文件不在 repo 内: {raw}", final_phase="preflight") from exc
517
+
518
+ posix = PurePosixPath(rel_path)
519
+ if not rel_path or rel_path in {".", ".."} or ".." in posix.parts or ".git" in posix.parts:
520
+ raise FinalizerError(
521
+ ErrorCode.SCOPE_INVALID,
522
+ f"路径必须是 repository-relative 普通文件路径(禁止 Git 元数据): {raw}",
523
+ final_phase="preflight",
524
+ )
525
+ if rel_path in seen:
526
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"路径列表包含重复项: {rel_path}", final_phase="preflight")
527
+ seen.add(rel_path)
528
+
529
+ target = repo / rel_path
530
+ if target.is_symlink():
531
+ # Allow tracked/staged symlinks living inside `repo`, while still blocking directory traversal outside `repo`.
532
+ try:
533
+ target.parent.resolve(strict=False).relative_to(repo)
534
+ except ValueError as exc:
535
+ raise FinalizerError(
536
+ ErrorCode.SCOPE_INVALID,
537
+ f"symlink 父目录解析后不在 repo 内: {raw}",
538
+ final_phase="preflight",
539
+ ) from exc
540
+ else:
541
+ try:
542
+ resolved = target.resolve(strict=False)
543
+ resolved.relative_to(repo)
544
+ except (OSError, ValueError) as exc:
545
+ raise FinalizerError(
546
+ ErrorCode.SCOPE_INVALID,
547
+ f"文件经符号链接解析后不在 repo 内: {raw}",
548
+ final_phase="preflight",
549
+ ) from exc
550
+ if target.is_dir():
551
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"只接受显式文件,不能指定目录: {raw}", final_phase="preflight")
552
+ if not target.exists():
553
+ tracked = run_git(repo, "--literal-pathspecs", "ls-files", "-z", "--", rel_path, env=env)
554
+ staged_del = _is_staged_deletion(repo, rel_path, is_unborn=is_unborn, env=env)
555
+ if (tracked.returncode != 0 or not parse_nul_records(tracked.stdout)) and not staged_del:
556
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"文件不存在且不是 tracked deletion: {raw}", final_phase="preflight")
557
+ elif not target.is_file():
558
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"目标路径不是普通文件: {raw}", final_phase="preflight")
559
+ else:
560
+ ig = run_git(repo, "check-ignore", "--quiet", "--no-index", "--", rel_path, env=env)
561
+ if ig.returncode == 0:
562
+ tracked = run_git(repo, "--literal-pathspecs", "ls-files", "-z", "--", rel_path, env=env)
563
+ staged_del = _is_staged_deletion(repo, rel_path, is_unborn=is_unborn, env=env)
564
+ if not parse_nul_records(tracked.stdout) and not staged_del:
565
+ raise FinalizerError(
566
+ ErrorCode.SCOPE_INVALID,
567
+ f"禁止提交被 .gitignore 忽略的未跟踪文件: {rel_path}",
568
+ final_phase="preflight",
569
+ )
570
+ cleaned.append(rel_path)
571
+
572
+ # Reject any pre-existing staged changes outside the requested explicit path set.
573
+ if is_unborn:
574
+ staged_res = run_git(repo, "ls-files", "--cached", "-z", env=env)
575
+ staged_paths = parse_nul_records(staged_res.stdout) if staged_res.returncode == 0 else []
576
+ else:
577
+ staged_res = run_git(repo, "diff", "--cached", "--name-only", "-z", env=env)
578
+ if staged_res.returncode != 0:
579
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法检查已有 staged index 状态", final_phase="preflight")
580
+ staged_paths = parse_nul_records(staged_res.stdout)
581
+
582
+ extra_staged = [p for p in staged_paths if p not in seen]
583
+ if extra_staged:
584
+ raise FinalizerError(
585
+ ErrorCode.INDEX_UNCLEAN,
586
+ f"index 中存在超出本次范围的已暂存改动: {', '.join(extra_staged[:5])}",
587
+ final_phase="preflight",
588
+ )
589
+ return cleaned
590
+
591
+
592
+ def working_tree_dirty_status(repo: Path, env: dict[str, str] | None = None) -> tuple[bool, bool, str]:
593
+ """Return `(dirty_worktree, dirty_index, status_short)`."""
594
+ wt = run_git(repo, "status", "--porcelain=v1", "-z", env=env)
595
+ if wt.returncode != 0:
596
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法读取 Git 工作区状态", final_phase="preflight")
597
+ records = parse_nul_records(wt.stdout)
598
+ dirty_wt = False
599
+ dirty_idx = False
600
+ for rec in records:
601
+ if len(rec) < 2:
602
+ continue
603
+ x, y = rec[0], rec[1]
604
+ if x == "?" and y == "?":
605
+ dirty_wt = True
606
+ else:
607
+ if x not in (" ", "!"):
608
+ dirty_idx = True
609
+ if y not in (" ", "!"):
610
+ dirty_wt = True
611
+ state_label = "dirty" if (dirty_wt or dirty_idx) else "clean"
612
+ return dirty_wt, dirty_idx, state_label