/
are_you_sure.go
67 lines (55 loc) · 1.17 KB
/
are_you_sure.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
package utils
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"golang.org/x/crypto/ssh/terminal"
)
type UserInputReader interface {
Read(secret bool) (string, error)
}
type StdinInputReader struct{}
func NewStdinInputReader() *StdinInputReader {
return &StdinInputReader{}
}
func (reader StdinInputReader) Read(secret bool) (string, error) {
if secret {
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", err
}
response := string(bytePassword)
return response, nil
}
stdin_reader := bufio.NewReader(os.Stdin)
response, err := stdin_reader.ReadString('\n')
if err != nil {
return "", err
}
return response, nil
}
func AreYouSure(message string, reader UserInputReader) bool {
for {
res := Ask(fmt.Sprintf("%s [y/n]", message), false, false, reader)
return res == "y"
}
}
func Ask(s string, required bool, secret bool, reader UserInputReader) string {
var response string
var err error
for {
fmt.Printf("%s: ", s)
response, err = reader.Read(secret)
response = strings.TrimSpace(response)
if err != nil {
continue
}
if len(response) == 0 && required {
continue
}
break
}
return response
}