Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils / __init__.py @ 90c22848

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:
75
            newstr = '%s%s' % (newstr, replacement)
76
            err_counter += 1
77
    if err_counter:
78
        log.warning('\t%s character%s failed to be encoded as %s' % (
79
            err_counter, 's' if err_counter > 1 else '', encoding))
80
    return newstr
81

    
82

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

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

    
104

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

    
114

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

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

    
134

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

    
149

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

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

    
160

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

    
171

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

175
    :param data: json-dumpable data
176

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

    
182

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

192
    :param d: (dict)
193

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

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

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

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

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

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

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

    
230

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

240
    :param l: (list)
241

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

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

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

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

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

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

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

    
285

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

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

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

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

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

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

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

    
324

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

    
345

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

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

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

    
372

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

    
385

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

    
395
# Split input auxiliary
396

    
397

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

    
402

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

    
412

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

    
435

    
436
def ask_user(msg, true_resp=('y', ), out=stdout, user_in=stdin):
437
    """Print msg and read user response
438

439
    :param true_resp: (tuple of chars)
440

441
    :returns: (bool) True if reponse in true responses, False otherwise
442
    """
443
    yep = ', '.join(true_resp)
444
    nope = '<not %s>' % yep if 'n' in true_resp or 'N' in true_resp else 'N'
445
    out.write('%s [%s/%s]: ' % (msg, yep, nope))
446
    user_response = user_in.readline()
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