gouick/helpers/input.go

133 lines
2.6 KiB
Go
Raw Normal View History

package helpers
import (
"bufio"
"os"
"regexp"
"strings"
"git.home.m-and-m.ovh/mderasse/gouick/models"
log "github.com/sirupsen/logrus"
)
// YesOrNoInput ask user for a yes or no reply and try until we get a possible answer.
func YesOrNoInput() bool {
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
userInput := scanner.Text()
lUserInput := strings.ToLower(userInput)
for _, positiveAnswer := range []string{"yes", "y", "1", "true"} {
if lUserInput == positiveAnswer {
return true
}
}
for _, negativeAnswer := range []string{"no", "n", "0", "false"} {
if lUserInput == negativeAnswer {
return false
}
}
log.Info("Expecting a yes or no answer, Try again")
}
}
// AlphanumericalInput ask user for a alphanumerical string and try until we get a possible answer.
func AlphanumericalInput() string {
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
userInput := scanner.Text()
if userInput == "" {
log.Warn("Empty input, try again")
continue
}
is_alphanumeric := regexp.MustCompile(`^[a-zA-Z0-9\-\_]*$`).MatchString(userInput)
if !is_alphanumeric {
log.Warn("Please use a-z, A-Z, 0-9 and - or _ characters only.")
}
return userInput
}
}
// StringInput ask user for a string and try until we get a possible answer.
func StringInput() string {
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
userInput := scanner.Text()
if userInput == "" {
log.Warn("Empty input, try again")
continue
}
return userInput
}
}
// PathInput ask user for a path string and try until we get a possible answer.
func PathInput() string {
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
userInput := scanner.Text()
if userInput == "" {
log.Warn("Empty input, try again")
continue
}
_, err := CheckAndCreateDir(userInput)
if err != nil {
log.Warnf("please, try again")
continue
}
return userInput
}
}
// APITypeNameInput ask user for a string that is a valid API Type name and try until we get a possible answer.
func APITypeNameInput() models.APITypeName {
possibleAPITypes := make([]string, 0)
for _, apiType := range models.GetListOfAPITypeName() {
possibleAPITypes = append(possibleAPITypes, string(apiType))
}
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
userInput := scanner.Text()
if userInput == "" {
log.Warn("Empty input, try again")
continue
}
apiTypeName, err := models.NewAPITypeNameFromInput(userInput)
if err != nil {
log.Warnf("invalid API type (possible values: %s)", strings.Join(possibleAPITypes, ", "))
continue
}
return apiTypeName
}
}