From 60e0471b88d90a3dfcafd56168f0373e822757a4 Mon Sep 17 00:00:00 2001 From: Nick Shobe Date: Wed, 20 Nov 2013 02:46:46 -0600 Subject: [PATCH] Allow --json output override printing dict/list Change-Id: Ib02f244cb969ac8dfc92ac94e6e915063d13764d --- troveclient/shell.py | 14 ++++++++++++++ troveclient/utils.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/troveclient/shell.py b/troveclient/shell.py index 2a6d803e..72aacde5 100644 --- a/troveclient/shell.py +++ b/troveclient/shell.py @@ -214,6 +214,14 @@ class OpenStackTroveShell(object): default=0, help='Number of retries.') + parser.add_argument('--json', '--os-json-output', + dest='json', + action='store_true', + default=utils.env('OS_JSON_OUTPUT', + default=False), + help='Output json instead of prettyprint. ' + 'Defaults to OS_JSON_OUTPUT') + # FIXME(dtroyer): The args below are here for diablo compatibility, # remove them in folsum cycle @@ -477,6 +485,12 @@ class OpenStackTroveShell(object): #raise exc.InvalidAPIVersion(msg) raise exc.UnsupportedVersion(msg) + # Override printing to json output + if args.json: + utils.json_output = True + else: + utils.json_output = False + args.func(self.cs, args) def _run_extension_hooks(self, hook_type, *args, **kwargs): diff --git a/troveclient/utils.py b/troveclient/utils.py index 2f5fb820..78fcc2ae 100644 --- a/troveclient/utils.py +++ b/troveclient/utils.py @@ -22,6 +22,7 @@ import os import re import sys import uuid +import simplejson as json import six import prettytable @@ -114,7 +115,28 @@ def translate_keys(collection, convert): setattr(item, to_key, item._info[from_key]) +def _output_override(objs, print_as): + """ + If an output override global flag is set, print with override + raise BaseException if no printing was overridden. + """ + if 'json_output' in globals() and json_output: + if print_as == 'list': + new_objs = [] + for o in objs: + new_objs.append(o._info) + elif print_as == 'dict': + new_objs = objs + # pretty print the json + print(json.dumps(new_objs, indent=' ')) + elif 'xml_output' in globals(): + print('not implemented') + else: + raise BaseException('No valid output override') + + def _print(pt, order): + if sys.version_info >= (3, 0): print(pt.get_string(sortby=order)) else: @@ -122,6 +144,11 @@ def _print(pt, order): def print_list(objs, fields, formatters={}, order_by=None): + try: + _output_override(objs, 'list') + return + except BaseException: + pass mixed_case_fields = [] pt = prettytable.PrettyTable([f for f in fields], caching=False) pt.aligns = ['l' for f in fields] @@ -146,6 +173,11 @@ def print_list(objs, fields, formatters={}, order_by=None): def print_dict(d, property="Property"): + try: + _output_override(d, 'dict') + return + except BaseException: + pass pt = prettytable.PrettyTable([property, 'Value'], caching=False) pt.aligns = ['l', 'l'] [pt.add_row(list(r)) for r in six.iteritems(d)]