from __future__ import annotations import json import shutil import subprocess from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, Iterable, List, Optional import yaml UTC = timezone.utc def now_utc() -> datetime: return datetime.now(tz=UTC) def isoformat(dt: datetime) -> str: return dt.astimezone(UTC).replace(microsecond=0).isoformat() def ensure_dir(path: Path) -> None: path.mkdir(parents=True, exist_ok=True) def read_json(path: Path, default: Any = None) -> Any: if not path.exists(): return default return json.loads(path.read_text(encoding="utf-8")) def write_json(path: Path, data: Any) -> None: ensure_dir(path.parent) content = json.dumps(data, indent=2, ensure_ascii=True, sort_keys=False) + "\n" if path.exists() and path.read_text(encoding="utf-8") == content: return path.write_text(content, encoding="utf-8") def read_yaml(path: Path, default: Any = None) -> Any: if not path.exists(): return default with path.open("r", encoding="utf-8") as handle: return yaml.safe_load(handle) def write_yaml(path: Path, data: Any) -> None: ensure_dir(path.parent) with path.open("w", encoding="utf-8") as handle: yaml.safe_dump(data, handle, allow_unicode=False, sort_keys=False) def write_text(path: Path, content: str) -> None: ensure_dir(path.parent) rendered = content.rstrip() + "\n" if path.exists() and path.read_text(encoding="utf-8") == rendered: return path.write_text(rendered, encoding="utf-8") def load_json_dir(path: Path) -> List[Dict[str, Any]]: if not path.exists(): return [] values: List[Dict[str, Any]] = [] for file_path in sorted(path.glob("*.json")): content = read_json(file_path, default=None) if isinstance(content, dict): values.append(content) return values def run(cmd: List[str], cwd: Optional[Path] = None, check: bool = False) -> subprocess.CompletedProcess: return subprocess.run( cmd, cwd=str(cwd) if cwd else None, text=True, capture_output=True, check=check, ) def command_available(name: str) -> bool: return shutil.which(name) is not None def slugify(value: str) -> str: safe = [] for ch in value.lower().strip(): if ch.isalnum(): safe.append(ch) else: safe.append("-") result = "".join(safe) while "--" in result: result = result.replace("--", "-") return result.strip("-") or "item" def unique(values: Iterable[str]) -> List[str]: seen = set() result = [] for value in values: if not value or value in seen: continue seen.add(value) result.append(value) return result