Skip to content

Commit de74ef7

Browse files
author
Tim Huff
committed
adding pretty print for return values
1 parent 987cc17 commit de74ef7

1 file changed

Lines changed: 21 additions & 5 deletions

File tree

src/groundlight/cli.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1+
import json
12
import logging
23
import sys
4+
from datetime import datetime
35
from enum import Enum
46
from functools import wraps
57
from typing import Any, Union
68

9+
from groundlight_openapi_client.model_utils import OpenApiModel
10+
from pydantic import BaseModel
11+
712
import typer
813
from typing_extensions import get_origin
914

@@ -52,15 +57,26 @@ def is_cli_representable(annotation) -> bool:
5257
return False
5358

5459

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+
5567
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.
5769
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().
5972
"""
60-
try:
73+
if isinstance(result, BaseModel):
6174
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)
6480

6581

6682
def class_func_to_cli(method, is_experimental: bool = False):

0 commit comments

Comments
 (0)