~ubuntu-branches/ubuntu/saucy/cinder/saucy

« back to all changes in this revision

Viewing changes to cinder/openstack/common/strutils.py

  • Committer: Package Import Robot
  • Author(s): James Page, Chuck Short, Adam Gandelman, James Page
  • Date: 2013-07-19 14:14:40 UTC
  • mfrom: (1.1.17)
  • Revision ID: package-import@ubuntu.com-20130719141440-brarmy8wxm3vosaf
Tags: 1:2013.2~b2-0ubuntu1
[ Chuck Short ]
* debian/patches/avoid_paramiko_vers_depends.patch: Refreshed
* debian/control: Add missing testrepostory.
* debian/rules: Use testr directly.

[ Adam Gandelman ]
* debian/control:
  - Add minimum requirement python-anyjson (>= 0.3.3).
  - Add minimum requirement python-keystoneclient (>= 0.2.3).
  - Add minimum requirement python-kombu (>= 2.5.12).

[ James Page ]
* New upstream release.
* d/control: Update VCS fields for new branch locations.
* d/rules: Run unit tests in parallel.

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
System-level utilities and helper functions.
20
20
"""
21
21
 
 
22
import re
22
23
import sys
 
24
import unicodedata
23
25
 
24
26
from cinder.openstack.common.gettextutils import _
25
27
 
26
28
 
 
29
# Used for looking up extensions of text
 
30
# to their 'multiplied' byte amount
 
31
BYTE_MULTIPLIERS = {
 
32
    '': 1,
 
33
    't': 1024 ** 4,
 
34
    'g': 1024 ** 3,
 
35
    'm': 1024 ** 2,
 
36
    'k': 1024,
 
37
}
 
38
BYTE_REGEX = re.compile(r'(^-?\d+)(\D*)')
 
39
 
27
40
TRUE_STRINGS = ('1', 't', 'true', 'on', 'y', 'yes')
28
41
FALSE_STRINGS = ('0', 'f', 'false', 'off', 'n', 'no')
29
42
 
 
43
SLUGIFY_STRIP_RE = re.compile(r"[^\w\s-]")
 
44
SLUGIFY_HYPHENATE_RE = re.compile(r"[-\s]+")
 
45
 
30
46
 
31
47
def int_from_bool_as_string(subject):
32
 
    """
33
 
    Interpret a string as a boolean and return either 1 or 0.
 
48
    """Interpret a string as a boolean and return either 1 or 0.
34
49
 
35
50
    Any string value in:
36
51
 
44
59
 
45
60
 
46
61
def bool_from_string(subject, strict=False):
47
 
    """
48
 
    Interpret a string as a boolean.
 
62
    """Interpret a string as a boolean.
49
63
 
50
64
    A case-insensitive match is performed such that strings matching 't',
51
65
    'true', 'on', 'y', 'yes', or '1' are considered True and, when
78
92
 
79
93
 
80
94
def safe_decode(text, incoming=None, errors='strict'):
81
 
    """
82
 
    Decodes incoming str using `incoming` if they're
83
 
    not already unicode.
 
95
    """Decodes incoming str using `incoming` if they're not already unicode.
84
96
 
85
97
    :param incoming: Text's current encoding
86
98
    :param errors: Errors handling policy. See here for valid
119
131
 
120
132
def safe_encode(text, incoming=None,
121
133
                encoding='utf-8', errors='strict'):
122
 
    """
123
 
    Encodes incoming str/unicode using `encoding`. If
124
 
    incoming is not specified, text is expected to
125
 
    be encoded with current python's default encoding.
126
 
    (`sys.getdefaultencoding`)
 
134
    """Encodes incoming str/unicode using `encoding`.
 
135
 
 
136
    If incoming is not specified, text is expected to be encoded with
 
137
    current python's default encoding. (`sys.getdefaultencoding`)
127
138
 
128
139
    :param incoming: Text's current encoding
129
140
    :param encoding: Expected encoding for text (Default UTF-8)
148
159
        return text.encode(encoding, errors)
149
160
 
150
161
    return text
 
162
 
 
163
 
 
164
def to_bytes(text, default=0):
 
165
    """Converts a string into an integer of bytes.
 
166
 
 
167
    Looks at the last characters of the text to determine
 
168
    what conversion is needed to turn the input text into a byte number.
 
169
    Supports "B, K(B), M(B), G(B), and T(B)". (case insensitive)
 
170
 
 
171
    :param text: String input for bytes size conversion.
 
172
    :param default: Default return value when text is blank.
 
173
 
 
174
    """
 
175
    match = BYTE_REGEX.search(text)
 
176
    if match:
 
177
        magnitude = int(match.group(1))
 
178
        mult_key_org = match.group(2)
 
179
        if not mult_key_org:
 
180
            return magnitude
 
181
    elif text:
 
182
        msg = _('Invalid string format: %s') % text
 
183
        raise TypeError(msg)
 
184
    else:
 
185
        return default
 
186
    mult_key = mult_key_org.lower().replace('b', '', 1)
 
187
    multiplier = BYTE_MULTIPLIERS.get(mult_key)
 
188
    if multiplier is None:
 
189
        msg = _('Unknown byte multiplier: %s') % mult_key_org
 
190
        raise TypeError(msg)
 
191
    return magnitude * multiplier
 
192
 
 
193
 
 
194
def to_slug(value, incoming=None, errors="strict"):
 
195
    """Normalize string.
 
196
 
 
197
    Convert to lowercase, remove non-word characters, and convert spaces
 
198
    to hyphens.
 
199
 
 
200
    Inspired by Django's `slugify` filter.
 
201
 
 
202
    :param value: Text to slugify
 
203
    :param incoming: Text's current encoding
 
204
    :param errors: Errors handling policy. See here for valid
 
205
        values http://docs.python.org/2/library/codecs.html
 
206
    :returns: slugified unicode representation of `value`
 
207
    :raises TypeError: If text is not an instance of basestring
 
208
    """
 
209
    value = safe_decode(value, incoming, errors)
 
210
    # NOTE(aababilov): no need to use safe_(encode|decode) here:
 
211
    # encodings are always "ascii", error handling is always "ignore"
 
212
    # and types are always known (first: unicode; second: str)
 
213
    value = unicodedata.normalize("NFKD", value).encode(
 
214
        "ascii", "ignore").decode("ascii")
 
215
    value = SLUGIFY_STRIP_RE.sub("", value).strip().lower()
 
216
    return SLUGIFY_HYPHENATE_RE.sub("-", value)