1 # Copyright 2011 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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.
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
40 from kamaki.cli.errors import raiseCLIError
46 suggest = dict(ansicolors=dict(
48 url='#install-ansicolors-progress',
49 description='Add colors to console responses'))
52 from colors import magenta, red, yellow, bold
54 # No colours? No worries, use dummy foo instead
57 red = yellow = magenta = bold = dummy
58 #from kamaki.cli import _colors
59 #if _colors.lower() == 'on':
60 suggest['ansicolors']['active'] = True
63 from progress.bar import ShadyBar
65 suggest['progress']['active'] = True
68 def suggest_missing(miss=None, exclude=[]):
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']))
94 red = yellow = magenta = bold = dummy
97 def pretty_keys(d, delim='_', recurcive=False):
98 """<term>delim<term> to <term> <term> transformation
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)
107 new_d[new_key] = new_val
111 def print_json(data):
112 """Print a list or dict as json in console
114 :param data: json-dumpable data
116 print(dumps(data, indent=IDENT_TAB))
119 def pretty_dict(d, *args, **kwargs):
120 print_dict(pretty_keys(d, *args, **kwargs))
125 exclude=(), indent=0,
126 with_enumeration=False, recursive_enumeration=False):
127 """Pretty-print a dictionary object
128 <indent>key: <non iterable item>
130 <indent + IDENT_TAB><pretty-print iterable>
134 :param exclude: (iterable of strings) keys to exclude from printing
136 :param indent: (int) initial indentation (recursive)
138 :param with_enumeration: (bool) enumerate 1st-level keys
140 :param recursive_enumeration: (bool) recursively enumerate iterables (does
141 not enumerate 1st level keys)
143 :raises CLIError: if preconditions fail
145 assert isinstance(d, dict), 'print_dict input must be a dict'
146 assert indent >= 0, 'print_dict indent must be >= 0'
148 for i, (k, v) in enumerate(d.items()):
149 k = ('%s' % k).strip()
152 print_str = ' ' * indent
153 print_str += '%s.' % (i + 1) if with_enumeration else ''
154 print_str += '%s:' % k
155 if isinstance(v, dict):
158 v, exclude, indent + IDENT_TAB,
159 recursive_enumeration, recursive_enumeration)
160 elif isinstance(v, list) or isinstance(v, tuple):
163 v, exclude, indent + IDENT_TAB,
164 recursive_enumeration, recursive_enumeration)
166 print '%s %s' % (print_str, v)
171 exclude=(), indent=0,
172 with_enumeration=False, recursive_enumeration=False):
173 """Pretty-print a list of items
174 <indent>key: <non iterable item>
176 <indent + IDENT_TAB><pretty-print iterable>
180 :param exclude: (iterable of strings) items to exclude from printing
182 :param indent: (int) initial indentation (recursive)
184 :param with_enumeration: (bool) enumerate 1st-level items
186 :param recursive_enumeration: (bool) recursively enumerate iterables (does
187 not enumerate 1st level keys)
189 :raises CLIError: if preconditions fail
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'
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):
202 item, exclude, indent,
203 recursive_enumeration, recursive_enumeration)
204 elif isinstance(item, list) or isinstance(item, tuple):
208 item, exclude, indent + IDENT_TAB,
209 recursive_enumeration, recursive_enumeration)
211 item = ('%s' % item).strip()
214 print '%s%s' % (print_str, item)
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
225 :returns: True if there are more to show, False if all results are shown
227 if index >= limit and index % limit == 0:
231 print('(%s listed - %s more - "enter" to continue)' % (
241 items, title=('id', 'name'),
242 with_enumeration=False, with_redundancy=False,
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
247 :param items: (list) items are lists or dict
249 :param title: (tuple) keys to use their values as title
251 :param with_enumeration: (boolean) enumerate items (order id on title)
253 :param with_redundancy: (boolean) values in title also appear on body
255 :param page_size: (int) show results in pages of page_size items, enter to
261 page_size = int(page_size) if int(page_size) > 0 else len(items)
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):
268 stdout.write('%s. ' % (i + 1))
269 if isinstance(item, dict):
270 title = sorted(set(title).intersection(item.keys()))
272 header = ' '.join('%s' % item[key] for key in title)
274 header = ' '.join('%s' % item.pop(key) for key in title)
276 if isinstance(item, dict):
277 print_dict(item, indent=IDENT_TAB)
278 elif isinstance(item, list):
279 print_list(item, indent=IDENT_TAB)
282 page_hold(i + 1, page_size, len(items))
285 def format_size(size):
286 units = ('B', 'KiB', 'MiB', 'GiB', 'TiB')
289 except ValueError as err:
290 raiseCLIError(err, 'Cannot format %s in bytes' % size)
296 while '.' in s and s[-1] in ('0', '.'):
301 def to_bytes(size, format):
303 :param size: (float) the size in the given format
304 :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
306 :returns: (int) the size in bytes
308 format = format.upper()
312 units_dc = ('KB', 'MB', 'GB', 'TB')
313 units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
315 factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
317 raise ValueError('Invalid data size format %s' % format)
318 for prefix in ('K', 'M', 'G', 'T'):
320 if format.startswith(prefix):
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):
330 dict2file(v, f, depth + 1)
331 elif isinstance(v, list):
333 list2file(v, f, depth + 1)
338 def list2file(l, f, depth=1):
340 if isinstance(item, dict):
341 dict2file(item, f, depth + 1)
342 elif isinstance(item, list):
343 list2file(item, f, depth + 1)
345 f.write('%s%s\n' % ('\t' * depth, item))
347 # Split input auxiliary
350 def _parse_with_regex(line, regex):
351 re_parser = regex_compile(regex)
352 return (re_parser.split(line), re_parser.findall(line))
355 def _sub_split(line):
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()
365 def old_split_input(line):
366 """Use regular expressions to split a line correctly"""
368 (trivial_parts, interesting_parts) = _parse_with_regex(line, ' \'.*?\' ')
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])
377 def _get_from_parsed(parsed_str):
379 parsed_str = parsed_str.strip()
383 if parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"'):
384 return [parsed_str[1:-1]]
385 return parsed_str.split(' ')
389 def split_input(line):
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)
398 for i, tpart in enumerate(trivial_parts):
399 part = _get_from_parsed(tpart)
403 part = _get_from_parsed(interesting_parts[i])
411 def ask_user(msg, true_resp=('y', )):
412 """Print msg and read user response
414 :param true_resp: (tuple of chars)
416 :returns: (bool) True if reponse in true responses, False otherwise
418 stdout.write('%s [%s/N]: ' % (msg, ', '.join(true_resp)))
420 user_response = stdin.readline()
421 return user_response[0].lower() in true_resp
424 def spiner(size=None):
425 spins = ('/', '-', '\\', '|')
430 stdout.write('\b%s' % spins[i % len(spins)])
437 if __name__ == '__main__':
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"',
457 '\'la "la" la\' "le \'le\' le" li_"li"_li',
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)))
466 def get_path_size(testpath):
467 if path.isfile(testpath):
468 return path.getsize(testpath)
470 for top, dirs, files in walk(path.abspath(testpath)):
472 f = path.join(top, f)
474 total_size += path.getsize(f)
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)