File: versionutils.py

package info (click to toggle)
python-oslo.utils 9.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,068 kB
  • sloc: python: 7,302; makefile: 21; sh: 2
file content (125 lines) | stat: -rw-r--r-- 4,057 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Helpers for comparing version strings.

.. versionadded:: 1.6
"""

import functools
import operator
import re

import packaging.version

from oslo_utils._i18n import _


def is_compatible(requested_version, current_version, same_major=True):
    """Determine whether `requested_version` is satisfied by
    `current_version`; in other words, `current_version` is >=
    `requested_version`.

    :param requested_version: version to check for compatibility
    :param current_version: version to check against
    :param same_major: if True, the major version must be identical between
        `requested_version` and `current_version`. This is used when a
        major-version difference indicates incompatibility between the two
        versions. Since this is the common-case in practice, the default is
        True.
    :returns: True if compatible, False if not
    """
    requested = packaging.version.Version(requested_version)
    current = packaging.version.Version(current_version)

    if same_major:
        if requested.major != current.major:
            return False

    return current >= requested


def convert_version_to_int(version):
    """Convert a version to an integer.

    *version* must be a string with dots or a tuple of integers.

    .. versionadded:: 2.0
    """
    try:
        if isinstance(version, str):
            version = convert_version_to_tuple(version)
        if isinstance(version, tuple):
            return functools.reduce(lambda x, y: (x * 1000) + y, version)
    except Exception as ex:
        msg = _("Version %s is invalid.") % version
        raise ValueError(msg) from ex


def convert_version_to_str(version_int):
    """Convert a version integer to a string with dots.

    .. versionadded:: 2.0
    """
    version_numbers = []
    factor = 1000
    while version_int != 0:
        version_number = version_int - (version_int // factor * factor)
        version_numbers.insert(0, str(version_number))
        version_int = version_int // factor

    return '.'.join(map(str, version_numbers))


def convert_version_to_tuple(version_str):
    """Convert a version string with dots to a tuple.

    .. versionadded:: 2.0
    """
    version_str = re.sub(r'(\d+)(a|alpha|b|beta|rc)\d+$', '\\1', version_str)
    return tuple(int(part) for part in version_str.split('.'))


class VersionPredicate:
    """Parse version predicate and check version requirements

    This is based on the implementation of distutils.VersionPredicate

    .. versionadded:: 7.4
    """
    _PREDICATE_MATCH = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s]+)\s*$")
    _COMP_MAP = {
        "<": operator.lt, "<=": operator.le, "==": operator.eq,
        ">": operator.gt, ">=": operator.ge, "!=": operator.ne
    }

    def __init__(self, predicate_str):
        self.pred = [self._parse_predicate(pred) for pred
                     in predicate_str.split(',')]

    def _parse_predicate(self, pred):
        res = self._PREDICATE_MATCH.match(pred)
        if not res:
            raise ValueError("bad package restriction syntax: %s" % pred)
        cond, ver_str = res.groups()
        return (cond, packaging.version.Version(ver_str))

    def satisfied_by(self, version_str):
        version = packaging.version.Version(version_str)
        for cond, ver in self.pred:
            if not self._COMP_MAP[cond](version, ver):
                return False
        return True