-
Notifications
You must be signed in to change notification settings - Fork 393
/
prompt.go
354 lines (311 loc) · 12.2 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
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
345
346
347
348
349
350
351
352
353
354
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package prompt provides functionality to retrieve free-form text, selection,
// and confirmation input from the user via a terminal.
package prompt
import (
"errors"
"os"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/core"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
func init() {
survey.ConfirmQuestionTemplate = `{{if not .Answer}}
{{end}}
{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}}
{{- if eq $i 0}} {{ $line }}
{{ else }} {{ $line }}
{{ end }}{{- end }}{{color "reset"}}{{end}}
{{- color .Config.Icons.Question.Format }}{{if not .Answer}} {{ .Config.Icons.Question.Text }}{{else}}{{ .Config.Icons.Question.Text }}{{end}}{{color "reset"}}
{{- color "default"}}{{ .Message }} {{color "reset"}}
{{- if .Answer}}
{{- color "default"}}{{.Answer}}{{color "reset"}}{{"\n"}}
{{- else }}
{{- if and .Help (not .ShowHelp)}}{{color "white"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}}
{{- color "default"}}{{if .Default}}(Y/n) {{else}}(y/N) {{end}}{{color "reset"}}
{{- end}}`
survey.SelectQuestionTemplate = `{{if not .Answer}}
{{end}}
{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}}
{{- if eq $i 0}} {{ $line }}
{{ else }} {{ $line }}
{{ end }}{{- end }}{{color "reset"}}{{end}}
{{- color .Config.Icons.Question.Format }}{{if not .ShowAnswer}} {{ .Config.Icons.Question.Text }}{{else}}{{ .Config.Icons.Question.Text }}{{end}}{{color "reset"}}
{{- color "default"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}}
{{- if .ShowAnswer}}{{color "default"}} {{parseAnswer .Answer}}{{color "reset"}}{{"\n"}}
{{- else}}
{{- " "}}{{- color "white"}}[Use arrows to move, type to filter{{- if and .Help (not .ShowHelp)}}, {{ .Config.HelpInput }} for more help{{end}}]{{color "reset"}}
{{- "\n"}}
{{- range $ix, $choice := .PageEntries}}
{{- if eq $ix $.SelectedIndex }}{{color "default+b" }} {{ $.Config.Icons.SelectFocus.Text }} {{else}}{{color "default"}} {{end}}
{{- $choice.Value}}
{{- color "reset"}}{{"\n"}}
{{- end}}
{{- end}}`
survey.InputQuestionTemplate = `{{if not .ShowAnswer}}
{{end}}
{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}}
{{- if eq $i 0}} {{ $line }}
{{ else }} {{ $line }}
{{ end }}{{- end }}{{color "reset"}}{{end}}
{{- color .Config.Icons.Question.Format }}{{if not .ShowAnswer}} {{ .Config.Icons.Question.Text }}{{else}}{{ .Config.Icons.Question.Text }}{{end}}{{color "reset"}}
{{- color "default"}}{{ .Message }} {{color "reset"}}
{{- if .ShowAnswer}}
{{- color "default"}}{{.Answer}}{{color "reset"}}{{"\n"}}
{{- else }}
{{- if and .Help (not .ShowHelp)}}{{color "white"}}[{{ print .Config.HelpInput }} for help]{{color "reset"}} {{end}}
{{- if .Default}}{{color "default"}}({{.Default}}) {{color "reset"}}{{end}}
{{- .Answer -}}
{{- end}}`
survey.PasswordQuestionTemplate = `
{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}}
{{- if eq $i 0}} {{ $line }}
{{ else }} {{ $line }}
{{ end }}{{- end }}{{color "reset"}}{{end}}
{{- color .Config.Icons.Question.Format }} {{ .Config.Icons.Question.Text }}{{color "reset"}}
{{- color "default"}}{{ .Message }} {{color "reset"}}
{{- if and .Help (not .ShowHelp)}}{{color "white"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}}`
survey.MultiSelectQuestionTemplate = `{{if not .Answer}}
{{end}}
{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }}{{$lines := split .Help "\n"}}{{range $i, $line := $lines}}
{{- if eq $i 0}} {{ $line }}
{{ else }} {{ $line }}
{{ end }}{{- end }}{{color "reset"}}{{end}}
{{- color .Config.Icons.Question.Format }}{{if not .ShowAnswer}} {{ .Config.Icons.Question.Text }}{{else}}{{ .Config.Icons.Question.Text }}{{end}}{{color "reset"}}
{{- color "default"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}}
{{- if .ShowAnswer}}{{color "default"}} {{.Answer}}{{color "reset"}}{{"\n"}}
{{- else }}
{{- " "}}{{- color "white"}}[Use arrows to move, space to select, type to filter{{- if and .Help (not .ShowHelp)}}, {{ .Config.HelpInput }} for more help{{end}}]{{color "reset"}}
{{- "\n"}}
{{- range $ix, $option := .PageEntries}}
{{- if eq $ix $.SelectedIndex }}{{color "default+b" }} {{ $.Config.Icons.SelectFocus.Text }}{{color "reset"}}{{else}} {{end}}
{{- if index $.Checked $option.Index }}{{color "default+b" }} {{ $.Config.Icons.MarkedOption.Text }} {{else}}{{color "default" }} {{ $.Config.Icons.UnmarkedOption.Text }} {{end}}
{{- color "reset"}}
{{- " "}}{{$option.Value}}{{"\n"}}
{{- end}}
{{- end}}`
split := func(s string, sep string) []string {
return strings.Split(s, sep)
}
core.TemplateFuncsWithColor["split"] = split
core.TemplateFuncsWithColor["parseAnswer"] = parseValueFromOptionFmt
core.TemplateFuncsNoColor["split"] = split
core.TemplateFuncsNoColor["parseAnswer"] = parseValueFromOptionFmt
}
// ErrEmptyOptions indicates the input options list was empty.
var ErrEmptyOptions = errors.New("list of provided options is empty")
// Prompt abstracts the survey.Askone function.
type Prompt func(survey.Prompt, interface{}, ...survey.AskOpt) error
// ValidatorFunc defines the function signature for validating inputs.
type ValidatorFunc func(interface{}) error
// New returns a Prompt with default configuration.
func New() Prompt {
return survey.AskOne
}
type prompter interface {
Prompt(config *survey.PromptConfig) (interface{}, error)
Cleanup(*survey.PromptConfig, interface{}) error
Error(*survey.PromptConfig, error) error
WithStdio(terminal.Stdio)
}
type prompt struct {
prompter
FinalMessage string // Text to display after the user selects an answer.
}
// Cleanup does a final render with the user's chosen value.
// This method overrides survey.Select's Cleanup method by assigning the prompt's message to be the final message.
func (p *prompt) Cleanup(config *survey.PromptConfig, val interface{}) error {
if p.FinalMessage == "" {
return p.prompter.Cleanup(config, val) // Delegate to the parent Cleanup.
}
// Update the message of the underlying struct.
switch typedPrompt := p.prompter.(type) {
case *survey.Select:
typedPrompt.Message = p.FinalMessage
case *survey.Input:
typedPrompt.Message = p.FinalMessage
case *passwordPrompt:
typedPrompt.Message = p.FinalMessage
case *survey.Confirm:
typedPrompt.Message = p.FinalMessage
case *survey.MultiSelect:
typedPrompt.Message = p.FinalMessage
}
return p.prompter.Cleanup(config, val)
}
// Get prompts the user for free-form text input.
func (p Prompt) Get(message, help string, validator ValidatorFunc, promptOpts ...PromptConfig) (string, error) {
input := &survey.Input{
Message: message,
}
if help != "" {
input.Help = color.Help(help)
}
prompt := &prompt{
prompter: input,
}
for _, opt := range promptOpts {
opt(prompt)
}
var result string
var err error
if validator == nil {
err = p(prompt, &result, stdio(), icons())
} else {
err = p(prompt, &result, stdio(), validators(validator), icons())
}
return result, err
}
type passwordPrompt struct {
*survey.Password
}
// Cleanup renders a new template that's left-shifted when the user answers the prompt.
func (pp *passwordPrompt) Cleanup(config *survey.PromptConfig, val interface{}) error {
// The user already entered their password, move the cursor one level up to override the prompt.
pp.Password.NewCursor().PreviousLine(1)
// survey.Password unlike other survey structs doesn't have an "Answer" field. Therefore, we can't use a single
// template like other prompts. Instead, when Cleanup is called, we render a new template
// that behaves as if the question is answered.
return pp.Password.Render(`
{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }}{{color "reset"}}
{{- color "default"}}{{ .Message }} {{color "reset"}}
`,
survey.PasswordTemplateData{
Password: *pp.Password,
Config: config,
ShowHelp: false,
})
}
// GetSecret prompts the user for sensitive input. Wraps survey.Password
func (p Prompt) GetSecret(message, help string, promptOpts ...PromptConfig) (string, error) {
passwd := &passwordPrompt{
Password: &survey.Password{
Message: message,
},
}
if help != "" {
passwd.Help = color.Help(help)
}
prompt := &prompt{
prompter: passwd,
}
for _, opt := range promptOpts {
opt(prompt)
}
var result string
err := p(prompt, &result, stdio(), icons())
return result, err
}
// MultiSelect prompts the user with a list of options to choose from with the arrow keys and enter key.
func (p Prompt) MultiSelect(message, help string, options []string, validator ValidatorFunc, promptCfgs ...PromptConfig) ([]string, error) {
if len(options) <= 0 {
// returns nil slice if error
return nil, ErrEmptyOptions
}
multiselect := &survey.MultiSelect{
Message: message,
Options: options,
Default: options[0],
}
if help != "" {
multiselect.Help = color.Help(help)
}
prompt := &prompt{
prompter: multiselect,
}
for _, cfg := range promptCfgs {
cfg(prompt)
}
var result []string
var err error
if validator == nil {
err = p(prompt, &result, stdio(), icons())
} else {
err = p(prompt, &result, stdio(), validators(validator), icons())
}
return result, err
}
// Confirm prompts the user with a yes/no option.
func (p Prompt) Confirm(message, help string, promptCfgs ...PromptConfig) (bool, error) {
confirm := &survey.Confirm{
Message: message,
}
if help != "" {
confirm.Help = color.Help(help)
}
prompt := &prompt{
prompter: confirm,
}
for _, cfg := range promptCfgs {
cfg(prompt)
}
var result bool
err := p(prompt, &result, stdio(), icons())
return result, err
}
// PromptConfig is a functional option to configure the prompt.
type PromptConfig func(*prompt)
// WithDefaultInput sets a default message for an input prompt.
func WithDefaultInput(s string) PromptConfig {
return func(p *prompt) {
if get, ok := p.prompter.(*survey.Input); ok {
get.Default = s
}
}
}
// WithFinalMessage sets a final message that replaces the question prompt once the user enters an answer.
func WithFinalMessage(msg string) PromptConfig {
return func(p *prompt) {
p.FinalMessage = color.Emphasize(msg)
}
}
// WithConfirmFinalMessage sets a short final message for to confirm the user's input.
func WithConfirmFinalMessage() PromptConfig {
return func(p *prompt) {
p.FinalMessage = color.Emphasize("Sure?")
}
}
// WithDefaultSelections selects the options to be checked by default for a multiselect prompt.
func WithDefaultSelections(options []string) PromptConfig {
return func(p *prompt) {
if confirm, ok := p.prompter.(*survey.MultiSelect); ok {
confirm.Default = options
}
}
}
// WithTrueDefault sets the default for a confirm prompt to true.
func WithTrueDefault() PromptConfig {
return func(p *prompt) {
if confirm, ok := p.prompter.(*survey.Confirm); ok {
confirm.Default = true
}
}
}
func stdio() survey.AskOpt {
return survey.WithStdio(os.Stdin, os.Stderr, os.Stderr)
}
func icons() survey.AskOpt {
return survey.WithIcons(func(icons *survey.IconSet) {
// The question mark "?" icon to denote a prompt will be colored in bold.
icons.Question.Text = ""
icons.Question.Format = "default+b"
// Survey uses https://github.com/mgutz/ansi to set colors which unfortunately doesn't support the "Faint" style.
// We are setting the help text to be fainted in the individual prompt methods instead.
icons.Help.Text = ""
icons.Help.Format = "default"
})
}
// RequireNonEmpty returns an error if v is a zero-value.
func RequireNonEmpty(v interface{}) error {
return survey.Required(v)
}
// RequireMinItems enforces at least min elements to be selected from MultiSelect.
func RequireMinItems(min int) ValidatorFunc {
return (ValidatorFunc)(survey.MinItems(min))
}
func validators(validatorFunc ValidatorFunc) survey.AskOpt {
return survey.WithValidator(survey.ComposeValidators(survey.Required, survey.Validator(validatorFunc)))
}