浏览代码

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
Antoine Beaupré 10 年之前
父节点
当前提交
c7c1b9222b
共有 2 个文件被更改,包括 16 次插入12 次删除
  1. 14 10
      borg/helpers.py
  2. 2 2
      borg/testsuite/helpers.py

+ 14 - 10
borg/helpers.py

@@ -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 '%.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):
 def format_archive(archive):

+ 2 - 2
borg/testsuite/helpers.py

@@ -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',