io.py 909 B

12345678910111213141516171819202122232425262728293031323334353637
  1. """
  2. JSON file I/O utilities.
  3. Provides read_json and write_json as the single source of truth
  4. for JSON file operations across all Trellis scripts.
  5. """
  6. from __future__ import annotations
  7. import json
  8. from pathlib import Path
  9. def read_json(path: Path) -> dict | None:
  10. """Read and parse a JSON file.
  11. Returns None if the file doesn't exist, is invalid JSON, or can't be read.
  12. """
  13. try:
  14. return json.loads(path.read_text(encoding="utf-8"))
  15. except (FileNotFoundError, json.JSONDecodeError, OSError):
  16. return None
  17. def write_json(path: Path, data: dict) -> bool:
  18. """Write dict to JSON file with pretty formatting.
  19. Returns True on success, False on error.
  20. """
  21. try:
  22. path.write_text(
  23. json.dumps(data, indent=2, ensure_ascii=False),
  24. encoding="utf-8",
  25. )
  26. return True
  27. except (OSError, IOError):
  28. return False