-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathterminal.go
70 lines (56 loc) · 1.39 KB
/
terminal.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
package utils
import (
"fmt"
"io"
"strings"
"syscall"
"github.com/Laisky/errors/v2"
"golang.org/x/term"
)
// InputPassword reads password from stdin input
// and returns it as a string.
func InputPassword(hint string, validator func(string) error) (passwd string, err error) {
fmt.Printf("%s: \n", hint)
for {
bytepw, err := term.ReadPassword(syscall.Stdin)
if err != nil {
return "", errors.Wrap(err, "read input password")
}
if validator == nil {
return string(bytepw), nil
}
if err := validator(string(bytepw)); err != nil {
fmt.Printf("invalid password: %s\n", err.Error())
fmt.Printf("try again: \n")
continue
}
return string(bytepw), nil
}
}
// InputYes require user input `y` or `Y` to continue
func InputYes(hint string) (ok bool, err error) {
fmt.Printf("%s, input y/Y to continue: \n", hint)
var confirm string
_, err = fmt.Scanln(&confirm)
if err != nil {
if err.Error() == "unexpected newline" || errors.Is(err, io.EOF) {
// user input nothing, use default value
confirm = "y"
} else {
return ok, errors.Wrap(err, "read input")
}
}
if strings.ToLower(confirm) != "y" {
return false, nil
}
return true, nil
}
// Input reads input from stdin
func Input(hint string) (input string, err error) {
fmt.Printf("%s: \n", hint)
_, err = fmt.Scanln(&input)
if err != nil {
return "", errors.Wrap(err, "read input")
}
return input, nil
}