versionutils: add version convert helper methods

Nova[1] and Cinder[2] have same version convert methods. We can
put them in versionutils and make them don't maintain their version.

[1]https://github.com/openstack/nova/blob/master/nova/utils.py#L1044
[2]https://github.com/openstack/cinder/blob/master/cinder/utils.py#L789

Change-Id: I5a7e212bd0d661ce9ec89ae06a9f4c3bc7200d1e
This commit is contained in:
ChangBo Guo(gcb) 2015-07-04 22:24:54 +08:00
parent 9989a94f01
commit 13b55bd749
4 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,6 @@
==============
versionutils
==============
.. automodule:: oslo_utils.versionutils
:members:

View File

@ -30,6 +30,7 @@ API Documentation
api/timeutils
api/units
api/uuidutils
api/versionutils
Indices and tables
==================

View File

@ -67,3 +67,19 @@ class IsCompatibleTestCase(test_base.BaseTestCase):
same_major=False))
self.assertTrue(versionutils.is_compatible('1.0', '2.0',
same_major=False))
def test_convert_version_to_int(self):
self.assertEqual(6002000, versionutils.convert_version_to_int('6.2.0'))
self.assertEqual(6004003,
versionutils.convert_version_to_int((6, 4, 3)))
self.assertEqual(5, versionutils.convert_version_to_int((5, )))
self.assertRaises(ValueError,
versionutils.convert_version_to_int, '5a.6b')
def test_convert_version_to_string(self):
self.assertEqual('6.7.0', versionutils.convert_version_to_str(6007000))
self.assertEqual('4', versionutils.convert_version_to_str(4))
def test_convert_version_to_tuple(self):
self.assertEqual((6, 7, 0),
versionutils.convert_version_to_tuple('6.7.0'))

View File

@ -19,7 +19,9 @@ Helpers for comparing version strings.
import logging
from oslo_utils._i18n import _
import pkg_resources
import six
LOG = logging.getLogger(__name__)
@ -46,3 +48,29 @@ def is_compatible(requested_version, current_version, same_major=True):
return False
return current_parts >= requested_parts
def convert_version_to_int(version):
try:
if isinstance(version, six.string_types):
version = convert_version_to_tuple(version)
if isinstance(version, tuple):
return six.moves.reduce(lambda x, y: (x * 1000) + y, version)
except Exception as ex:
msg = _("Version %s is invalid.") % version
six.raise_from(ValueError(msg), ex)
def convert_version_to_str(version_int):
version_numbers = []
factor = 1000
while version_int != 0:
version_number = version_int - (version_int // factor * factor)
version_numbers.insert(0, six.text_type(version_number))
version_int = version_int // factor
return '.'.join(map(str, version_numbers))
def convert_version_to_tuple(version_str):
return tuple(int(part) for part in version_str.split('.'))