Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils.py @ 24ff0a35

History | View | Annotate | Download (13.5 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
try:
41
    from colors import magenta, red, yellow, bold
42
except ImportError:
43
    # No colours? No worries, use dummy foo instead
44
    def dummy(val):
45
        return val
46
    red = yellow = magenta = bold = dummy
47

    
48

    
49
def remove_colors():
50
    global bold
51
    global red
52
    global yellow
53
    global magenta
54

    
55
    def dummy(val):
56
        return val
57
    red = yellow = magenta = bold = dummy
58

    
59

    
60
def pretty_keys(d, delim='_', recurcive=False):
61
    """<term>delim<term> to <term> <term> transformation
62
    """
63
    new_d = {}
64
    for key, val in d.items():
65
        new_key = key.split(delim)[-1]
66
        if recurcive and isinstance(val, dict):
67
            new_val = pretty_keys(val, delim, recurcive)
68
        else:
69
            new_val = val
70
        new_d[new_key] = new_val
71
    return new_d
72

    
73

    
74
def print_dict(
75
        d, exclude=(), ident=0,
76
        with_enumeration=False, recursive_enumeration=False):
77
    """
78
    Pretty-print a dictionary object
79

80
    :param d: (dict) the input
81

82
    :param excelude: (set or list) keys to exclude from printing
83

84
    :param ident: (int) initial indentation (recursive)
85

86
    :param with_enumeration: (bool) enumerate each 1st level key if true
87

88
    :recursive_enumeration: (bool) recursively enumerate dicts and lists of
89
        2nd level or deeper
90

91
    :raises CLIError: (TypeError wrapper) non-dict input
92
    """
93
    if not isinstance(d, dict):
94
        raiseCLIError(TypeError('Cannot dict_print a non-dict object'))
95

    
96
    if d:
97
        margin = max(len(('%s' % key).strip()) for key in d.keys() if (
98
            key not in exclude))
99

    
100
    counter = 1
101
    for key, val in sorted(d.items()):
102
        if key in exclude:
103
            continue
104
        print_str = ''
105
        if with_enumeration:
106
            print_str = '%s. ' % counter
107
            counter += 1
108
        print_str = '%s%s' % (' ' * (ident - len(print_str)), print_str)
109
        print_str += ('%s' % key).strip()
110
        print_str += ' ' * (margin - len(unicode(key).strip()))
111
        print_str += ': '
112
        if isinstance(val, dict):
113
            print(print_str)
114
            print_dict(
115
                val,
116
                exclude=exclude,
117
                ident=margin + ident,
118
                with_enumeration=recursive_enumeration,
119
                recursive_enumeration=recursive_enumeration)
120
        elif isinstance(val, list):
121
            print(print_str)
122
            print_list(
123
                val,
124
                exclude=exclude,
125
                ident=margin + ident,
126
                with_enumeration=recursive_enumeration,
127
                recursive_enumeration=recursive_enumeration)
128
        else:
129
            print print_str + ' ' + unicode(val).strip()
130

    
131

    
132
def print_list(
133
        l, exclude=(), ident=0,
134
        with_enumeration=False, recursive_enumeration=False):
135
    """
136
    Pretty-print a list object
137

138
    :param l: (list) the input
139

140
    :param excelude: (object - anytype) values to exclude from printing
141

142
    :param ident: (int) initial indentation (recursive)
143

144
    :param with_enumeration: (bool) enumerate each 1st level value if true
145

146
    :recursive_enumeration: (bool) recursively enumerate dicts and lists of
147
        2nd level or deeper
148

149
    :raises CLIError: (TypeError wrapper) non-list input
150
    """
151
    if not isinstance(l, list):
152
        raiseCLIError(TypeError('Cannot list_print a non-list object'))
153

    
154
    if l:
155
        try:
156
            margin = max(len(('%s' % item).strip()) for item in l if not (
157
                isinstance(item, dict) or
158
                isinstance(item, list) or
159
                item in exclude))
160
        except ValueError:
161
            margin = (2 + len(unicode(len(l)))) if enumerate else 1
162

    
163
    counter = 1
164
    prefix = ''
165
    for item in sorted(l):
166
        if item in exclude:
167
            continue
168
        elif with_enumeration:
169
            prefix = '%s. ' % counter
170
            counter += 1
171
            prefix = '%s%s' % (' ' * (ident - len(prefix)), prefix)
172
        else:
173
            prefix = ' ' * ident
174
        if isinstance(item, dict):
175
            if with_enumeration:
176
                print(prefix)
177
            print_dict(
178
                item,
179
                exclude=exclude,
180
                ident=margin + ident,
181
                with_enumeration=recursive_enumeration,
182
                recursive_enumeration=recursive_enumeration)
183
        elif isinstance(item, list):
184
            if with_enumeration:
185
                print(prefix)
186
            print_list(
187
                item,
188
                exclude=exclude,
189
                ident=margin + ident,
190
                with_enumeration=recursive_enumeration,
191
                recursive_enumeration=recursive_enumeration)
192
        else:
193
            print('%s%s' % (prefix, item))
194

    
195

    
196
def page_hold(index, limit, maxlen):
197
    """Check if there are results to show, and hold the page when needed
198
    :param index: (int) > 0
199
    :param limit: (int) 0 < limit <= max, page hold if limit mod index == 0
200
    :param maxlen: (int) Don't hold if index reaches maxlen
201

202
    :returns: True if there are more to show, False if all results are shown
203
    """
204
    if index >= limit and index % limit == 0:
205
        if index >= maxlen:
206
            return False
207
        else:
208
            print('(%s listed - %s more - "enter" to continue)' % (
209
                index,
210
                maxlen - index))
211
            c = ' '
212
            while c != '\n':
213
                c = stdin.read(1)
214
    return True
215

    
216

    
217
def print_items(
218
        items, title=('id', 'name'),
219
        with_enumeration=False, with_redundancy=False,
220
        page_size=0):
221
    """print dict or list items in a list, using some values as title
222
    Objects of next level don't inherit enumeration (default: off) or titles
223

224
    :param items: (list) items are lists or dict
225
    :param title: (tuple) keys to use their values as title
226
    :param with_enumeration: (boolean) enumerate items (order id on title)
227
    :param with_redundancy: (boolean) values in title also appear on body
228
    :param page_size: (int) show results in pages of page_size items, enter to
229
        continue
230
    """
231
    if not items:
232
        return
233
    try:
234
        page_size = int(page_size) if int(page_size) > 0 else len(items)
235
    except:
236
        page_size = len(items)
237
    num_of_pages = len(items) // page_size
238
    num_of_pages += 1 if len(items) % page_size else 0
239
    for i, item in enumerate(items):
240
        if with_enumeration:
241
            stdout.write('%s. ' % (i + 1))
242
        if isinstance(item, dict):
243
            title = sorted(set(title).intersection(item.keys()))
244
            if with_redundancy:
245
                header = ' '.join(unicode(item[key]) for key in title)
246
            else:
247
                header = ' '.join(unicode(item.pop(key)) for key in title)
248
            print(bold(header))
249
        if isinstance(item, dict):
250
            print_dict(item, ident=1)
251
        elif isinstance(item, list):
252
            print_list(item, ident=1)
253
        else:
254
            print(' %s' % item)
255
        page_hold(i + 1, page_size, len(items))
256

    
257

    
258
def format_size(size):
259
    units = ('B', 'KiB', 'MiB', 'GiB', 'TiB')
260
    try:
261
        size = float(size)
262
    except ValueError as err:
263
        raiseCLIError(err, 'Cannot format %s in bytes' % size)
264
    for unit in units:
265
        if size < 1024:
266
            break
267
        size /= 1024.0
268
    s = ('%.2f' % size)
269
    while '.' in s and s[-1] in ('0', '.'):
270
        s = s[:-1]
271
    return s + unit
272

    
273

    
274
def to_bytes(size, format):
275
    """
276
    :param size: (float) the size in the given format
277
    :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
278

279
    :returns: (int) the size in bytes
280
    """
281
    format = format.upper()
282
    if format == 'B':
283
        return int(size)
284
    size = float(size)
285
    units_dc = ('KB', 'MB', 'GB', 'TB')
286
    units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
287

    
288
    factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
289
    if not factor:
290
        raise ValueError('Invalid data size format %s' % format)
291
    for prefix in ('K', 'M', 'G', 'T'):
292
        size *= factor
293
        if format.startswith(prefix):
294
            break
295
    return int(size)
296

    
297

    
298
def dict2file(d, f, depth=0):
299
    for k, v in d.items():
300
        f.write('%s%s: ' % ('\t' * depth, k))
301
        if isinstance(v, dict):
302
            f.write('\n')
303
            dict2file(v, f, depth + 1)
304
        elif isinstance(v, list):
305
            f.write('\n')
306
            list2file(v, f, depth + 1)
307
        else:
308
            f.write(' %s\n' % unicode(v))
309

    
310

    
311
def list2file(l, f, depth=1):
312
    for item in l:
313
        if isinstance(item, dict):
314
            dict2file(item, f, depth + 1)
315
        elif isinstance(item, list):
316
            list2file(item, f, depth + 1)
317
        else:
318
            f.write('%s%s\n' % ('\t' * depth, unicode(item)))
319

    
320
# Split input auxiliary
321

    
322

    
323
def _parse_with_regex(line, regex):
324
    re_parser = regex_compile(regex)
325
    return (re_parser.split(line), re_parser.findall(line))
326

    
327

    
328
def _sub_split(line):
329
    terms = []
330
    (sub_trivials, sub_interesting) = _parse_with_regex(line, ' ".*?" ')
331
    for subi, subipart in enumerate(sub_interesting):
332
        terms += sub_trivials[subi].split()
333
        terms.append(subipart[2:-2])
334
    terms += sub_trivials[-1].split()
335
    return terms
336

    
337

    
338
def old_split_input(line):
339
    """Use regular expressions to split a line correctly"""
340
    line = ' %s ' % line
341
    (trivial_parts, interesting_parts) = _parse_with_regex(line, ' \'.*?\' ')
342
    terms = []
343
    for i, ipart in enumerate(interesting_parts):
344
        terms += _sub_split(trivial_parts[i])
345
        terms.append(ipart[2:-2])
346
    terms += _sub_split(trivial_parts[-1])
347
    return terms
348

    
349

    
350
def _get_from_parsed(parsed_str):
351
    try:
352
        parsed_str = parsed_str.strip()
353
    except:
354
        return None
355
    if parsed_str:
356
        if parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"'):
357
            return [parsed_str[1:-1]]
358
        return parsed_str.split(' ')
359
    return None
360

    
361

    
362
def split_input(line):
363
    if not line:
364
        return []
365
    reg_expr = '\'.*?\'|".*?"|^[\S]*$'
366
    (trivial_parts, interesting_parts) = _parse_with_regex(line, reg_expr)
367
    assert(len(trivial_parts) == 1 + len(interesting_parts))
368
    #print('  [split_input] trivial_parts %s are' % trivial_parts)
369
    #print('  [split_input] interesting_parts %s are' % interesting_parts)
370
    terms = []
371
    for i, tpart in enumerate(trivial_parts):
372
        part = _get_from_parsed(tpart)
373
        if part:
374
            terms += part
375
        try:
376
            part = _get_from_parsed(interesting_parts[i])
377
        except IndexError:
378
            break
379
        if part:
380
            terms += part
381
    return terms
382

    
383

    
384
def ask_user(msg, true_resp=['Y', 'y']):
385
    """Print msg and read user response
386

387
    :param true_resp: (tuple of chars)
388

389
    :returns: (bool) True if reponse in true responses, False otherwise
390
    """
391
    stdout.write('%s (%s or enter for yes):' % (msg, ', '.join(true_resp)))
392
    stdout.flush()
393
    user_response = stdin.readline()
394
    return user_response[0] in true_resp + ['\n']
395

    
396

    
397
def spiner(size=None):
398
    spins = ('/', '-', '\\', '|')
399
    stdout.write(' ')
400
    size = size or -1
401
    i = 0
402
    while size - i:
403
        stdout.write('\b%s' % spins[i % len(spins)])
404
        stdout.flush()
405
        i += 1
406
        sleep(0.1)
407
        yield
408

    
409
if __name__ == '__main__':
410
    examples = [
411
        'la_la le_le li_li',
412
        '\'la la\' \'le le\' \'li li\'',
413
        '\'la la\' le_le \'li li\'',
414
        'la_la \'le le\' li_li',
415
        'la_la \'le le\' \'li li\'',
416
        '"la la" "le le" "li li"',
417
        '"la la" le_le "li li"',
418
        'la_la "le le" li_li',
419
        '"la_la" "le le" "li li"',
420
        '\'la la\' "le le" \'li li\'',
421
        'la_la \'le le\' "li li"',
422
        'la_la \'le le\' li_li',
423
        '\'la la\' le_le "li li"',
424
        '"la la" le_le \'li li\'',
425
        '"la la" \'le le\' li_li',
426
        'la_la \'le\'le\' "li\'li"',
427
        '"la \'le le\' la"',
428
        '\'la "le le" la\'',
429
        '\'la "la" la\' "le \'le\' le" li_"li"_li',
430
        '\'\' \'L\' "" "A"']
431

    
432
    for i, example in enumerate(examples):
433
        print('%s. Split this: (%s)' % (i + 1, example))
434
        ret = old_split_input(example)
435
        print('\t(%s) of size %s' % (ret, len(ret)))