Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils.py @ 60c42f9f

History | View | Annotate | Download (14.7 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
    try:
266
        page_size = int(page_size) if int(page_size) > 0 else len(items)
267
    except:
268
        page_size = len(items)
269
    num_of_pages = len(items) // page_size
270
    num_of_pages += 1 if len(items) % page_size else 0
271
    for i, item in enumerate(items):
272
        if with_enumeration:
273
            stdout.write('%s. ' % (i + 1))
274
        if isinstance(item, dict):
275
            title = sorted(set(title).intersection(item.keys()))
276
            if with_redundancy:
277
                header = ' '.join('%s' % item[key] for key in title)
278
            else:
279
                header = ' '.join('%s' % item.pop(key) for key in title)
280
            print(bold(header))
281
        if isinstance(item, dict):
282
            print_dict(item, indent=INDENT_TAB)
283
        elif isinstance(item, list):
284
            print_list(item, indent=INDENT_TAB)
285
        else:
286
            print(' %s' % item)
287
        page_hold(i + 1, page_size, len(items))
288

    
289

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

    
305

    
306
def to_bytes(size, format):
307
    """
308
    :param size: (float) the size in the given format
309
    :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
310

311
    :returns: (int) the size in bytes
312
    """
313
    format = format.upper()
314
    if format == 'B':
315
        return int(size)
316
    size = float(size)
317
    units_dc = ('KB', 'MB', 'GB', 'TB')
318
    units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
319

    
320
    factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
321
    if not factor:
322
        raise ValueError('Invalid data size format %s' % format)
323
    for prefix in ('K', 'M', 'G', 'T'):
324
        size *= factor
325
        if format.startswith(prefix):
326
            break
327
    return int(size)
328

    
329

    
330
def dict2file(d, f, depth=0):
331
    for k, v in d.items():
332
        f.write('%s%s: ' % ('\t' * depth, k))
333
        if isinstance(v, dict):
334
            f.write('\n')
335
            dict2file(v, f, depth + 1)
336
        elif isinstance(v, list):
337
            f.write('\n')
338
            list2file(v, f, depth + 1)
339
        else:
340
            f.write(' %s\n' % v)
341

    
342

    
343
def list2file(l, f, depth=1):
344
    for item in l:
345
        if isinstance(item, dict):
346
            dict2file(item, f, depth + 1)
347
        elif isinstance(item, list):
348
            list2file(item, f, depth + 1)
349
        else:
350
            f.write('%s%s\n' % ('\t' * depth, item))
351

    
352
# Split input auxiliary
353

    
354

    
355
def _parse_with_regex(line, regex):
356
    re_parser = regex_compile(regex)
357
    return (re_parser.split(line), re_parser.findall(line))
358

    
359

    
360
def _sub_split(line):
361
    terms = []
362
    (sub_trivials, sub_interesting) = _parse_with_regex(line, ' ".*?" ')
363
    for subi, subipart in enumerate(sub_interesting):
364
        terms += sub_trivials[subi].split()
365
        terms.append(subipart[2:-2])
366
    terms += sub_trivials[-1].split()
367
    return terms
368

    
369

    
370
def old_split_input(line):
371
    """Use regular expressions to split a line correctly"""
372
    line = ' %s ' % line
373
    (trivial_parts, interesting_parts) = _parse_with_regex(line, ' \'.*?\' ')
374
    terms = []
375
    for i, ipart in enumerate(interesting_parts):
376
        terms += _sub_split(trivial_parts[i])
377
        terms.append(ipart[2:-2])
378
    terms += _sub_split(trivial_parts[-1])
379
    return terms
380

    
381

    
382
def _get_from_parsed(parsed_str):
383
    try:
384
        parsed_str = parsed_str.strip()
385
    except:
386
        return None
387
    if parsed_str:
388
        if parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"'):
389
            return [parsed_str[1:-1]]
390
        return parsed_str.split(' ')
391
    return None
392

    
393

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

    
415

    
416
def ask_user(msg, true_resp=('y', )):
417
    """Print msg and read user response
418

419
    :param true_resp: (tuple of chars)
420

421
    :returns: (bool) True if reponse in true responses, False otherwise
422
    """
423
    stdout.write('%s [%s/N]: ' % (msg, ', '.join(true_resp)))
424
    stdout.flush()
425
    user_response = stdin.readline()
426
    return user_response[0].lower() in true_resp
427

    
428

    
429
def spiner(size=None):
430
    spins = ('/', '-', '\\', '|')
431
    stdout.write(' ')
432
    size = size or -1
433
    i = 0
434
    while size - i:
435
        stdout.write('\b%s' % spins[i % len(spins)])
436
        stdout.flush()
437
        i += 1
438
        sleep(0.1)
439
        yield
440
    yield
441

    
442
if __name__ == '__main__':
443
    examples = [
444
        'la_la le_le li_li',
445
        '\'la la\' \'le le\' \'li li\'',
446
        '\'la la\' le_le \'li li\'',
447
        'la_la \'le le\' li_li',
448
        'la_la \'le le\' \'li li\'',
449
        '"la la" "le le" "li li"',
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 \'le le\' la"',
461
        '\'la "le le" la\'',
462
        '\'la "la" la\' "le \'le\' le" li_"li"_li',
463
        '\'\' \'L\' "" "A"']
464

    
465
    for i, example in enumerate(examples):
466
        print('%s. Split this: (%s)' % (i + 1, example))
467
        ret = old_split_input(example)
468
        print('\t(%s) of size %s' % (ret, len(ret)))
469

    
470

    
471
def get_path_size(testpath):
472
    if path.isfile(testpath):
473
        return path.getsize(testpath)
474
    total_size = 0
475
    for top, dirs, files in walk(path.abspath(testpath)):
476
        for f in files:
477
            f = path.join(top, f)
478
            if path.isfile(f):
479
                total_size += path.getsize(f)
480
    return total_size
481

    
482

    
483
def remove_from_items(list_of_dicts, key_to_remove):
484
    for item in list_of_dicts:
485
        assert isinstance(item, dict), 'Item %s not a dict' % item
486
        item.pop(key_to_remove, None)