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