diff options
| author | zhiyuan_cai <luckyvega.g@gmail.com> | 2015-01-21 17:19:46 +0800 |
|---|---|---|
| committer | zhiyuan_cai <luckyvega.g@gmail.com> | 2015-02-06 10:57:10 +0800 |
| commit | 42cff388349186b70559650237d2667da1cb903f (patch) | |
| tree | 055ea0522cbb7293dc5d941477aaaa6d9fae86fe /openstackclient/common | |
| parent | 0cc3955f0aedab76313aa09edd3f31bb9d08b55d (diff) | |
| download | python-openstackclient-42cff388349186b70559650237d2667da1cb903f.tar.gz | |
Add sort support to image list
Add sort support to image list by sorting items in the client side.
The parameter syntax follows this spec[1].
[1] https://review.openstack.org/#/c/145544/
Change-Id: I42b487d18f00f937db1938daa46487cea2a896ab
Closes-Bug: #1410251
Diffstat (limited to 'openstackclient/common')
| -rw-r--r-- | openstackclient/common/utils.py | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/openstackclient/common/utils.py b/openstackclient/common/utils.py index 9ad3823c..01a40e74 100644 --- a/openstackclient/common/utils.py +++ b/openstackclient/common/utils.py @@ -122,6 +122,17 @@ def format_list(data): return ', '.join(sorted(data)) +def get_field(item, field): + try: + if isinstance(item, dict): + return item[field] + else: + return getattr(item, field) + except Exception: + msg = "Resource doesn't have field %s" % field + raise exceptions.CommandError(msg) + + def get_item_properties(item, fields, mixed_case_fields=[], formatters={}): """Return a tuple containing the item properties. @@ -170,6 +181,35 @@ def get_dict_properties(item, fields, mixed_case_fields=[], formatters={}): return tuple(row) +def sort_items(items, sort_str): + """Sort items based on sort keys and sort directions given by sort_str. + + :param items: a list or generator object of items + :param sort_str: a string defining the sort rules, the format is + '<key1>:[direction1],<key2>:[direction2]...', direction can be 'asc' + for ascending or 'desc' for descending, if direction is not given, + it's ascending by default + :return: sorted items + """ + if not sort_str: + return items + # items may be a generator object, transform it to a list + items = list(items) + sort_keys = sort_str.strip().split(',') + for sort_key in reversed(sort_keys): + reverse = False + if ':' in sort_key: + sort_key, direction = sort_key.split(':', 1) + if direction not in ['asc', 'desc']: + msg = "Specify sort direction by asc or desc" + raise exceptions.CommandError(msg) + if direction == 'desc': + reverse = True + items.sort(key=lambda item: get_field(item, sort_key), + reverse=reverse) + return items + + def string_to_bool(arg): return arg.strip().lower() in ('t', 'true', 'yes', '1') |
