e5bc7f7b24c6c813b8a80c9eb0216b79f6d1ba7c
[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 json
18 import yaml
19 import click
20 from prettytable import PrettyTable
21
22 from jsonpath_ng import parse
23
24
25 def print_output(format, headers, rows):
26 if format == "table":
27 table = PrettyTable(headers)
28 for row in rows:
29 table.add_row(row)
30 print(table)
31 elif format == "json":
32 data = []
33 for row in rows:
34 data.append(dict(zip(headers, row)))
35 json_data = json.dumps(data)
36 print(json_data)
37 elif format == "csv":
38 table = PrettyTable(headers)
39 for row in rows:
40 table.add_row(row)
41 print(table.get_csv_string())
42 elif format == "yaml":
43 data = []
44 for row in rows:
45 data.append(dict(zip(headers, row)))
46 yaml_string = yaml.safe_dump(data, sort_keys=False)
47 print(yaml_string)
48 elif format.startswith("jsonpath="):
49 # JSONPath expression
50 json_path_expression = format.partition("=")[-1]
51 json_path = parse(json_path_expression)
52 data = []
53 for row in rows:
54 data.append(dict(zip(headers, row)))
55 # json_data = json.dumps(data)
56 # Apply JSONPath expression on the JSON object
57 results = [match.value for match in json_path.find(data)]
58 print(results)
59 else:
60 print("Valid values for -o are table, yaml, csv, json, jsonpath")
61
62
63 def validate_command_output(ctx, param, value):
64 allowed_commands = [
65 "ns-list",
66 "ns-show",
67 "vim-list",
68 "vim-show",
69 "vnf-list",
70 "vnf-show",
71 ] # List of allowed commands
72
73 if ctx.command.name in allowed_commands:
74 return value
75 # if param:
76 # print (value)
77 else:
78 raise click.BadParameter(
79 f'Option "{param.name}" is not allowed for this command.'
80 )