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