| 1 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4 |
| 2 |
|
| 3 |
# Copyright 2011 OpenStack Foundation. |
| 4 |
# All Rights Reserved. |
| 5 |
# |
| 6 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 7 |
# not use this file except in compliance with the License. You may obtain |
| 8 |
# a copy of the License at |
| 9 |
# |
| 10 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
# |
| 12 |
# Unless required by applicable law or agreed to in writing, software |
| 13 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 14 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 15 |
# License for the specific language governing permissions and limitations |
| 16 |
# under the License. |
| 17 |
|
| 18 |
""" |
| 19 |
System-level utilities and helper functions. |
| 20 |
""" |
| 21 |
|
| 22 |
import re |
| 23 |
import sys |
| 24 |
import unicodedata |
| 25 |
|
| 26 |
import six |
| 27 |
|
| 28 |
from seamicroclient.openstack.common.gettextutils import _ # noqa |
| 29 |
|
| 30 |
|
| 31 |
# Used for looking up extensions of text |
| 32 |
# to their 'multiplied' byte amount |
| 33 |
BYTE_MULTIPLIERS = { |
| 34 |
'': 1, |
| 35 |
't': 1024 ** 4, |
| 36 |
'g': 1024 ** 3, |
| 37 |
'm': 1024 ** 2, |
| 38 |
'k': 1024, |
| 39 |
} |
| 40 |
BYTE_REGEX = re.compile(r'(^-?\d+)(\D*)') |
| 41 |
|
| 42 |
TRUE_STRINGS = ('1', 't', 'true', 'on', 'y', 'yes') |
| 43 |
FALSE_STRINGS = ('0', 'f', 'false', 'off', 'n', 'no') |
| 44 |
|
| 45 |
SLUGIFY_STRIP_RE = re.compile(r"[^\w\s-]") |
| 46 |
SLUGIFY_HYPHENATE_RE = re.compile(r"[-\s]+") |
| 47 |
|
| 48 |
|
| 49 |
def int_from_bool_as_string(subject): |
| 50 |
"""Interpret a string as a boolean and return either 1 or 0. |
| 51 |
|
| 52 |
Any string value in: |
| 53 |
|
| 54 |
('True', 'true', 'On', 'on', '1') |
| 55 |
|
| 56 |
is interpreted as a boolean True. |
| 57 |
|
| 58 |
Useful for JSON-decoded stuff and config file parsing |
| 59 |
""" |
| 60 |
return bool_from_string(subject) and 1 or 0 |
| 61 |
|
| 62 |
|
| 63 |
def bool_from_string(subject, strict=False): |
| 64 |
"""Interpret a string as a boolean. |
| 65 |
|
| 66 |
A case-insensitive match is performed such that strings matching 't', |
| 67 |
'true', 'on', 'y', 'yes', or '1' are considered True and, when |
| 68 |
`strict=False`, anything else is considered False. |
| 69 |
|
| 70 |
Useful for JSON-decoded stuff and config file parsing. |
| 71 |
|
| 72 |
If `strict=True`, unrecognized values, including None, will raise a |
| 73 |
ValueError which is useful when parsing values passed in from an API call. |
| 74 |
Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'. |
| 75 |
""" |
| 76 |
if not isinstance(subject, six.string_types): |
| 77 |
subject = str(subject) |
| 78 |
|
| 79 |
lowered = subject.strip().lower() |
| 80 |
|
| 81 |
if lowered in TRUE_STRINGS: |
| 82 |
return True |
| 83 |
elif lowered in FALSE_STRINGS: |
| 84 |
return False |
| 85 |
elif strict: |
| 86 |
acceptable = ', '.join( |
| 87 |
"'%s'" % s for s in sorted(TRUE_STRINGS + FALSE_STRINGS)) |
| 88 |
msg = _("Unrecognized value '%(val)s', acceptable values are:" |
| 89 |
" %(acceptable)s") % {'val': subject, |
| 90 |
'acceptable': acceptable} |
| 91 |
raise ValueError(msg) |
| 92 |
else: |
| 93 |
return False |
| 94 |
|
| 95 |
|
| 96 |
def safe_decode(text, incoming=None, errors='strict'): |
| 97 |
"""Decodes incoming str using `incoming` if they're not already unicode. |
| 98 |
|
| 99 |
:param incoming: Text's current encoding |
| 100 |
:param errors: Errors handling policy. See here for valid |
| 101 |
values http://docs.python.org/2/library/codecs.html |
| 102 |
:returns: text or a unicode `incoming` encoded |
| 103 |
representation of it. |
| 104 |
:raises TypeError: If text is not an isntance of str |
| 105 |
""" |
| 106 |
if not isinstance(text, six.string_types): |
| 107 |
raise TypeError("%s can't be decoded" % type(text)) |
| 108 |
|
| 109 |
if isinstance(text, six.text_type): |
| 110 |
return text |
| 111 |
|
| 112 |
if not incoming: |
| 113 |
incoming = (sys.stdin.encoding or |
| 114 |
sys.getdefaultencoding()) |
| 115 |
|
| 116 |
try: |
| 117 |
return text.decode(incoming, errors) |
| 118 |
except UnicodeDecodeError: |
| 119 |
# Note(flaper87) If we get here, it means that |
| 120 |
# sys.stdin.encoding / sys.getdefaultencoding |
| 121 |
# didn't return a suitable encoding to decode |
| 122 |
# text. This happens mostly when global LANG |
| 123 |
# var is not set correctly and there's no |
| 124 |
# default encoding. In this case, most likely |
| 125 |
# python will use ASCII or ANSI encoders as |
| 126 |
# default encodings but they won't be capable |
| 127 |
# of decoding non-ASCII characters. |
| 128 |
# |
| 129 |
# Also, UTF-8 is being used since it's an ASCII |
| 130 |
# extension. |
| 131 |
return text.decode('utf-8', errors) |
| 132 |
|
| 133 |
|
| 134 |
def safe_encode(text, incoming=None, |
| 135 |
encoding='utf-8', errors='strict'): |
| 136 |
"""Encodes incoming str/unicode using `encoding`. |
| 137 |
|
| 138 |
If incoming is not specified, text is expected to be encoded with |
| 139 |
current python's default encoding. (`sys.getdefaultencoding`) |
| 140 |
|
| 141 |
:param incoming: Text's current encoding |
| 142 |
:param encoding: Expected encoding for text (Default UTF-8) |
| 143 |
:param errors: Errors handling policy. See here for valid |
| 144 |
values http://docs.python.org/2/library/codecs.html |
| 145 |
:returns: text or a bytestring `encoding` encoded |
| 146 |
representation of it. |
| 147 |
:raises TypeError: If text is not an isntance of str |
| 148 |
""" |
| 149 |
if not isinstance(text, six.string_types): |
| 150 |
raise TypeError("%s can't be encoded" % type(text)) |
| 151 |
|
| 152 |
if not incoming: |
| 153 |
incoming = (sys.stdin.encoding or |
| 154 |
sys.getdefaultencoding()) |
| 155 |
|
| 156 |
if isinstance(text, six.text_type): |
| 157 |
return text.encode(encoding, errors) |
| 158 |
elif text and encoding != incoming: |
| 159 |
# Decode text before encoding it with `encoding` |
| 160 |
text = safe_decode(text, incoming, errors) |
| 161 |
return text.encode(encoding, errors) |
| 162 |
|
| 163 |
return text |
| 164 |
|
| 165 |
|
| 166 |
def to_bytes(text, default=0): |
| 167 |
"""Converts a string into an integer of bytes. |
| 168 |
|
| 169 |
Looks at the last characters of the text to determine |
| 170 |
what conversion is needed to turn the input text into a byte number. |
| 171 |
Supports "B, K(B), M(B), G(B), and T(B)". (case insensitive) |
| 172 |
|
| 173 |
:param text: String input for bytes size conversion. |
| 174 |
:param default: Default return value when text is blank. |
| 175 |
|
| 176 |
""" |
| 177 |
match = BYTE_REGEX.search(text) |
| 178 |
if match: |
| 179 |
magnitude = int(match.group(1)) |
| 180 |
mult_key_org = match.group(2) |
| 181 |
if not mult_key_org: |
| 182 |
return magnitude |
| 183 |
elif text: |
| 184 |
msg = _('Invalid string format: %s') % text |
| 185 |
raise TypeError(msg) |
| 186 |
else: |
| 187 |
return default |
| 188 |
mult_key = mult_key_org.lower().replace('b', '', 1) |
| 189 |
multiplier = BYTE_MULTIPLIERS.get(mult_key) |
| 190 |
if multiplier is None: |
| 191 |
msg = _('Unknown byte multiplier: %s') % mult_key_org |
| 192 |
raise TypeError(msg) |
| 193 |
return magnitude * multiplier |
| 194 |
|
| 195 |
|
| 196 |
def to_slug(value, incoming=None, errors="strict"): |
| 197 |
"""Normalize string. |
| 198 |
|
| 199 |
Convert to lowercase, remove non-word characters, and convert spaces |
| 200 |
to hyphens. |
| 201 |
|
| 202 |
Inspired by Django's `slugify` filter. |
| 203 |
|
| 204 |
:param value: Text to slugify |
| 205 |
:param incoming: Text's current encoding |
| 206 |
:param errors: Errors handling policy. See here for valid |
| 207 |
values http://docs.python.org/2/library/codecs.html |
| 208 |
:returns: slugified unicode representation of `value` |
| 209 |
:raises TypeError: If text is not an instance of str |
| 210 |
""" |
| 211 |
value = safe_decode(value, incoming, errors) |
| 212 |
# NOTE(aababilov): no need to use safe_(encode|decode) here: |
| 213 |
# encodings are always "ascii", error handling is always "ignore" |
| 214 |
# and types are always known (first: unicode; second: str) |
| 215 |
value = unicodedata.normalize("NFKD", value).encode( |
| 216 |
"ascii", "ignore").decode("ascii") |
| 217 |
value = SLUGIFY_STRIP_RE.sub("", value).strip().lower() |
| 218 |
return SLUGIFY_HYPHENATE_RE.sub("-", value) |