Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils / __init__.py @ c49188b7

History | View | Annotate | Download (14.2 kB)

1
# Copyright 2011-2013 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 sys import stdout, stdin
35
from re import compile as regex_compile
36
from os import walk, path
37
from json import dumps
38
from pydoc import pager
39

    
40
from kamaki.cli.errors import raiseCLIError
41

    
42

    
43
INDENT_TAB = 4
44

    
45

    
46
suggest = dict(ansicolors=dict(
47
        active=False,
48
        url='#install-ansicolors-progress',
49
        description='Add colors to console responses'))
50

    
51
try:
52
    from colors import magenta, red, yellow, bold
53
except ImportError:
54
    def dummy(val):
55
        return val
56
    red = yellow = magenta = bold = dummy
57
    suggest['ansicolors']['active'] = True
58

    
59

    
60
def suggest_missing(miss=None, exclude=[]):
61
    global suggest
62
    sgs = dict(suggest)
63
    for exc in exclude:
64
        try:
65
            sgs.pop(exc)
66
        except KeyError:
67
            pass
68
    kamaki_docs = 'http://www.synnefo.org/docs/kamaki/latest'
69
    for k, v in (miss, sgs[miss]) if miss else sgs.items():
70
        if v['active'] and stdout.isatty():
71
            print('Suggestion: for better user experience install %s' % k)
72
            print('\t%s' % v['description'])
73
            print('\tIt is easy, here are the instructions:')
74
            print('\t%s/installation.html%s' % (kamaki_docs, v['url']))
75
            print('')
76

    
77

    
78
def guess_mime_type(
79
        filename,
80
        default_content_type='application/octet-stream',
81
        default_encoding=None):
82
    assert filename, 'Cannot guess mimetype for empty filename'
83
    try:
84
        from mimetypes import guess_type
85
        ctype, cenc = guess_type(filename)
86
        return ctype or default_content_type, cenc or default_encoding
87
    except ImportError:
88
        print 'WARNING: Cannot import mimetypes, using defaults'
89
        return (default_content_type, default_encoding)
90

    
91

    
92
def remove_colors():
93
    global bold
94
    global red
95
    global yellow
96
    global magenta
97

    
98
    def dummy(val):
99
        return val
100
    red = yellow = magenta = bold = dummy
101

    
102

    
103
def pretty_keys(d, delim='_', recursive=False):
104
    """<term>delim<term> to <term> <term> transformation"""
105
    new_d = dict(d)
106
    for k, v in d.items():
107
        new_v = new_d.pop(k)
108
        new_d[k.replace(delim, ' ').strip()] = pretty_keys(
109
            new_v, delim, True) if (
110
                recursive and isinstance(v, dict)) else new_v
111
    return new_d
112

    
113

    
114
def print_json(data, out=stdout):
115
    """Print a list or dict as json in console
116

117
    :param data: json-dumpable data
118

119
    :param out: Input/Output stream to dump values into
120
    """
121
    out.writelines(unicode(dumps(data, indent=INDENT_TAB) + '\n'))
122

    
123

    
124
def print_dict(
125
        d,
126
        exclude=(), indent=0,
127
        with_enumeration=False, recursive_enumeration=False, out=stdout):
128
    """Pretty-print a dictionary object
129
    <indent>key: <non iterable item>
130
    <indent>key:
131
    <indent + INDENT_TAB><pretty-print iterable>
132

133
    :param d: (dict)
134

135
    :param exclude: (iterable of strings) keys to exclude from printing
136

137
    :param indent: (int) initial indentation (recursive)
138

139
    :param with_enumeration: (bool) enumerate 1st-level keys
140

141
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
142
        not enumerate 1st level keys)
143

144
    :param out: Input/Output stream to dump values into
145

146
    :raises CLIError: if preconditions fail
147
    """
148
    assert isinstance(d, dict), 'print_dict input must be a dict'
149
    assert indent >= 0, 'print_dict indent must be >= 0'
150

    
151
    for i, (k, v) in enumerate(d.items()):
152
        k = ('%s' % k).strip()
153
        if k in exclude:
154
            continue
155
        print_str = u' ' * indent
156
        print_str += u'%s.' % (i + 1) if with_enumeration else u''
157
        print_str += u'%s:' % k
158
        if isinstance(v, dict):
159
            out.writelines(print_str + '\n')
160
            print_dict(
161
                v, exclude, indent + INDENT_TAB,
162
                recursive_enumeration, recursive_enumeration, out)
163
        elif isinstance(v, list) or isinstance(v, tuple):
164
            out.writelines(print_str + '\n')
165
            print_list(
166
                v, exclude, indent + INDENT_TAB,
167
                recursive_enumeration, recursive_enumeration, out)
168
        else:
169
            out.writelines(u'%s %s\n' % (print_str, v))
170

    
171

    
172
def print_list(
173
        l,
174
        exclude=(), indent=0,
175
        with_enumeration=False, recursive_enumeration=False, out=stdout):
176
    """Pretty-print a list of items
177
    <indent>key: <non iterable item>
178
    <indent>key:
179
    <indent + INDENT_TAB><pretty-print iterable>
180

181
    :param l: (list)
182

183
    :param exclude: (iterable of strings) items to exclude from printing
184

185
    :param indent: (int) initial indentation (recursive)
186

187
    :param with_enumeration: (bool) enumerate 1st-level items
188

189
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
190
        not enumerate 1st level keys)
191

192
    :param out: Input/Output stream to dump values into
193

194
    :raises CLIError: if preconditions fail
195
    """
196
    assert isinstance(l, list) or isinstance(l, tuple), (
197
        'print_list prinbts a list or tuple')
198
    assert indent >= 0, 'print_list indent must be >= 0'
199

    
200
    for i, item in enumerate(l):
201
        print_str = u' ' * indent
202
        print_str += u'%s.' % (i + 1) if with_enumeration else u''
203
        if isinstance(item, dict):
204
            if with_enumeration:
205
                out.writelines(print_str + '\n')
206
            elif i and i < len(l):
207
                out.writelines(u'\n')
208
            print_dict(
209
                item, exclude,
210
                indent + (INDENT_TAB if with_enumeration else 0),
211
                recursive_enumeration, recursive_enumeration, out)
212
        elif isinstance(item, list) or isinstance(item, tuple):
213
            if with_enumeration:
214
                out.writelines(print_str + '\n')
215
            elif i and i < len(l):
216
                out.writelines(u'\n')
217
            print_list(
218
                item, exclude, indent + INDENT_TAB,
219
                recursive_enumeration, recursive_enumeration, out)
220
        else:
221
            item = ('%s' % item).strip()
222
            if item in exclude:
223
                continue
224
            out.write(u'%s%s\n' % (print_str, item))
225
            out.flush()
226

    
227

    
228
def print_items(
229
        items, title=('id', 'name'),
230
        with_enumeration=False, with_redundancy=False, out=stdout):
231
    """print dict or list items in a list, using some values as title
232
    Objects of next level don't inherit enumeration (default: off) or titles
233

234
    :param items: (list) items are lists or dict
235

236
    :param title: (tuple) keys to use their values as title
237

238
    :param with_enumeration: (boolean) enumerate items (order id on title)
239

240
    :param with_redundancy: (boolean) values in title also appear on body
241

242
    :param out: Input/Output stream to dump values into
243
    """
244
    if not items:
245
        return
246
    if not (isinstance(items, dict) or isinstance(items, list) or isinstance(
247
                items, tuple)):
248
        out.writelines(u'%s\n' % items)
249
        return
250

    
251
    for i, item in enumerate(items):
252
        if with_enumeration:
253
            out.write(u'%s. ' % (i + 1))
254
        if isinstance(item, dict):
255
            item = dict(item)
256
            title = sorted(set(title).intersection(item))
257
            pick = item.get if with_redundancy else item.pop
258
            header = u' '.join(u'%s' % pick(key) for key in title)
259
            out.writelines((unicode(bold(header) if header else '') + '\n'))
260
            print_dict(item, indent=INDENT_TAB, out=out)
261
        elif isinstance(item, list) or isinstance(item, tuple):
262
            print_list(item, indent=INDENT_TAB, out=out)
263
        else:
264
            out.writelines(u' %s\n' % item)
265

    
266

    
267
def format_size(size, decimal_factors=False):
268
    units = ('B', 'KB', 'MB', 'GB', 'TB') if decimal_factors else (
269
        'B', 'KiB', 'MiB', 'GiB', 'TiB')
270
    step = 1000 if decimal_factors else 1024
271
    fstep = float(step)
272
    try:
273
        size = float(size)
274
    except (ValueError, TypeError) as err:
275
        raiseCLIError(err, 'Cannot format %s in bytes' % (
276
            ','.join(size) if isinstance(size, tuple) else size))
277
    for i, unit in enumerate(units):
278
        if size < step or i + 1 == len(units):
279
            break
280
        size /= fstep
281
    s = ('%.2f' % size)
282
    s = s.replace('%s' % step, '%s.99' % (step - 1)) if size <= fstep else s
283
    while '.' in s and s[-1] in ('0', '.'):
284
        s = s[:-1]
285
    return s + unit
286

    
287

    
288
def to_bytes(size, format):
289
    """
290
    :param size: (float) the size in the given format
291
    :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
292

293
    :returns: (int) the size in bytes
294
    :raises ValueError: if invalid size or format
295
    :raises AttributeError: if format is not str
296
    :raises TypeError: if size is not arithmetic or convertible to arithmetic
297
    """
298
    format = format.upper()
299
    if format == 'B':
300
        return int(size)
301
    size = float(size)
302
    units_dc = ('KB', 'MB', 'GB', 'TB')
303
    units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
304

    
305
    factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
306
    if not factor:
307
        raise ValueError('Invalid data size format %s' % format)
308
    for prefix in ('K', 'M', 'G', 'T'):
309
        size *= factor
310
        if format.startswith(prefix):
311
            break
312
    return int(size)
313

    
314

    
315
def dict2file(d, f, depth=0):
316
    for k, v in d.items():
317
        f.write('%s%s: ' % (' ' * INDENT_TAB * depth, k))
318
        if isinstance(v, dict):
319
            f.write('\n')
320
            dict2file(v, f, depth + 1)
321
        elif isinstance(v, list) or isinstance(v, tuple):
322
            f.write('\n')
323
            list2file(v, f, depth + 1)
324
        else:
325
            f.write('%s\n' % v)
326

    
327

    
328
def list2file(l, f, depth=1):
329
    for item in l:
330
        if isinstance(item, dict):
331
            dict2file(item, f, depth + 1)
332
        elif isinstance(item, list) or isinstance(item, tuple):
333
            list2file(item, f, depth + 1)
334
        else:
335
            f.write('%s%s\n' % (' ' * INDENT_TAB * depth, item))
336

    
337
# Split input auxiliary
338

    
339

    
340
def _parse_with_regex(line, regex):
341
    re_parser = regex_compile(regex)
342
    return (re_parser.split(line), re_parser.findall(line))
343

    
344

    
345
def _get_from_parsed(parsed_str):
346
    try:
347
        parsed_str = parsed_str.strip()
348
    except:
349
        return None
350
    return ([parsed_str[1:-1]] if (
351
        parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"')) else (
352
            parsed_str.split(' '))) if parsed_str else None
353

    
354

    
355
def split_input(line):
356
    if not line:
357
        return []
358
    reg_expr = '\'.*?\'|".*?"|^[\S]*$'
359
    (trivial_parts, interesting_parts) = _parse_with_regex(line, reg_expr)
360
    assert(len(trivial_parts) == 1 + len(interesting_parts))
361
    terms = []
362
    for i, tpart in enumerate(trivial_parts):
363
        part = _get_from_parsed(tpart)
364
        if part:
365
            terms += part
366
        try:
367
            part = _get_from_parsed(interesting_parts[i])
368
        except IndexError:
369
            break
370
        if part:
371
            if tpart and not tpart[-1].endswith(' '):
372
                terms[-1] += ' '.join(part)
373
            else:
374
                terms += part
375
    return terms
376

    
377

    
378
def ask_user(msg, true_resp=('y', ), out=stdout, user_in=stdin):
379
    """Print msg and read user response
380

381
    :param true_resp: (tuple of chars)
382

383
    :returns: (bool) True if reponse in true responses, False otherwise
384
    """
385
    yep = ', '.join(true_resp)
386
    nope = '<not %s>' % yep if 'n' in true_resp or 'N' in true_resp else 'N'
387
    out.write(u'%s [%s/%s]: ' % (msg, yep, nope))
388
    out.flush()
389
    user_response = user_in.readline()
390
    return user_response[0].lower() in [s.lower() for s in true_resp]
391

    
392

    
393
def get_path_size(testpath):
394
    if path.isfile(testpath):
395
        return path.getsize(testpath)
396
    total_size = 0
397
    for top, dirs, files in walk(path.abspath(testpath)):
398
        for f in files:
399
            f = path.join(top, f)
400
            if path.isfile(f):
401
                total_size += path.getsize(f)
402
    return total_size
403

    
404

    
405
def remove_from_items(list_of_dicts, key_to_remove):
406
    for item in list_of_dicts:
407
        assert isinstance(item, dict), 'Item %s not a dict' % item
408
        item.pop(key_to_remove, None)
409

    
410

    
411
def filter_dicts_by_dict(
412
    list_of_dicts, filters,
413
    exact_match=True, case_sensitive=False):
414
    """
415
    :param list_of_dicts: (list) each dict contains "raw" key-value pairs
416

417
    :param filters: (dict) filters in key-value form
418

419
    :param exact_match: (bool) if false, check if the filter value is part of
420
        the actual value
421

422
    :param case_sensitive: (bool) revers to values only (not keys)
423

424
    :returns: (list) only the dicts that match all filters
425
    """
426
    new_dicts = []
427
    for d in list_of_dicts:
428
        if set(filters).difference(d):
429
            continue
430
        match = True
431
        for k, v in filters.items():
432
            dv, v = ('%s' % d[k]), ('%s' % v)
433
            if not case_sensitive:
434
                dv, v = dv.lower(), v.lower()
435
            if not ((
436
                    exact_match and v == dv) or (
437
                    (not exact_match) and v in dv)):
438
                match = False
439
                break
440
        if match:
441
            new_dicts.append(d)
442
    return new_dicts