diff --git a/lib/ansible/plugins/filter/mathstuff.py b/lib/ansible/plugins/filter/mathstuff.py index c6a49485a4..516ef1c677 100644 --- a/lib/ansible/plugins/filter/mathstuff.py +++ b/lib/ansible/plugins/filter/mathstuff.py @@ -101,6 +101,32 @@ def inversepower(x, base=2): raise errors.AnsibleFilterError('root() can only be used on numbers: %s' % str(e)) +def human_readable(size, isbits=False, unit=None): + + base = 'bits' if isbits else 'Bytes' + suffix = '' + + ranges = ( + (1<<70L, 'Z'), + (1<<60L, 'E'), + (1<<50L, 'P'), + (1<<40L, 'T'), + (1<<30L, 'G'), + (1<<20L, 'M'), + (1<<10L, 'K'), + (1, base) + ) + + for limit, suffix in ranges: + if (unit is None and size >= limit) or \ + unit is not None and unit.upper() == suffix: + break + + if limit != 1: + suffix += base[0] + + return '%.2f %s' % (float(size)/ limit, suffix) + class FilterModule(object): ''' Ansible math jinja2 filters ''' @@ -123,4 +149,7 @@ class FilterModule(object): 'symmetric_difference': symmetric_difference, 'union': union, + # computer theory + 'human_readable' : human_readable, + } diff --git a/test/integration/roles/test_filters/tasks/main.yml b/test/integration/roles/test_filters/tasks/main.yml index 3d1ee322e3..e0a2281501 100644 --- a/test/integration/roles/test_filters/tasks/main.yml +++ b/test/integration/roles/test_filters/tasks/main.yml @@ -41,3 +41,11 @@ that: - 'diff_result.stdout == ""' +- name: Verify human_readable + assert: + that: + - '"10.00 KB" == 10240|human_readable' + - '"97.66 MB" == 102400000|human_readable' + - '"0.10 GB" == 102400000|human_readable(unit="G")' + - '"0.10 Gb" == 102400000|human_readable(isbits=True, unit="G")' +