From 688088547b80f74708afbcb5066be75fe3f3ab2a Mon Sep 17 00:00:00 2001 From: Brian Coca Date: Tue, 7 Jul 2015 15:58:18 -0400 Subject: [PATCH] new human_readable filter to transform bits and bytes into cake (not really) --- lib/ansible/plugins/filter/mathstuff.py | 29 +++++++++++++++++++ .../roles/test_filters/tasks/main.yml | 8 +++++ 2 files changed, 37 insertions(+) diff --git a/lib/ansible/plugins/filter/mathstuff.py b/lib/ansible/plugins/filter/mathstuff.py index c6a49485a40..516ef1c6774 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 3d1ee322e30..e0a22815017 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")' +