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