This repository has been archived by the owner on Jun 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathprompt.go
94 lines (81 loc) · 1.69 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package prompt
import "github.com/howeyc/gopass"
import "strings"
import "strconv"
import "fmt"
// String prompt.
func String(prompt string, args ...interface{}) string {
var s string
fmt.Printf(prompt+": ", args...)
fmt.Scanln(&s)
return s
}
// String prompt (required).
func StringRequired(prompt string, args ...interface{}) (s string) {
for strings.Trim(s, " ") == "" {
s = String(prompt, args...)
}
return s
}
// Confirm continues prompting until the input is boolean-ish.
func Confirm(prompt string, args ...interface{}) bool {
for {
switch String(prompt, args...) {
case "Yes", "yes", "y", "Y":
return true
case "No", "no", "n", "N":
return false
}
}
}
// Choose prompts for a single selection from `list`, returning in the index.
func Choose(prompt string, list []string) int {
fmt.Println()
for i, val := range list {
fmt.Printf(" %d) %s\n", i+1, val)
}
fmt.Println()
i := -1
for {
s := String(prompt)
// index
n, err := strconv.Atoi(s)
if err == nil {
if n > 0 && n <= len(list) {
i = n - 1
break
} else {
continue
}
}
// value
i = indexOf(s, list)
if i != -1 {
break
}
}
return i
}
// Password prompt.
func Password(prompt string, args ...interface{}) string {
fmt.Printf(prompt+": ", args...)
password, _ := gopass.GetPasswd()
s := string(password[0:])
return s
}
// Password prompt with mask.
func PasswordMasked(prompt string, args ...interface{}) string {
fmt.Printf(prompt+": ", args...)
password, _ := gopass.GetPasswdMasked()
s := string(password[0:])
return s
}
// index of `s` in `list`.
func indexOf(s string, list []string) int {
for i, val := range list {
if val == s {
return i
}
}
return -1
}