-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconfirm.go
71 lines (64 loc) · 1.57 KB
/
confirm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package interact
import (
"errors"
"fmt"
"strings"
)
var (
// errNoOptionSelected is returned when the user has not selected either yes or no
errNoOptionSelected = errors.New("Please select y/n!")
)
// ConfirmDefault specifies what an empty user input defaults to
type ConfirmDefault int
// Possible options for what an empty user input defaults to
const (
ConfirmDefaultToYes ConfirmDefault = iota
ConfirmDefaultToNo
ConfirmNoDefault
)
// Confirm provides the message to the user and asks yes or no. If the user
// doesn't select either of the possible answers they will be prompted to answer
// again until they do
func (a Actor) Confirm(message string, def ConfirmDefault) (confirmed bool, err error) {
for {
confirmed, err := a.confirmOnce(message, def)
if err == errNoOptionSelected {
fmt.Fprintln(a.w, err)
continue
}
return confirmed, err
}
}
func (a Actor) confirmOnce(message string, def ConfirmDefault) (bool, error) {
var options string
switch def {
case ConfirmDefaultToYes:
options = "[Y/n]"
case ConfirmDefaultToNo:
options = "[y/N]"
case ConfirmNoDefault:
options = "[y/n]"
}
fmt.Fprintf(a.w, "%s %s: ", message, options)
line, err := a.rd.ReadString('\n')
input := strings.TrimSpace(line)
if err != nil {
return false, err
} else if input == "" {
switch def {
case ConfirmDefaultToYes:
return true, nil
case ConfirmDefaultToNo:
return false, nil
case ConfirmNoDefault:
return false, errNoOptionSelected
}
}
switch input {
case "y":
return true, nil
case "n":
return false, nil
}
return false, errNoOptionSelected
}