"""Shared result, subprocess, and artifact helpers.""" from __future__ import annotations import hashlib import json import os import tempfile from pathlib import Path from typing import Any def atomic_json(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent)) try: with os.fdopen(fd, "w", encoding="utf-8") as stream: json.dump(value, stream, ensure_ascii=False, indent=2, sort_keys=True) stream.write("\n") stream.flush() os.fsync(stream.fileno()) os.replace(temporary, path) except BaseException: try: os.unlink(temporary) except FileNotFoundError: pass raise def sha256_file(path: Path) -> str: value = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): value.update(chunk) return value.hexdigest() def artifact_inventory(root: Path) -> list[dict[str, Any]]: artifacts: list[dict[str, Any]] = [] for path in sorted(item for item in root.rglob("*") if item.is_file() and not item.is_symlink()): artifacts.append( { "path": str(path.relative_to(root)), "size": path.stat().st_size, "sha256": sha256_file(path), } ) return artifacts def clipped(value: str, limit: int) -> str: if len(value) <= limit: return value return value[:limit] + f"...[clipped {len(value) - limit} chars]"