From 0283fcc38b13c2d090b1d25be732e6f5f43b834c Mon Sep 17 00:00:00 2001 From: Alfredo Deza Date: Mon, 16 Jul 2018 09:22:50 -0400 Subject: [PATCH] ceph-volume util create prompt helpers Signed-off-by: Alfredo Deza --- src/ceph-volume/ceph_volume/util/__init__.py | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/ceph-volume/ceph_volume/util/__init__.py b/src/ceph-volume/ceph_volume/util/__init__.py index 1da2a3da6a34f..0222d56a0791f 100644 --- a/src/ceph-volume/ceph_volume/util/__init__.py +++ b/src/ceph-volume/ceph_volume/util/__init__.py @@ -1,5 +1,6 @@ import logging from math import floor +from ceph_volume import terminal logger = logging.getLogger(__name__) @@ -32,3 +33,42 @@ def str_to_int(string, round_down=True): else: integer = round(integer) return int(integer) + + +def str_to_bool(val): + """ + Convert a string representation of truth to True or False + + True values are 'y', 'yes', or ''; case-insensitive + False values are 'n', or 'no'; case-insensitive + Raises ValueError if 'val' is anything else. + """ + true_vals = ['yes', 'y', ''] + false_vals = ['no', 'n'] + try: + val = val.lower() + except AttributeError: + val = str(val).lower() + if val in true_vals: + return True + elif val in false_vals: + return False + else: + raise ValueError("Invalid input value: %s" % val) + + +def prompt_bool(question, _raw_input=None): + """ + Interface to prompt a boolean (or boolean-like) response from a user. + Usually a confirmation. + """ + input_prompt = _raw_input or raw_input + prompt_format = '--> {question} '.format(question=question) + response = input_prompt(prompt_format) + try: + return str_to_bool(response) + except ValueError: + terminal.error('Valid true responses are: y, yes, ') + terminal.error('Valid false responses are: n, no') + terminal.error('That response was invalid, please try again') + return prompt_bool(question, _raw_input=input_prompt) -- 2.39.5