-
Notifications
You must be signed in to change notification settings - Fork 55
/
questionnaire.go
344 lines (310 loc) · 10.3 KB
/
questionnaire.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package utils
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/c-bata/go-prompt"
"github.com/jfrog/jfrog-cli-core/utils/coreutils"
)
const (
InsertValuePromptMsg = "Insert the value for "
DummyDefaultAnswer = "-"
)
// The interactive questionnaire works as follows:
// We have to provide a map of QuestionInfo which include all possible questions may be asked.
// 1. Mandatory Questions:
// * We will ask all the questions in MandatoryQuestionsKeys list one after the other.
// 2. Optional questions:
// * We have to provide a slice of prompt.Suggest, in which each suggest.Text is a key of a question in the map.
// * After a suggest was chosen from the list, the corresponding question from the map will be asked.
// * Each answer is written to to the configMap using its writer, under the MapKey specified in the questionInfo.
// * We will execute the previous step until the SaveAndExit string was inserted.
type InteractiveQuestionnaire struct {
QuestionsMap map[string]QuestionInfo
MandatoryQuestionsKeys []string
OptionalKeysSuggests []prompt.Suggest
AnswersMap map[string]interface{}
}
// Each question can have the following properties:
// * Msg - will be printed in separate line
// * PromptPrefix - will be printed before the input cursor in the answer line
// * Options - In case the answer must be selected from a predefined list
// * AllowVars - a flag indicates whether a variable (in form of ${var}) is an acceptable answer despite the predefined list
// * Writer - how to write the answer to the final config map
// * MapKey - the key under which the answer will be written to the configMap
// * Callback - optional function can be executed after the answer was inserted. Can be used to implement some dependencies between questions.
type AnswerWriter func(resultMap *map[string]interface{}, key, value string) error
type questionCallback func(*InteractiveQuestionnaire, string) (string, error)
type QuestionInfo struct {
Msg string
PromptPrefix string
Options []prompt.Suggest
AllowVars bool
Writer AnswerWriter
MapKey string
Callback questionCallback
}
const (
PressTabMsg = " (press Tab for options):"
InvalidAnswerMsg = "Invalid answer. Please select value from the suggestions list."
VariableUseMsg = " You may use dynamic variable in the form of ${key}."
EmptyValueMsg = "The value cannot be empty. Please enter a valid value."
OptionalKey = "OptionalKey"
SaveAndExit = ":x"
// Boolean answers
True = "true"
False = "false"
CommaSeparatedListMsg = "The value should be a comma separated list"
)
// Var can be inserted in the form of ${key}
var VarPattern = regexp.MustCompile(`^\$\{\w+\}+$`)
func prefixCompleter(options []prompt.Suggest) prompt.Completer {
return func(document prompt.Document) []prompt.Suggest {
return prompt.FilterHasPrefix(options, document.GetWordBeforeCursor(), true)
}
}
// Bind ctrl+c key to interrupt the command
func interruptKeyBind() prompt.Option {
interrupt := prompt.KeyBind{
Key: prompt.ControlC,
Fn: func(buf *prompt.Buffer) {
panic("Interrupted")
},
}
return prompt.OptionAddKeyBind(interrupt)
}
// Ask question with free string answer.
// If answer is empty and defaultValue isn't, return defaultValue.
// Otherwise, answer cannot be empty.
// Variable aren't checked and can be part of the answer.
func AskStringWithDefault(msg, promptPrefix, defaultValue string) string {
return askString(msg, promptPrefix, defaultValue, false, false)
}
// Ask question with free string answer, allow an empty string as an answer
func AskString(msg, promptPrefix string, allowEmpty bool, allowVars bool) string {
return askString(msg, promptPrefix, "", allowEmpty, allowVars)
}
// Ask question with free string answer.
// If an empty answer is allowed, the answer returned as is,
// if not and a default value was provided, the default value is returned.
func askString(msg, promptPrefix, defaultValue string, allowEmpty bool, allowVars bool) string {
if msg != "" {
fmt.Println(msg + ":")
}
errMsg := EmptyValueMsg
if allowVars {
errMsg += VariableUseMsg
}
promptPrefix = addDefaultValueToPrompt(promptPrefix, defaultValue)
for {
answer := prompt.Input(promptPrefix, prefixCompleter(nil), interruptKeyBind())
answer = strings.TrimSpace(answer)
if allowEmpty || answer != "" {
return answer
}
// An empty answer wan given, default value wad provided.
if defaultValue != "" {
return defaultValue
}
fmt.Println(errMsg)
}
}
// Ask question with list of possible answers.
// If answer is empty and defaultValue isn't, return defaultValue.
// Otherwise, the answer must be chosen from the list, but can be a variable if allowVars set to true.
func AskFromList(msg, promptPrefix string, allowVars bool, options []prompt.Suggest, defaultValue string) string {
if msg != "" {
fmt.Println(msg + PressTabMsg)
}
errMsg := InvalidAnswerMsg
if allowVars {
errMsg += VariableUseMsg
}
promptPrefix = addDefaultValueToPrompt(promptPrefix, defaultValue)
for {
answer := prompt.Input(promptPrefix, prefixCompleter(options), interruptKeyBind())
answer = strings.TrimSpace(answer)
if answer == "" && defaultValue != "" {
return defaultValue
}
if validateAnswer(answer, options, allowVars) {
return answer
}
fmt.Println(errMsg)
}
}
func addDefaultValueToPrompt(promptPrefix, defaultValue string) string {
if defaultValue != "" && defaultValue != DummyDefaultAnswer {
return promptPrefix + " [" + defaultValue + "]: "
}
return promptPrefix + " "
}
func validateAnswer(answer string, options []prompt.Suggest, allowVars bool) bool {
if allowVars {
if regexMatch := VarPattern.FindStringSubmatch(answer); regexMatch != nil {
return true
}
}
for _, option := range options {
if answer == option.Text {
return true
}
}
return false
}
// Ask question with list of possible answers.
// If the provided answer does not appear in list, confirm the choice.
func AskFromListWithMismatchConfirmation(promptPrefix, misMatchMsg string, options []prompt.Suggest) string {
for {
answer := prompt.Input(promptPrefix+" ", prefixCompleter(options), interruptKeyBind())
if answer == "" {
fmt.Println(EmptyValueMsg)
}
for _, option := range options {
if answer == option.Text {
return answer
}
}
if coreutils.AskYesNo(misMatchMsg+" continue anyway?", false) {
return answer
}
}
}
// Ask question steps:
// 1. Ask for string/from list
// 2. Write the answer to answersMap (if writer provided)
// 3. Run callback (if provided)
func (iq *InteractiveQuestionnaire) AskQuestion(question QuestionInfo) (value string, err error) {
var answer string
if question.Options != nil {
answer = AskFromList(question.Msg, question.PromptPrefix, question.AllowVars, question.Options, "")
} else {
answer = AskString(question.Msg, question.PromptPrefix, false, question.AllowVars)
}
if question.Writer != nil {
err = question.Writer(&iq.AnswersMap, question.MapKey, answer)
if err != nil {
return "", err
}
}
if question.Callback != nil {
_, err = question.Callback(iq, answer)
if err != nil {
return "", err
}
}
return answer, nil
}
// The main function to perform the questionnaire
func (iq *InteractiveQuestionnaire) Perform() error {
iq.AnswersMap = make(map[string]interface{})
for i := 0; i < len(iq.MandatoryQuestionsKeys); i++ {
iq.AskQuestion(iq.QuestionsMap[iq.MandatoryQuestionsKeys[i]])
}
fmt.Println("You can type \":x\" at any time to save and exit.")
OptionalKeyQuestion := iq.QuestionsMap[OptionalKey]
OptionalKeyQuestion.Options = iq.OptionalKeysSuggests
for {
key, err := iq.AskQuestion(OptionalKeyQuestion)
if err != nil {
return err
}
if key == SaveAndExit {
break
}
}
return nil
}
// Common questions
var FreeStringQuestionInfo = QuestionInfo{
Options: nil,
AllowVars: false,
Writer: WriteStringAnswer,
}
func GetBoolSuggests() []prompt.Suggest {
return []prompt.Suggest{
{Text: True},
{Text: False},
}
}
var BoolQuestionInfo = QuestionInfo{
Options: GetBoolSuggests(),
AllowVars: true,
Writer: WriteBoolAnswer,
}
var IntQuestionInfo = QuestionInfo{
Options: nil,
AllowVars: true,
Writer: WriteIntAnswer,
}
var StringListQuestionInfo = QuestionInfo{
Msg: CommaSeparatedListMsg,
Options: nil,
AllowVars: true,
Writer: WriteStringArrayAnswer,
}
// Common writers
func WriteStringAnswer(resultMap *map[string]interface{}, key, value string) error {
(*resultMap)[key] = value
return nil
}
func WriteBoolAnswer(resultMap *map[string]interface{}, key, value string) error {
if regexMatch := VarPattern.FindStringSubmatch(value); regexMatch != nil {
return WriteStringAnswer(resultMap, key, value)
}
boolValue, err := strconv.ParseBool(value)
if err != nil {
return err
}
(*resultMap)[key] = boolValue
return nil
}
func WriteIntAnswer(resultMap *map[string]interface{}, key, value string) error {
if regexMatch := VarPattern.FindStringSubmatch(value); regexMatch != nil {
return WriteStringAnswer(resultMap, key, value)
}
intValue, err := strconv.Atoi(value)
if err != nil {
return err
}
(*resultMap)[key] = intValue
return nil
}
func WriteStringArrayAnswer(resultMap *map[string]interface{}, key, value string) error {
if regexMatch := VarPattern.FindStringSubmatch(value); regexMatch != nil {
return WriteStringAnswer(resultMap, key, value)
}
arrValue := strings.Split(value, ",")
(*resultMap)[key] = arrValue
return nil
}
func GetSuggestsFromKeys(keys []string, SuggestionMap map[string]prompt.Suggest) []prompt.Suggest {
var suggests []prompt.Suggest
for _, key := range keys {
suggests = append(suggests, SuggestionMap[key])
}
return suggests
}
func ConvertToSuggests(options []string) []prompt.Suggest {
var suggests []prompt.Suggest
for _, opt := range options {
suggests = append(suggests, prompt.Suggest{Text: opt})
}
return suggests
}
// After an optional value was chosen we'll ask for its value.
func OptionalKeyCallback(iq *InteractiveQuestionnaire, key string) (value string, err error) {
if key != SaveAndExit {
valueQuestion := iq.QuestionsMap[key]
// Since we are using default question in most of the cases we set the map key here.
valueQuestion.MapKey = key
valueQuestion.PromptPrefix = InsertValuePromptMsg + key
if valueQuestion.Options != nil {
valueQuestion.PromptPrefix += PressTabMsg
}
valueQuestion.PromptPrefix += " >"
value, err = iq.AskQuestion(valueQuestion)
}
return value, err
}