/
prompt.go
105 lines (86 loc) · 2.26 KB
/
prompt.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package console
import (
"fmt"
"github.com/manifoldco/promptui"
"github.com/pkg/errors"
"strings"
)
type prompt struct{}
func NewPrompt() Prompt {
return &prompt{}
}
func (prompt *prompt) RequestPassphrase() string {
passphrase := prompt.RequestHiddenString("🔑 Please enter passphrase", nil)
_, err := (&promptui.Prompt{
Label: "🔑 Please repeat a passphrase to confirm ",
Mask: '*',
Validate: func(s string) error {
if s != passphrase {
return errors.New("passphrase does not match")
}
return nil
},
}).Run()
if err != nil {
ExitWithError(ExitBadArgs, err)
}
return passphrase
}
func (prompt *prompt) RequestHiddenString(label string, validate promptui.ValidateFunc) string {
userInput, err := (&promptui.Prompt{
Label: fmt.Sprintf("%s ", label),
Mask: '*',
Validate: validate,
}).Run()
if err != nil {
ExitWithError(ExitBadArgs, err)
}
return userInput
}
func (prompt *prompt) RequestString(label string, validate promptui.ValidateFunc) string {
userInput, err := (&promptui.Prompt{
Label: fmt.Sprintf("%s ", label),
Validate: validate,
}).Run()
if err != nil {
ExitWithError(ExitBadArgs, err)
}
return userInput
}
func (prompt *prompt) RequestConfirmation(label string) bool {
userInput, err := (&promptui.Prompt{
Label: fmt.Sprintf("%s (Yes/no) ", label),
Validate: func(s string) error {
if strings.ToLower(s) == "yes" || strings.ToLower(s) == "no" {
return nil
}
return errors.New(`please input "yes" or "no"`)
},
}).Run()
if err != nil {
ExitWithError(ExitBadArgs, err)
}
return strings.ToLower(userInput) == "yes"
}
type RequestChoiceOptions struct {
ActiveChoice string
ActiveChoiceLabel string
}
func (prompt *prompt) RequestChoice(label string, choices []string, opt RequestChoiceOptions) int {
labelledChoices := make([]string, len(choices))
for i, choice := range choices {
if strings.ToLower(opt.ActiveChoice) == strings.ToLower(choice) {
choice = fmt.Sprintf("%s (%s)", choice, opt.ActiveChoiceLabel)
}
choice = fmt.Sprintf("%d. %s", i+1, choice)
labelledChoices[i] = choice
}
index, _, err := (&promptui.Select{
Label: fmt.Sprintf("%s ", label),
Items: labelledChoices,
}).Run()
if err != nil {
ExitWithError(ExitBadArgs, err)
}
return index
}