8f42cb2db47af81e13b970208377e2d0a58af0b3
[kamaki] / kamaki / cli / utils.py
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 from os import walk, path
38 from json import dumps
39
40 from kamaki.cli.errors import raiseCLIError
41
42
43 IDENT_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     # No colours? No worries, use dummy foo instead
55     def dummy(val):
56         return val
57     red = yellow = magenta = bold = dummy
58     #from kamaki.cli import _colors
59     #if _colors.lower() == 'on':
60     suggest['ansicolors']['active'] = True
61
62 try:
63     from progress.bar import ShadyBar
64 except ImportError:
65     suggest['progress']['active'] = True
66
67
68 def suggest_missing(miss=None, exclude=[]):
69     global suggest
70     sgs = dict(suggest)
71     for exc in exclude:
72         try:
73             sgs.pop(exc)
74         except KeyError:
75             pass
76     kamaki_docs = 'http://www.synnefo.org/docs/kamaki/latest'
77     for k, v in (miss, sgs[miss]) if miss else sgs.items():
78         if v['active'] and stdout.isatty():
79             print('Suggestion: for better user experience install %s' % k)
80             print('\t%s' % v['description'])
81             print('\tIt is easy, here are the instructions:')
82             print('\t%s/installation.html%s' % (kamaki_docs, v['url']))
83             print('')
84
85
86 def remove_colors():
87     global bold
88     global red
89     global yellow
90     global magenta
91
92     def dummy(val):
93         return val
94     red = yellow = magenta = bold = dummy
95
96
97 def pretty_keys(d, delim='_', recurcive=False):
98     """<term>delim<term> to <term> <term> transformation
99     """
100     new_d = {}
101     for key, val in d.items():
102         new_key = key.split(delim)[-1]
103         if recurcive and isinstance(val, dict):
104             new_val = pretty_keys(val, delim, recurcive)
105         else:
106             new_val = val
107         new_d[new_key] = new_val
108     return new_d
109
110
111 def print_json(data):
112     """Print a list or dict as json in console
113
114     :param data: json-dumpable data
115     """
116     print(dumps(data, indent=IDENT_TAB))
117
118
119 def pretty_dict(d, *args, **kwargs):
120     print_dict(pretty_keys(d, *args, **kwargs))
121
122
123 def print_dict(
124         d,
125         exclude=(), indent=0,
126         with_enumeration=False, recursive_enumeration=False):
127     """Pretty-print a dictionary object
128     <indent>key: <non iterable item>
129     <indent>key:
130     <indent + IDENT_TAB><pretty-print iterable>
131
132     :param d: (dict)
133
134     :param exclude: (iterable of strings) keys to exclude from printing
135
136     :param indent: (int) initial indentation (recursive)
137
138     :param with_enumeration: (bool) enumerate 1st-level keys
139
140     :param recursive_enumeration: (bool) recursively enumerate iterables (does
141         not enumerate 1st level keys)
142
143     :raises CLIError: if preconditions fail
144     """
145     assert isinstance(d, dict), 'print_dict input must be a dict'
146     assert indent >= 0, 'print_dict indent must be >= 0'
147
148     for i, (k, v) in enumerate(d.items()):
149         k = ('%s' % k).strip()
150         if k in exclude:
151             continue
152         print_str = ' ' * indent
153         print_str += '%s.' % (i + 1) if with_enumeration else ''
154         print_str += '%s:' % k
155         if isinstance(v, dict):
156             print print_str
157             print_dict(
158                 v, exclude, indent + IDENT_TAB,
159                 recursive_enumeration, recursive_enumeration)
160         elif isinstance(v, list) or isinstance(v, tuple):
161             print print_str
162             print_list(
163                 v, exclude, indent + IDENT_TAB,
164                 recursive_enumeration, recursive_enumeration)
165         else:
166             print '%s %s' % (print_str, v)
167
168
169 def print_list(
170         l,
171         exclude=(), indent=0,
172         with_enumeration=False, recursive_enumeration=False):
173     """Pretty-print a list of items
174     <indent>key: <non iterable item>
175     <indent>key:
176     <indent + IDENT_TAB><pretty-print iterable>
177
178     :param l: (list)
179
180     :param exclude: (iterable of strings) items to exclude from printing
181
182     :param indent: (int) initial indentation (recursive)
183
184     :param with_enumeration: (bool) enumerate 1st-level items
185
186     :param recursive_enumeration: (bool) recursively enumerate iterables (does
187         not enumerate 1st level keys)
188
189     :raises CLIError: if preconditions fail
190     """
191     assert isinstance(l, list) or isinstance(l, tuple), (
192         'print_list prinbts a list or tuple')
193     assert indent >= 0, 'print_list indent must be >= 0'
194
195     for i, item in enumerate(l):
196         print_str = ' ' * indent
197         print_str += '%s.' % (i + 1) if with_enumeration else ''
198         if isinstance(item, dict):
199             if with_enumeration:
200                 print print_str
201             print_dict(
202                 item, exclude, indent,
203                 recursive_enumeration, recursive_enumeration)
204         elif isinstance(item, list) or isinstance(item, tuple):
205             if with_enumeration:
206                 print print_str
207             print_list(
208                 item, exclude, indent + IDENT_TAB,
209                 recursive_enumeration, recursive_enumeration)
210         else:
211             item = ('%s' % item).strip()
212             if item in exclude:
213                 continue
214             print '%s%s' % (print_str, item)
215         if (i + 1) < len(l):
216             print
217
218
219 def page_hold(index, limit, maxlen):
220     """Check if there are results to show, and hold the page when needed
221     :param index: (int) > 0
222     :param limit: (int) 0 < limit <= max, page hold if limit mod index == 0
223     :param maxlen: (int) Don't hold if index reaches maxlen
224
225     :returns: True if there are more to show, False if all results are shown
226     """
227     if index >= limit and index % limit == 0:
228         if index >= maxlen:
229             return False
230         else:
231             print('(%s listed - %s more - "enter" to continue)' % (
232                 index,
233                 maxlen - index))
234             c = ' '
235             while c != '\n':
236                 c = stdin.read(1)
237     return True
238
239
240 def print_items(
241         items, title=('id', 'name'),
242         with_enumeration=False, with_redundancy=False,
243         page_size=0):
244     """print dict or list items in a list, using some values as title
245     Objects of next level don't inherit enumeration (default: off) or titles
246
247     :param items: (list) items are lists or dict
248
249     :param title: (tuple) keys to use their values as title
250
251     :param with_enumeration: (boolean) enumerate items (order id on title)
252
253     :param with_redundancy: (boolean) values in title also appear on body
254
255     :param page_size: (int) show results in pages of page_size items, enter to
256         continue
257     """
258     if not items:
259         return
260     try:
261         page_size = int(page_size) if int(page_size) > 0 else len(items)
262     except:
263         page_size = len(items)
264     num_of_pages = len(items) // page_size
265     num_of_pages += 1 if len(items) % page_size else 0
266     for i, item in enumerate(items):
267         if with_enumeration:
268             stdout.write('%s. ' % (i + 1))
269         if isinstance(item, dict):
270             title = sorted(set(title).intersection(item.keys()))
271             if with_redundancy:
272                 header = ' '.join('%s' % item[key] for key in title)
273             else:
274                 header = ' '.join('%s' % item.pop(key) for key in title)
275             print(bold(header))
276         if isinstance(item, dict):
277             print_dict(item, indent=IDENT_TAB)
278         elif isinstance(item, list):
279             print_list(item, indent=IDENT_TAB)
280         else:
281             print(' %s' % item)
282         page_hold(i + 1, page_size, len(items))
283
284
285 def format_size(size):
286     units = ('B', 'KiB', 'MiB', 'GiB', 'TiB')
287     try:
288         size = float(size)
289     except ValueError as err:
290         raiseCLIError(err, 'Cannot format %s in bytes' % size)
291     for unit in units:
292         if size < 1024:
293             break
294         size /= 1024.0
295     s = ('%.2f' % size)
296     while '.' in s and s[-1] in ('0', '.'):
297         s = s[:-1]
298     return s + unit
299
300
301 def to_bytes(size, format):
302     """
303     :param size: (float) the size in the given format
304     :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
305
306     :returns: (int) the size in bytes
307     """
308     format = format.upper()
309     if format == 'B':
310         return int(size)
311     size = float(size)
312     units_dc = ('KB', 'MB', 'GB', 'TB')
313     units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
314
315     factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
316     if not factor:
317         raise ValueError('Invalid data size format %s' % format)
318     for prefix in ('K', 'M', 'G', 'T'):
319         size *= factor
320         if format.startswith(prefix):
321             break
322     return int(size)
323
324
325 def dict2file(d, f, depth=0):
326     for k, v in d.items():
327         f.write('%s%s: ' % ('\t' * depth, k))
328         if isinstance(v, dict):
329             f.write('\n')
330             dict2file(v, f, depth + 1)
331         elif isinstance(v, list):
332             f.write('\n')
333             list2file(v, f, depth + 1)
334         else:
335             f.write(' %s\n' % v)
336
337
338 def list2file(l, f, depth=1):
339     for item in l:
340         if isinstance(item, dict):
341             dict2file(item, f, depth + 1)
342         elif isinstance(item, list):
343             list2file(item, f, depth + 1)
344         else:
345             f.write('%s%s\n' % ('\t' * depth, item))
346
347 # Split input auxiliary
348
349
350 def _parse_with_regex(line, regex):
351     re_parser = regex_compile(regex)
352     return (re_parser.split(line), re_parser.findall(line))
353
354
355 def _sub_split(line):
356     terms = []
357     (sub_trivials, sub_interesting) = _parse_with_regex(line, ' ".*?" ')
358     for subi, subipart in enumerate(sub_interesting):
359         terms += sub_trivials[subi].split()
360         terms.append(subipart[2:-2])
361     terms += sub_trivials[-1].split()
362     return terms
363
364
365 def old_split_input(line):
366     """Use regular expressions to split a line correctly"""
367     line = ' %s ' % line
368     (trivial_parts, interesting_parts) = _parse_with_regex(line, ' \'.*?\' ')
369     terms = []
370     for i, ipart in enumerate(interesting_parts):
371         terms += _sub_split(trivial_parts[i])
372         terms.append(ipart[2:-2])
373     terms += _sub_split(trivial_parts[-1])
374     return terms
375
376
377 def _get_from_parsed(parsed_str):
378     try:
379         parsed_str = parsed_str.strip()
380     except:
381         return None
382     if parsed_str:
383         if parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"'):
384             return [parsed_str[1:-1]]
385         return parsed_str.split(' ')
386     return None
387
388
389 def split_input(line):
390     if not line:
391         return []
392     reg_expr = '\'.*?\'|".*?"|^[\S]*$'
393     (trivial_parts, interesting_parts) = _parse_with_regex(line, reg_expr)
394     assert(len(trivial_parts) == 1 + len(interesting_parts))
395     #print('  [split_input] trivial_parts %s are' % trivial_parts)
396     #print('  [split_input] interesting_parts %s are' % interesting_parts)
397     terms = []
398     for i, tpart in enumerate(trivial_parts):
399         part = _get_from_parsed(tpart)
400         if part:
401             terms += part
402         try:
403             part = _get_from_parsed(interesting_parts[i])
404         except IndexError:
405             break
406         if part:
407             terms += part
408     return terms
409
410
411 def ask_user(msg, true_resp=('y', )):
412     """Print msg and read user response
413
414     :param true_resp: (tuple of chars)
415
416     :returns: (bool) True if reponse in true responses, False otherwise
417     """
418     stdout.write('%s [%s/N]: ' % (msg, ', '.join(true_resp)))
419     stdout.flush()
420     user_response = stdin.readline()
421     return user_response[0].lower() in true_resp
422
423
424 def spiner(size=None):
425     spins = ('/', '-', '\\', '|')
426     stdout.write(' ')
427     size = size or -1
428     i = 0
429     while size - i:
430         stdout.write('\b%s' % spins[i % len(spins)])
431         stdout.flush()
432         i += 1
433         sleep(0.1)
434         yield
435     yield
436
437 if __name__ == '__main__':
438     examples = [
439         'la_la le_le li_li',
440         '\'la la\' \'le le\' \'li li\'',
441         '\'la la\' le_le \'li li\'',
442         'la_la \'le le\' li_li',
443         'la_la \'le le\' \'li li\'',
444         '"la la" "le le" "li li"',
445         '"la la" le_le "li li"',
446         'la_la "le le" li_li',
447         '"la_la" "le le" "li li"',
448         '\'la la\' "le le" \'li li\'',
449         'la_la \'le le\' "li li"',
450         'la_la \'le le\' li_li',
451         '\'la la\' le_le "li li"',
452         '"la la" le_le \'li li\'',
453         '"la la" \'le le\' li_li',
454         'la_la \'le\'le\' "li\'li"',
455         '"la \'le le\' la"',
456         '\'la "le le" la\'',
457         '\'la "la" la\' "le \'le\' le" li_"li"_li',
458         '\'\' \'L\' "" "A"']
459
460     for i, example in enumerate(examples):
461         print('%s. Split this: (%s)' % (i + 1, example))
462         ret = old_split_input(example)
463         print('\t(%s) of size %s' % (ret, len(ret)))
464
465
466 def get_path_size(testpath):
467     if path.isfile(testpath):
468         return path.getsize(testpath)
469     total_size = 0
470     for top, dirs, files in walk(path.abspath(testpath)):
471         for f in files:
472             f = path.join(top, f)
473             if path.isfile(f):
474                 total_size += path.getsize(f)
475     return total_size
476
477
478 def remove_from_items(list_of_dicts, key_to_remove):
479     for item in list_of_dicts:
480         assert isinstance(item, dict), 'Item %s not a dict' % item
481         item.pop(key_to_remove, None)