Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils / __init__.py @ fa9c0c38

History | View | Annotate | Download (14.2 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 os import walk, path
37
from json import dumps
38
from pydoc import pager
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 guess_mime_type(
79
        filename,
80
        default_content_type='application/octet-stream',
81
        default_encoding=None):
82
    assert filename, 'Cannot guess mimetype for empty filename'
83
    try:
84
        from mimetypes import guess_type
85
        ctype, cenc = guess_type(filename)
86
        return ctype or default_content_type, cenc or default_encoding
87
    except ImportError:
88
        print 'WARNING: Cannot import mimetypes, using defaults'
89
        return (default_content_type, default_encoding)
90

    
91

    
92
def remove_colors():
93
    global bold
94
    global red
95
    global yellow
96
    global magenta
97

    
98
    def dummy(val):
99
        return val
100
    red = yellow = magenta = bold = dummy
101

    
102

    
103
def pretty_keys(d, delim='_', recursive=False):
104
    """<term>delim<term> to <term> <term> transformation"""
105
    new_d = dict(d)
106
    for k, v in d.items():
107
        new_v = new_d.pop(k)
108
        new_d[k.replace(delim, ' ').strip()] = pretty_keys(
109
            new_v, delim, True) if (
110
                recursive and isinstance(v, dict)) else new_v
111
    return new_d
112

    
113

    
114
def print_json(data, out=stdout):
115
    """Print a list or dict as json in console
116

117
    :param data: json-dumpable data
118

119
    :param out: Input/Output stream to dump values into
120
    """
121
    out.writelines(unicode(dumps(data, indent=INDENT_TAB) + '\n'))
122

    
123

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

133
    :param d: (dict)
134

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

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

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

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

144
    :param out: Input/Output stream to dump values into
145

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

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

    
171

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

181
    :param l: (list)
182

183
    :param exclude: (iterable of strings) items to exclude from printing
184

185
    :param indent: (int) initial indentation (recursive)
186

187
    :param with_enumeration: (bool) enumerate 1st-level items
188

189
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
190
        not enumerate 1st level keys)
191

192
    :param out: Input/Output stream to dump values into
193

194
    :raises CLIError: if preconditions fail
195
    """
196
    assert isinstance(l, list) or isinstance(l, tuple), (
197
        'print_list prinbts a list or tuple')
198
    assert indent >= 0, 'print_list indent must be >= 0'
199

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

    
226

    
227
def print_items(
228
        items, title=('id', 'name'),
229
        with_enumeration=False, with_redundancy=False, out=stdout):
230
    """print dict or list items in a list, using some values as title
231
    Objects of next level don't inherit enumeration (default: off) or titles
232

233
    :param items: (list) items are lists or dict
234

235
    :param title: (tuple) keys to use their values as title
236

237
    :param with_enumeration: (boolean) enumerate items (order id on title)
238

239
    :param with_redundancy: (boolean) values in title also appear on body
240

241
    :param out: Input/Output stream to dump values into
242
    """
243
    if not items:
244
        return
245
    if not (isinstance(items, dict) or isinstance(items, list) or isinstance(
246
                items, tuple)):
247
        out.writelines(u'%s\n' % items)
248
        return
249

    
250
    for i, item in enumerate(items):
251
        if with_enumeration:
252
            out.write(u'%s. ' % (i + 1))
253
        if isinstance(item, dict):
254
            item = dict(item)
255
            title = sorted(set(title).intersection(item))
256
            pick = item.get if with_redundancy else item.pop
257
            header = u' '.join(u'%s' % pick(key) for key in title)
258
            out.writelines(unicode(bold(header) + '\n'))
259
            print_dict(item, indent=INDENT_TAB, out=out)
260
        elif isinstance(item, list) or isinstance(item, tuple):
261
            print_list(item, indent=INDENT_TAB, out=out)
262
        else:
263
            out.writelines(u' %s\n' % item)
264

    
265

    
266
def format_size(size, decimal_factors=False):
267
    units = ('B', 'KB', 'MB', 'GB', 'TB') if decimal_factors else (
268
        'B', 'KiB', 'MiB', 'GiB', 'TiB')
269
    step = 1000 if decimal_factors else 1024
270
    fstep = float(step)
271
    try:
272
        size = float(size)
273
    except (ValueError, TypeError) as err:
274
        raiseCLIError(err, 'Cannot format %s in bytes' % (
275
            ','.join(size) if isinstance(size, tuple) else size))
276
    for i, unit in enumerate(units):
277
        if size < step or i + 1 == len(units):
278
            break
279
        size /= fstep
280
    s = ('%.2f' % size)
281
    s = s.replace('%s' % step, '%s.99' % (step - 1)) if size <= fstep else s
282
    while '.' in s and s[-1] in ('0', '.'):
283
        s = s[:-1]
284
    return s + unit
285

    
286

    
287
def to_bytes(size, format):
288
    """
289
    :param size: (float) the size in the given format
290
    :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
291

292
    :returns: (int) the size in bytes
293
    :raises ValueError: if invalid size or format
294
    :raises AttributeError: if format is not str
295
    :raises TypeError: if size is not arithmetic or convertible to arithmetic
296
    """
297
    format = format.upper()
298
    if format == 'B':
299
        return int(size)
300
    size = float(size)
301
    units_dc = ('KB', 'MB', 'GB', 'TB')
302
    units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
303

    
304
    factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
305
    if not factor:
306
        raise ValueError('Invalid data size format %s' % format)
307
    for prefix in ('K', 'M', 'G', 'T'):
308
        size *= factor
309
        if format.startswith(prefix):
310
            break
311
    return int(size)
312

    
313

    
314
def dict2file(d, f, depth=0):
315
    for k, v in d.items():
316
        f.write('%s%s: ' % (' ' * INDENT_TAB * depth, k))
317
        if isinstance(v, dict):
318
            f.write('\n')
319
            dict2file(v, f, depth + 1)
320
        elif isinstance(v, list) or isinstance(v, tuple):
321
            f.write('\n')
322
            list2file(v, f, depth + 1)
323
        else:
324
            f.write('%s\n' % v)
325

    
326

    
327
def list2file(l, f, depth=1):
328
    for item in l:
329
        if isinstance(item, dict):
330
            dict2file(item, f, depth + 1)
331
        elif isinstance(item, list) or isinstance(item, tuple):
332
            list2file(item, f, depth + 1)
333
        else:
334
            f.write('%s%s\n' % (' ' * INDENT_TAB * depth, item))
335

    
336
# Split input auxiliary
337

    
338

    
339
def _parse_with_regex(line, regex):
340
    re_parser = regex_compile(regex)
341
    return (re_parser.split(line), re_parser.findall(line))
342

    
343

    
344
def _get_from_parsed(parsed_str):
345
    try:
346
        parsed_str = parsed_str.strip()
347
    except:
348
        return None
349
    return ([parsed_str[1:-1]] if (
350
        parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"')) else (
351
            parsed_str.split(' '))) if parsed_str else None
352

    
353

    
354
def split_input(line):
355
    if not line:
356
        return []
357
    reg_expr = '\'.*?\'|".*?"|^[\S]*$'
358
    (trivial_parts, interesting_parts) = _parse_with_regex(line, reg_expr)
359
    assert(len(trivial_parts) == 1 + len(interesting_parts))
360
    terms = []
361
    for i, tpart in enumerate(trivial_parts):
362
        part = _get_from_parsed(tpart)
363
        if part:
364
            terms += part
365
        try:
366
            part = _get_from_parsed(interesting_parts[i])
367
        except IndexError:
368
            break
369
        if part:
370
            if tpart and not tpart[-1].endswith(' '):
371
                terms[-1] += ' '.join(part)
372
            else:
373
                terms += part
374
    return terms
375

    
376

    
377
def ask_user(msg, true_resp=('y', ), out=stdout, user_in=stdin):
378
    """Print msg and read user response
379

380
    :param true_resp: (tuple of chars)
381

382
    :returns: (bool) True if reponse in true responses, False otherwise
383
    """
384
    yep = ', '.join(true_resp)
385
    nope = '<not %s>' % yep if 'n' in true_resp or 'N' in true_resp else 'N'
386
    out.write(u'%s [%s/%s]: ' % (msg, yep, nope))
387
    out.flush()
388
    user_response = user_in.readline()
389
    return user_response[0].lower() in [s.lower() for s in true_resp]
390

    
391

    
392
def get_path_size(testpath):
393
    if path.isfile(testpath):
394
        return path.getsize(testpath)
395
    total_size = 0
396
    for top, dirs, files in walk(path.abspath(testpath)):
397
        for f in files:
398
            f = path.join(top, f)
399
            if path.isfile(f):
400
                total_size += path.getsize(f)
401
    return total_size
402

    
403

    
404
def remove_from_items(list_of_dicts, key_to_remove):
405
    for item in list_of_dicts:
406
        assert isinstance(item, dict), 'Item %s not a dict' % item
407
        item.pop(key_to_remove, None)
408

    
409

    
410
def filter_dicts_by_dict(
411
    list_of_dicts, filters,
412
    exact_match=True, case_sensitive=False):
413
    """
414
    :param list_of_dicts: (list) each dict contains "raw" key-value pairs
415

416
    :param filters: (dict) filters in key-value form
417

418
    :param exact_match: (bool) if false, check if the filter value is part of
419
        the actual value
420

421
    :param case_sensitive: (bool) revers to values only (not keys)
422

423
    :returns: (list) only the dicts that match all filters
424
    """
425
    new_dicts = []
426
    for d in list_of_dicts:
427
        if set(filters).difference(d):
428
            continue
429
        match = True
430
        for k, v in filters.items():
431
            dv, v = ('%s' % d[k]), ('%s' % v)
432
            if not case_sensitive:
433
                dv, v = dv.lower(), v.lower()
434
            if not ((
435
                    exact_match and v == dv) or (
436
                    (not exact_match) and v in dv)):
437
                match = False
438
                break
439
        if match:
440
            new_dicts.append(d)
441
    return new_dicts