comparison env/lib/python3.9/site-packages/galaxy/util/bytesize.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
1 SUFFIX_TO_BYTES = {
2 'KI': 1024,
3 'MI': 1024**2,
4 'GI': 1024**3,
5 'TI': 1024**4,
6 'PI': 1024**5,
7 'EI': 1024**6,
8 'K': 1000,
9 'M': 1000**2,
10 'G': 1000**3,
11 'T': 1000**4,
12 'P': 1000**5,
13 'E': 1000**6,
14 }
15
16
17 class ByteSize:
18 """Convert multiples of bytes to various units."""
19
20 def __init__(self, value):
21 """
22 Represents a quantity of bytes.
23
24 `value` may be an integer, in which case it is assumed to be bytes.
25 If value is a string, it is parsed as bytes if no suffix (Mi, M, Gi, G ...)
26 is found.
27
28 >>> values = [128974848, '129e6', '129M', '123Mi' ]
29 >>> [ByteSize(v).to_unit('M') for v in values]
30 ['128M', '129M', '129M', '128M']
31 """
32 self.value = parse_bytesize(value)
33
34 def to_unit(self, unit=None, as_string=True):
35 """unit must be `None` or one of Ki,Mi,Gi,Ti,Pi,Ei,K,M,G,T,P."""
36 if unit is None:
37 if as_string:
38 return str(self.value)
39 return self.value
40 unit = unit.upper()
41 new_value = int(self.value / SUFFIX_TO_BYTES[unit])
42 if not as_string:
43 return new_value
44 return f"{new_value}{unit}"
45
46
47 def parse_bytesize(value):
48 if isinstance(value, int) or isinstance(value, float):
49 # Assume bytes
50 return value
51 value = value.upper()
52 found_suffix = None
53 for suffix in SUFFIX_TO_BYTES:
54 if value.endswith(suffix):
55 found_suffix = suffix
56 break
57 if found_suffix:
58 value = value[:-len(found_suffix)]
59 try:
60 value = int(value)
61 except ValueError:
62 try:
63 value = float(value)
64 except ValueError:
65 raise ValueError(f"{value} is not a valid integer or float value")
66 if found_suffix:
67 value = value * SUFFIX_TO_BYTES[found_suffix]
68 return value