Skip to content
This repository has been archived by the owner on Jun 9, 2022. It is now read-only.

Commit

Permalink
add InputName as new input option
Browse files Browse the repository at this point in the history
  • Loading branch information
martinnirtl committed Feb 11, 2020
1 parent e4eaed3 commit e1169ed
Showing 1 changed file with 54 additions and 6 deletions.
60 changes: 54 additions & 6 deletions internal/survey/survey.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,46 @@ package survey
import (
"fmt"
"os"
"regexp"

"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/terminal"
)

func checkError(err error) {
if err == terminal.InterruptErr {
fmt.Println("Interrupted.")
// NameRegex should be used to verify all names
var NameRegex string = "^[a-zA-Z].[-.a-zA-Z0-9]*[a-zA-Z0-9]$"

os.Exit(0)
} else if err != nil {
panic(err)
// ValidateName implements the validate func type
func ValidateName(val interface{}) error {
switch name := val.(type) {
case string:
match, err := CheckName(name)

if err != nil {
return err
}

if !match {
return fmt.Errorf("'%s' has to comply with regex /%s/", name, NameRegex)
}

return nil
default:
return fmt.Errorf("Input is not a string")
}
}

// CheckName verifies the name against utils.NameRegex
func CheckName(name string) (match bool, err error) {
match, err = regexp.MatchString(NameRegex, name)

if err != nil {
return false, fmt.Errorf("Matching string with regex failed")
}

return
}

// Confirm abstracts survey's confirm and adds styling
func Confirm(message string, preselected bool) (confirm bool) {
err := survey.AskOne(&survey.Confirm{
Expand All @@ -42,6 +67,19 @@ func Input(message string, suggestion string) (response string) {
return
}

// InputName abstracts survey's input and validates input
func InputName(message string, suggestion string) (response string) {
err := survey.AskOne(&survey.Input{
Message: message,
Default: suggestion,
Help: fmt.Sprintf("Name has to comply with regex: %s", NameRegex),
}, &response, survey.WithValidator(ValidateName))

checkError(err)

return
}

// Select abstracts survey's select and adds styling
func Select(message string, options []string) (selection string) {
err := survey.AskOne(&survey.Select{
Expand Down Expand Up @@ -78,3 +116,13 @@ func MultiSelect(message string, options []string, preselected []string) (select

return
}

func checkError(err error) {
if err == terminal.InterruptErr {
fmt.Println("Interrupted.")

os.Exit(0)
} else if err != nil {
panic(err)
}
}

0 comments on commit e1169ed

Please sign in to comment.