|
| 1 | +import json |
1 | 2 | import logging |
2 | 3 | import sys |
| 4 | +from datetime import datetime |
3 | 5 | from enum import Enum |
4 | 6 | from functools import wraps |
5 | 7 | from typing import Any, Union |
6 | 8 |
|
| 9 | +from groundlight_openapi_client.model_utils import OpenApiModel |
| 10 | +from pydantic import BaseModel |
| 11 | + |
7 | 12 | import typer |
8 | 13 | from typing_extensions import get_origin |
9 | 14 |
|
@@ -52,15 +57,26 @@ def is_cli_representable(annotation) -> bool: |
52 | 57 | return False |
53 | 58 |
|
54 | 59 |
|
| 60 | +def _json_default(obj: Any) -> Any: |
| 61 | + """Fallback serializer for json.dumps — handles datetime values.""" |
| 62 | + if isinstance(obj, datetime): |
| 63 | + return obj.isoformat() |
| 64 | + raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable") |
| 65 | + |
| 66 | + |
55 | 67 | def _format_result(result: Any) -> str: |
56 | | - """Format a method return value for CLI output. |
| 68 | + """Format a CLI result value as a human-readable, jq-compatible string. |
57 | 69 |
|
58 | | - Pydantic models are serialized to indented JSON. Everything else falls back to str(). |
| 70 | + Pydantic models and OpenAPI client objects are serialized to indented JSON. |
| 71 | + Plain dicts and lists are also JSON. Everything else falls back to str(). |
59 | 72 | """ |
60 | | - try: |
| 73 | + if isinstance(result, BaseModel): |
61 | 74 | return result.model_dump_json(indent=2) |
62 | | - except AttributeError: |
63 | | - return str(result) |
| 75 | + if isinstance(result, OpenApiModel): |
| 76 | + return json.dumps(result.to_dict(), indent=2, default=_json_default) |
| 77 | + if isinstance(result, (dict, list)): |
| 78 | + return json.dumps(result, indent=2, default=_json_default) |
| 79 | + return str(result) |
64 | 80 |
|
65 | 81 |
|
66 | 82 | def class_func_to_cli(method, is_experimental: bool = False): |
|
0 commit comments