cli_result.py 998 B

123456789101112131415161718192021222324252627282930313233
  1. """CLI job result helpers: logging, JSON stdout, exit code contract."""
  2. from __future__ import annotations
  3. import json
  4. import logging
  5. import sys
  6. from collections.abc import Callable
  7. from typing import Any
  8. def configure_cli_logging() -> None:
  9. logging.basicConfig(
  10. level=logging.INFO,
  11. format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
  12. )
  13. def emit_and_exit(result: Any) -> None:
  14. """Print one JSON line to stdout; exit 1 when result.success is False."""
  15. print(json.dumps(result, ensure_ascii=False, default=str))
  16. if isinstance(result, dict) and result.get("success") is False:
  17. sys.exit(1)
  18. sys.exit(0)
  19. def run_cli(action: Callable[[], Any], *, label: str) -> None:
  20. """Configure logging, run action, emit JSON result, and exit."""
  21. configure_cli_logging()
  22. try:
  23. emit_and_exit(action())
  24. except Exception as exc:
  25. logging.exception("%s failed", label)
  26. emit_and_exit({"success": False, "error": str(exc)})