provide sizes in readable units when possible for resize
authorPaul Tonelli <paul.tonelli@logilab.fr>
Thu, 21 Mar 2013 14:05:08 +0100
changeset 86 ce88c3698ff5
parent 85 8010f73133e5
child 87 ed84dcff0f2c
provide sizes in readable units when possible for resize
_states/tmp_state.py
--- a/_states/tmp_state.py	Mon Mar 18 11:47:15 2013 +0100
+++ b/_states/tmp_state.py	Thu Mar 21 14:05:08 2013 +0100
@@ -1,6 +1,7 @@
 # -*- coding: utf-8 -*-
 # author: Paul Tonelli <ptonelli@logilab.fr>
 
+from math import log, floor
 import salt.utils
 import os
 
@@ -146,7 +147,8 @@
         return ret
     ret['changes']['resized'] = True
     ret['comment'] = 'Resized filesystem {0} from {1} to {2}'.format(name,
-            str(current_size * block_size), str(max(new_size, minimum_size)))
+            _convert_to_units(current_size * block_size, improve=True),
+            _convert_to_units(max(new_size, minimum_size)), improve=True)
     return ret
 
 def _has_enough_free_space(fs, space):
@@ -156,7 +158,7 @@
         return True
     return False
 
-def _convert_to_units(value):
+def _convert_to_units(value, improve=False):
     '''
     convert value to a float in the correct unit. Accepted units are:
         - K (kilobytes)
@@ -164,13 +166,28 @@
         - G (gigabytes)
         - T (terabytes)
     '''
-    conversion_factor={'K': 1, 'M': 2, 'G': 3, 'T': 4}
-    if str(value)[-1].isalpha():
-        assert str(value)[-1] in conversion_factor
-        factor = conversion_factor[str(value)[-1]]
-        value = str(value)[:-1]
+    cf={'K': 1, 'M': 2, 'G': 3, 'T': 4}
+    if improve:
+        assert not str(value)[-1].isalpha()
+        assert float(value)
+        factor = floor(log(value)/log(1024))
+        if factor > 0:
+            if factor <= max(cf.values()):
+                return '{0:.2f}'.format(value / (1024**factor)) + [item for item in cf if
+                        cf[item] == factor][0]
+            else:
+                return '{0:.2f}'.format(value / (1024**max(cf.values()))) + [item for item in cf if
+                        cf[item] == max(cf.values())][0]
+        else:
+            return str(value)
+
     else:
-        factor = 0
-    value=float(value)
-    return int(value * pow(1024,factor))
+        if str(value)[-1].isalpha():
+            assert str(value)[-1] in cf
+            factor = cf[str(value)[-1]]
+            value = str(value)[:-1]
+        else:
+            factor = 0
+        value=float(value)
+        return int(value * 1024**factor)