convert to more flexible size formatters

those can now support both file sizes (in SI/decimal format, powers of 10) and memory sizes (in binary format, powers of 2)

tests still fail because the result is always displayed as floats
This commit is contained in:
Antoine Beaupré 2015-10-20 12:42:54 -04:00
parent de390b1ca6
commit c7c1b9222b
2 changed files with 16 additions and 12 deletions

View File

@ -460,16 +460,20 @@ def format_file_mode(mod):
def format_file_size(v):
"""Format file size into a human friendly format
"""
if abs(v) > 10**12:
return '%.2f TB' % (v / 10**12)
elif abs(v) > 10**9:
return '%.2f GB' % (v / 10**9)
elif abs(v) > 10**6:
return '%.2f MB' % (v / 10**6)
elif abs(v) > 10**3:
return '%.2f kB' % (v / 10**3)
else:
return '%d B' % v
return sizeof_fmt_decimal(v, suffix='B', sep=' ')
def sizeof_fmt(num, suffix='B', units=None, power=None, sep=''):
for unit in units[:-1]:
if abs(round(num, 2)) < power:
return "%3.2f%s%s%s" % (num, sep, unit, suffix)
num /= float(power)
return "%.2f%s%s%s" % (num, sep, units[-1], suffix)
def sizeof_fmt_iec(num, suffix='B', sep=''):
return sizeof_fmt(num, suffix=suffix, sep=sep, units=['','Ki','Mi','Gi','Ti','Pi','Ei','Zi', 'Yi'], power=1024)
def sizeof_fmt_decimal(num, suffix='B', sep=''):
return sizeof_fmt(num, suffix=suffix, sep=sep, units=['','k','M','G','T','P','E','Z', 'Y'], power=1000)
def format_archive(archive):

View File

@ -450,7 +450,7 @@ def test_size():
1: '1 B',
142: '142 B',
999: '999 B',
1000: '1000 B', # XXX: fail
1000: '1.00 kB',
1001: '1.00 kB',
1234: '1.23 kB',
10**6: '1.00 MB',
@ -459,7 +459,7 @@ def test_size():
10**9+1: '1.00 GB',
10**9-1: '1.00 GB',
10**9-10*10**3: '999.99 MB',
10**9-10*10**3+1: '1.00 GB',
10**9-10*10**3+5*10**3: '1.00 GB',
10**12+1: '1.00 TB',
10**15+1: '1.00 PB',
10**18+1: '1.00 EB',