from __future__ import annotations import hashlib import json from pathlib import Path from typing import Any from ruamel.yaml import YAML from ruamel.yaml.error import YAMLError class ResourceError(ValueError): """Input cannot be safely parsed as an expected resource.""" def _safe_yaml() -> YAML: yaml = YAML(typ="safe", pure=True) yaml.allow_duplicate_keys = False return yaml def _output_yaml() -> YAML: yaml = YAML() yaml.default_flow_style = False yaml.allow_unicode = True yaml.indent(mapping=2, sequence=4, offset=2) return yaml def load_yaml(path: Path) -> Any: try: with path.open("r", encoding="utf-8") as handle: return _safe_yaml().load(handle) except (OSError, YAMLError) as exc: raise ResourceError(f"Cannot parse YAML: {exc}") from exc def yaml_text(data: Any) -> str: from io import StringIO stream = StringIO() _output_yaml().dump(data, stream) return stream.getvalue() def primitive(value: Any) -> Any: if isinstance(value, dict): return {str(key): primitive(item) for key, item in value.items()} if isinstance(value, (list, tuple)): return [primitive(item) for item in value] if hasattr(value, "isoformat") and not isinstance(value, str): return value.isoformat() return value def canonical_json(value: Any) -> str: return json.dumps(primitive(value), ensure_ascii=False, sort_keys=True, separators=(",", ":")) def sha256(value: Any) -> str: return "sha256:" + hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest() def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return "sha256:" + digest.hexdigest() def write_text_atomic(path: Path, content: str) -> None: """Write ``content`` to ``path`` via a temp file in the same directory, then replace. Uses ``\\n`` line endings unconditionally so hashes and diffs are platform independent. """ path.parent.mkdir(parents=True, exist_ok=True) normalized = content.replace("\r\n", "\n") tmp = path.parent / f".{path.name}.repoctl-tmp" with tmp.open("w", encoding="utf-8", newline="\n") as handle: handle.write(normalized) tmp.replace(path) def dump_json(value: Any) -> str: return json.dumps(primitive(value), ensure_ascii=False, indent=2, sort_keys=False) + "\n"