gouick/helpers/input.go
2022-08-01 21:55:50 +00:00

134 lines
2.2 KiB
Go

package helpers
import (
"bufio"
"os"
"regexp"
"strings"
"git.home.m-and-m.ovh/mderasse/gouick/helpers/models"
log "github.com/sirupsen/logrus"
)
// YesOrNoInput
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
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
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
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
func ApiTypeNameInput() models.ApiTypeName {
var possibleApiTypes []string
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
}
}