Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils / __init__.py @ 36fa6ffb

History | View | Annotate | Download (16.1 kB)

1
# Copyright 2011-2014 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, stderr
35
from re import compile as regex_compile
36
from os import walk, path
37
from json import dumps
38
from kamaki.cli.logger import get_logger
39
from locale import getpreferredencoding
40

    
41
from kamaki.cli.errors import raiseCLIError
42

    
43

    
44
INDENT_TAB = 4
45
log = get_logger(__name__)
46
pref_enc = getpreferredencoding()
47

    
48

    
49
suggest = dict(ansicolors=dict(
50
        active=False,
51
        url='#install-ansicolors',
52
        description='Add colors to console responses'))
53

    
54
try:
55
    from colors import magenta, red, yellow, bold
56
except ImportError:
57
    def dummy(val):
58
        return val
59
    red = yellow = magenta = bold = dummy
60
    suggest['ansicolors']['active'] = True
61

    
62

    
63
def _encode_nicely(somestr, encoding, replacement='?'):
64
    """Encode somestr as 'encoding', but don't raise errors (replace with ?)
65
        This method is slow. Us it only for grace.
66
        :param encoding: (str) encode every character in this encoding
67
        :param replacement: (char) replace each char raising encode-decode errs
68
    """
69
    newstr, err_counter = '', 0
70
    for c in somestr:
71
        try:
72
            newc = c.decode('utf-8').encode(encoding)
73
            newstr = '%s%s' % (newstr, newc)
74
        except UnicodeError as e:
75
            newstr = '%s%s' % (newstr, replacement)
76
            err_counter += 1
77
    if err_counter:
78
        log.warning('WARNING: \t%s character%s failed to be encoded as %s' % (
79
            err_counter, 's' if err_counter > 1 else '', encoding))
80
        log.debug('Unicode Error %s' % e)
81
    return newstr
82

    
83

    
84
def DontRaiseUnicodeError(foo):
85
    if pref_enc.lower() == 'utf-8':
86
        return foo
87

    
88
    def wrap(self, *args, **kwargs):
89
        try:
90
            s = kwargs.pop('s')
91
        except KeyError:
92
            try:
93
                s = args[0]
94
            except IndexError:
95
                return foo(self, *args, **kwargs)
96
            args = args[1:]
97
        try:
98
            s = (u'%s' % s).decode('utf-8').encode(pref_enc)
99
        except UnicodeError as ue:
100
            log.debug('Encoding(%s): %s' % (pref_enc, ue))
101
            s = _encode_nicely(u'%s' % s, pref_enc, replacement='?')
102
        return foo(self, s, *args, **kwargs)
103
    return wrap
104

    
105

    
106
def encode_for_console(s, encoding=pref_enc, replacement='?'):
107
    if encoding.lower() == 'utf-8':
108
        return s
109
    try:
110
        return s.decode('utf-8').encode(encoding)
111
    except UnicodeError as ue:
112
        log.debug('Encoding(%s): %s' % (encoding, ue))
113
        return _encode_nicely(s, encoding, replacement)
114

    
115

    
116
def suggest_missing(miss=None, exclude=[]):
117
    global suggest
118
    sgs = dict(suggest)
119
    for exc in exclude:
120
        try:
121
            sgs.pop(exc)
122
        except KeyError:
123
            pass
124
    kamaki_docs = 'http://www.synnefo.org/docs/kamaki/latest'
125

    
126
    for k, v in (miss, sgs[miss]) if miss else sgs.items():
127
        if v['active'] and stderr.isatty():
128
            stderr.write('Suggestion: you may like to install %s\n' % k)
129
            stderr.write('\t%s\n' % encode_for_console(v['description']))
130
            stderr.write('\tIt is easy, here are the instructions:\n')
131
            stderr.write('\t%s/installation.html%s\n' % (
132
                kamaki_docs, v['url']))
133
            stderr.flush()
134

    
135

    
136
def guess_mime_type(
137
        filename,
138
        default_content_type='application/octet-stream',
139
        default_encoding=None):
140
    assert filename, 'Cannot guess mimetype for empty filename'
141
    try:
142
        from mimetypes import guess_type
143
        ctype, cenc = guess_type(filename)
144
        return ctype or default_content_type, cenc or default_encoding
145
    except ImportError:
146
        stderr.write('WARNING: Cannot import mimetypes, using defaults\n')
147
        stderr.flush()
148
        return (default_content_type, default_encoding)
149

    
150

    
151
def remove_colors():
152
    global bold
153
    global red
154
    global yellow
155
    global magenta
156

    
157
    def dummy(val):
158
        return val
159
    red = yellow = magenta = bold = dummy
160

    
161

    
162
def pretty_keys(d, delim='_', recursive=False):
163
    """<term>delim<term> to <term> <term> transformation"""
164
    new_d = dict(d)
165
    for k, v in d.items():
166
        new_v = new_d.pop(k)
167
        new_d[k.replace(delim, ' ').strip()] = pretty_keys(
168
            new_v, delim, True) if (
169
                recursive and isinstance(v, dict)) else new_v
170
    return new_d
171

    
172

    
173
def print_json(data, out=stdout, encoding=pref_enc):
174
    """Print a list or dict as json in console
175

176
    :param data: json-dumpable data
177

178
    :param out: Input/Output stream to dump values into
179
    """
180
    out.write(dumps(data, indent=INDENT_TAB))
181
    out.write('\n')
182

    
183

    
184
def print_dict(
185
        d,
186
        exclude=(), indent=0,
187
        with_enumeration=False, recursive_enumeration=False, out=stdout):
188
    """Pretty-print a dictionary object
189
    <indent>key: <non iterable item>
190
    <indent>key:
191
    <indent + INDENT_TAB><pretty-print iterable>
192

193
    :param d: (dict)
194

195
    :param exclude: (iterable of strings) keys to exclude from printing
196

197
    :param indent: (int) initial indentation (recursive)
198

199
    :param with_enumeration: (bool) enumerate 1st-level keys
200

201
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
202
        not enumerate 1st level keys)
203

204
    :param out: Input/Output stream to dump values into
205

206
    :raises CLIError: if preconditions fail
207
    """
208
    assert isinstance(d, dict), 'print_dict input must be a dict'
209
    assert indent >= 0, 'print_dict indent must be >= 0'
210

    
211
    for i, (k, v) in enumerate(d.items()):
212
        k = ('%s' % k).strip()
213
        if k in exclude:
214
            continue
215
        print_str = ' ' * indent
216
        print_str += '%s.' % (i + 1) if with_enumeration else ''
217
        print_str += '%s:' % k
218
        if isinstance(v, dict):
219
            out.write(print_str + '\n')
220
            print_dict(
221
                v, exclude, indent + INDENT_TAB,
222
                recursive_enumeration, recursive_enumeration, out)
223
        elif isinstance(v, list) or isinstance(v, tuple):
224
            out.write(print_str + '\n')
225
            print_list(
226
                v, exclude, indent + INDENT_TAB,
227
                recursive_enumeration, recursive_enumeration, out)
228
        else:
229
            out.write('%s %s\n' % (print_str, v))
230

    
231

    
232
def print_list(
233
        l,
234
        exclude=(), indent=0,
235
        with_enumeration=False, recursive_enumeration=False, out=stdout):
236
    """Pretty-print a list of items
237
    <indent>key: <non iterable item>
238
    <indent>key:
239
    <indent + INDENT_TAB><pretty-print iterable>
240

241
    :param l: (list)
242

243
    :param exclude: (iterable of strings) items to exclude from printing
244

245
    :param indent: (int) initial indentation (recursive)
246

247
    :param with_enumeration: (bool) enumerate 1st-level items
248

249
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
250
        not enumerate 1st level keys)
251

252
    :param out: Input/Output stream to dump values into
253

254
    :raises CLIError: if preconditions fail
255
    """
256
    assert isinstance(l, list) or isinstance(l, tuple), (
257
        'print_list prinbts a list or tuple')
258
    assert indent >= 0, 'print_list indent must be >= 0'
259

    
260
    for i, item in enumerate(l):
261
        print_str = ' ' * indent
262
        print_str += '%s.' % (i + 1) if with_enumeration else ''
263
        if isinstance(item, dict):
264
            if with_enumeration:
265
                out.write(print_str + '\n')
266
            elif i and i < len(l):
267
                out.write('\n')
268
            print_dict(
269
                item, exclude,
270
                indent + (INDENT_TAB if with_enumeration else 0),
271
                recursive_enumeration, recursive_enumeration, out)
272
        elif isinstance(item, list) or isinstance(item, tuple):
273
            if with_enumeration:
274
                out.write(print_str + '\n')
275
            elif i and i < len(l):
276
                out.write('\n')
277
            print_list(
278
                item, exclude, indent + INDENT_TAB,
279
                recursive_enumeration, recursive_enumeration, out)
280
        else:
281
            item = ('%s' % item).strip()
282
            if item in exclude:
283
                continue
284
            out.write('%s%s\n' % (print_str, item))
285

    
286

    
287
def print_items(
288
        items, title=('id', 'name'),
289
        with_enumeration=False, with_redundancy=False, out=stdout):
290
    """print dict or list items in a list, using some values as title
291
    Objects of next level don't inherit enumeration (default: off) or titles
292

293
    :param items: (list) items are lists or dict
294

295
    :param title: (tuple) keys to use their values as title
296

297
    :param with_enumeration: (boolean) enumerate items (order id on title)
298

299
    :param with_redundancy: (boolean) values in title also appear on body
300

301
    :param out: Input/Output stream to dump values into
302
    """
303
    if not items:
304
        return
305
    if not (isinstance(items, dict) or isinstance(items, list) or isinstance(
306
                items, tuple)):
307
        out.write('%s\n' % items)
308
        return
309

    
310
    for i, item in enumerate(items):
311
        if with_enumeration:
312
            out.write('%s. ' % (i + 1))
313
        if isinstance(item, dict):
314
            item = dict(item)
315
            title = sorted(set(title).intersection(item))
316
            pick = item.get if with_redundancy else item.pop
317
            header = ' '.join('%s' % pick(key) for key in title)
318
            out.write((unicode(bold(header) if header else '') + '\n'))
319
            print_dict(item, indent=INDENT_TAB, out=out)
320
        elif isinstance(item, list) or isinstance(item, tuple):
321
            print_list(item, indent=INDENT_TAB, out=out)
322
        else:
323
            out.write(' %s\n' % item)
324

    
325

    
326
def format_size(size, decimal_factors=False):
327
    units = ('B', 'KB', 'MB', 'GB', 'TB') if decimal_factors else (
328
        'B', 'KiB', 'MiB', 'GiB', 'TiB')
329
    step = 1000 if decimal_factors else 1024
330
    fstep = float(step)
331
    try:
332
        size = float(size)
333
    except (ValueError, TypeError) as err:
334
        raiseCLIError(err, 'Cannot format %s in bytes' % (
335
            ','.join(size) if isinstance(size, tuple) else size))
336
    for i, unit in enumerate(units):
337
        if size < step or i + 1 == len(units):
338
            break
339
        size /= fstep
340
    s = ('%.2f' % size)
341
    s = s.replace('%s' % step, '%s.99' % (step - 1)) if size <= fstep else s
342
    while '.' in s and s[-1] in ('0', '.'):
343
        s = s[:-1]
344
    return s + unit
345

    
346

    
347
def to_bytes(size, format):
348
    """
349
    :param size: (float) the size in the given format
350
    :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
351

352
    :returns: (int) the size in bytes
353
    :raises ValueError: if invalid size or format
354
    :raises AttributeError: if format is not str
355
    :raises TypeError: if size is not arithmetic or convertible to arithmetic
356
    """
357
    format = format.upper()
358
    if format == 'B':
359
        return int(size)
360
    size = float(size)
361
    units_dc = ('KB', 'MB', 'GB', 'TB')
362
    units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
363

    
364
    factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
365
    if not factor:
366
        raise ValueError('Invalid data size format %s' % format)
367
    for prefix in ('K', 'M', 'G', 'T'):
368
        size *= factor
369
        if format.startswith(prefix):
370
            break
371
    return int(size)
372

    
373

    
374
def dict2file(d, f, depth=0):
375
    for k, v in d.items():
376
        f.write('%s%s: ' % (' ' * INDENT_TAB * depth, k))
377
        if isinstance(v, dict):
378
            f.write('\n')
379
            dict2file(v, f, depth + 1)
380
        elif isinstance(v, list) or isinstance(v, tuple):
381
            f.write('\n')
382
            list2file(v, f, depth + 1)
383
        else:
384
            f.write('%s\n' % v)
385

    
386

    
387
def list2file(l, f, depth=1):
388
    for item in l:
389
        if isinstance(item, dict):
390
            dict2file(item, f, depth + 1)
391
        elif isinstance(item, list) or isinstance(item, tuple):
392
            list2file(item, f, depth + 1)
393
        else:
394
            f.write('%s%s\n' % (' ' * INDENT_TAB * depth, item))
395

    
396
# Split input auxiliary
397

    
398

    
399
def _parse_with_regex(line, regex):
400
    re_parser = regex_compile(regex)
401
    return (re_parser.split(line), re_parser.findall(line))
402

    
403

    
404
def _get_from_parsed(parsed_str):
405
    try:
406
        parsed_str = parsed_str.strip()
407
    except:
408
        return None
409
    return ([parsed_str[1:-1]] if (
410
        parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"')) else (
411
            parsed_str.split(' '))) if parsed_str else None
412

    
413

    
414
def split_input(line):
415
    if not line:
416
        return []
417
    reg_expr = '\'.*?\'|".*?"|^[\S]*$'
418
    (trivial_parts, interesting_parts) = _parse_with_regex(line, reg_expr)
419
    assert(len(trivial_parts) == 1 + len(interesting_parts))
420
    terms = []
421
    for i, tpart in enumerate(trivial_parts):
422
        part = _get_from_parsed(tpart)
423
        if part:
424
            terms += part
425
        try:
426
            part = _get_from_parsed(interesting_parts[i])
427
        except IndexError:
428
            break
429
        if part:
430
            if tpart and not tpart[-1].endswith(' '):
431
                terms[-1] += ' '.join(part)
432
            else:
433
                terms += part
434
    return terms
435

    
436

    
437
def ask_user(msg, true_resp=('y', ), **kwargs):
438
    """Print msg and read user response
439

440
    :param true_resp: (tuple of chars)
441

442
    :returns: (bool) True if reponse in true responses, False otherwise
443
    """
444
    yep = ', '.join(true_resp)
445
    nope = '<not %s>' % yep if 'n' in true_resp or 'N' in true_resp else 'N'
446
    user_response = raw_input('%s [%s/%s]: ' % (msg, yep, nope))
447
    return user_response[0].lower() in [s.lower() for s in true_resp]
448

    
449

    
450
def get_path_size(testpath):
451
    if path.isfile(testpath):
452
        return path.getsize(testpath)
453
    total_size = 0
454
    for top, dirs, files in walk(path.abspath(testpath)):
455
        for f in files:
456
            f = path.join(top, f)
457
            if path.isfile(f):
458
                total_size += path.getsize(f)
459
    return total_size
460

    
461

    
462
def remove_from_items(list_of_dicts, key_to_remove):
463
    for item in list_of_dicts:
464
        assert isinstance(item, dict), 'Item %s not a dict' % item
465
        item.pop(key_to_remove, None)
466

    
467

    
468
def filter_dicts_by_dict(
469
    list_of_dicts, filters,
470
    exact_match=True, case_sensitive=False):
471
    """
472
    :param list_of_dicts: (list) each dict contains "raw" key-value pairs
473

474
    :param filters: (dict) filters in key-value form
475

476
    :param exact_match: (bool) if false, check if the filter value is part of
477
        the actual value
478

479
    :param case_sensitive: (bool) refers to values only (not keys)
480

481
    :returns: (list) only the dicts that match all filters
482
    """
483
    new_dicts = []
484
    for d in list_of_dicts:
485
        if set(filters).difference(d):
486
            continue
487
        match = True
488
        for k, v in filters.items():
489
            dv, v = ('%s' % d[k]), ('%s' % v)
490
            if not case_sensitive:
491
                dv, v = dv.lower(), v.lower()
492
            if not ((
493
                    exact_match and v == dv) or (
494
                    (not exact_match) and v in dv)):
495
                match = False
496
                break
497
        if match:
498
            new_dicts.append(d)
499
    return new_dicts