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