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,1057 @@
1
+ #!/usr/bin/env python3
2
+ """Create and safely clean registered task directories under /tmp (portable pure Python)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from dataclasses import dataclass
8
+ from datetime import UTC, datetime
9
+ import hashlib
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import re
14
+ import secrets
15
+ import stat
16
+ import sys
17
+ from typing import Any
18
+
19
+ from git_finalizer import __version__
20
+ from git_finalizer.errors import ErrorCode
21
+
22
+ TMP_ROOT = Path("/tmp")
23
+ STATE_ROOT = Path.home() / ".local/state/tool-temp-dir"
24
+ RECORD_VERSION = 2
25
+ TOOL_VERSION = __version__
26
+ PREFIX_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
27
+ NAME_RE = re.compile(
28
+ r"^tool-task-(?P<prefix>[A-Za-z0-9][A-Za-z0-9_-]{0,63})-"
29
+ r"(?P<random>[0-9a-f]{16})$"
30
+ )
31
+ MAX_RECORD_BYTES = 16_384
32
+ FIXTURE_PREFIX_TOKENS = frozenset(
33
+ {"fixture", "profile", "profiling", "pytest", "test", "tests"}
34
+ )
35
+ _O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
36
+ _O_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
37
+
38
+
39
+ class TempDirError(Exception):
40
+ """A safety invariant rejected the requested operation."""
41
+
42
+ def __init__(self, code: str, reason: str) -> None:
43
+ super().__init__(reason)
44
+ self.code = code
45
+ self.error_code = ErrorCode.TEMP_DIR_FAILED
46
+ self.reason = reason
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class CleanupValidation:
51
+ path: Path
52
+ record_path: Path
53
+ prefix: str
54
+ uid: int
55
+ device: int
56
+ inode: int
57
+ entries: tuple[CleanupEntry, ...]
58
+ fixture_socket_paths: frozenset[str] = frozenset()
59
+ pytest_basetemps: frozenset[str] = frozenset()
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class CleanupEntry:
64
+ relative_path: str
65
+ kind: str
66
+ mode: int
67
+ uid: int
68
+ device: int
69
+ inode: int
70
+ size: int
71
+
72
+
73
+ def _resolved_tmp_root() -> Path:
74
+ try:
75
+ return TMP_ROOT.resolve(strict=True)
76
+ except OSError:
77
+ return TMP_ROOT
78
+
79
+
80
+ def _private_mode(path: Path, expected_mode: int) -> os.stat_result:
81
+ try:
82
+ metadata = path.lstat()
83
+ except FileNotFoundError as exc:
84
+ raise TempDirError("registry_missing", f"登记路径不存在:{path}") from exc
85
+ if not stat.S_ISDIR(metadata.st_mode):
86
+ raise TempDirError("registry_unsafe", f"登记路径不是普通目录:{path}")
87
+ if metadata.st_uid != os.getuid():
88
+ raise TempDirError("registry_unsafe", f"登记路径不属于当前 UID:{path}")
89
+ if stat.S_IMODE(metadata.st_mode) != expected_mode:
90
+ raise TempDirError(
91
+ "registry_unsafe",
92
+ f"登记路径权限必须为 {expected_mode:04o}:{path}",
93
+ )
94
+ return metadata
95
+
96
+
97
+ def _registry_dir(*, create: bool) -> Path:
98
+ records = STATE_ROOT / "records"
99
+ if create:
100
+ old_umask = os.umask(0o077)
101
+ try:
102
+ STATE_ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
103
+ records.mkdir(mode=0o700, exist_ok=True)
104
+ except OSError as exc:
105
+ raise TempDirError("registry_unavailable", f"无法创建登记目录:{exc}") from exc
106
+ finally:
107
+ os.umask(old_umask)
108
+ _private_mode(STATE_ROOT, 0o700)
109
+ _private_mode(records, 0o700)
110
+ return records
111
+
112
+
113
+ def _record_path(path: Path, *, create_registry: bool = False) -> Path:
114
+ try:
115
+ records = _registry_dir(create=create_registry)
116
+ except TempDirError as exc:
117
+ if not create_registry and exc.code == "registry_missing":
118
+ raise TempDirError(
119
+ "not_registered", "目标不存在于本工具的创建登记中"
120
+ ) from exc
121
+ raise
122
+ digest = hashlib.sha256(os.fsencode(path)).hexdigest()
123
+ return records / f"{digest}.json"
124
+
125
+
126
+ def _write_record(record_path: Path, record: dict[str, Any]) -> None:
127
+ payload = (
128
+ json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
129
+ + "\n"
130
+ ).encode("utf-8")
131
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_CLOEXEC | _O_NOFOLLOW
132
+ old_umask = os.umask(0o077)
133
+ try:
134
+ descriptor = os.open(record_path, flags, 0o600)
135
+ except OSError as exc:
136
+ raise TempDirError("registration_failed", f"无法创建登记记录:{exc}") from exc
137
+ finally:
138
+ os.umask(old_umask)
139
+
140
+ try:
141
+ offset = 0
142
+ while offset < len(payload):
143
+ offset += os.write(descriptor, payload[offset:])
144
+ os.fsync(descriptor)
145
+ metadata = os.fstat(descriptor)
146
+ if stat.S_IMODE(metadata.st_mode) != 0o600:
147
+ raise TempDirError("registration_failed", "登记记录权限不是 0600")
148
+ finally:
149
+ os.close(descriptor)
150
+
151
+
152
+ def _read_record(record_path: Path) -> dict[str, Any]:
153
+ flags = os.O_RDONLY | _O_CLOEXEC | _O_NOFOLLOW
154
+ try:
155
+ descriptor = os.open(record_path, flags)
156
+ except FileNotFoundError as exc:
157
+ raise TempDirError("not_registered", "目标不存在于本工具的创建登记中") from exc
158
+ except OSError as exc:
159
+ raise TempDirError("registry_unsafe", f"无法安全打开登记记录:{exc}") from exc
160
+
161
+ try:
162
+ metadata = os.fstat(descriptor)
163
+ if not stat.S_ISREG(metadata.st_mode):
164
+ raise TempDirError("registry_unsafe", "登记记录不是普通文件")
165
+ if metadata.st_uid != os.getuid():
166
+ raise TempDirError("registry_unsafe", "登记记录不属于当前 UID")
167
+ if stat.S_IMODE(metadata.st_mode) != 0o600:
168
+ raise TempDirError("registry_unsafe", "登记记录权限必须为 0600")
169
+ if metadata.st_size > MAX_RECORD_BYTES:
170
+ raise TempDirError("registry_corrupt", "登记记录超过大小限制")
171
+ chunks: list[bytes] = []
172
+ remaining = MAX_RECORD_BYTES + 1
173
+ while remaining:
174
+ chunk = os.read(descriptor, min(4096, remaining))
175
+ if not chunk:
176
+ break
177
+ chunks.append(chunk)
178
+ remaining -= len(chunk)
179
+ finally:
180
+ os.close(descriptor)
181
+
182
+ raw = b"".join(chunks)
183
+ if len(raw) > MAX_RECORD_BYTES:
184
+ raise TempDirError("registry_corrupt", "登记记录超过大小限制")
185
+ try:
186
+ record = json.loads(raw)
187
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
188
+ raise TempDirError("registry_corrupt", "登记记录不是有效 JSON") from exc
189
+ if not isinstance(record, dict):
190
+ raise TempDirError("registry_corrupt", "登记记录必须是 JSON 对象")
191
+ return record
192
+
193
+
194
+ def _validate_prefix(task_prefix: str) -> None:
195
+ if not task_prefix:
196
+ raise TempDirError("invalid_prefix", "task-prefix 不得为空")
197
+ if PREFIX_RE.fullmatch(task_prefix) is None:
198
+ raise TempDirError(
199
+ "invalid_prefix",
200
+ "task-prefix 仅允许 1–64 个 ASCII 字母、数字、下划线或连字符,且首字符必须为字母或数字",
201
+ )
202
+
203
+
204
+ def create_directory(task_prefix: str) -> dict[str, Any]:
205
+ _validate_prefix(task_prefix)
206
+ records = _registry_dir(create=True)
207
+ tmp_resolved = _resolved_tmp_root()
208
+ old_umask = os.umask(0o077)
209
+ try:
210
+ for _attempt in range(128):
211
+ path = TMP_ROOT / f"tool-task-{task_prefix}-{secrets.token_hex(8)}"
212
+ try:
213
+ path.mkdir(mode=0o700)
214
+ except FileExistsError:
215
+ continue
216
+ break
217
+ else:
218
+ raise TempDirError("create_failed", "无法生成未占用的随机目录名")
219
+ except OSError as exc:
220
+ raise TempDirError("create_failed", f"无法在 /tmp 创建目录:{exc}") from exc
221
+ finally:
222
+ os.umask(old_umask)
223
+
224
+ metadata = path.lstat()
225
+ canonical_expected = tmp_resolved / path.name
226
+ record_path = records / f"{hashlib.sha256(os.fsencode(path)).hexdigest()}.json"
227
+ try:
228
+ if path.parent.resolve(strict=True) != tmp_resolved or NAME_RE.fullmatch(path.name) is None:
229
+ raise TempDirError("create_failed", "创建结果不符合固定 /tmp 命名合同")
230
+ if path.resolve(strict=True) != canonical_expected:
231
+ raise TempDirError("create_failed", "创建结果无法规范化为原始路径")
232
+ if not stat.S_ISDIR(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
233
+ raise TempDirError("create_failed", "创建结果不是普通目录")
234
+ if metadata.st_uid != os.getuid():
235
+ raise TempDirError("create_failed", "创建目录不属于当前 UID")
236
+ os.chmod(path, 0o700)
237
+ metadata = path.lstat()
238
+ if stat.S_IMODE(metadata.st_mode) != 0o700:
239
+ raise TempDirError("create_failed", "创建目录权限不是 0700")
240
+ created_at = datetime.now(UTC).isoformat(timespec="seconds")
241
+ record = {
242
+ "version": RECORD_VERSION,
243
+ "path": str(path),
244
+ "basename": path.name,
245
+ "uid": metadata.st_uid,
246
+ "device": metadata.st_dev,
247
+ "inode": metadata.st_ino,
248
+ "created_at": created_at,
249
+ "prefix": task_prefix,
250
+ }
251
+ _write_record(record_path, record)
252
+ except Exception:
253
+ try:
254
+ current = path.lstat()
255
+ if (
256
+ stat.S_ISDIR(current.st_mode)
257
+ and not stat.S_ISLNK(current.st_mode)
258
+ and current.st_dev == metadata.st_dev
259
+ and current.st_ino == metadata.st_ino
260
+ and not any(path.iterdir())
261
+ ):
262
+ path.rmdir()
263
+ except OSError:
264
+ pass
265
+ raise
266
+
267
+ return {
268
+ "ok": True,
269
+ "command": "create",
270
+ "path": str(path),
271
+ "record": str(record_path),
272
+ "created_at": created_at,
273
+ }
274
+
275
+
276
+ def _normalize_cleanup_path(raw_path: str) -> Path:
277
+ if not raw_path or not os.path.isabs(raw_path):
278
+ raise TempDirError("invalid_path", "cleanup 目标必须是绝对路径")
279
+ if any(character in raw_path for character in ("\x00", "\n", "\r")):
280
+ raise TempDirError("invalid_path", "cleanup 目标包含非法控制字符")
281
+ normalized = os.path.normpath(raw_path)
282
+ if normalized != raw_path:
283
+ raise TempDirError("path_not_canonical", "cleanup 目标必须已规范化,不接受路径穿越或多余分隔符")
284
+ path = Path(normalized)
285
+ if path.parent != TMP_ROOT:
286
+ raise TempDirError("outside_tmp", "cleanup 目标必须直接位于 /tmp 下")
287
+ if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,160}", path.name) is None:
288
+ raise TempDirError("name_mismatch", "cleanup 目标 basename 不符合登记名称合同")
289
+ return path
290
+
291
+
292
+ def _decode_mount_path(value: str) -> str:
293
+ return re.sub(
294
+ r"\\([0-7]{3})",
295
+ lambda match: chr(int(match.group(1), 8)),
296
+ value,
297
+ )
298
+
299
+
300
+ def _read_mount_points() -> set[str]:
301
+ mount_points: set[str] = set()
302
+ if sys.platform.startswith("linux") or Path("/proc/self/mountinfo").exists():
303
+ try:
304
+ with open("/proc/self/mountinfo", encoding="utf-8") as stream:
305
+ for line in stream:
306
+ fields = line.split()
307
+ if len(fields) < 5:
308
+ raise TempDirError("mountinfo_invalid", "mountinfo 行格式异常")
309
+ mount_points.add(os.path.normpath(_decode_mount_path(fields[4])))
310
+ except OSError as exc:
311
+ raise TempDirError("mountinfo_unavailable", f"无法读取 mountinfo:{exc}") from exc
312
+ return mount_points
313
+
314
+
315
+ def _reject_mounts(path: Path, mount_points: set[str]) -> None:
316
+ target = str(path)
317
+ resolved_target = str(_resolved_tmp_root() / path.name)
318
+ if os.path.ismount(path) or target in mount_points or resolved_target in mount_points:
319
+ raise TempDirError("target_is_mount", "cleanup 目标本身是 mount point")
320
+ prefix = target + os.sep
321
+ resolved_prefix = resolved_target + os.sep
322
+ nested = sorted(
323
+ point
324
+ for point in mount_points
325
+ if point.startswith(prefix) or point.startswith(resolved_prefix)
326
+ )
327
+ if nested:
328
+ raise TempDirError("nested_mount", f"目录树包含挂载点:{nested[0]}")
329
+
330
+
331
+ def _entry_kind(mode: int) -> str:
332
+ if stat.S_ISREG(mode):
333
+ return "regular file"
334
+ if stat.S_ISDIR(mode):
335
+ return "directory"
336
+ if stat.S_ISLNK(mode):
337
+ return "symlink"
338
+ if stat.S_ISSOCK(mode):
339
+ return "socket"
340
+ if stat.S_ISFIFO(mode):
341
+ return "FIFO"
342
+ if stat.S_ISCHR(mode):
343
+ return "character device"
344
+ if stat.S_ISBLK(mode):
345
+ return "block device"
346
+ return "unsupported file type"
347
+
348
+
349
+ def _prefix_allows_fixture_fifo(prefix: str) -> bool:
350
+ tokens = frozenset(part for part in re.split(r"[-_]", prefix) if part)
351
+ return bool(tokens & FIXTURE_PREFIX_TOKENS)
352
+
353
+
354
+ def _pytest_basetemps(raw_paths: tuple[str, ...]) -> frozenset[str]:
355
+ for relative in raw_paths:
356
+ if (
357
+ not relative
358
+ or os.path.isabs(relative)
359
+ or os.path.normpath(relative) != relative
360
+ or any(part in {"", ".", ".."} or part.strip() != part
361
+ for part in relative.split("/"))
362
+ or any(ord(character) < 32 or ord(character) == 127
363
+ or character in "*?[]" for character in relative)
364
+ ):
365
+ raise TempDirError("pytest_scope_rejected", f"pytest basetemp 必须为规范相对目录:{relative}")
366
+ return frozenset(raw_paths)
367
+
368
+
369
+ def _declared_pytest_node(relative: str, basetemps: frozenset[str]) -> bool:
370
+ for base in basetemps:
371
+ if relative.startswith(base + "/"):
372
+ node, separator, _rest = relative[len(base) + 1:].partition("/")
373
+ if separator and re.fullmatch(r"test_.+\d+", node):
374
+ return True
375
+ return False
376
+
377
+
378
+ def _basetemp_entries(
379
+ entries: list[CleanupEntry] | tuple[CleanupEntry, ...], paths: frozenset[str],
380
+ ) -> dict[str, CleanupEntry]:
381
+ selected = {entry.relative_path: entry for entry in entries if entry.relative_path in paths}
382
+ if set(selected) != paths or any(entry.kind != "directory" for entry in selected.values()):
383
+ raise TempDirError("pytest_scope_rejected", "pytest basetemp 缺失或不是实际目录")
384
+ return selected
385
+
386
+
387
+ def _fixture_socket_paths(
388
+ raw_paths: tuple[str, ...], *, fixture_root: bool = False,
389
+ pytest_basetemps: frozenset[str] = frozenset(),
390
+ ) -> frozenset[str]:
391
+ for relative in raw_paths:
392
+ parts = relative.split("/")
393
+ numbered_node = len(parts) >= 3 and re.fullmatch(r"test_.+\d+", parts[1])
394
+ nested_node = any(
395
+ (root == "pytest" or (root.startswith("pytest-") and root != "pytest-"))
396
+ and re.fullmatch(r"test_.+\d+", parts[index + 1])
397
+ for index, root in enumerate(parts[1:-2], start=1)
398
+ )
399
+ if (
400
+ not relative
401
+ or os.path.isabs(relative)
402
+ or os.path.normpath(relative) != relative
403
+ or any(ord(character) < 32 or ord(character) == 127 for character in relative)
404
+ or any(part in {"", ".", ".."} or part.strip() != part for part in parts)
405
+ or not (fixture_root or numbered_node or nested_node
406
+ or _declared_pytest_node(relative, pytest_basetemps))
407
+ ):
408
+ raise TempDirError(
409
+ "socket_scope_rejected",
410
+ f"socket 必须显式指定为 fixture task root 或 numbered pytest fixture 中的规范相对路径:{relative}",
411
+ )
412
+ return frozenset(raw_paths)
413
+
414
+
415
+ def _ensure_fixture_socket_inactive(path: Path) -> None:
416
+ proc_unix = Path("/proc/net/unix")
417
+ if not sys.platform.startswith("linux") and not proc_unix.exists():
418
+ return
419
+ try:
420
+ lines = proc_unix.read_text(
421
+ encoding="utf-8", errors="surrogateescape"
422
+ ).splitlines()
423
+ except OSError as exc:
424
+ raise TempDirError("socket_activity_unknown", f"无法读取 Unix socket 状态:{exc}") from exc
425
+ if not lines or not lines[0].startswith("Num"):
426
+ raise TempDirError("socket_activity_unknown", "Unix socket 状态格式异常")
427
+ for line in lines[1:]:
428
+ fields = line.split(maxsplit=7)
429
+ if len(fields) < 7:
430
+ raise TempDirError("socket_activity_unknown", "Unix socket 状态行格式异常")
431
+ if len(fields) == 7 or fields[7].startswith("@"):
432
+ continue
433
+ bound_path = os.path.normpath(fields[7])
434
+ # Relative bind paths have no cwd in /proc/net/unix: ambiguous matches fail closed.
435
+ matches = (
436
+ str(path) == bound_path
437
+ if os.path.isabs(bound_path)
438
+ else Path(bound_path).name == path.name
439
+ )
440
+ if matches:
441
+ raise TempDirError("socket_active", f"socket 仍被进程绑定:{path}")
442
+
443
+
444
+ def _fixture_socket_entries(
445
+ entries: list[CleanupEntry] | tuple[CleanupEntry, ...],
446
+ paths: frozenset[str],
447
+ ) -> dict[str, CleanupEntry]:
448
+ selected = {entry.relative_path: entry for entry in entries if entry.relative_path in paths}
449
+ if set(selected) != paths or any(entry.kind != "socket" for entry in selected.values()):
450
+ raise TempDirError("socket_scope_rejected", "显式指定的 fixture socket 缺失或不是 socket")
451
+ return selected
452
+
453
+
454
+ def _allowed_entry_kind(
455
+ mode: int,
456
+ relative_path: str,
457
+ *,
458
+ allow_owned_fixture_fifo: bool,
459
+ fifo_requires_pytest_subtree: bool = False,
460
+ fixture_socket_paths: frozenset[str] = frozenset(),
461
+ pytest_basetemps: frozenset[str] = frozenset(),
462
+ ) -> str:
463
+ kind = _entry_kind(mode)
464
+ if kind == "FIFO" and allow_owned_fixture_fifo and fifo_requires_pytest_subtree:
465
+ first, separator, _rest = relative_path.partition("/")
466
+ parts = relative_path.split("/")
467
+ named_pytest_root = first.startswith("pytest-") and first != "pytest-"
468
+ # --basetemp may use any name, including a short path for AF_UNIX sockets.
469
+ numbered_test_node = len(parts) >= 3 and re.fullmatch(r"test_.+\d+", parts[1]) is not None
470
+ # Acceptance runners nest a named pytest basetemp under their work directory.
471
+ # Only descendants of its numbered test nodes extend the existing FIFO scope.
472
+ nested_pytest_node = any(
473
+ (root == "pytest" or (root.startswith("pytest-") and root != "pytest-"))
474
+ and re.fullmatch(r"test_.+\d+", parts[index + 1]) is not None
475
+ for index, root in enumerate(parts[1:-2], start=1)
476
+ )
477
+ if not separator or not (named_pytest_root or numbered_test_node or nested_pytest_node
478
+ or _declared_pytest_node(relative_path, pytest_basetemps)):
479
+ raise TempDirError(
480
+ "fifo_scope_rejected",
481
+ f"FIFO 不在 pytest 临时子目录中:{relative_path}",
482
+ )
483
+ allowed = {"regular file", "directory", "symlink"}
484
+ if allow_owned_fixture_fifo:
485
+ allowed.add("FIFO")
486
+ if relative_path in fixture_socket_paths:
487
+ allowed.add("socket")
488
+ if kind not in allowed:
489
+ raise TempDirError(
490
+ "unsafe_entry",
491
+ f"目录树包含不允许的 {kind}:{relative_path}",
492
+ )
493
+ return kind
494
+
495
+
496
+ def _open_directory(path: str | bytes, *, dir_fd: int | None = None) -> int:
497
+ flags = os.O_RDONLY | os.O_DIRECTORY | _O_CLOEXEC | _O_NOFOLLOW
498
+ try:
499
+ return os.open(path, flags, dir_fd=dir_fd)
500
+ except OSError as exc:
501
+ raise TempDirError("directory_changed", f"无法无跟随打开目录:{exc}") from exc
502
+
503
+
504
+ def _scan_tree(
505
+ descriptor: int,
506
+ *,
507
+ expected_uid: int,
508
+ expected_device: int,
509
+ allow_owned_fixture_fifo: bool,
510
+ fifo_requires_pytest_subtree: bool = False,
511
+ fixture_socket_paths: frozenset[str] = frozenset(),
512
+ pytest_basetemps: frozenset[str] = frozenset(),
513
+ fixture_root: Path | None = None,
514
+ relative_root: str = "",
515
+ entries: list[CleanupEntry] | None = None,
516
+ ) -> list[CleanupEntry]:
517
+ if entries is None:
518
+ entries = []
519
+ try:
520
+ with os.scandir(descriptor) as iterator:
521
+ names = sorted(entry.name for entry in iterator)
522
+ except OSError as exc:
523
+ raise TempDirError("scan_failed", f"无法遍历目录树:{exc}") from exc
524
+
525
+ for name in names:
526
+ relative = f"{relative_root}/{name}" if relative_root else name
527
+ try:
528
+ metadata = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
529
+ except OSError as exc:
530
+ raise TempDirError("directory_changed", f"遍历期间条目发生变化:{relative}: {exc}") from exc
531
+ if metadata.st_uid != expected_uid:
532
+ raise TempDirError("owner_mismatch", f"目录树条目不属于登记 UID:{relative}")
533
+ if metadata.st_dev != expected_device:
534
+ raise TempDirError("cross_device_entry", f"目录树条目跨越登记 filesystem:{relative}")
535
+ kind = _allowed_entry_kind(
536
+ metadata.st_mode,
537
+ relative,
538
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
539
+ fifo_requires_pytest_subtree=fifo_requires_pytest_subtree,
540
+ fixture_socket_paths=fixture_socket_paths,
541
+ pytest_basetemps=pytest_basetemps,
542
+ )
543
+ if kind == "socket":
544
+ if fixture_root is None:
545
+ raise TempDirError("socket_activity_unknown", "缺少 fixture 根目录")
546
+ _ensure_fixture_socket_inactive(fixture_root / relative)
547
+ entries.append(
548
+ CleanupEntry(
549
+ relative_path=relative,
550
+ kind=kind,
551
+ mode=stat.S_IMODE(metadata.st_mode),
552
+ uid=metadata.st_uid,
553
+ device=metadata.st_dev,
554
+ inode=metadata.st_ino,
555
+ size=metadata.st_size,
556
+ )
557
+ )
558
+ if kind != "directory":
559
+ continue
560
+ child = _open_directory(name, dir_fd=descriptor)
561
+ try:
562
+ opened = os.fstat(child)
563
+ if (opened.st_dev, opened.st_ino) != (metadata.st_dev, metadata.st_ino):
564
+ raise TempDirError("directory_changed", f"遍历期间目录 inode 发生变化:{relative}")
565
+ _scan_tree(
566
+ child,
567
+ expected_uid=expected_uid,
568
+ expected_device=expected_device,
569
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
570
+ fifo_requires_pytest_subtree=fifo_requires_pytest_subtree,
571
+ fixture_socket_paths=fixture_socket_paths,
572
+ pytest_basetemps=pytest_basetemps,
573
+ fixture_root=fixture_root,
574
+ relative_root=relative,
575
+ entries=entries,
576
+ )
577
+ finally:
578
+ os.close(child)
579
+ return entries
580
+
581
+
582
+ def _validate_record(
583
+ record: dict[str, Any],
584
+ *,
585
+ path: Path,
586
+ metadata: os.stat_result,
587
+ ) -> None:
588
+ expected_keys = {
589
+ "version",
590
+ "path",
591
+ "basename",
592
+ "uid",
593
+ "device",
594
+ "inode",
595
+ "created_at",
596
+ "prefix",
597
+ }
598
+ if set(record) != expected_keys:
599
+ raise TempDirError("registry_corrupt", "登记记录字段集合不符合合同")
600
+ if record.get("version") != RECORD_VERSION or record.get("path") != str(path):
601
+ raise TempDirError("registry_corrupt", "登记记录版本或路径不匹配")
602
+ prefix = record.get("prefix")
603
+ # The exact registered basename survives a namespace migration. Cleanup never
604
+ # guesses another tool's directory format or accepts an unregistered path.
605
+ if (
606
+ record.get("basename") != path.name
607
+ or not isinstance(prefix, str)
608
+ or PREFIX_RE.fullmatch(prefix) is None
609
+ or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}-" + re.escape(prefix)
610
+ + r"-[0-9a-f]{16}", path.name) is None
611
+ ):
612
+ raise TempDirError("registry_corrupt", "登记前缀或精确名称与目标不匹配")
613
+ created_at = record.get("created_at")
614
+ if not isinstance(created_at, str):
615
+ raise TempDirError("registry_corrupt", "登记创建时间格式异常")
616
+ try:
617
+ datetime.fromisoformat(created_at)
618
+ except ValueError as exc:
619
+ raise TempDirError("registry_corrupt", "登记创建时间不是 ISO-8601") from exc
620
+ expected_identity = (
621
+ record.get("uid"),
622
+ record.get("device"),
623
+ record.get("inode"),
624
+ )
625
+ current_identity = (metadata.st_uid, metadata.st_dev, metadata.st_ino)
626
+ if expected_identity != current_identity:
627
+ raise TempDirError("identity_mismatch", "当前目录 UID、device 或 inode 与创建登记不一致")
628
+ if metadata.st_uid != os.getuid():
629
+ raise TempDirError("owner_mismatch", "cleanup 目标不属于当前 UID")
630
+ if stat.S_IMODE(metadata.st_mode) != 0o700:
631
+ raise TempDirError("mode_mismatch", "cleanup 目标目录权限必须保持为 0700")
632
+
633
+
634
+ def validate_cleanup(
635
+ raw_path: str,
636
+ *,
637
+ allow_owned_fixture_fifo: bool = False,
638
+ allow_owned_fixture_sockets: tuple[str, ...] = (),
639
+ pytest_basetemps: tuple[str, ...] = (),
640
+ ) -> CleanupValidation:
641
+ # Check lexical scope before filesystem access; fixture-root authority comes
642
+ # only from the verified creation record below, never the supplied basename.
643
+ socket_paths = _fixture_socket_paths(allow_owned_fixture_sockets, fixture_root=True)
644
+ basetemps = _pytest_basetemps(pytest_basetemps)
645
+ path = _normalize_cleanup_path(raw_path)
646
+ try:
647
+ metadata = path.lstat()
648
+ except FileNotFoundError as exc:
649
+ raise TempDirError("target_missing", "cleanup 目标不存在") from exc
650
+ except OSError as exc:
651
+ raise TempDirError("target_unreadable", f"无法读取 cleanup 目标:{exc}") from exc
652
+ if stat.S_ISLNK(metadata.st_mode):
653
+ raise TempDirError("target_symlink", "cleanup 目标本身不得是 symlink")
654
+ if not stat.S_ISDIR(metadata.st_mode):
655
+ raise TempDirError("target_not_directory", "cleanup 目标不是目录")
656
+ tmp_resolved = _resolved_tmp_root()
657
+ try:
658
+ resolved = path.resolve(strict=True)
659
+ except OSError as exc:
660
+ raise TempDirError("path_unresolvable", f"无法规范化 cleanup 目标:{exc}") from exc
661
+ if resolved != tmp_resolved / path.name or resolved.parent != tmp_resolved:
662
+ raise TempDirError("path_not_canonical", "规范化后目标不再直接位于 /tmp")
663
+
664
+ record_path = _record_path(path)
665
+ record = _read_record(record_path)
666
+ _validate_record(record, path=path, metadata=metadata)
667
+ prefix = record["prefix"]
668
+ _fixture_socket_paths(
669
+ allow_owned_fixture_sockets,
670
+ fixture_root=_prefix_allows_fixture_fifo(prefix),
671
+ pytest_basetemps=basetemps,
672
+ )
673
+ fifo_requires_pytest_subtree = (
674
+ allow_owned_fixture_fifo and not _prefix_allows_fixture_fifo(prefix)
675
+ )
676
+ mount_points = _read_mount_points()
677
+ _reject_mounts(path, mount_points)
678
+
679
+ descriptor = _open_directory(str(path))
680
+ try:
681
+ opened = os.fstat(descriptor)
682
+ if (opened.st_uid, opened.st_dev, opened.st_ino) != (
683
+ metadata.st_uid,
684
+ metadata.st_dev,
685
+ metadata.st_ino,
686
+ ):
687
+ raise TempDirError("identity_mismatch", "打开后的目标 identity 与登记不一致")
688
+ entries = _scan_tree(
689
+ descriptor,
690
+ expected_uid=metadata.st_uid,
691
+ expected_device=metadata.st_dev,
692
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
693
+ fifo_requires_pytest_subtree=fifo_requires_pytest_subtree,
694
+ fixture_socket_paths=socket_paths,
695
+ pytest_basetemps=basetemps,
696
+ fixture_root=path,
697
+ )
698
+ _fixture_socket_entries(entries, socket_paths)
699
+ _basetemp_entries(entries, basetemps)
700
+ if fifo_requires_pytest_subtree and not any(
701
+ entry.kind == "FIFO" for entry in entries
702
+ ):
703
+ raise TempDirError(
704
+ "fifo_scope_rejected",
705
+ "普通临时根仅可显式清理 pytest 子目录中的 FIFO",
706
+ )
707
+ finally:
708
+ os.close(descriptor)
709
+
710
+ return CleanupValidation(
711
+ path=path,
712
+ record_path=record_path,
713
+ prefix=prefix,
714
+ uid=metadata.st_uid,
715
+ device=metadata.st_dev,
716
+ inode=metadata.st_ino,
717
+ entries=tuple(entries),
718
+ fixture_socket_paths=socket_paths,
719
+ pytest_basetemps=basetemps,
720
+ )
721
+
722
+
723
+ def _delete_contents(
724
+ descriptor: int,
725
+ *,
726
+ expected_uid: int,
727
+ expected_device: int,
728
+ allow_owned_fixture_fifo: bool,
729
+ fifo_requires_pytest_subtree: bool = False,
730
+ fixture_sockets: dict[str, CleanupEntry] | None = None,
731
+ basetemp_entries: dict[str, CleanupEntry] | None = None,
732
+ fixture_root: Path | None = None,
733
+ relative_root: str = "",
734
+ ) -> None:
735
+ directory = os.fstat(descriptor)
736
+ if not stat.S_ISDIR(directory.st_mode):
737
+ raise TempDirError("directory_changed", f"待删除条目不再是目录:{relative_root}")
738
+ if directory.st_uid != expected_uid:
739
+ raise TempDirError("owner_mismatch", f"目录树条目不属于登记 UID:{relative_root}")
740
+ if directory.st_dev != expected_device:
741
+ raise TempDirError("cross_device_entry", f"目录树条目跨越登记 filesystem:{relative_root}")
742
+ if not directory.st_mode & stat.S_IWUSR:
743
+ try:
744
+ os.fchmod(descriptor, stat.S_IMODE(directory.st_mode) | stat.S_IWUSR)
745
+ except OSError as exc:
746
+ raise TempDirError(
747
+ "cleanup_failed", f"无法写入待删除目录:{relative_root}: {exc}"
748
+ ) from exc
749
+ try:
750
+ with os.scandir(descriptor) as iterator:
751
+ names = sorted(entry.name for entry in iterator)
752
+ except OSError as exc:
753
+ raise TempDirError("cleanup_failed", f"无法读取待删除目录:{exc}") from exc
754
+
755
+ for name in names:
756
+ relative = f"{relative_root}/{name}" if relative_root else name
757
+ try:
758
+ metadata = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
759
+ except OSError as exc:
760
+ raise TempDirError("directory_changed", f"清理期间条目发生变化:{relative}: {exc}") from exc
761
+ if metadata.st_uid != expected_uid:
762
+ raise TempDirError("owner_mismatch", f"目录树条目不属于登记 UID:{relative}")
763
+ if metadata.st_dev != expected_device:
764
+ raise TempDirError("cross_device_entry", f"目录树条目跨越登记 filesystem:{relative}")
765
+ kind = _allowed_entry_kind(
766
+ metadata.st_mode,
767
+ relative,
768
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
769
+ fifo_requires_pytest_subtree=fifo_requires_pytest_subtree,
770
+ fixture_socket_paths=frozenset(fixture_sockets or ()),
771
+ pytest_basetemps=frozenset(basetemp_entries or ()),
772
+ )
773
+ if basetemp_entries and relative in basetemp_entries:
774
+ expected_base = basetemp_entries[relative]
775
+ if kind != "directory" or (metadata.st_dev, metadata.st_ino) != (
776
+ expected_base.device, expected_base.inode
777
+ ):
778
+ raise TempDirError("identity_mismatch", f"pytest basetemp identity 发生变化:{relative}")
779
+ if fixture_sockets and relative in fixture_sockets:
780
+ expected = fixture_sockets[relative]
781
+ if kind != "socket" or (metadata.st_dev, metadata.st_ino) != (
782
+ expected.device, expected.inode
783
+ ):
784
+ raise TempDirError("identity_mismatch", f"fixture socket identity 发生变化:{relative}")
785
+ if fixture_root is None:
786
+ raise TempDirError("socket_activity_unknown", "缺少 fixture 根目录")
787
+ _ensure_fixture_socket_inactive(fixture_root / relative)
788
+ try:
789
+ if kind == "directory":
790
+ child = _open_directory(name, dir_fd=descriptor)
791
+ try:
792
+ opened = os.fstat(child)
793
+ if (opened.st_dev, opened.st_ino) != (
794
+ metadata.st_dev,
795
+ metadata.st_ino,
796
+ ):
797
+ raise TempDirError(
798
+ "directory_changed",
799
+ f"清理期间目录 inode 发生变化:{relative}",
800
+ )
801
+ _delete_contents(
802
+ child,
803
+ expected_uid=expected_uid,
804
+ expected_device=expected_device,
805
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
806
+ fifo_requires_pytest_subtree=fifo_requires_pytest_subtree,
807
+ fixture_sockets=fixture_sockets,
808
+ basetemp_entries=basetemp_entries,
809
+ fixture_root=fixture_root,
810
+ relative_root=relative,
811
+ )
812
+ finally:
813
+ os.close(child)
814
+ os.rmdir(name, dir_fd=descriptor)
815
+ else:
816
+ os.unlink(name, dir_fd=descriptor)
817
+ except TempDirError:
818
+ raise
819
+ except OSError as exc:
820
+ raise TempDirError("cleanup_failed", f"删除失败:{relative}: {exc}") from exc
821
+
822
+
823
+ def cleanup_directory(
824
+ raw_path: str,
825
+ *,
826
+ allow_owned_fixture_fifo: bool = False,
827
+ allow_owned_fixture_sockets: tuple[str, ...] = (),
828
+ pytest_basetemps: tuple[str, ...] = (),
829
+ ) -> dict[str, Any]:
830
+ validation = validate_cleanup(
831
+ raw_path,
832
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
833
+ allow_owned_fixture_sockets=allow_owned_fixture_sockets,
834
+ pytest_basetemps=pytest_basetemps,
835
+ )
836
+ fixture_sockets = _fixture_socket_entries(validation.entries, validation.fixture_socket_paths)
837
+ basetemp_entries = _basetemp_entries(validation.entries, validation.pytest_basetemps)
838
+ fifo_requires_pytest_subtree = (
839
+ allow_owned_fixture_fifo
840
+ and not _prefix_allows_fixture_fifo(validation.prefix)
841
+ )
842
+ _reject_mounts(validation.path, _read_mount_points())
843
+ descriptor = _open_directory(str(validation.path))
844
+ try:
845
+ metadata = os.fstat(descriptor)
846
+ if (metadata.st_uid, metadata.st_dev, metadata.st_ino) != (
847
+ validation.uid,
848
+ validation.device,
849
+ validation.inode,
850
+ ):
851
+ raise TempDirError("identity_mismatch", "删除前目标 identity 与登记不一致")
852
+ current_entries = _scan_tree(
853
+ descriptor,
854
+ expected_uid=validation.uid,
855
+ expected_device=validation.device,
856
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
857
+ fifo_requires_pytest_subtree=fifo_requires_pytest_subtree,
858
+ fixture_socket_paths=validation.fixture_socket_paths,
859
+ pytest_basetemps=validation.pytest_basetemps,
860
+ fixture_root=validation.path,
861
+ )
862
+ if _fixture_socket_entries(current_entries, validation.fixture_socket_paths) != fixture_sockets:
863
+ raise TempDirError("identity_mismatch", "删除前 fixture socket identity 发生变化")
864
+ if _basetemp_entries(current_entries, validation.pytest_basetemps) != basetemp_entries:
865
+ raise TempDirError("identity_mismatch", "删除前 pytest basetemp identity 发生变化")
866
+ _delete_contents(
867
+ descriptor,
868
+ expected_uid=validation.uid,
869
+ expected_device=validation.device,
870
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
871
+ fifo_requires_pytest_subtree=fifo_requires_pytest_subtree,
872
+ fixture_sockets=fixture_sockets,
873
+ basetemp_entries=basetemp_entries,
874
+ fixture_root=validation.path,
875
+ )
876
+ finally:
877
+ os.close(descriptor)
878
+
879
+ try:
880
+ final_metadata = validation.path.lstat()
881
+ if (
882
+ final_metadata.st_uid,
883
+ final_metadata.st_dev,
884
+ final_metadata.st_ino,
885
+ ) != (validation.uid, validation.device, validation.inode):
886
+ raise TempDirError("identity_mismatch", "删除根目录前目标 identity 发生变化")
887
+ validation.path.rmdir()
888
+ except TempDirError:
889
+ raise
890
+ except OSError as exc:
891
+ raise TempDirError("cleanup_failed", f"无法删除根目录:{exc}") from exc
892
+
893
+ try:
894
+ validation.record_path.unlink()
895
+ except OSError as exc:
896
+ raise TempDirError(
897
+ "record_cleanup_failed",
898
+ f"目录已删除,但登记记录保留且无法移除:{exc}",
899
+ ) from exc
900
+ return {
901
+ "ok": True,
902
+ "command": "cleanup",
903
+ "path": str(validation.path),
904
+ "record_removed": True,
905
+ }
906
+
907
+
908
+ def dry_run_cleanup(
909
+ raw_path: str,
910
+ *,
911
+ allow_owned_fixture_fifo: bool = False,
912
+ allow_owned_fixture_sockets: tuple[str, ...] = (),
913
+ pytest_basetemps: tuple[str, ...] = (),
914
+ ) -> dict[str, Any]:
915
+ validation = validate_cleanup(
916
+ raw_path,
917
+ allow_owned_fixture_fifo=allow_owned_fixture_fifo,
918
+ allow_owned_fixture_sockets=allow_owned_fixture_sockets,
919
+ pytest_basetemps=pytest_basetemps,
920
+ )
921
+ entries = [
922
+ {
923
+ "device": entry.device,
924
+ "inode": entry.inode,
925
+ "kind": entry.kind,
926
+ "mode": f"{entry.mode:04o}",
927
+ "path": entry.relative_path,
928
+ "size": entry.size,
929
+ "uid": entry.uid,
930
+ }
931
+ for entry in validation.entries
932
+ ]
933
+ return {
934
+ "ok": True,
935
+ "command": "dry-run-cleanup",
936
+ "path": str(validation.path),
937
+ "record": str(validation.record_path),
938
+ "prefix": validation.prefix,
939
+ "entry_count": len(entries),
940
+ "regular_file_bytes": sum(
941
+ entry.size for entry in validation.entries if entry.kind == "regular file"
942
+ ),
943
+ "entries": entries,
944
+ "pytest_basetemps": sorted(validation.pytest_basetemps),
945
+ "delete_root": True,
946
+ "delete_record": True,
947
+ }
948
+
949
+
950
+ def _emit(payload: dict[str, Any]) -> None:
951
+ print(json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")))
952
+
953
+
954
+ def _parser() -> argparse.ArgumentParser:
955
+ parser = argparse.ArgumentParser(prog="tool-temp-dir")
956
+ parser.add_argument("--version", action="version", version=f"%(prog)s {TOOL_VERSION}")
957
+ subparsers = parser.add_subparsers(dest="command", required=True)
958
+ create_parser = subparsers.add_parser("create")
959
+ create_parser.add_argument("task_prefix")
960
+ fifo_help = "allow owned FIFOs in fixture task roots or pytest fixture subtrees"
961
+ socket_help = (
962
+ "allow one exact owned, inactive socket in a registered fixture task root "
963
+ "or below a numbered pytest fixture (repeatable)"
964
+ )
965
+ cleanup_parser = subparsers.add_parser("cleanup")
966
+ cleanup_parser.add_argument("absolute_path")
967
+ cleanup_parser.add_argument(
968
+ "--allow-owned-fixture-fifo", action="store_true", help=fifo_help
969
+ )
970
+ cleanup_parser.add_argument(
971
+ "--allow-owned-fixture-socket", action="append", default=[], metavar="RELATIVE_PATH",
972
+ help=socket_help,
973
+ )
974
+ dry_run_parser = subparsers.add_parser("dry-run-cleanup")
975
+ dry_run_parser.add_argument("absolute_path")
976
+ dry_run_parser.add_argument(
977
+ "--allow-owned-fixture-fifo", action="store_true", help=fifo_help
978
+ )
979
+ dry_run_parser.add_argument(
980
+ "--allow-owned-fixture-socket", action="append", default=[], metavar="RELATIVE_PATH",
981
+ help=socket_help,
982
+ )
983
+ validate_parser = subparsers.add_parser("validate-cleanup")
984
+ validate_parser.add_argument("absolute_path")
985
+ validate_parser.add_argument(
986
+ "--allow-owned-fixture-fifo", action="store_true", help=fifo_help
987
+ )
988
+ validate_parser.add_argument(
989
+ "--allow-owned-fixture-socket", action="append", default=[], metavar="RELATIVE_PATH",
990
+ help=socket_help,
991
+ )
992
+ for cleanup_command in (cleanup_parser, dry_run_parser, validate_parser):
993
+ cleanup_command.add_argument(
994
+ "--pytest-basetemp", action="append", default=[], metavar="RELATIVE_PATH",
995
+ help="declare one exact owned pytest basetemp; only numbered test descendants gain fixture scope (repeatable)",
996
+ )
997
+ return parser
998
+
999
+
1000
+ def main(argv: list[str] | None = None) -> int:
1001
+ arguments = _parser().parse_args(argv)
1002
+ try:
1003
+ if arguments.command == "create":
1004
+ result = create_directory(arguments.task_prefix)
1005
+ elif arguments.command == "cleanup":
1006
+ result = cleanup_directory(
1007
+ arguments.absolute_path,
1008
+ allow_owned_fixture_fifo=arguments.allow_owned_fixture_fifo,
1009
+ allow_owned_fixture_sockets=tuple(arguments.allow_owned_fixture_socket),
1010
+ pytest_basetemps=tuple(arguments.pytest_basetemp),
1011
+ )
1012
+ elif arguments.command == "dry-run-cleanup":
1013
+ result = dry_run_cleanup(
1014
+ arguments.absolute_path,
1015
+ allow_owned_fixture_fifo=arguments.allow_owned_fixture_fifo,
1016
+ allow_owned_fixture_sockets=tuple(arguments.allow_owned_fixture_socket),
1017
+ pytest_basetemps=tuple(arguments.pytest_basetemp),
1018
+ )
1019
+ else:
1020
+ validation = validate_cleanup(
1021
+ arguments.absolute_path,
1022
+ allow_owned_fixture_fifo=arguments.allow_owned_fixture_fifo,
1023
+ allow_owned_fixture_sockets=tuple(arguments.allow_owned_fixture_socket),
1024
+ pytest_basetemps=tuple(arguments.pytest_basetemp),
1025
+ )
1026
+ result = {
1027
+ "ok": True,
1028
+ "command": "validate-cleanup",
1029
+ "path": str(validation.path),
1030
+ "record": str(validation.record_path),
1031
+ }
1032
+ except TempDirError as exc:
1033
+ _emit(
1034
+ {
1035
+ "ok": False,
1036
+ "command": arguments.command,
1037
+ "code": exc.code,
1038
+ "reason": exc.reason,
1039
+ }
1040
+ )
1041
+ return 2
1042
+ except OSError as exc:
1043
+ _emit(
1044
+ {
1045
+ "ok": False,
1046
+ "command": arguments.command,
1047
+ "code": "os_error",
1048
+ "reason": str(exc),
1049
+ }
1050
+ )
1051
+ return 1
1052
+ _emit(result)
1053
+ return 0
1054
+
1055
+
1056
+ if __name__ == "__main__":
1057
+ raise SystemExit(main())