Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils.py @ f93854ae

History | View | Annotate | Download (5.4 kB)

1
# Copyright 2011 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from .errors import CLIError
35

    
36
try:
37
    from colors import magenta, red, yellow, bold
38
except ImportError:
39
    # No colours? No worries, use dummy foo instead
40
    def dummy(val):
41
        return val
42
    red = yellow = magenta = bold = dummy
43

    
44

    
45
def remove_colors():
46
    global bold
47
    global red
48
    global yellow
49
    global magenta
50

    
51
    def dummy(val):
52
        return val
53
    red = yellow = magenta = bold = dummy
54

    
55

    
56
def pretty_keys(d, delim='_', recurcive=False):
57
    """Transform keys of a dict from the form
58
    str1_str2_..._strN to the form strN
59
    where _ is the delimeter
60
    """
61
    new_d = {}
62
    for key, val in d.items():
63
        new_key = key.split(delim)[-1]
64
        if recurcive and isinstance(val, dict):
65
            new_val = pretty_keys(val, delim, recurcive)
66
        else:
67
            new_val = val
68
        new_d[new_key] = new_val
69
    return new_d
70

    
71

    
72
def print_dict(d, exclude=(), ident=0):
73
    if not isinstance(d, dict):
74
        raise CLIError(message='Cannot dict_print a non-dict object')
75
    try:
76
        margin = max(
77
            1 + max(len(unicode(key).strip()) for key in d.keys() \
78
                if not isinstance(key, dict) and not isinstance(key, list)),
79
            ident)
80
    except ValueError:
81
        margin = ident
82

    
83
    for key, val in sorted(d.items()):
84
        if key in exclude:
85
            continue
86
        print_str = '%s:' % unicode(key).strip()
87
        if isinstance(val, dict):
88
            print(print_str.rjust(margin) + ' {')
89
            print_dict(val, exclude=exclude, ident=margin + 6)
90
            print '}'.rjust(margin)
91
        elif isinstance(val, list):
92
            print(print_str.rjust(margin) + ' [')
93
            print_list(val, exclude=exclude, ident=margin + 6)
94
            print ']'.rjust(margin)
95
        else:
96
            print print_str.rjust(margin) + ' ' + unicode(val).strip()
97

    
98

    
99
def print_list(l, exclude=(), ident=0):
100
    if not isinstance(l, list):
101
        raise CLIError(message='Cannot list_print a non-list object')
102
    try:
103
        margin = max(
104
            1 + max(len(unicode(item).strip()) for item in l \
105
                if not isinstance(item, dict) and not isinstance(item, list)),
106
            ident)
107
    except ValueError:
108
        margin = ident
109

    
110
    for item in sorted(l):
111
        if item in exclude:
112
            continue
113
        if isinstance(item, dict):
114
            print('{'.rjust(margin))
115
            print_dict(item, exclude=exclude, ident=margin + 6)
116
            print '}'.rjust(margin)
117
        elif isinstance(item, list):
118
            print '['.rjust(margin)
119
            print_list(item, exclude=exclude, ident=margin + 6)
120
            print ']'.rjust(margin)
121
        else:
122
            print unicode(item).rjust(margin)
123

    
124

    
125
def print_items(items, title=('id', 'name')):
126
    for item in items:
127
        if isinstance(item, dict) or isinstance(item, list):
128
            print ' '.join(unicode(item.pop(key))\
129
                for key in title if key in item)
130
        if isinstance(item, dict):
131
            print_dict(item)
132

    
133

    
134
def format_size(size):
135
    units = ('B', 'K', 'M', 'G', 'T')
136
    try:
137
        size = float(size)
138
    except ValueError:
139
        raise CLIError(message='Cannot format %s in bytes' % size)
140
    for unit in units:
141
        if size < 1024:
142
            break
143
        size /= 1024
144
    s = ('%.1f' % size)
145
    if '.0' == s[-2:]:
146
        s = s[:-2]
147
    return s + unit
148

    
149

    
150
def dict2file(d, f, depth=0):
151
    for k, v in d.items():
152
        f.write('%s%s: ' % ('\t' * depth, k))
153
        if isinstance(v, dict):
154
            f.write('\n')
155
            dict2file(v, f, depth + 1)
156
        elif isinstance(v, list):
157
            f.write('\n')
158
            list2file(v, f, depth + 1)
159
        else:
160
            f.write(' %s\n' % unicode(v))
161

    
162

    
163
def list2file(l, f, depth=1):
164
    for item in l:
165
        if isinstance(item, dict):
166
            dict2file(item, f, depth + 1)
167
        elif isinstance(item, list):
168
            list2file(item, f, depth + 1)
169
        else:
170
            f.write('%s%s\n' % ('\t' * depth, unicode(item)))