Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils.py @ 67083ca0

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
    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 remove_colors():
79
    global bold
80
    global red
81
    global yellow
82
    global magenta
83

    
84
    def dummy(val):
85
        return val
86
    red = yellow = magenta = bold = dummy
87

    
88

    
89
def pretty_keys(d, delim='_', recurcive=False):
90
    """<term>delim<term> to <term> <term> transformation
91
    """
92
    new_d = {}
93
    for key, val in d.items():
94
        new_key = key.split(delim)[-1]
95
        if recurcive and isinstance(val, dict):
96
            new_val = pretty_keys(val, delim, recurcive)
97
        else:
98
            new_val = val
99
        new_d[new_key] = new_val
100
    return new_d
101

    
102

    
103
def print_json(data):
104
    """Print a list or dict as json in console
105

106
    :param data: json-dumpable data
107
    """
108
    print(dumps(data, indent=INDENT_TAB))
109

    
110

    
111
def pretty_dict(d, *args, **kwargs):
112
    print_dict(pretty_keys(d, *args, **kwargs))
113

    
114

    
115
def print_dict(
116
        d,
117
        exclude=(), indent=0,
118
        with_enumeration=False, recursive_enumeration=False):
119
    """Pretty-print a dictionary object
120
    <indent>key: <non iterable item>
121
    <indent>key:
122
    <indent + INDENT_TAB><pretty-print iterable>
123

124
    :param d: (dict)
125

126
    :param exclude: (iterable of strings) keys to exclude from printing
127

128
    :param indent: (int) initial indentation (recursive)
129

130
    :param with_enumeration: (bool) enumerate 1st-level keys
131

132
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
133
        not enumerate 1st level keys)
134

135
    :raises CLIError: if preconditions fail
136
    """
137
    assert isinstance(d, dict), 'print_dict input must be a dict'
138
    assert indent >= 0, 'print_dict indent must be >= 0'
139

    
140
    for i, (k, v) in enumerate(d.items()):
141
        k = ('%s' % k).strip()
142
        if k in exclude:
143
            continue
144
        print_str = ' ' * indent
145
        print_str += '%s.' % (i + 1) if with_enumeration else ''
146
        print_str += '%s:' % k
147
        if isinstance(v, dict):
148
            print print_str
149
            print_dict(
150
                v, exclude, indent + INDENT_TAB,
151
                recursive_enumeration, recursive_enumeration)
152
        elif isinstance(v, list) or isinstance(v, tuple):
153
            print print_str
154
            print_list(
155
                v, exclude, indent + INDENT_TAB,
156
                recursive_enumeration, recursive_enumeration)
157
        else:
158
            print '%s %s' % (print_str, v)
159

    
160

    
161
def print_list(
162
        l,
163
        exclude=(), indent=0,
164
        with_enumeration=False, recursive_enumeration=False):
165
    """Pretty-print a list of items
166
    <indent>key: <non iterable item>
167
    <indent>key:
168
    <indent + INDENT_TAB><pretty-print iterable>
169

170
    :param l: (list)
171

172
    :param exclude: (iterable of strings) items to exclude from printing
173

174
    :param indent: (int) initial indentation (recursive)
175

176
    :param with_enumeration: (bool) enumerate 1st-level items
177

178
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
179
        not enumerate 1st level keys)
180

181
    :raises CLIError: if preconditions fail
182
    """
183
    assert isinstance(l, list) or isinstance(l, tuple), (
184
        'print_list prinbts a list or tuple')
185
    assert indent >= 0, 'print_list indent must be >= 0'
186

    
187
    counter = 0
188
    for i, item in enumerate(l):
189
        print_str = ' ' * indent
190
        print_str += '%s.' % (i + 1) if with_enumeration else ''
191
        if isinstance(item, dict):
192
            if with_enumeration:
193
                print print_str
194
            elif counter and counter < len(l):
195
                print
196
            print_dict(
197
                item, exclude,
198
                indent + (INDENT_TAB if with_enumeration else 0),
199
                recursive_enumeration, recursive_enumeration)
200
        elif isinstance(item, list) or isinstance(item, tuple):
201
            if with_enumeration:
202
                print print_str
203
            elif counter and counter < len(l):
204
                print
205
            print_list(
206
                item, exclude, indent + INDENT_TAB,
207
                recursive_enumeration, recursive_enumeration)
208
        else:
209
            item = ('%s' % item).strip()
210
            if item in exclude:
211
                continue
212
            print '%s%s' % (print_str, item)
213
        counter += 1
214

    
215

    
216
def page_hold(index, limit, maxlen):
217
    """Check if there are results to show, and hold the page when needed
218
    :param index: (int) > 0
219
    :param limit: (int) 0 < limit <= max, page hold if limit mod index == 0
220
    :param maxlen: (int) Don't hold if index reaches maxlen
221

222
    :returns: True if there are more to show, False if all results are shown
223
    """
224
    if index >= limit and index % limit == 0:
225
        if index >= maxlen:
226
            return False
227
        else:
228
            print('(%s listed - %s more - "enter" to continue)' % (
229
                index,
230
                maxlen - index))
231
            c = ' '
232
            while c != '\n':
233
                c = stdin.read(1)
234
    return True
235

    
236

    
237
def print_items(
238
        items, title=('id', 'name'),
239
        with_enumeration=False, with_redundancy=False,
240
        page_size=0):
241
    """print dict or list items in a list, using some values as title
242
    Objects of next level don't inherit enumeration (default: off) or titles
243

244
    :param items: (list) items are lists or dict
245

246
    :param title: (tuple) keys to use their values as title
247

248
    :param with_enumeration: (boolean) enumerate items (order id on title)
249

250
    :param with_redundancy: (boolean) values in title also appear on body
251

252
    :param page_size: (int) show results in pages of page_size items, enter to
253
        continue
254
    """
255
    if not items:
256
        return
257
    elif not (
258
            isinstance(items, dict) or isinstance(
259
                items, list) or isinstance(items, dict)):
260
        print '%s' % items
261
        return
262

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

    
287

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

    
303

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

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

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

    
327

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

    
340

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

    
350
# Split input auxiliary
351

    
352

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

    
357

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

    
367

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

    
379

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

    
391

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

    
413

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

417
    :param true_resp: (tuple of chars)
418

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

    
426

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

    
440
if __name__ == '__main__':
441
    examples = [
442
        'la_la le_le li_li',
443
        '\'la la\' \'le le\' \'li li\'',
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 \'le le\' la"',
459
        '\'la "le le" la\'',
460
        '\'la "la" la\' "le \'le\' le" li_"li"_li',
461
        '\'\' \'L\' "" "A"']
462

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

    
468

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

    
480

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