-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
ask_util.go
69 lines (63 loc) · 1.29 KB
/
ask_util.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
package cmd
import (
"fmt"
"gopkg.in/readline.v1"
"strings"
)
type AskOptions struct {
Candidates []string
Validate func(string) error
Default string
}
func AskForRequiredInput(prompt string, opts ...AskOptions) string {
pcItems := []readline.PrefixCompleterInterface{}
validate := func(item string) error { return nil }
defaultValue := ""
if len(opts) > 0 {
o := opts[0]
for _, c := range o.Candidates {
pcItems = append(pcItems, readline.PcItem(c))
}
if o.Validate != nil {
validate = o.Validate
}
if o.Default != "" {
defaultValue = o.Default
}
}
var completer = readline.NewPrefixCompleter(
pcItems...,
)
fullPrompt := ""
if defaultValue != "" {
fullPrompt = fmt.Sprintf("%s(Default: %s)> ", prompt, defaultValue)
} else {
fullPrompt = fmt.Sprintf("%s> ", prompt)
}
rl, err := readline.NewEx(&readline.Config{
Prompt: fullPrompt,
AutoComplete: completer,
})
if err != nil {
panic(err)
}
defer rl.Close()
for {
input, err := rl.Readline()
if err == readline.ErrInterrupt {
panic(err)
}
input = strings.TrimSpace(input)
if err == nil { // or io.EOF
if input == "" {
input = defaultValue
}
r := validate(input)
if r == nil {
return input
} else {
fmt.Printf("%s is not valid: %v\n", input, r)
}
}
}
}