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