Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cortexapps_cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,13 @@ def humanize_value(value):
return json.dumps(value, indent=2)
return str(value)


def validate_sort_path(table_data, jsonpath):
if not table_data:
return
if not any(get_value_at_path(item, jsonpath) is not None for item in table_data):
raise typer.BadParameter(f"Sort path '{jsonpath}' did not match any values")

def print_output(data, columns=None, filters=None, sort=None, output_format='json', no_headers=False):
"""
Print output in the specified format.
Expand Down Expand Up @@ -161,6 +168,7 @@ def print_output(data, columns=None, filters=None, sort=None, output_format='jso
if not re.match(r"^[a-zA-Z0-9_.]+:(asc|ASC|desc|DESC)$", sort_item):
raise typer.BadParameter("Sort must be in the format jsonpath:asc or jsonpath:desc")
(jsonpath, order) = sort_item.split(':')
validate_sort_path(table_data, jsonpath)
if order.lower() == 'asc':
table_data = sorted(table_data, key=lambda x: get_value_at_path(x, jsonpath))
elif order.lower() == 'desc':
Expand Down
6 changes: 6 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,12 @@ def test_print_output_table_invalid_sort_raises():
print_output(data, columns=["a"], sort=["bad_sort"], output_format="table")


def test_print_output_table_unknown_sort_path_raises():
data = {"items": [{"tag": "b"}, {"tag": "a"}]}
with pytest.raises(typer.BadParameter, match="Sort path 'Tag' did not match any values"):
print_output(data, columns=["tag"], sort=["Tag:asc"], output_format="table")


def test_print_output_csv(capsys):
data = {"items": [{"name": "foo"}, {"name": "bar"}]}
print_output(data, columns=["Name=name"], output_format="csv")
Expand Down