New global option to adapt output format
[osm/osmclient.git] / osmclient / common / print_output.py
diff --git a/osmclient/common/print_output.py b/osmclient/common/print_output.py
new file mode 100644 (file)
index 0000000..e5bc7f7
--- /dev/null
@@ -0,0 +1,80 @@
+#######################################################################################
+# Copyright ETSI Contributors and Others.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#######################################################################################
+import json
+import yaml
+import click
+from prettytable import PrettyTable
+
+from jsonpath_ng import parse
+
+
+def print_output(format, headers, rows):
+    if format == "table":
+        table = PrettyTable(headers)
+        for row in rows:
+            table.add_row(row)
+        print(table)
+    elif format == "json":
+        data = []
+        for row in rows:
+            data.append(dict(zip(headers, row)))
+        json_data = json.dumps(data)
+        print(json_data)
+    elif format == "csv":
+        table = PrettyTable(headers)
+        for row in rows:
+            table.add_row(row)
+        print(table.get_csv_string())
+    elif format == "yaml":
+        data = []
+        for row in rows:
+            data.append(dict(zip(headers, row)))
+        yaml_string = yaml.safe_dump(data, sort_keys=False)
+        print(yaml_string)
+    elif format.startswith("jsonpath="):
+        # JSONPath expression
+        json_path_expression = format.partition("=")[-1]
+        json_path = parse(json_path_expression)
+        data = []
+        for row in rows:
+            data.append(dict(zip(headers, row)))
+        # json_data = json.dumps(data)
+        # Apply JSONPath expression on the JSON object
+        results = [match.value for match in json_path.find(data)]
+        print(results)
+    else:
+        print("Valid values for -o are table, yaml, csv, json, jsonpath")
+
+
+def validate_command_output(ctx, param, value):
+    allowed_commands = [
+        "ns-list",
+        "ns-show",
+        "vim-list",
+        "vim-show",
+        "vnf-list",
+        "vnf-show",
+    ]  # List of allowed commands
+
+    if ctx.command.name in allowed_commands:
+        return value
+    # if param:
+    #     print (value)
+    else:
+        raise click.BadParameter(
+            f'Option "{param.name}" is not allowed for this command.'
+        )