From f0f4b545f5c85d7f14c6f3f1db403eaf1fc56d08 Mon Sep 17 00:00:00 2001 From: derrod Date: Wed, 29 Dec 2021 12:55:35 +0100 Subject: [PATCH] [utils] Add get_int_choice helper --- legendary/utils/cli.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/legendary/utils/cli.py b/legendary/utils/cli.py index c99bda7..bfce13c 100644 --- a/legendary/utils/cli.py +++ b/legendary/utils/cli.py @@ -13,6 +13,36 @@ def get_boolean_choice(prompt, default=True): return False +def get_int_choice(prompt, default=None, min_choice=None, max_choice=None, return_on_invalid=False): + if default is not None: + prompt = f'{prompt} [{default}]: ' + else: + prompt = f'{prompt}: ' + + while True: + try: + choice = int(input(prompt)) + except ValueError: + if default is not None: + return default + else: + continue + else: + if min_choice is not None and choice < min_choice: + print(f'Number must be greater than {min_choice}') + if return_on_invalid: + return None + return_on_invalid = True + continue + if max_choice is not None and choice > max_choice: + print(f'Number must be less than {max_choice}') + if return_on_invalid: + return None + return_on_invalid = True + continue + return choice + + def sdl_prompt(sdl_data, title): tags = [''] if '__required' in sdl_data: