Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / utils / __init__.py @ 026e10fc

History | View | Annotate | Download (14.3 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 suggest_missing(miss=None, exclude=[]):
64
    global suggest
65
    sgs = dict(suggest)
66
    for exc in exclude:
67
        try:
68
            sgs.pop(exc)
69
        except KeyError:
70
            pass
71
    kamaki_docs = 'http://www.synnefo.org/docs/kamaki/latest'
72

    
73
    for k, v in (miss, sgs[miss]) if miss else sgs.items():
74
        if v['active'] and stderr.isatty():
75
            stderr.write('Suggestion: you may like to install %s\n' % k)
76
            stderr.write(
77
                ('%s\n' % v['description']).encode(pref_enc, errors='replace'))
78
            stderr.write('\tIt is easy, here are the instructions:\n')
79
            stderr.write('\t%s/installation.html%s\n' % (
80
                kamaki_docs, v['url']))
81
            stderr.flush()
82

    
83

    
84
def guess_mime_type(
85
        filename,
86
        default_content_type='application/octet-stream',
87
        default_encoding=None):
88
    assert filename, 'Cannot guess mimetype for empty filename'
89
    try:
90
        from mimetypes import guess_type
91
        ctype, cenc = guess_type(filename)
92
        return ctype or default_content_type, cenc or default_encoding
93
    except ImportError:
94
        stderr.write('WARNING: Cannot import mimetypes, using defaults\n')
95
        stderr.flush()
96
        return (default_content_type, default_encoding)
97

    
98

    
99
def remove_colors():
100
    global bold
101
    global red
102
    global yellow
103
    global magenta
104

    
105
    def dummy(val):
106
        return val
107
    red = yellow = magenta = bold = dummy
108

    
109

    
110
def pretty_keys(d, delim='_', recursive=False):
111
    """<term>delim<term> to <term> <term> transformation"""
112
    new_d = dict(d)
113
    for k, v in d.items():
114
        new_v = new_d.pop(k)
115
        new_d[k.replace(delim, ' ').strip()] = pretty_keys(
116
            new_v, delim, True) if (
117
                recursive and isinstance(v, dict)) else new_v
118
    return new_d
119

    
120

    
121
def print_json(data, out=stdout):
122
    """Print a list or dict as json in console
123

124
    :param data: json-dumpable data
125

126
    :param out: Input/Output stream to dump values into
127
    """
128
    out.write(dumps(data, indent=INDENT_TAB))
129
    out.write('\n')
130

    
131

    
132
def print_dict(
133
        d,
134
        exclude=(), indent=0,
135
        with_enumeration=False, recursive_enumeration=False, out=stdout):
136
    """Pretty-print a dictionary object
137
    <indent>key: <non iterable item>
138
    <indent>key:
139
    <indent + INDENT_TAB><pretty-print iterable>
140

141
    :param d: (dict)
142

143
    :param exclude: (iterable of strings) keys to exclude from printing
144

145
    :param indent: (int) initial indentation (recursive)
146

147
    :param with_enumeration: (bool) enumerate 1st-level keys
148

149
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
150
        not enumerate 1st level keys)
151

152
    :param out: Input/Output stream to dump values into
153

154
    :raises CLIError: if preconditions fail
155
    """
156
    assert isinstance(d, dict), 'print_dict input must be a dict'
157
    assert indent >= 0, 'print_dict indent must be >= 0'
158

    
159
    for i, (k, v) in enumerate(d.items()):
160
        k = ('%s' % k).strip()
161
        if k in exclude:
162
            continue
163
        print_str = ' ' * indent
164
        print_str += '%s.' % (i + 1) if with_enumeration else ''
165
        print_str += '%s:' % k
166
        if isinstance(v, dict):
167
            out.write(print_str + '\n')
168
            print_dict(
169
                v, exclude, indent + INDENT_TAB,
170
                recursive_enumeration, recursive_enumeration, out)
171
        elif isinstance(v, list) or isinstance(v, tuple):
172
            out.write(print_str + '\n')
173
            print_list(
174
                v, exclude, indent + INDENT_TAB,
175
                recursive_enumeration, recursive_enumeration, out)
176
        else:
177
            out.write('%s %s\n' % (print_str, v))
178

    
179

    
180
def print_list(
181
        l,
182
        exclude=(), indent=0,
183
        with_enumeration=False, recursive_enumeration=False, out=stdout):
184
    """Pretty-print a list of items
185
    <indent>key: <non iterable item>
186
    <indent>key:
187
    <indent + INDENT_TAB><pretty-print iterable>
188

189
    :param l: (list)
190

191
    :param exclude: (iterable of strings) items to exclude from printing
192

193
    :param indent: (int) initial indentation (recursive)
194

195
    :param with_enumeration: (bool) enumerate 1st-level items
196

197
    :param recursive_enumeration: (bool) recursively enumerate iterables (does
198
        not enumerate 1st level keys)
199

200
    :param out: Input/Output stream to dump values into
201

202
    :raises CLIError: if preconditions fail
203
    """
204
    assert isinstance(l, list) or isinstance(l, tuple), (
205
        'print_list prinbts a list or tuple')
206
    assert indent >= 0, 'print_list indent must be >= 0'
207

    
208
    for i, item in enumerate(l):
209
        print_str = ' ' * indent
210
        print_str += '%s.' % (i + 1) if with_enumeration else ''
211
        if isinstance(item, dict):
212
            if with_enumeration:
213
                out.write(print_str + '\n')
214
            elif i and i < len(l):
215
                out.write('\n')
216
            print_dict(
217
                item, exclude,
218
                indent + (INDENT_TAB if with_enumeration else 0),
219
                recursive_enumeration, recursive_enumeration, out)
220
        elif isinstance(item, list) or isinstance(item, tuple):
221
            if with_enumeration:
222
                out.write(print_str + '\n')
223
            elif i and i < len(l):
224
                out.write('\n')
225
            print_list(
226
                item, exclude, indent + INDENT_TAB,
227
                recursive_enumeration, recursive_enumeration, out)
228
        else:
229
            item = ('%s' % item).strip()
230
            if item in exclude:
231
                continue
232
            out.write('%s%s\n' % (print_str, item))
233

    
234

    
235
def print_items(
236
        items, title=('id', 'name'),
237
        with_enumeration=False, with_redundancy=False, out=stdout):
238
    """print dict or list items in a list, using some values as title
239
    Objects of next level don't inherit enumeration (default: off) or titles
240

241
    :param items: (list) items are lists or dict
242

243
    :param title: (tuple) keys to use their values as title
244

245
    :param with_enumeration: (boolean) enumerate items (order id on title)
246

247
    :param with_redundancy: (boolean) values in title also appear on body
248

249
    :param out: Input/Output stream to dump values into
250
    """
251
    if not items:
252
        return
253
    if not (isinstance(items, dict) or isinstance(items, list) or isinstance(
254
                items, tuple)):
255
        out.write('%s\n' % items)
256
        return
257

    
258
    for i, item in enumerate(items):
259
        if with_enumeration:
260
            out.write('%s. ' % (i + 1))
261
        if isinstance(item, dict):
262
            item = dict(item)
263
            title = sorted(set(title).intersection(item))
264
            pick = item.get if with_redundancy else item.pop
265
            header = ' '.join('%s' % pick(key) for key in title)
266
            out.write((unicode(bold(header) if header else '') + '\n'))
267
            print_dict(item, indent=INDENT_TAB, out=out)
268
        elif isinstance(item, list) or isinstance(item, tuple):
269
            print_list(item, indent=INDENT_TAB, out=out)
270
        else:
271
            out.write(' %s\n' % item)
272

    
273

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

    
294

    
295
def to_bytes(size, format):
296
    """
297
    :param size: (float) the size in the given format
298
    :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
299

300
    :returns: (int) the size in bytes
301
    :raises ValueError: if invalid size or format
302
    :raises AttributeError: if format is not str
303
    :raises TypeError: if size is not arithmetic or convertible to arithmetic
304
    """
305
    format = format.upper()
306
    if format == 'B':
307
        return int(size)
308
    size = float(size)
309
    units_dc = ('KB', 'MB', 'GB', 'TB')
310
    units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
311

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

    
321

    
322
def dict2file(d, f, depth=0):
323
    for k, v in d.items():
324
        f.write('%s%s: ' % (' ' * INDENT_TAB * depth, k))
325
        if isinstance(v, dict):
326
            f.write('\n')
327
            dict2file(v, f, depth + 1)
328
        elif isinstance(v, list) or isinstance(v, tuple):
329
            f.write('\n')
330
            list2file(v, f, depth + 1)
331
        else:
332
            f.write('%s\n' % v)
333

    
334

    
335
def list2file(l, f, depth=1):
336
    for item in l:
337
        if isinstance(item, dict):
338
            dict2file(item, f, depth + 1)
339
        elif isinstance(item, list) or isinstance(item, tuple):
340
            list2file(item, f, depth + 1)
341
        else:
342
            f.write('%s%s\n' % (' ' * INDENT_TAB * depth, item))
343

    
344
# Split input auxiliary
345

    
346

    
347
def _parse_with_regex(line, regex):
348
    re_parser = regex_compile(regex)
349
    return (re_parser.split(line), re_parser.findall(line))
350

    
351

    
352
def _get_from_parsed(parsed_str):
353
    try:
354
        parsed_str = parsed_str.strip()
355
    except:
356
        return None
357
    return ([parsed_str[1:-1]] if (
358
        parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"')) else (
359
            parsed_str.split(' '))) if parsed_str else 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
    terms = []
369
    for i, tpart in enumerate(trivial_parts):
370
        part = _get_from_parsed(tpart)
371
        if part:
372
            terms += part
373
        try:
374
            part = _get_from_parsed(interesting_parts[i])
375
        except IndexError:
376
            break
377
        if part:
378
            if tpart and not tpart[-1].endswith(' '):
379
                terms[-1] += ' '.join(part)
380
            else:
381
                terms += part
382
    return terms
383

    
384

    
385
def ask_user(msg, true_resp=('y', ), **kwargs):
386
    """Print msg and read user response
387

388
    :param true_resp: (tuple of chars)
389

390
    :returns: (bool) True if reponse in true responses, False otherwise
391
    """
392
    yep = ', '.join(true_resp)
393
    nope = '<not %s>' % yep if 'n' in true_resp or 'N' in true_resp else 'N'
394
    user_response = raw_input('%s [%s/%s]: ' % (msg, yep, nope))
395
    return user_response[0].lower() in [s.lower() for s in true_resp]
396

    
397

    
398
def get_path_size(testpath):
399
    if path.isfile(testpath):
400
        return path.getsize(testpath)
401
    total_size = 0
402
    for top, dirs, files in walk(path.abspath(testpath)):
403
        for f in files:
404
            f = path.join(top, f)
405
            if path.isfile(f):
406
                total_size += path.getsize(f)
407
    return total_size
408

    
409

    
410
def remove_from_items(list_of_dicts, key_to_remove):
411
    for item in list_of_dicts:
412
        assert isinstance(item, dict), 'Item %s not a dict' % item
413
        item.pop(key_to_remove, None)
414

    
415

    
416
def filter_dicts_by_dict(
417
    list_of_dicts, filters,
418
    exact_match=True, case_sensitive=False):
419
    """
420
    :param list_of_dicts: (list) each dict contains "raw" key-value pairs
421

422
    :param filters: (dict) filters in key-value form
423

424
    :param exact_match: (bool) if false, check if the filter value is part of
425
        the actual value
426

427
    :param case_sensitive: (bool) refers to values only (not keys)
428

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