Clean user given filenames, and set the same behaviour in curses as in gtk:
[pysize.git] / ui / utils.py
blob6fb1c7a8afcef6c229f67de9859e9394f2d58cb1
1 import re
3 UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
5 def human_unit(size):
6 """Return a string of the form '12.34 MiB' given a size in bytes."""
7 for i in xrange(len(UNITS) - 1, 0, -1):
8 base = 1 << (10 * i)
9 if (2 * base < size):
10 return '%.2f %s' % ((float(size) / base), UNITS[i])
11 return str(size) + ' ' + UNITS[0]
13 def short_string(string, length):
14 """Returned a cut copy of the string, replace the middle with '~'."""
15 if (len(string) > length):
16 middle = length / 2
17 return string[:middle] + '~' + string[middle - length + 1:]
18 return string
20 MIN_SIZE_REGEXP = re.compile('^([0-9]+)(.?)(.*)$')
22 def min_size_to_consider(min_size='auto', height=0):
23 if min_size == 'auto':
24 return 1.0 / height
25 match = MIN_SIZE_REGEXP.match(min_size)
26 if not match:
27 raise Exception, 'Cannot parse: ' + min_size
28 (min_size, letter, suffix) = match.groups()
29 units_letters = [u[0] for u in UNITS]
30 if not letter:
31 letter = 'B'
32 letter = letter.upper()
33 if not (letter in units_letters and suffix in ('iB', '')):
34 raise Exception, 'Cannot parse unit in: ' + min_size
35 return int(min_size) * 1024 ** units_letters.index(letter)
37 def clean_filename(filename):
38 filename = filename.rstrip('/')
39 while '//' in filename:
40 filename = filename.replace('//', '/')
41 return filename