Refactor -o option to simplify code
[osm/osmclient.git] / osmclient / common / print_output.py
1 #######################################################################################
2 # Copyright ETSI Contributors and Others.
3 #
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
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
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
13 # implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #######################################################################################
17 import click
18 import logging
19 import json
20 import yaml
21 from prettytable import PrettyTable
22
23 from jsonpath_ng import parse
24
25
26 logger = logging.getLogger("osmclient")
27
28
29 def evaluate_output_format(ctx, param, value):
30 logger.debug("")
31 if value in ["table", "json", "yaml", "csv"]:
32 return value
33 elif value.startswith("jsonpath="):
34 return value
35 else:
36 raise click.BadParameter(
37 f"{value} is not one of 'table', 'json', 'yaml', 'csv', 'jsonpath'"
38 )
39
40
41 output_option = click.option(
42 "-o",
43 "--output",
44 default="table",
45 is_eager=True,
46 callback=evaluate_output_format,
47 help="output format (default: table)",
48 )
49
50
51 literal_option = click.option(
52 "--literal", is_flag=True, help="print literally, no pretty table"
53 )
54
55
56 def print_output(format, headers, rows):
57 logger.debug("")
58 if format == "table":
59 table = PrettyTable(headers)
60 table.align = "l"
61 for row in rows:
62 table.add_row(row)
63 print(table)
64 elif format == "csv":
65 table = PrettyTable(headers)
66 for row in rows:
67 table.add_row(row)
68 print(table.get_csv_string())
69 elif format == "json" or format == "yaml" or format.startswith("jsonpath="):
70 data = []
71 for row in rows:
72 item = {}
73 for i in range(len(row)):
74 item[headers[i]] = row[i]
75 data.append(item)
76 if format == "json":
77 print(json.dumps(data, indent=4))
78 elif format == "yaml":
79 print(
80 yaml.safe_dump(
81 data, indent=4, default_flow_style=False, sort_keys=False
82 )
83 )
84 elif format.startswith("jsonpath="):
85 # JSONPath expression
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)]
91 for i in results:
92 print(i)