-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
82 lines (70 loc) · 1.73 KB
/
cli.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
package utilz
import (
"fmt"
"os"
"strings"
"golang.org/x/crypto/ssh/terminal"
)
// CLIAskYesNo parses an input from the terminal and returns whether the
// response is affirmative or negative.
func CLIAskYesNo(message string) (bool, error) {
fmt.Println()
fmt.Println(message, "[y/n]")
var input string
_, err := fmt.Scanln(&input)
if err != nil {
if err.Error() == "unexpected newline" {
return CLIAskYesNo(message)
}
return false, err
}
// clean the input
input = strings.ToLower(input)
input = strings.TrimSpace(input)
okayResponses := []string{"y", "yes"}
nokayResponses := []string{"n", "no"}
if SliceContains(okayResponses, input) {
return true, nil
} else if SliceContains(nokayResponses, input) {
return false, nil
} else {
fmt.Println("Not recognized. Please type yes/no or y/n and then press enter.")
return CLIAskYesNo(message)
}
}
// CLIAskPassword prompts the user for a password input fro the CLI
func CLIAskPassword() ([]byte, error) {
return terminal.ReadPassword(int(os.Stdin.Fd()))
}
// CLIAskString prompts the user for a string input from the CLI
func CLIAskString() (string, error) {
var input string
_, err := fmt.Scanln(&input)
if err != nil {
fmt.Println("fatal: ", err) //TODO: handle error
return "", err
}
return input, nil
}
type FlagStringArray []string
func (i *FlagStringArray) String() string {
return strings.Join(*i, ",")
}
func (i *FlagStringArray) Set(value string) error {
value = strings.TrimSpace(value)
if value != "" {
*i = append(*i, value)
}
// TODO: sort by len here?
return nil
}
func CLIMustConfirmYes(message string) {
doContinue, err := CLIAskYesNo(message)
if err != nil {
panic(err)
}
if !doContinue {
Ln(Orange("Aborting"))
os.Exit(0)
}
}