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
38 from kamaki.cli.errors import raiseCLIError
41 from colors import magenta, red, yellow, bold
43 # No colours? No worries, use dummy foo instead
46 red = yellow = magenta = bold = dummy
57 red = yellow = magenta = bold = dummy
60 def pretty_keys(d, delim='_', recurcive=False):
61 """<term>delim<term> to <term> <term> transformation
64 for key, val in d.items():
65 new_key = key.split(delim)[-1]
66 if recurcive and isinstance(val, dict):
67 new_val = pretty_keys(val, delim, recurcive)
70 new_d[new_key] = new_val
75 d, exclude=(), ident=0,
76 with_enumeration=False, recursive_enumeration=False):
78 Pretty-print a dictionary object
80 :param d: (dict) the input
82 :param excelude: (set or list) keys to exclude from printing
84 :param ident: (int) initial indentation (recursive)
86 :param with_enumeration: (bool) enumerate each 1st level key if true
88 :recursive_enumeration: (bool) recursively enumerate dicts and lists of
91 :raises CLIError: (TypeError wrapper) non-dict input
93 if not isinstance(d, dict):
94 raiseCLIError(TypeError('Cannot dict_print a non-dict object'))
97 margin = max(len(('%s' % key).strip()) for key in d.keys() if (
101 for key, val in sorted(d.items()):
106 print_str = '%s. ' % counter
108 print_str = '%s%s' % (' ' * (ident - len(print_str)), print_str)
109 print_str += ('%s' % key).strip()
110 print_str += ' ' * (margin - len(unicode(key).strip()))
112 if isinstance(val, dict):
117 ident=margin + ident,
118 with_enumeration=recursive_enumeration,
119 recursive_enumeration=recursive_enumeration)
120 elif isinstance(val, list):
125 ident=margin + ident,
126 with_enumeration=recursive_enumeration,
127 recursive_enumeration=recursive_enumeration)
129 print print_str + ' ' + unicode(val).strip()
133 l, exclude=(), ident=0,
134 with_enumeration=False, recursive_enumeration=False):
136 Pretty-print a list object
138 :param l: (list) the input
140 :param excelude: (object - anytype) values to exclude from printing
142 :param ident: (int) initial indentation (recursive)
144 :param with_enumeration: (bool) enumerate each 1st level value if true
146 :recursive_enumeration: (bool) recursively enumerate dicts and lists of
149 :raises CLIError: (TypeError wrapper) non-list input
151 if not isinstance(l, list):
152 raiseCLIError(TypeError('Cannot list_print a non-list object'))
156 margin = max(len(('%s' % item).strip()) for item in l if not (
157 isinstance(item, dict) or
158 isinstance(item, list) or
161 margin = (2 + len(unicode(len(l)))) if enumerate else 1
165 for item in sorted(l):
168 elif with_enumeration:
169 prefix = '%s. ' % counter
171 prefix = '%s%s' % (' ' * (ident - len(prefix)), prefix)
174 if isinstance(item, dict):
180 ident=margin + ident,
181 with_enumeration=recursive_enumeration,
182 recursive_enumeration=recursive_enumeration)
183 elif isinstance(item, list):
189 ident=margin + ident,
190 with_enumeration=recursive_enumeration,
191 recursive_enumeration=recursive_enumeration)
193 print('%s%s' % (prefix, item))
196 def page_hold(index, limit, maxlen):
197 """Check if there are results to show, and hold the page when needed
198 :param index: (int) > 0
199 :param limit: (int) 0 < limit <= max, page hold if limit mod index == 0
200 :param maxlen: (int) Don't hold if index reaches maxlen
202 :returns: True if there are more to show, False if all results are shown
204 if index >= limit and index % limit == 0:
208 print('(%s listed - %s more - "enter" to continue)' % (
218 items, title=('id', 'name'),
219 with_enumeration=False, with_redundancy=False,
221 """print dict or list items in a list, using some values as title
222 Objects of next level don't inherit enumeration (default: off) or titles
224 :param items: (list) items are lists or dict
225 :param title: (tuple) keys to use their values as title
226 :param with_enumeration: (boolean) enumerate items (order id on title)
227 :param with_redundancy: (boolean) values in title also appear on body
228 :param page_size: (int) show results in pages of page_size items, enter to
234 page_size = int(page_size) if int(page_size) > 0 else len(items)
236 page_size = len(items)
237 num_of_pages = len(items) // page_size
238 num_of_pages += 1 if len(items) % page_size else 0
239 for i, item in enumerate(items):
241 stdout.write('%s. ' % (i + 1))
242 if isinstance(item, dict):
243 title = sorted(set(title).intersection(item.keys()))
245 header = ' '.join(unicode(item[key]) for key in title)
247 header = ' '.join(unicode(item.pop(key)) for key in title)
249 if isinstance(item, dict):
250 print_dict(item, ident=1)
251 elif isinstance(item, list):
252 print_list(item, ident=1)
255 page_hold(i + 1, page_size, len(items))
258 def format_size(size):
259 units = ('B', 'KiB', 'MiB', 'GiB', 'TiB')
262 except ValueError as err:
263 raiseCLIError(err, 'Cannot format %s in bytes' % size)
269 while '.' in s and s[-1] in ('0', '.'):
274 def to_bytes(size, format):
276 :param size: (float) the size in the given format
277 :param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
279 :returns: (int) the size in bytes
281 format = format.upper()
285 units_dc = ('KB', 'MB', 'GB', 'TB')
286 units_bi = ('KIB', 'MIB', 'GIB', 'TIB')
288 factor = 1024 if format in units_bi else 1000 if format in units_dc else 0
290 raise ValueError('Invalid data size format %s' % format)
291 for prefix in ('K', 'M', 'G', 'T'):
293 if format.startswith(prefix):
298 def dict2file(d, f, depth=0):
299 for k, v in d.items():
300 f.write('%s%s: ' % ('\t' * depth, k))
301 if isinstance(v, dict):
303 dict2file(v, f, depth + 1)
304 elif isinstance(v, list):
306 list2file(v, f, depth + 1)
308 f.write(' %s\n' % unicode(v))
311 def list2file(l, f, depth=1):
313 if isinstance(item, dict):
314 dict2file(item, f, depth + 1)
315 elif isinstance(item, list):
316 list2file(item, f, depth + 1)
318 f.write('%s%s\n' % ('\t' * depth, unicode(item)))
320 # Split input auxiliary
323 def _parse_with_regex(line, regex):
324 re_parser = regex_compile(regex)
325 return (re_parser.split(line), re_parser.findall(line))
328 def _sub_split(line):
330 (sub_trivials, sub_interesting) = _parse_with_regex(line, ' ".*?" ')
331 for subi, subipart in enumerate(sub_interesting):
332 terms += sub_trivials[subi].split()
333 terms.append(subipart[2:-2])
334 terms += sub_trivials[-1].split()
338 def old_split_input(line):
339 """Use regular expressions to split a line correctly"""
341 (trivial_parts, interesting_parts) = _parse_with_regex(line, ' \'.*?\' ')
343 for i, ipart in enumerate(interesting_parts):
344 terms += _sub_split(trivial_parts[i])
345 terms.append(ipart[2:-2])
346 terms += _sub_split(trivial_parts[-1])
350 def _get_from_parsed(parsed_str):
352 parsed_str = parsed_str.strip()
356 if parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"'):
357 return [parsed_str[1:-1]]
358 return parsed_str.split(' ')
362 def split_input(line):
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 #print(' [split_input] trivial_parts %s are' % trivial_parts)
369 #print(' [split_input] interesting_parts %s are' % interesting_parts)
371 for i, tpart in enumerate(trivial_parts):
372 part = _get_from_parsed(tpart)
376 part = _get_from_parsed(interesting_parts[i])
384 def ask_user(msg, true_resp=['Y', 'y']):
385 """Print msg and read user response
387 :param true_resp: (tuple of chars)
389 :returns: (bool) True if reponse in true responses, False otherwise
391 stdout.write('%s (%s or enter for yes):' % (msg, ', '.join(true_resp)))
393 user_response = stdin.readline()
394 return user_response[0] in true_resp + ['\n']
397 def spiner(size=None):
398 spins = ('/', '-', '\\', '|')
403 stdout.write('\b%s' % spins[i % len(spins)])
410 if __name__ == '__main__':
413 '\'la la\' \'le le\' \'li li\'',
414 '\'la la\' le_le \'li li\'',
415 'la_la \'le le\' li_li',
416 'la_la \'le le\' \'li li\'',
417 '"la la" "le le" "li li"',
418 '"la la" le_le "li li"',
419 'la_la "le le" li_li',
420 '"la_la" "le le" "li li"',
421 '\'la la\' "le le" \'li li\'',
422 'la_la \'le le\' "li li"',
423 'la_la \'le le\' li_li',
424 '\'la la\' le_le "li li"',
425 '"la la" le_le \'li li\'',
426 '"la la" \'le le\' li_li',
427 'la_la \'le\'le\' "li\'li"',
430 '\'la "la" la\' "le \'le\' le" li_"li"_li',
433 for i, example in enumerate(examples):
434 print('%s. Split this: (%s)' % (i + 1, example))
435 ret = old_split_input(example)
436 print('\t(%s) of size %s' % (ret, len(ret)))