-
Notifications
You must be signed in to change notification settings - Fork 44
/
prompt.go
79 lines (69 loc) · 1.46 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
package cli
import (
"errors"
"io"
"os"
"golang.org/x/crypto/ssh/terminal"
)
var (
errRequiredMissing = errors.New("required missing")
errInvalidBoolean = errors.New("invalid boolean")
)
type readerWriter struct {
io.Reader
io.Writer
}
func doPrompt(text string, password bool) (string, error) {
stdin := os.Stdin
stdout := os.Stdout
term := terminal.NewTerminal(readerWriter{stdin, stdout}, text)
stdinFD := int(stdin.Fd())
stdinState, err := terminal.MakeRaw(stdinFD)
if err != nil {
return "", err
}
defer terminal.Restore(stdinFD, stdinState)
var line string
if password {
line, err = term.ReadPassword(text)
} else {
line, err = term.ReadLine()
}
if err != nil {
return "", err
}
return line, nil
}
func prompt(text string, required bool) (string, error) {
line, err := doPrompt(text, false)
if err != nil {
return line, err
}
if required && line == "" {
return line, errRequiredMissing
}
return line, err
}
func promptDefault(text string, dft string) (string, error) {
line, err := doPrompt(text, false)
if err != nil {
return line, err
}
if line == "" {
return dft, nil
}
return line, err
}
func password(text string) (string, error) {
return doPrompt(text, true)
}
func ask(question string, dft bool) (bool, error) {
line, err := doPrompt(question, false)
if err != nil {
return false, err
}
if line == "" {
return dft, nil
}
return line == "y" || line == "Y" || line == "yes" || line == "Yes" || line == "YES", nil
}