root / kamaki / cli / utils / __init__.py @ 2f302751
History | View | Annotate | Download (15.7 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 os import walk, path |
37 |
from json import dumps |
38 |
from kamaki.cli.logger import get_logger |
39 |
from locale import getpreferredencoding |
40 |
|
41 |
from kamaki.cli.errors import raiseCLIError |
42 |
|
43 |
|
44 |
INDENT_TAB = 4
|
45 |
log = get_logger(__name__) |
46 |
pref_enc = getpreferredencoding() |
47 |
|
48 |
|
49 |
suggest = dict(ansicolors=dict( |
50 |
active=False,
|
51 |
url='#install-ansicolors-progress',
|
52 |
description='Add colors to console responses'))
|
53 |
|
54 |
try:
|
55 |
from colors import magenta, red, yellow, bold |
56 |
except ImportError: |
57 |
def dummy(val): |
58 |
return val
|
59 |
red = yellow = magenta = bold = dummy |
60 |
suggest['ansicolors']['active'] = True |
61 |
|
62 |
|
63 |
def _encode_nicely(somestr, encoding, replacement='?'): |
64 |
"""Encode somestr as 'encoding', but don't raise errors (replace with ?)
|
65 |
This method is slow. Us it only for grace.
|
66 |
:param encoding: (str) encode every character in this encoding
|
67 |
:param replacement: (char) replace each char raising encode-decode errs
|
68 |
"""
|
69 |
newstr, err_counter = '', 0 |
70 |
for c in somestr: |
71 |
try:
|
72 |
newc = c.encode(encoding) |
73 |
newstr = '%s%s' % (newstr, newc)
|
74 |
except UnicodeError: |
75 |
newstr = '%s%s' % (newstr, replacement)
|
76 |
err_counter += 1
|
77 |
if err_counter:
|
78 |
log.debug('\t%s character%s failed to be encoded as %s' % (
|
79 |
err_counter, 's' if err_counter > 1 else '', encoding)) |
80 |
return newstr
|
81 |
|
82 |
|
83 |
def DontRaiseUnicodeError(foo): |
84 |
def wrap(self, *args, **kwargs): |
85 |
try:
|
86 |
s = kwargs.pop('s')
|
87 |
except KeyError: |
88 |
try:
|
89 |
s = args[0]
|
90 |
except IndexError: |
91 |
return foo(self, *args, **kwargs) |
92 |
args = args[1:]
|
93 |
try:
|
94 |
s = s.encode(pref_enc) |
95 |
except UnicodeError as ue: |
96 |
log.debug('Encoding(%s): %s' % (pref_enc, ue))
|
97 |
s = _encode_nicely(s, pref_enc, replacement='?')
|
98 |
return foo(self, s, *args, **kwargs) |
99 |
return wrap
|
100 |
|
101 |
|
102 |
def suggest_missing(miss=None, exclude=[]): |
103 |
global suggest
|
104 |
sgs = dict(suggest)
|
105 |
for exc in exclude: |
106 |
try:
|
107 |
sgs.pop(exc) |
108 |
except KeyError: |
109 |
pass
|
110 |
kamaki_docs = 'http://www.synnefo.org/docs/kamaki/latest'
|
111 |
for k, v in (miss, sgs[miss]) if miss else sgs.items(): |
112 |
if v['active'] and stdout.isatty(): |
113 |
print('Suggestion: for better user experience install %s' % k)
|
114 |
print('\t%s' % v['description']) |
115 |
print('\tIt is easy, here are the instructions:')
|
116 |
print('\t%s/installation.html%s' % (kamaki_docs, v['url'])) |
117 |
print('')
|
118 |
|
119 |
|
120 |
def guess_mime_type( |
121 |
filename, |
122 |
default_content_type='application/octet-stream',
|
123 |
default_encoding=None):
|
124 |
assert filename, 'Cannot guess mimetype for empty filename' |
125 |
try:
|
126 |
from mimetypes import guess_type |
127 |
ctype, cenc = guess_type(filename) |
128 |
return ctype or default_content_type, cenc or default_encoding |
129 |
except ImportError: |
130 |
print 'WARNING: Cannot import mimetypes, using defaults' |
131 |
return (default_content_type, default_encoding)
|
132 |
|
133 |
|
134 |
def remove_colors(): |
135 |
global bold
|
136 |
global red
|
137 |
global yellow
|
138 |
global magenta
|
139 |
|
140 |
def dummy(val): |
141 |
return val
|
142 |
red = yellow = magenta = bold = dummy |
143 |
|
144 |
|
145 |
def pretty_keys(d, delim='_', recursive=False): |
146 |
"""<term>delim<term> to <term> <term> transformation"""
|
147 |
new_d = dict(d)
|
148 |
for k, v in d.items(): |
149 |
new_v = new_d.pop(k) |
150 |
new_d[k.replace(delim, ' ').strip()] = pretty_keys(
|
151 |
new_v, delim, True) if ( |
152 |
recursive and isinstance(v, dict)) else new_v |
153 |
return new_d
|
154 |
|
155 |
|
156 |
def print_json(data, out=stdout): |
157 |
"""Print a list or dict as json in console
|
158 |
|
159 |
:param data: json-dumpable data
|
160 |
|
161 |
:param out: Input/Output stream to dump values into
|
162 |
"""
|
163 |
out.write(unicode(dumps(data, indent=INDENT_TAB) + '\n')) |
164 |
out.flush() |
165 |
|
166 |
|
167 |
def print_dict( |
168 |
d, |
169 |
exclude=(), indent=0,
|
170 |
with_enumeration=False, recursive_enumeration=False, out=stdout): |
171 |
"""Pretty-print a dictionary object
|
172 |
<indent>key: <non iterable item>
|
173 |
<indent>key:
|
174 |
<indent + INDENT_TAB><pretty-print iterable>
|
175 |
|
176 |
:param d: (dict)
|
177 |
|
178 |
:param exclude: (iterable of strings) keys to exclude from printing
|
179 |
|
180 |
:param indent: (int) initial indentation (recursive)
|
181 |
|
182 |
:param with_enumeration: (bool) enumerate 1st-level keys
|
183 |
|
184 |
:param recursive_enumeration: (bool) recursively enumerate iterables (does
|
185 |
not enumerate 1st level keys)
|
186 |
|
187 |
:param out: Input/Output stream to dump values into
|
188 |
|
189 |
:raises CLIError: if preconditions fail
|
190 |
"""
|
191 |
assert isinstance(d, dict), 'print_dict input must be a dict' |
192 |
assert indent >= 0, 'print_dict indent must be >= 0' |
193 |
|
194 |
for i, (k, v) in enumerate(d.items()): |
195 |
k = ('%s' % k).strip()
|
196 |
if k in exclude: |
197 |
continue
|
198 |
print_str = ' ' * indent
|
199 |
print_str += '%s.' % (i + 1) if with_enumeration else '' |
200 |
print_str += '%s:' % k
|
201 |
if isinstance(v, dict): |
202 |
out.write(print_str + '\n')
|
203 |
print_dict( |
204 |
v, exclude, indent + INDENT_TAB, |
205 |
recursive_enumeration, recursive_enumeration, out) |
206 |
elif isinstance(v, list) or isinstance(v, tuple): |
207 |
out.write(print_str + '\n')
|
208 |
print_list( |
209 |
v, exclude, indent + INDENT_TAB, |
210 |
recursive_enumeration, recursive_enumeration, out) |
211 |
else:
|
212 |
out.write('%s %s\n' % (print_str, v))
|
213 |
out.flush() |
214 |
|
215 |
|
216 |
def print_list( |
217 |
l, |
218 |
exclude=(), indent=0,
|
219 |
with_enumeration=False, recursive_enumeration=False, out=stdout): |
220 |
"""Pretty-print a list of items
|
221 |
<indent>key: <non iterable item>
|
222 |
<indent>key:
|
223 |
<indent + INDENT_TAB><pretty-print iterable>
|
224 |
|
225 |
:param l: (list)
|
226 |
|
227 |
:param exclude: (iterable of strings) items to exclude from printing
|
228 |
|
229 |
:param indent: (int) initial indentation (recursive)
|
230 |
|
231 |
:param with_enumeration: (bool) enumerate 1st-level items
|
232 |
|
233 |
:param recursive_enumeration: (bool) recursively enumerate iterables (does
|
234 |
not enumerate 1st level keys)
|
235 |
|
236 |
:param out: Input/Output stream to dump values into
|
237 |
|
238 |
:raises CLIError: if preconditions fail
|
239 |
"""
|
240 |
assert isinstance(l, list) or isinstance(l, tuple), ( |
241 |
'print_list prinbts a list or tuple')
|
242 |
assert indent >= 0, 'print_list indent must be >= 0' |
243 |
|
244 |
for i, item in enumerate(l): |
245 |
print_str = ' ' * indent
|
246 |
print_str += '%s.' % (i + 1) if with_enumeration else '' |
247 |
if isinstance(item, dict): |
248 |
if with_enumeration:
|
249 |
out.write(print_str + '\n')
|
250 |
elif i and i < len(l): |
251 |
out.write('\n')
|
252 |
print_dict( |
253 |
item, exclude, |
254 |
indent + (INDENT_TAB if with_enumeration else 0), |
255 |
recursive_enumeration, recursive_enumeration, out) |
256 |
elif isinstance(item, list) or isinstance(item, tuple): |
257 |
if with_enumeration:
|
258 |
out.write(print_str + '\n')
|
259 |
elif i and i < len(l): |
260 |
out.write('\n')
|
261 |
print_list( |
262 |
item, exclude, indent + INDENT_TAB, |
263 |
recursive_enumeration, recursive_enumeration, out) |
264 |
else:
|
265 |
item = ('%s' % item).strip()
|
266 |
if item in exclude: |
267 |
continue
|
268 |
out.write('%s%s\n' % (print_str, item))
|
269 |
out.flush() |
270 |
out.flush() |
271 |
|
272 |
|
273 |
def print_items( |
274 |
items, title=('id', 'name'), |
275 |
with_enumeration=False, with_redundancy=False, out=stdout): |
276 |
"""print dict or list items in a list, using some values as title
|
277 |
Objects of next level don't inherit enumeration (default: off) or titles
|
278 |
|
279 |
:param items: (list) items are lists or dict
|
280 |
|
281 |
:param title: (tuple) keys to use their values as title
|
282 |
|
283 |
:param with_enumeration: (boolean) enumerate items (order id on title)
|
284 |
|
285 |
:param with_redundancy: (boolean) values in title also appear on body
|
286 |
|
287 |
:param out: Input/Output stream to dump values into
|
288 |
"""
|
289 |
if not items: |
290 |
return
|
291 |
if not (isinstance(items, dict) or isinstance(items, list) or isinstance( |
292 |
items, tuple)):
|
293 |
out.write('%s\n' % items)
|
294 |
out.flush() |
295 |
return
|
296 |
|
297 |
for i, item in enumerate(items): |
298 |
if with_enumeration:
|
299 |
out.write('%s. ' % (i + 1)) |
300 |
if isinstance(item, dict): |
301 |
item = dict(item)
|
302 |
title = sorted(set(title).intersection(item)) |
303 |
pick = item.get if with_redundancy else item.pop |
304 |
header = ' '.join('%s' % pick(key) for key in title) |
305 |
out.write((unicode(bold(header) if header else '') + '\n')) |
306 |
print_dict(item, indent=INDENT_TAB, out=out) |
307 |
elif isinstance(item, list) or isinstance(item, tuple): |
308 |
print_list(item, indent=INDENT_TAB, out=out) |
309 |
else:
|
310 |
out.write(' %s\n' % item)
|
311 |
out.flush() |
312 |
out.flush() |
313 |
|
314 |
|
315 |
def format_size(size, decimal_factors=False): |
316 |
units = ('B', 'KB', 'MB', 'GB', 'TB') if decimal_factors else ( |
317 |
'B', 'KiB', 'MiB', 'GiB', 'TiB') |
318 |
step = 1000 if decimal_factors else 1024 |
319 |
fstep = float(step)
|
320 |
try:
|
321 |
size = float(size)
|
322 |
except (ValueError, TypeError) as err: |
323 |
raiseCLIError(err, 'Cannot format %s in bytes' % (
|
324 |
','.join(size) if isinstance(size, tuple) else size)) |
325 |
for i, unit in enumerate(units): |
326 |
if size < step or i + 1 == len(units): |
327 |
break
|
328 |
size /= fstep |
329 |
s = ('%.2f' % size)
|
330 |
s = s.replace('%s' % step, '%s.99' % (step - 1)) if size <= fstep else s |
331 |
while '.' in s and s[-1] in ('0', '.'): |
332 |
s = s[:-1]
|
333 |
return s + unit
|
334 |
|
335 |
|
336 |
def to_bytes(size, format): |
337 |
"""
|
338 |
:param size: (float) the size in the given format
|
339 |
:param format: (case insensitive) KiB, KB, MiB, MB, GiB, GB, TiB, TB
|
340 |
|
341 |
:returns: (int) the size in bytes
|
342 |
:raises ValueError: if invalid size or format
|
343 |
:raises AttributeError: if format is not str
|
344 |
:raises TypeError: if size is not arithmetic or convertible to arithmetic
|
345 |
"""
|
346 |
format = format.upper() |
347 |
if format == 'B': |
348 |
return int(size) |
349 |
size = float(size)
|
350 |
units_dc = ('KB', 'MB', 'GB', 'TB') |
351 |
units_bi = ('KIB', 'MIB', 'GIB', 'TIB') |
352 |
|
353 |
factor = 1024 if format in units_bi else 1000 if format in units_dc else 0 |
354 |
if not factor: |
355 |
raise ValueError('Invalid data size format %s' % format) |
356 |
for prefix in ('K', 'M', 'G', 'T'): |
357 |
size *= factor |
358 |
if format.startswith(prefix):
|
359 |
break
|
360 |
return int(size) |
361 |
|
362 |
|
363 |
def dict2file(d, f, depth=0): |
364 |
for k, v in d.items(): |
365 |
f.write('%s%s: ' % (' ' * INDENT_TAB * depth, k)) |
366 |
if isinstance(v, dict): |
367 |
f.write('\n')
|
368 |
dict2file(v, f, depth + 1)
|
369 |
elif isinstance(v, list) or isinstance(v, tuple): |
370 |
f.write('\n')
|
371 |
list2file(v, f, depth + 1)
|
372 |
else:
|
373 |
f.write('%s\n' % v)
|
374 |
|
375 |
|
376 |
def list2file(l, f, depth=1): |
377 |
for item in l: |
378 |
if isinstance(item, dict): |
379 |
dict2file(item, f, depth + 1)
|
380 |
elif isinstance(item, list) or isinstance(item, tuple): |
381 |
list2file(item, f, depth + 1)
|
382 |
else:
|
383 |
f.write('%s%s\n' % (' ' * INDENT_TAB * depth, item)) |
384 |
|
385 |
# Split input auxiliary
|
386 |
|
387 |
|
388 |
def _parse_with_regex(line, regex): |
389 |
re_parser = regex_compile(regex) |
390 |
return (re_parser.split(line), re_parser.findall(line))
|
391 |
|
392 |
|
393 |
def _get_from_parsed(parsed_str): |
394 |
try:
|
395 |
parsed_str = parsed_str.strip() |
396 |
except:
|
397 |
return None |
398 |
return ([parsed_str[1:-1]] if ( |
399 |
parsed_str[0] == parsed_str[-1] and parsed_str[0] in ("'", '"')) else ( |
400 |
parsed_str.split(' '))) if parsed_str else None |
401 |
|
402 |
|
403 |
def split_input(line): |
404 |
if not line: |
405 |
return []
|
406 |
reg_expr = '\'.*?\'|".*?"|^[\S]*$'
|
407 |
(trivial_parts, interesting_parts) = _parse_with_regex(line, reg_expr) |
408 |
assert(len(trivial_parts) == 1 + len(interesting_parts)) |
409 |
terms = [] |
410 |
for i, tpart in enumerate(trivial_parts): |
411 |
part = _get_from_parsed(tpart) |
412 |
if part:
|
413 |
terms += part |
414 |
try:
|
415 |
part = _get_from_parsed(interesting_parts[i]) |
416 |
except IndexError: |
417 |
break
|
418 |
if part:
|
419 |
if tpart and not tpart[-1].endswith(' '): |
420 |
terms[-1] += ' '.join(part) |
421 |
else:
|
422 |
terms += part |
423 |
return terms
|
424 |
|
425 |
|
426 |
def ask_user(msg, true_resp=('y', ), out=stdout, user_in=stdin): |
427 |
"""Print msg and read user response
|
428 |
|
429 |
:param true_resp: (tuple of chars)
|
430 |
|
431 |
:returns: (bool) True if reponse in true responses, False otherwise
|
432 |
"""
|
433 |
yep = ', '.join(true_resp)
|
434 |
nope = '<not %s>' % yep if 'n' in true_resp or 'N' in true_resp else 'N' |
435 |
out.write('%s [%s/%s]: ' % (msg, yep, nope))
|
436 |
out.flush() |
437 |
user_response = user_in.readline() |
438 |
return user_response[0].lower() in [s.lower() for s in true_resp] |
439 |
|
440 |
|
441 |
def get_path_size(testpath): |
442 |
if path.isfile(testpath):
|
443 |
return path.getsize(testpath)
|
444 |
total_size = 0
|
445 |
for top, dirs, files in walk(path.abspath(testpath)): |
446 |
for f in files: |
447 |
f = path.join(top, f) |
448 |
if path.isfile(f):
|
449 |
total_size += path.getsize(f) |
450 |
return total_size
|
451 |
|
452 |
|
453 |
def remove_from_items(list_of_dicts, key_to_remove): |
454 |
for item in list_of_dicts: |
455 |
assert isinstance(item, dict), 'Item %s not a dict' % item |
456 |
item.pop(key_to_remove, None)
|
457 |
|
458 |
|
459 |
def filter_dicts_by_dict( |
460 |
list_of_dicts, filters, |
461 |
exact_match=True, case_sensitive=False): |
462 |
"""
|
463 |
:param list_of_dicts: (list) each dict contains "raw" key-value pairs
|
464 |
|
465 |
:param filters: (dict) filters in key-value form
|
466 |
|
467 |
:param exact_match: (bool) if false, check if the filter value is part of
|
468 |
the actual value
|
469 |
|
470 |
:param case_sensitive: (bool) revers to values only (not keys)
|
471 |
|
472 |
:returns: (list) only the dicts that match all filters
|
473 |
"""
|
474 |
new_dicts = [] |
475 |
for d in list_of_dicts: |
476 |
if set(filters).difference(d): |
477 |
continue
|
478 |
match = True
|
479 |
for k, v in filters.items(): |
480 |
dv, v = ('%s' % d[k]), ('%s' % v) |
481 |
if not case_sensitive: |
482 |
dv, v = dv.lower(), v.lower() |
483 |
if not (( |
484 |
exact_match and v == dv) or ( |
485 |
(not exact_match) and v in dv)): |
486 |
match = False
|
487 |
break
|
488 |
if match:
|
489 |
new_dicts.append(d) |
490 |
return new_dicts
|