~verterok/charms/xenial/conn-check/focal

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/core/strutils.py

  • Committer: Guillermo Gonzalez
  • Date: 2023-06-29 16:33:24 UTC
  • Revision ID: guillermo.gonzalez@canonical.com-20230629163324-03vq3m9qtvu6f6or
update charmhelpers

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# See the License for the specific language governing permissions and
16
16
# limitations under the License.
17
17
 
18
 
import six
19
18
import re
20
19
 
21
 
 
22
 
def bool_from_string(value):
 
20
TRUTHY_STRINGS = {'y', 'yes', 'true', 't', 'on'}
 
21
FALSEY_STRINGS = {'n', 'no', 'false', 'f', 'off'}
 
22
 
 
23
 
 
24
def bool_from_string(value, truthy_strings=TRUTHY_STRINGS, falsey_strings=FALSEY_STRINGS, assume_false=False):
23
25
    """Interpret string value as boolean.
24
26
 
25
27
    Returns True if value translates to True otherwise False.
26
28
    """
27
 
    if isinstance(value, six.string_types):
28
 
        value = six.text_type(value)
 
29
    if isinstance(value, str):
 
30
        value = str(value)
29
31
    else:
30
32
        msg = "Unable to interpret non-string value '%s' as boolean" % (value)
31
33
        raise ValueError(msg)
32
34
 
33
35
    value = value.strip().lower()
34
36
 
35
 
    if value in ['y', 'yes', 'true', 't', 'on']:
 
37
    if value in truthy_strings:
36
38
        return True
37
 
    elif value in ['n', 'no', 'false', 'f', 'off']:
 
39
    elif value in falsey_strings or assume_false:
38
40
        return False
39
41
 
40
42
    msg = "Unable to interpret string value '%s' as boolean" % (value)
58
60
        'P': 5,
59
61
        'PB': 5,
60
62
    }
61
 
    if isinstance(value, six.string_types):
62
 
        value = six.text_type(value)
 
63
    if isinstance(value, str):
 
64
        value = str(value)
63
65
    else:
64
 
        msg = "Unable to interpret non-string value '%s' as boolean" % (value)
 
66
        msg = "Unable to interpret non-string value '%s' as bytes" % (value)
65
67
        raise ValueError(msg)
66
68
    matches = re.match("([0-9]+)([a-zA-Z]+)", value)
67
 
    if not matches:
68
 
        msg = "Unable to interpret string value '%s' as bytes" % (value)
69
 
        raise ValueError(msg)
70
 
    return int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])
 
69
    if matches:
 
70
        size = int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])
 
71
    else:
 
72
        # Assume that value passed in is bytes
 
73
        try:
 
74
            size = int(value)
 
75
        except ValueError:
 
76
            msg = "Unable to interpret string value '%s' as bytes" % (value)
 
77
            raise ValueError(msg)
 
78
    return size
 
79
 
 
80
 
 
81
class BasicStringComparator(object):
 
82
    """Provides a class that will compare strings from an iterator type object.
 
83
    Used to provide > and < comparisons on strings that may not necessarily be
 
84
    alphanumerically ordered.  e.g. OpenStack or Ubuntu releases AFTER the
 
85
    z-wrap.
 
86
    """
 
87
 
 
88
    _list = None
 
89
 
 
90
    def __init__(self, item):
 
91
        if self._list is None:
 
92
            raise Exception("Must define the _list in the class definition!")
 
93
        try:
 
94
            self.index = self._list.index(item)
 
95
        except Exception:
 
96
            raise KeyError("Item '{}' is not in list '{}'"
 
97
                           .format(item, self._list))
 
98
 
 
99
    def __eq__(self, other):
 
100
        assert isinstance(other, str) or isinstance(other, self.__class__)
 
101
        return self.index == self._list.index(other)
 
102
 
 
103
    def __ne__(self, other):
 
104
        return not self.__eq__(other)
 
105
 
 
106
    def __lt__(self, other):
 
107
        assert isinstance(other, str) or isinstance(other, self.__class__)
 
108
        return self.index < self._list.index(other)
 
109
 
 
110
    def __ge__(self, other):
 
111
        return not self.__lt__(other)
 
112
 
 
113
    def __gt__(self, other):
 
114
        assert isinstance(other, str) or isinstance(other, self.__class__)
 
115
        return self.index > self._list.index(other)
 
116
 
 
117
    def __le__(self, other):
 
118
        return not self.__gt__(other)
 
119
 
 
120
    def __str__(self):
 
121
        """Always give back the item at the index so it can be used in
 
122
        comparisons like:
 
123
 
 
124
        s_mitaka = CompareOpenStack('mitaka')
 
125
        s_newton = CompareOpenstack('newton')
 
126
 
 
127
        assert s_newton > s_mitaka
 
128
 
 
129
        @returns: <string>
 
130
        """
 
131
        return self._list[self.index]