1# 2# Copyright (C) 2024 The Android Open Source Project 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15# 16 17from .validation_error import ValidationError 18 19class HandleInput: 20 """Class that requests input from the user with a message and then calls a 21 callback based on the user's input, or gives an error if no valid input was 22 given 23 24 Attributes: 25 input_msg: A string containing a message that is displayed when requesting user input 26 fail_suggestion: A string containing a suggestion displayed when the user exceeds max attempts 27 choices: A dictionary mapping possible user inputs (key) to functions (value) 28 default_choice: A default choice from the choices dictionary if the user inputs nothing. 29 """ 30 def __init__(self, input_msg, fail_suggestion, choices, 31 default_choice = None): 32 self.input_msg = input_msg 33 self.fail_suggestion = fail_suggestion 34 self.choices = choices 35 self.max_attempts = 3 36 if default_choice is not None and default_choice not in choices: 37 raise Exception("Default choice is not in choices dictionary.") 38 self.default_choice = default_choice 39 40 def handle_input(self): 41 i = 0 42 while i < self.max_attempts: 43 response = input(self.input_msg).lower() 44 45 if response == "" and self.default_choice is not None: 46 return self.choices[self.default_choice]() 47 elif response in self.choices: 48 return self.choices[response]() 49 50 i += 1 51 if i < self.max_attempts: 52 print("Invalid input. Please try again.") 53 54 return ValidationError("Invalid inputs.", 55 self.fail_suggestion) 56