in pkg/question/question.go [57:125]
func AskQuestion(input *AskQuestionInput) string {
fmt.Println()
if input.OptionsString != nil {
fmt.Print(*input.OptionsString)
}
if input.DefaultOptionRepr != nil {
fmt.Printf("%s [%s]: ", input.QuestionString, *input.DefaultOptionRepr)
} else if input.DefaultOption != nil {
fmt.Printf("%s [%s]: ", input.QuestionString, *input.DefaultOption)
} else {
fmt.Printf(input.QuestionString + ": ")
}
// Keep asking for user input until one valid input in entered
for {
// Read input from the user and convert CRLF to LF
reader := bufio.NewReader(os.Stdin)
answer, _ := reader.ReadString('\n')
answer = strings.Replace(answer, "\n", "", -1)
// If no input is entered, simply return the default value, if there is one
if answer == "" && input.DefaultOption != nil {
return *input.DefaultOption
}
// Check if the answer is a valid index in the indexed options. If so, return the option value
if input.IndexedOptions != nil {
index, err := strconv.Atoi(answer)
if err == nil && index >= 1 && index <= len(input.IndexedOptions) {
return input.IndexedOptions[index-1]
}
}
// Check if the input matches any string option. If so, return it immediately
if input.StringOptions != nil {
for _, input := range input.StringOptions {
if input == answer {
return answer
}
}
}
// Check if any CheckInput function validates the input. If so, return it immediately
if input.EC2Helper != nil && input.Fns != nil {
for _, fn := range input.Fns {
if fn(input.EC2Helper, answer) {
return answer
}
}
}
// If an arbitrary integer is allowed, try to parse the input as an integer
if input.AcceptAnyInteger {
_, err := strconv.Atoi(answer)
if err == nil {
return answer
}
}
// If an arbitrary string is allowed, return the answer anyway
if input.AcceptAnyString {
return answer
}
// No match at all
fmt.Println("Input invalid. Please try again.")
}
}