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