]> git.proxmox.com Git - ceph.git/blob - ceph/src/ceph-volume/ceph_volume/util/__init__.py
update sources to 12.2.8
[ceph.git] / ceph / src / ceph-volume / ceph_volume / util / __init__.py
1 import logging
2 from math import floor
3 from ceph_volume import terminal
4
5
6 logger = logging.getLogger(__name__)
7
8
9 def as_string(string):
10 """
11 Ensure that whatever type of string is incoming, it is returned as an
12 actual string, versus 'bytes' which Python 3 likes to use.
13 """
14 if isinstance(string, bytes):
15 # we really ignore here if we can't properly decode with utf-8
16 return string.decode('utf-8', 'ignore')
17 return string
18
19
20 def as_bytes(string):
21 """
22 Ensure that whatever type of string is incoming, it is returned as bytes,
23 encoding to utf-8 otherwise
24 """
25 if isinstance(string, bytes):
26 return string
27 return string.encode('utf-8', errors='ignore')
28
29
30 def str_to_int(string, round_down=True):
31 """
32 Parses a string number into an integer, optionally converting to a float
33 and rounding down.
34 """
35 error_msg = "Unable to convert to integer: '%s'" % str(string)
36 try:
37 integer = float(string)
38 except (TypeError, ValueError):
39 logger.exception(error_msg)
40 raise RuntimeError(error_msg)
41
42 if round_down:
43 integer = floor(integer)
44 else:
45 integer = round(integer)
46 return int(integer)
47
48
49 def str_to_bool(val):
50 """
51 Convert a string representation of truth to True or False
52
53 True values are 'y', 'yes', or ''; case-insensitive
54 False values are 'n', or 'no'; case-insensitive
55 Raises ValueError if 'val' is anything else.
56 """
57 true_vals = ['yes', 'y', '']
58 false_vals = ['no', 'n']
59 try:
60 val = val.lower()
61 except AttributeError:
62 val = str(val).lower()
63 if val in true_vals:
64 return True
65 elif val in false_vals:
66 return False
67 else:
68 raise ValueError("Invalid input value: %s" % val)
69
70
71 def prompt_bool(question, _raw_input=None):
72 """
73 Interface to prompt a boolean (or boolean-like) response from a user.
74 Usually a confirmation.
75 """
76 input_prompt = _raw_input or raw_input
77 prompt_format = '--> {question} '.format(question=question)
78 response = input_prompt(prompt_format)
79 try:
80 return str_to_bool(response)
81 except ValueError:
82 terminal.error('Valid true responses are: y, yes, <Enter>')
83 terminal.error('Valid false responses are: n, no')
84 terminal.error('That response was invalid, please try again')
85 return prompt_bool(question, _raw_input=input_prompt)