Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils.py @ 0d735aaf

History | View | Annotate | Download (14.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 sys import stdout, stdin
35
from re import compile as regex_compile
36
from time import sleep
37

    
38
from kamaki.cli.errors import raiseCLIError
39

    
40
suggest = dict(
41
    ansicolors=dict(
42
        active=False,
43
        url='#install-ansicolors-progress',
44
        description='Add colors to console responses'),
45
    progress=dict(
46
        active=False,
47
        url='#install-ansicolors-progress',
48
        description='Add progress bars to some commands'))
49

    
50
try:
51
    from colors import magenta, red, yellow, bold
52
except ImportError:
53
    # No colours? No worries, use dummy foo instead
54
    def dummy(val):
55
        return val
56
    red = yellow = magenta = bold = dummy
57
    suggest['ansicolors']['active'] = True
58

    
59
try:
60
    from progress.bar import ShadyBar
61
except ImportError:
62
    suggest['progress']['active'] = True
63

    
64

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

    
76

    
77
def remove_colors():
78
    global bold
79
    global red
80
    global yellow
81
    global magenta
82

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

    
87

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

    
101

    
102
def print_dict(
103
        d, exclude=(), ident=0,
104
        with_enumeration=False, recursive_enumeration=False):
105
    """
106
    Pretty-print a dictionary object
107

108
    :param d: (dict) the input
109

110
    :param excelude: (set or list) keys to exclude from printing
111

112
    :param ident: (int) initial indentation (recursive)
113

114
    :param with_enumeration: (bool) enumerate each 1st level key if true
115

116
    :recursive_enumeration: (bool) recursively enumerate dicts and lists of
117
        2nd level or deeper
118

119
    :raises CLIError: (TypeError wrapper) non-dict input
120
    """
121
    if not isinstance(d, dict):
122
        raiseCLIError(TypeError('Cannot dict_print a non-dict object'))
123

    
124
    if d:
125
        margin = max(len(('%s' % key).strip()) for key in d.keys() if (
126
            key not in exclude))
127

    
128
    counter = 1
129
    for key, val in sorted(d.items()):
130
        key = '%s' % key
131
        if key in exclude:
132
            continue
133
        print_str = ''
134
        if with_enumeration:
135
            print_str = '%s. ' % counter
136
            counter += 1
137
        print_str = '%s%s' % (' ' * (ident - len(print_str)), print_str)
138
        print_str += key.strip()
139
        print_str += ' ' * (margin - len(key.strip()))
140
        print_str += ': '
141
        if isinstance(val, dict):
142
            print(print_str)
143
            print_dict(
144
                val,
145
                exclude=exclude,
146
                ident=margin + ident,
147
                with_enumeration=recursive_enumeration,
148
                recursive_enumeration=recursive_enumeration)
149
        elif isinstance(val, list):
150
            print(print_str)
151
            print_list(
152
                val,
153
                exclude=exclude,
154
                ident=margin + ident,
155
                with_enumeration=recursive_enumeration,
156
                recursive_enumeration=recursive_enumeration)
157
        else:
158
            print print_str + ' ' + ('%s' % val).strip()
159

    
160

    
161
def print_list(
162
        l, exclude=(), ident=0,
163
        with_enumeration=False, recursive_enumeration=False):
164
    """
165
    Pretty-print a list object
166

167
    :param l: (list) the input
168

169
    :param excelude: (object - anytype) values to exclude from printing
170

171
    :param ident: (int) initial indentation (recursive)
172

173
    :param with_enumeration: (bool) enumerate each 1st level value if true
174

175
    :recursive_enumeration: (bool) recursively enumerate dicts and lists of
176
        2nd level or deeper
177

178
    :raises CLIError: (TypeError wrapper) non-list input
179
    """
180
    if not isinstance(l, list):
181
        raiseCLIError(TypeError('Cannot list_print a non-list object'))
182

    
183
    if l:
184
        try:
185
            margin = max(len(('%s' % item).strip()) for item in l if not (
186
                isinstance(item, dict) or
187
                isinstance(item, list) or
188
                item in exclude))
189
        except ValueError:
190
            margin = (2 + len(('%s' % len(l)))) if enumerate else 1
191

    
192
    counter = 1
193
    prefix = ''
194
    for item in sorted(l):
195
        if item in exclude:
196
            continue
197
        elif with_enumeration:
198
            prefix = '%s. ' % counter
199
            counter += 1
200
            prefix = '%s%s' % (' ' * (ident - len(prefix)), prefix)
201
        else:
202
            prefix = ' ' * ident
203
        if isinstance(item, dict):
204
            if with_enumeration:
205
                print(prefix)
206
            print_dict(
207
                item,
208
                exclude=exclude,
209
                ident=margin + ident,
210
                with_enumeration=recursive_enumeration,
211
                recursive_enumeration=recursive_enumeration)
212
        elif isinstance(item, list):
213
            if with_enumeration:
214
                print(prefix)
215
            print_list(
216
                item,
217
                exclude=exclude,
218
                ident=margin + ident,
219
                with_enumeration=recursive_enumeration,
220
                recursive_enumeration=recursive_enumeration)
221
        else:
222
            print('%s%s' % (prefix, item))
223

    
224

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

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

    
245

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

253
    :param items: (list) items are lists or dict
254
    :param title: (tuple) keys to use their values as title
255
    :param with_enumeration: (boolean) enumerate items (order id on title)
256
    :param with_redundancy: (boolean) values in title also appear on body
257
    :param page_size: (int) show results in pages of page_size items, enter to
258
        continue
259
    """
260
    if not items:
261
        return
262
    try:
263
        page_size = int(page_size) if int(page_size) > 0 else len(items)
264
    except:
265
        page_size = len(items)
266
    num_of_pages = len(items) // page_size
267
    num_of_pages += 1 if len(items) % page_size else 0
268
    for i, item in enumerate(items):
269
        if with_enumeration:
270
            stdout.write('%s. ' % (i + 1))
271
        if isinstance(item, dict):
272
            title = sorted(set(title).intersection(item.keys()))
273
            if with_redundancy:
274
                header = ' '.join('%s' % item[key] for key in title)
275
            else:
276
                header = ' '.join('%s' % item.pop(key) for key in title)
277
            print(bold(header))
278
        if isinstance(item, dict):
279
            print_dict(item, ident=1)
280
        elif isinstance(item, list):
281
            print_list(item, ident=1)
282
        else:
283
            print(' %s' % item)
284
        page_hold(i + 1, page_size, len(items))
285

    
286

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

    
302

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

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

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

    
326

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

    
339

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

    
349
# Split input auxiliary
350

    
351

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

    
356

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

    
366

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

    
378

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

    
390

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

    
412

    
413
def ask_user(msg, true_resp=['Y', 'y']):
414
    """Print msg and read user response
415

416
    :param true_resp: (tuple of chars)
417

418
    :returns: (bool) True if reponse in true responses, False otherwise
419
    """
420
    stdout.write('%s (%s or enter for yes):' % (msg, ', '.join(true_resp)))
421
    stdout.flush()
422
    user_response = stdin.readline()
423
    return user_response[0] in true_resp + ['\n']
424

    
425

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

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

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