adressing scanln error return

This commit is contained in:
Erin Corson 2017-01-11 13:56:39 -07:00
parent 9296f58ae2
commit 4ee2d484b5
3 changed files with 24 additions and 11 deletions

View File

@ -53,7 +53,11 @@ var deleteCmd = &cobra.Command{
Retries: 2,
}
if !ui.GetConfirm(c) {
confirmed, err := ui.GetConfirm(c)
if err != nil {
exitWithError(err)
}
if !confirmed {
os.Exit(1)
}

View File

@ -51,7 +51,10 @@ func TestConfirmation(t *testing.T) {
Default: "no",
}
answer := ui.GetConfirm(c)
answer, err := ui.GetConfirm(c)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "Are you sure") {
t.Fatal("Confirmation not in output")
}
@ -63,13 +66,19 @@ func TestConfirmation(t *testing.T) {
}
c.Default = "yes"
answer = ui.GetConfirm(c)
answer, err = ui.GetConfirm(c)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "Y/n") {
t.Fatal("Default 'Yes' was not set")
}
c.TestVal = "yes"
answer = ui.GetConfirm(c)
answer, err = ui.GetConfirm(c)
if err != nil {
t.Fatal(err)
}
if answer != true {
t.Fatal("Confirmation should have been approved.")
}

View File

@ -38,7 +38,7 @@ type ConfirmArgs struct {
// out: an io.Writer that allows you to direct prints to stdout or another location
// message: the string that will be printed just before prompting for a yes or no.
// answer: "", "yes", or "no" - this allows for easier testing
func GetConfirm(c *ConfirmArgs) bool {
func GetConfirm(c *ConfirmArgs) (bool, error) {
if c.Default != "" {
c.Default = strings.ToLower(c.Default)
}
@ -62,28 +62,28 @@ func GetConfirm(c *ConfirmArgs) bool {
if response == "" {
_, err := fmt.Scanln(&response)
if err != nil {
return false
return false, err
}
}
responseLower := strings.ToLower(response)
// make sure the response is valid
if ContainsString(okayResponses, responseLower) {
return true
return true, nil
} else if ContainsString(nokayResponses, responseLower) {
return false
return false, nil
} else if c.Default != "" && response == "" {
if string(c.Default[0]) == "y" {
return true
return true, nil
}
return false
return false, nil
}
fmt.Printf("invalid response: %s\n\n", response)
// if c.RetryCount exceeds the requested number of retries then five up
if c.RetryCount >= c.Retries {
return false
return false, nil
}
c.RetryCount++