Mercurial > repos > guerler > springsuite
comparison planemo/lib/python3.7/site-packages/galaxy/util/bytesize.py @ 1:56ad4e20f292 draft
"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
| author | guerler |
|---|---|
| date | Fri, 31 Jul 2020 00:32:28 -0400 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 0:d30785e31577 | 1:56ad4e20f292 |
|---|---|
| 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(object): | |
| 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 "{value}{suffix}".format(value=new_value, suffix=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("{value} is not a valid integer or float value".format(value=value)) | |
| 66 if found_suffix: | |
| 67 value = value * SUFFIX_TO_BYTES[found_suffix] | |
| 68 return value |
