~james-page/charms/trusty/swift-proxy/trunk

« back to all changes in this revision

Viewing changes to charmhelpers/core/strutils.py

  • Committer: James Page
  • Date: 2016-01-19 14:46:01 UTC
  • mfrom: (134.1.1 stable.remote)
  • Revision ID: james.page@ubuntu.com-20160119144601-66bdh4r0va0pn9og
Fix liberty/mitaka typo from previous test definition update batch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# -*- coding: utf-8 -*-
 
3
 
 
4
# Copyright 2014-2015 Canonical Limited.
 
5
#
 
6
# This file is part of charm-helpers.
 
7
#
 
8
# charm-helpers is free software: you can redistribute it and/or modify
 
9
# it under the terms of the GNU Lesser General Public License version 3 as
 
10
# published by the Free Software Foundation.
 
11
#
 
12
# charm-helpers is distributed in the hope that it will be useful,
 
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
15
# GNU Lesser General Public License for more details.
 
16
#
 
17
# You should have received a copy of the GNU Lesser General Public License
 
18
# along with charm-helpers.  If not, see <http://www.gnu.org/licenses/>.
 
19
 
 
20
import six
 
21
import re
 
22
 
 
23
 
 
24
def bool_from_string(value):
 
25
    """Interpret string value as boolean.
 
26
 
 
27
    Returns True if value translates to True otherwise False.
 
28
    """
 
29
    if isinstance(value, six.string_types):
 
30
        value = six.text_type(value)
 
31
    else:
 
32
        msg = "Unable to interpret non-string value '%s' as boolean" % (value)
 
33
        raise ValueError(msg)
 
34
 
 
35
    value = value.strip().lower()
 
36
 
 
37
    if value in ['y', 'yes', 'true', 't', 'on']:
 
38
        return True
 
39
    elif value in ['n', 'no', 'false', 'f', 'off']:
 
40
        return False
 
41
 
 
42
    msg = "Unable to interpret string value '%s' as boolean" % (value)
 
43
    raise ValueError(msg)
 
44
 
 
45
 
 
46
def bytes_from_string(value):
 
47
    """Interpret human readable string value as bytes.
 
48
 
 
49
    Returns int
 
50
    """
 
51
    BYTE_POWER = {
 
52
        'K': 1,
 
53
        'KB': 1,
 
54
        'M': 2,
 
55
        'MB': 2,
 
56
        'G': 3,
 
57
        'GB': 3,
 
58
        'T': 4,
 
59
        'TB': 4,
 
60
        'P': 5,
 
61
        'PB': 5,
 
62
    }
 
63
    if isinstance(value, six.string_types):
 
64
        value = six.text_type(value)
 
65
    else:
 
66
        msg = "Unable to interpret non-string value '%s' as boolean" % (value)
 
67
        raise ValueError(msg)
 
68
    matches = re.match("([0-9]+)([a-zA-Z]+)", value)
 
69
    if not matches:
 
70
        msg = "Unable to interpret string value '%s' as bytes" % (value)
 
71
        raise ValueError(msg)
 
72
    return int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])