1 #######################################################################################
2 # Copyright ETSI Contributors and Others.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #######################################################################################
21 from prettytable
import PrettyTable
23 from jsonpath_ng
import parse
26 logger
= logging
.getLogger("osmclient")
29 def evaluate_output_format(ctx
, param
, value
):
31 if value
in ["table", "json", "yaml", "csv"]:
33 elif value
.startswith("jsonpath="):
36 raise click
.BadParameter(
37 f
"{value} is not one of 'table', 'json', 'yaml', 'csv', 'jsonpath'"
41 output_option
= click
.option(
46 callback
=evaluate_output_format
,
47 help="output format (default: table)",
51 literal_option
= click
.option(
52 "--literal", is_flag
=True, help="print literally, no pretty table"
56 def print_output(format
, headers
, rows
):
59 table
= PrettyTable(headers
)
65 table
= PrettyTable(headers
)
68 print(table
.get_csv_string())
69 elif format
== "json" or format
== "yaml" or format
.startswith("jsonpath="):
73 for i
in range(len(row
)):
74 item
[headers
[i
]] = row
[i
]
77 print(json
.dumps(data
, indent
=4))
78 elif format
== "yaml":
81 data
, indent
=4, default_flow_style
=False, sort_keys
=False
84 elif format
.startswith("jsonpath="):
86 json_path_expression
= format
.partition("=")[-1]
87 logger
.debug(f
"Jsonpath expression: {json_path_expression}")
88 json_path
= parse(json_path_expression
)
89 # Apply JSONPath expression on the JSON object
90 results
= [match
.value
for match
in json_path
.find(data
)]