15
15
# See the License for the specific language governing permissions and
16
16
# limitations under the License.
22
def bool_from_string(value):
20
TRUTHY_STRINGS = {'y', 'yes', 'true', 't', 'on'}
21
FALSEY_STRINGS = {'n', 'no', 'false', 'f', 'off'}
24
def bool_from_string(value, truthy_strings=TRUTHY_STRINGS, falsey_strings=FALSEY_STRINGS, assume_false=False):
23
25
"""Interpret string value as boolean.
25
27
Returns True if value translates to True otherwise False.
27
if isinstance(value, six.string_types):
28
value = six.text_type(value)
29
if isinstance(value, str):
30
32
msg = "Unable to interpret non-string value '%s' as boolean" % (value)
31
33
raise ValueError(msg)
33
35
value = value.strip().lower()
35
if value in ['y', 'yes', 'true', 't', 'on']:
37
if value in truthy_strings:
37
elif value in ['n', 'no', 'false', 'f', 'off']:
39
elif value in falsey_strings or assume_false:
40
42
msg = "Unable to interpret string value '%s' as boolean" % (value)
61
if isinstance(value, six.string_types):
62
value = six.text_type(value)
63
if isinstance(value, str):
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)
68
msg = "Unable to interpret string value '%s' as bytes" % (value)
70
return int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])
70
size = int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])
72
# Assume that value passed in is bytes
76
msg = "Unable to interpret string value '%s' as bytes" % (value)
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
90
def __init__(self, item):
91
if self._list is None:
92
raise Exception("Must define the _list in the class definition!")
94
self.index = self._list.index(item)
96
raise KeyError("Item '{}' is not in list '{}'"
97
.format(item, self._list))
99
def __eq__(self, other):
100
assert isinstance(other, str) or isinstance(other, self.__class__)
101
return self.index == self._list.index(other)
103
def __ne__(self, other):
104
return not self.__eq__(other)
106
def __lt__(self, other):
107
assert isinstance(other, str) or isinstance(other, self.__class__)
108
return self.index < self._list.index(other)
110
def __ge__(self, other):
111
return not self.__lt__(other)
113
def __gt__(self, other):
114
assert isinstance(other, str) or isinstance(other, self.__class__)
115
return self.index > self._list.index(other)
117
def __le__(self, other):
118
return not self.__gt__(other)
121
"""Always give back the item at the index so it can be used in
124
s_mitaka = CompareOpenStack('mitaka')
125
s_newton = CompareOpenstack('newton')
127
assert s_newton > s_mitaka
131
return self._list[self.index]