This repository has been archived by the owner on Jan 20, 2024. It is now read-only.
forked from segmentio/aws-okta
-
Notifications
You must be signed in to change notification settings - Fork 6
/
prompt.go
77 lines (70 loc) · 1.77 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
package provider
import (
"bufio"
"fmt"
"regexp"
"strings"
"golang.org/x/crypto/ssh/terminal"
)
type matcher func(string) bool
func Prompt(prompt string, sensitive bool) (string, error) {
fmt.Fprintf(ProviderOut, "%s: ", prompt)
if sensitive {
var input []byte
input, err := terminal.ReadPassword(1)
if err != nil {
return "", err
}
return strings.TrimSpace(string(input)), nil
}
reader := bufio.NewReader(ProviderIn)
value, err := reader.ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimSpace(value), nil
}
func PromptMulti(choices []string) (string, int) {
match := func(_ string) bool {
return false
}
return PromptMultiMatch(choices, match)
}
func PromptMultiMatch(choices []string, match matcher) (string, int) {
if len(choices) == 0 {
return "error", -1
} else if len(choices) == 1 {
return choices[0], 0
}
str := ""
for i, c := range choices {
if match(c) {
return c, i
}
// not the optimal way to biuld a string, I know
str = fmt.Sprintf("%s[%3d] %s\n", str, i, c)
}
fmt.Fprintf(ProviderOut, "%sChoice: ", str)
for {
var selection int = -1
fmt.Fscanf(ProviderIn, "%d", &selection)
if selection < 0 || selection >= len(choices) {
fmt.Fprintf(ProviderOut, "Invalid choice, try again\n")
} else {
return choices[selection], selection
}
}
}
func PromptMultiMatchRole(choices []string, opt string) (string, int) {
re, err := regexp.Compile("role/(keycloak-)?(" + opt + ")$")
if err != nil {
fmt.Fprintf(ProviderErr, "Error interpreting requested role: %s", opt)
return PromptMulti(choices)
}
match := func(c string) bool {
return re.Match([]byte(c))
}
choice, n := PromptMultiMatch(choices, match)
m := regexp.MustCompile("role/(keycloak-)?(.*)").FindStringSubmatch(choice)
return m[len(m)-1], n
}