Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils.py @ a624a072

History | View | Annotate | Download (14.9 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 time import sleep
37
from os import walk, path
38
from json import dumps
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
    # No colours? No worries, use dummy foo instead
55
    def dummy(val):
56
        return val
57
    red = yellow = magenta = bold = dummy
58
    #from kamaki.cli import _colors
59
    #if _colors.lower() == 'on':
60
    suggest['ansicolors']['active'] = True
61

    
62
try:
63
    from progress.bar import ShadyBar
64
except ImportError:
65
    suggest['progress']['active'] = True
66

    
67

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

    
85

    
86
def remove_colors():
87
    global bold
88
    global red
89
    global yellow
90
    global magenta
91

    
92
    def dummy(val):
93
        return val
94
    red = yellow = magenta = bold = dummy
95

    
96

    
97
def pretty_keys(d, delim='_', recurcive=False):
98
    """<term>delim<term> to <term> <term> transformation
99
    """
100
    new_d = {}
101
    for key, val in d.items():
102
        new_key = key.split(delim)[-1]
103
        if recurcive and isinstance(val, dict):
104
            new_val = pretty_keys(val, delim, recurcive)
105
        else:
106
            new_val = val
107
        new_d[new_key] = new_val
108
    return new_d
109

    
110

    
111
def print_json(data):
112
    """Print a list or dict as json in console
113

114
    :param data: json-dumpable data
115
    """
116
    print(dumps(data, indent=INDENT_TAB))
117

    
118

    
119
def pretty_dict(d, *args, **kwargs):
120
    print_dict(pretty_keys(d, *args, **kwargs))
121

    
122

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

132
    :param d: (dict)
133

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

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

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

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

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

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

    
168

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

178
    :param l: (list)
179

180
    :param exclude: (iterable of strings) items to exclude from printing
181

182
    :param indent: (int) initial indentation (recursive)
183

184
    :param with_enumeration: (bool) enumerate 1st-level items
185

186
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
187
        not enumerate 1st level keys)
188

189
    :raises CLIError: if preconditions fail
190
    """
191
    assert isinstance(l, list) or isinstance(l, tuple), (
192
        'print_list prinbts a list or tuple')
193
    assert indent >= 0, 'print_list indent must be >= 0'
194

    
195
    counter = 0
196
    for i, item in enumerate(l):
197
        print_str = ' ' * indent
198
        print_str += '%s.' % (i + 1) if with_enumeration else ''
199
        if isinstance(item, dict):
200
            if with_enumeration:
201
                print print_str
202
            elif counter and counter < len(l):
203
                print
204
            print_dict(
205
                item, exclude,
206
                indent + (INDENT_TAB if with_enumeration else 0),
207
                recursive_enumeration, recursive_enumeration)
208
        elif isinstance(item, list) or isinstance(item, tuple):
209
            if with_enumeration:
210
                print print_str
211
            elif counter and counter < len(l):
212
                print
213
            print_list(
214
                item, exclude, indent + INDENT_TAB,
215
                recursive_enumeration, recursive_enumeration)
216
        else:
217
            item = ('%s' % item).strip()
218
            if item in exclude:
219
                continue
220
            print '%s%s' % (print_str, item)
221
        counter += 1
222

    
223

    
224
def page_hold(index, limit, maxlen):
225
    """Check if there are results to show, and hold the page when needed
226
    :param index: (int) > 0
227
    :param limit: (int) 0 < limit <= max, page hold if limit mod index == 0
228
    :param maxlen: (int) Don't hold if index reaches maxlen
229

230
    :returns: True if there are more to show, False if all results are shown
231
    """
232
    if index >= limit and index % limit == 0:
233
        if index >= maxlen:
234
            return False
235
        else:
236
            print('(%s listed - %s more - "enter" to continue)' % (
237
                index,
238
                maxlen - index))
239
            c = ' '
240
            while c != '\n':
241
                c = stdin.read(1)
242
    return True
243

    
244

    
245
def print_items(
246
        items, title=('id', 'name'),
247
        with_enumeration=False, with_redundancy=False,
248
        page_size=0):
249
    """print dict or list items in a list, using some values as title
250
    Objects of next level don't inherit enumeration (default: off) or titles
251

252
    :param items: (list) items are lists or dict
253

254
    :param title: (tuple) keys to use their values as title
255

256
    :param with_enumeration: (boolean) enumerate items (order id on title)
257

258
    :param with_redundancy: (boolean) values in title also appear on body
259

260
    :param page_size: (int) show results in pages of page_size items, enter to
261
        continue
262
    """
263
    if not items:
264
        return
265
    elif not (
266
            isinstance(items, dict) or isinstance(
267
                items, list) or isinstance(items, dict)):
268
        print '%s' % items
269
        return
270

    
271
    try:
272
        page_size = int(page_size) if int(page_size) > 0 else len(items)
273
    except:
274
        page_size = len(items)
275
    num_of_pages = len(items) // page_size
276
    num_of_pages += 1 if len(items) % page_size else 0
277
    for i, item in enumerate(items):
278
        if with_enumeration:
279
            stdout.write('%s. ' % (i + 1))
280
        if isinstance(item, dict):
281
            title = sorted(set(title).intersection(item.keys()))
282
            if with_redundancy:
283
                header = ' '.join('%s' % item[key] for key in title)
284
            else:
285
                header = ' '.join('%s' % item.pop(key) for key in title)
286
            print(bold(header))
287
        if isinstance(item, dict):
288
            print_dict(item, indent=INDENT_TAB)
289
        elif isinstance(item, list):
290
            print_list(item, indent=INDENT_TAB)
291
        else:
292
            print(' %s' % item)
293
        page_hold(i + 1, page_size, len(items))
294

    
295

    
296
def format_size(size):
297
    units = ('B', 'KiB', 'MiB', 'GiB', 'TiB')
298
    try:
299
        size = float(size)
300
    except ValueError as err:
301
        raiseCLIError(err, 'Cannot format %s in bytes' % size)
302
    for unit in units:
303
        if size < 1024:
304
            break
305
        size /= 1024.0
306
    s = ('%.2f' % size)
307
    while '.' in s and s[-1] in ('0', '.'):
308
        s = s[:-1]
309
    return s + unit
310

    
311

    
312
def to_bytes(size, format):
313
    """
314
    :param size: (float) the size in the given format
315
    :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
316

317
    :returns: (int) the size in bytes
318
    """
319
    format = format.upper()
320
    if format == 'B':
321
        return int(size)
322
    size = float(size)
323
    units_dc = ('KB', 'MB', 'GB', 'TB')
324
    units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
325

    
326
    factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
327
    if not factor:
328
        raise ValueError('Invalid data size format %s' % format)
329
    for prefix in ('K', 'M', 'G', 'T'):
330
        size *= factor
331
        if format.startswith(prefix):
332
            break
333
    return int(size)
334

    
335

    
336
def dict2file(d, f, depth=0):
337
    for k, v in d.items():
338
        f.write('%s%s: ' % ('\t' * depth, k))
339
        if isinstance(v, dict):
340
            f.write('\n')
341
            dict2file(v, f, depth + 1)
342
        elif isinstance(v, list):
343
            f.write('\n')
344
            list2file(v, f, depth + 1)
345
        else:
346
            f.write(' %s\n' % v)
347

    
348

    
349
def list2file(l, f, depth=1):
350
    for item in l:
351
        if isinstance(item, dict):
352
            dict2file(item, f, depth + 1)
353
        elif isinstance(item, list):
354
            list2file(item, f, depth + 1)
355
        else:
356
            f.write('%s%s\n' % ('\t' * depth, item))
357

    
358
# Split input auxiliary
359

    
360

    
361
def _parse_with_regex(line, regex):
362
    re_parser = regex_compile(regex)
363
    return (re_parser.split(line), re_parser.findall(line))
364

    
365

    
366
def _sub_split(line):
367
    terms = []
368
    (sub_trivials, sub_interesting) = _parse_with_regex(line, ' ".*?" ')
369
    for subi, subipart in enumerate(sub_interesting):
370
        terms += sub_trivials[subi].split()
371
        terms.append(subipart[2:-2])
372
    terms += sub_trivials[-1].split()
373
    return terms
374

    
375

    
376
def old_split_input(line):
377
    """Use regular expressions to split a line correctly"""
378
    line = ' %s ' % line
379
    (trivial_parts, interesting_parts) = _parse_with_regex(line, ' \'.*?\' ')
380
    terms = []
381
    for i, ipart in enumerate(interesting_parts):
382
        terms += _sub_split(trivial_parts[i])
383
        terms.append(ipart[2:-2])
384
    terms += _sub_split(trivial_parts[-1])
385
    return terms
386

    
387

    
388
def _get_from_parsed(parsed_str):
389
    try:
390
        parsed_str = parsed_str.strip()
391
    except:
392
        return None
393
    if parsed_str:
394
        if parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"'):
395
            return [parsed_str[1:-1]]
396
        return parsed_str.split(' ')
397
    return None
398

    
399

    
400
def split_input(line):
401
    if not line:
402
        return []
403
    reg_expr = '\'.*?\'|".*?"|^[\S]*$'
404
    (trivial_parts, interesting_parts) = _parse_with_regex(line, reg_expr)
405
    assert(len(trivial_parts) == 1 + len(interesting_parts))
406
    #print('  [split_input] trivial_parts %s are' % trivial_parts)
407
    #print('  [split_input] interesting_parts %s are' % interesting_parts)
408
    terms = []
409
    for i, tpart in enumerate(trivial_parts):
410
        part = _get_from_parsed(tpart)
411
        if part:
412
            terms += part
413
        try:
414
            part = _get_from_parsed(interesting_parts[i])
415
        except IndexError:
416
            break
417
        if part:
418
            terms += part
419
    return terms
420

    
421

    
422
def ask_user(msg, true_resp=('y', )):
423
    """Print msg and read user response
424

425
    :param true_resp: (tuple of chars)
426

427
    :returns: (bool) True if reponse in true responses, False otherwise
428
    """
429
    stdout.write('%s [%s/N]: ' % (msg, ', '.join(true_resp)))
430
    stdout.flush()
431
    user_response = stdin.readline()
432
    return user_response[0].lower() in true_resp
433

    
434

    
435
def spiner(size=None):
436
    spins = ('/', '-', '\\', '|')
437
    stdout.write(' ')
438
    size = size or -1
439
    i = 0
440
    while size - i:
441
        stdout.write('\b%s' % spins[i % len(spins)])
442
        stdout.flush()
443
        i += 1
444
        sleep(0.1)
445
        yield
446
    yield
447

    
448
if __name__ == '__main__':
449
    examples = [
450
        'la_la le_le li_li',
451
        '\'la la\' \'le le\' \'li li\'',
452
        '\'la la\' le_le \'li li\'',
453
        'la_la \'le le\' li_li',
454
        'la_la \'le le\' \'li li\'',
455
        '"la la" "le le" "li li"',
456
        '"la la" le_le "li li"',
457
        'la_la "le le" li_li',
458
        '"la_la" "le le" "li li"',
459
        '\'la la\' "le le" \'li li\'',
460
        'la_la \'le le\' "li li"',
461
        'la_la \'le le\' li_li',
462
        '\'la la\' le_le "li li"',
463
        '"la la" le_le \'li li\'',
464
        '"la la" \'le le\' li_li',
465
        'la_la \'le\'le\' "li\'li"',
466
        '"la \'le le\' la"',
467
        '\'la "le le" la\'',
468
        '\'la "la" la\' "le \'le\' le" li_"li"_li',
469
        '\'\' \'L\' "" "A"']
470

    
471
    for i, example in enumerate(examples):
472
        print('%s. Split this: (%s)' % (i + 1, example))
473
        ret = old_split_input(example)
474
        print('\t(%s) of size %s' % (ret, len(ret)))
475

    
476

    
477
def get_path_size(testpath):
478
    if path.isfile(testpath):
479
        return path.getsize(testpath)
480
    total_size = 0
481
    for top, dirs, files in walk(path.abspath(testpath)):
482
        for f in files:
483
            f = path.join(top, f)
484
            if path.isfile(f):
485
                total_size += path.getsize(f)
486
    return total_size
487

    
488

    
489
def remove_from_items(list_of_dicts, key_to_remove):
490
    for item in list_of_dicts:
491
        assert isinstance(item, dict), 'Item %s not a dict' % item
492
        item.pop(key_to_remove, None)