-
Notifications
You must be signed in to change notification settings - Fork 52
/
prompts.go
218 lines (186 loc) · 5.56 KB
/
prompts.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package context
import (
"fmt"
"log"
"os"
"os/exec"
"regexp"
"strings"
"github.com/commitdev/zero/internal/config/globalconfig"
"github.com/commitdev/zero/internal/config/moduleconfig"
"github.com/commitdev/zero/pkg/credentials"
"github.com/commitdev/zero/pkg/util/exit"
"github.com/manifoldco/promptui"
"gopkg.in/yaml.v2"
)
// Constant to maintain prompt orders so users can have the same flow,
// modules get downloaded asynchronously therefore its easier to just hardcode an order
var AvailableVendorOrders = []string{"aws", "github", "circleci"}
const awsPickProfile = "Existing AWS Profiles"
const awsManualInputCredentials = "Enter my own AWS credentials"
type PromptHandler struct {
moduleconfig.Parameter
Condition CustomConditionSignature
Validate func(string) error
}
type CredentialPrompts struct {
Vendor string
Prompts []PromptHandler
}
type CustomConditionSignature func(map[string]string) bool
func NoCondition(map[string]string) bool {
return true
}
func KeyMatchCondition(key string, value string) CustomConditionSignature {
return func(param map[string]string) bool {
return param[key] == value
}
}
func CustomCondition(fn CustomConditionSignature) CustomConditionSignature {
return func(param map[string]string) bool {
return fn(param)
}
}
func NoValidation(string) error {
return nil
}
func SpecificValueValidation(values ...string) func(string) error {
return func(checkValue string) error {
for _, allowedValue := range values {
if checkValue == allowedValue {
return nil
}
}
return fmt.Errorf("Please choose one of %s", strings.Join(values, "/"))
}
}
// TODO: validation / allow prompt retry ...etc
func (p PromptHandler) GetParam(projectParams map[string]string) string {
var err error
var result string
if p.Condition(projectParams) {
// TODO: figure out scope of projectParams per project
// potentially dangerous to have cross module env leaking
// so if community module has an `execute: twitter tweet $ENV`
// it wouldnt leak things the module shouldnt have access to
if p.Parameter.Execute != "" {
result = executeCmd(p.Parameter.Execute, projectParams)
} else if p.Parameter.Value != "" {
result = p.Parameter.Value
} else {
err, result = promptParameter(p)
}
if err != nil {
exit.Fatal("Exiting prompt: %v\n", err)
}
return sanitizeParameterValue(result)
}
return ""
}
func promptParameter(prompt PromptHandler) (error, string) {
param := prompt.Parameter
label := param.Label
if param.Label == "" {
label = param.Field
}
defaultValue := param.Default
var err error
var result string
if len(param.Options) > 0 {
prompt := promptui.Select{
Label: label,
Items: param.Options,
}
_, result, err = prompt.Run()
} else {
prompt := promptui.Prompt{
Label: label,
Default: defaultValue,
AllowEdit: true,
Validate: prompt.Validate,
}
result, err = prompt.Run()
}
if err != nil {
exit.Fatal("Exiting prompt: %v\n", err)
}
return nil, result
}
func executeCmd(command string, envVars map[string]string) string {
cmd := exec.Command("bash", "-c", command)
cmd.Env = appendProjectEnvToCmdEnv(envVars, os.Environ())
out, err := cmd.Output()
if err != nil {
log.Fatalf("Failed to execute %v\n", err)
}
return string(out)
}
// aws cli prints output with linebreak in them
func sanitizeParameterValue(str string) string {
re := regexp.MustCompile("\\n")
return re.ReplaceAllString(str, "")
}
func appendProjectEnvToCmdEnv(envMap map[string]string, envList []string) []string {
for key, val := range envMap {
if val != "" {
envList = append(envList, fmt.Sprintf("%s=%s", key, val))
}
}
return envList
}
// PromptParams renders series of prompt UI based on the config
func PromptModuleParams(moduleConfig moduleconfig.ModuleConfig, parameters map[string]string) (map[string]string, error) {
for _, promptConfig := range moduleConfig.Parameters {
// deduplicate fields already prompted and received
if _, isAlreadySet := parameters[promptConfig.Field]; isAlreadySet {
continue
}
promptHandler := PromptHandler{
promptConfig,
NoCondition,
NoValidation,
}
result := promptHandler.GetParam(parameters)
parameters[promptConfig.Field] = result
}
return parameters, nil
}
func promptCredentialsAndFillProjectCreds(credentialPrompts []CredentialPrompts, creds globalconfig.ProjectCredential) globalconfig.ProjectCredential {
promptsValues := map[string]map[string]string{}
for _, prompts := range credentialPrompts {
vendor := prompts.Vendor
vendorPromptValues := map[string]string{}
// vendors like AWS have multiple prompts (accessKeyId and secretAccessKey)
for _, prompt := range prompts.Prompts {
vendorPromptValues[prompt.Field] = prompt.GetParam(vendorPromptValues)
}
promptsValues[vendor] = vendorPromptValues
}
// FIXME: what is a good way to dynamically modify partial data of a struct
// current just marashing to yaml, then unmarshaling into the base struct
yamlContent, _ := yaml.Marshal(promptsValues)
yaml.Unmarshal(yamlContent, &creds)
// Fill AWS credentials based on profile from ~/.aws/credentials
if val, ok := promptsValues["aws"]; ok {
if val["use_aws_profile"] == awsPickProfile {
creds = credentials.GetAWSProfileProjectCredentials(val["aws_profile"], creds)
}
}
return creds
}
func appendToSet(set []string, toAppend []string) []string {
for _, appendee := range toAppend {
if !itemInSlice(set, appendee) {
set = append(set, appendee)
}
}
return set
}
func itemInSlice(slice []string, target string) bool {
for _, item := range slice {
if item == target {
return true
}
}
return false
}