From 54e147cf3efe50a77bdd8f0b3c2887e2ba5f38f8 Mon Sep 17 00:00:00 2001 From: OpenStack Proposal Bot Date: Wed, 16 Nov 2016 22:15:02 +0000 Subject: [PATCH] To display image size in human friendly format Include option '--human-readable' to 'image show' command. This option displays image size in human readable format (such as K, M, G, T,..) (Re-submitted as the original https://review.openstack.org/#/c/399982/ had a parent commit not present in Gerrit, was proposed by "OpenStack Proposal Bot") Change-Id: I0ef74c2ec978483fe49156c88acf5c369a8fa5c2 Closes-Bug: #1640086 Co-Authored-By: Badhmapriya Boopalan --- osc_lib/tests/test_utils.py | 12 ++++++++++++ osc_lib/utils.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/osc_lib/tests/test_utils.py b/osc_lib/tests/test_utils.py index 2c5e34f..4128fac 100644 --- a/osc_lib/tests/test_utils.py +++ b/osc_lib/tests/test_utils.py @@ -310,6 +310,18 @@ class TestUtils(test_utils.TestCase): def test_is_ascii_string(self): self.assertFalse(utils.is_ascii(u'\u2665')) + def test_format_size(self): + self.assertEqual("999", utils.format_size(999)) + self.assertEqual("100K", utils.format_size(100000)) + self.assertEqual("2M", utils.format_size(2000000)) + self.assertEqual( + "16.4M", utils.format_size(16361280) + ) + self.assertEqual( + "1.6G", utils.format_size(1576395005) + ) + self.assertEqual("0", utils.format_size(None)) + class NoUniqueMatch(Exception): pass diff --git a/osc_lib/utils.py b/osc_lib/utils.py index 95ef920..3d7d1dc 100644 --- a/osc_lib/utils.py +++ b/osc_lib/utils.py @@ -489,3 +489,33 @@ def wait_for_status(status_f, callback(progress) time.sleep(sleep_time) return retval + + +def format_size(size): + """Display size of a resource in a human readable format + + :param string size: + The size of the resource in bytes. + + :returns: + Returns the size in human-friendly format + :rtype string: + + This function converts the size (provided in bytes) of a resource + into a human-friendly format such as K, M, G, T, P, E, Z + """ + + suffix = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z'] + base = 1000.0 + index = 0 + + if size is None: + size = 0 + while size >= base: + index = index + 1 + size = size / base + + padded = '%.1f' % size + stripped = padded.rstrip('0').rstrip('.') + + return '%s%s' % (stripped, suffix[index])