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): def format_file_size(v):
"""Format file size into a human friendly format """Format file size into a human friendly format
""" """
if abs(v) > 10**12: return sizeof_fmt_decimal(v, suffix='B', sep=' ')
return '%.2f TB' % (v / 10**12)
elif abs(v) > 10**9: def sizeof_fmt(num, suffix='B', units=None, power=None, sep=''):
return '%.2f GB' % (v / 10**9) for unit in units[:-1]:
elif abs(v) > 10**6: if abs(round(num, 2)) < power:
return '%.2f MB' % (v / 10**6) return "%3.2f%s%s%s" % (num, sep, unit, suffix)
elif abs(v) > 10**3: num /= float(power)
return '%.2f kB' % (v / 10**3) return "%.2f%s%s%s" % (num, sep, units[-1], suffix)
else:
return '%d B' % v 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): def format_archive(archive):

View File

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