forked from manifoldco/promptui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prompt.go
325 lines (254 loc) · 6.16 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
package promptui
import (
"fmt"
"io"
"strings"
"text/template"
"github.com/chzyer/readline"
"github.com/manifoldco/promptui/screenbuf"
)
const cursor = "\u2588"
// Prompt represents a single line text field input.
type Prompt struct {
// Label is the value displayed on the command line prompt. It can be any
// value one would pass to a text/template Execute(), including just a string.
Label interface{}
Default string // Default is the initial value to populate in the prompt
// Validate is optional. If set, this function is used to validate the input
// after each character entry.
Validate ValidateFunc
// If mask is set, this value is displayed instead of the actual input
// characters.
Mask rune
// Templates can be used to customize the prompt output. If nil is passed, the
// default templates are used.
Templates *PromptTemplates
IsConfirm bool
IsVimMode bool
stdin io.Reader
stdout io.Writer
}
// PromptTemplates allow a prompt to be customized following stdlib
// text/template syntax. If any field is blank a default template is used.
type PromptTemplates struct {
// Prompt is a text/template for the initial prompt question.
Prompt string
// Prompt is a text/template if the prompt is a confirmation.
Confirm string
// Valid is a text/template for when the current input is valid.
Valid string
// Invalid is a text/template for when the current input is invalid.
Invalid string
// Success is a text/template for the successful result.
Success string
// Prompt is a text/template when there is a validation error.
ValidationError string
// FuncMap is a map of helpers for the templates. If nil, the default helpers
// are used.
FuncMap template.FuncMap
prompt *template.Template
valid *template.Template
invalid *template.Template
validation *template.Template
success *template.Template
}
// Run runs the prompt, returning the validated input.
func (p *Prompt) Run() (string, error) {
c := &readline.Config{}
err := c.Init()
if err != nil {
return "", err
}
err = p.prepareTemplates()
if err != nil {
return "", err
}
if p.stdin != nil {
c.Stdin = p.stdin
}
if p.stdout != nil {
c.Stdout = p.stdout
}
if p.Mask != 0 {
c.EnableMask = true
c.MaskRune = p.Mask
}
if p.IsVimMode {
c.VimMode = true
}
c.HistoryLimit = -1
c.UniqueEditLine = true
rl, err := readline.NewEx(c)
if err != nil {
return "", err
}
rl.Write([]byte(hideCursor))
sb := screenbuf.New(rl)
validFn := func(x string) error {
return nil
}
if p.Validate != nil {
validFn = p.Validate
}
var inputErr error
input := p.Default
eraseDefault := input != ""
c.SetListener(func(line []rune, pos int, key rune) ([]rune, int, bool) {
if line != nil {
input += string(line)
}
switch key {
case 0: // empty
case readline.CharEnter:
return nil, 0, false
case readline.CharBackspace:
if eraseDefault {
eraseDefault = false
input = ""
}
if len(input) > 0 {
input = input[:len(input)-1]
}
default:
if eraseDefault {
eraseDefault = false
input = string(line)
}
}
err := validFn(input)
var prompt []byte
if err != nil {
prompt = render(p.Templates.invalid, p.Label)
} else {
prompt = render(p.Templates.valid, p.Label)
if p.IsConfirm {
prompt = render(p.Templates.prompt, p.Label)
}
}
echo := input
if p.Mask != 0 {
echo = strings.Repeat(string(p.Mask), len(echo))
}
prompt = append(prompt, []byte(echo+cursor)...)
sb.Reset()
sb.Write(prompt)
if inputErr != nil {
validation := render(p.Templates.validation, inputErr)
sb.Write(validation)
inputErr = nil
}
sb.Flush()
return nil, 0, true
})
for {
_, err = rl.Readline()
inputErr = validFn(input)
if inputErr == nil {
break
}
if err != nil {
switch err {
case readline.ErrInterrupt:
err = ErrInterrupt
case io.EOF:
err = ErrEOF
}
break
}
}
if err != nil {
if err.Error() == "Interrupt" {
err = ErrInterrupt
}
sb.Reset()
sb.WriteString("")
sb.Flush()
rl.Write([]byte(showCursor))
rl.Close()
return "", err
}
echo := input
if p.Mask != 0 {
echo = strings.Repeat(string(p.Mask), len(echo))
}
prompt := render(p.Templates.valid, p.Label)
prompt = append(prompt, []byte(echo)...)
if p.IsConfirm && strings.ToLower(echo) != "y" {
prompt = render(p.Templates.invalid, p.Label)
err = ErrAbort
}
sb.Reset()
sb.Write(prompt)
sb.Flush()
rl.Write([]byte(showCursor))
rl.Close()
return input, err
}
func (p *Prompt) prepareTemplates() error {
tpls := p.Templates
if tpls == nil {
tpls = &PromptTemplates{}
}
if tpls.FuncMap == nil {
tpls.FuncMap = FuncMap
}
bold := Styler(FGBold)
if p.IsConfirm {
p.Default = ""
if tpls.Confirm == "" {
confirm := "y/N"
if strings.ToLower(p.Default) == "y" {
confirm = "Y/n"
}
tpls.Confirm = fmt.Sprintf(`{{ "%s" | bold }} {{ . | bold }}? {{ "[%s]" | faint }} `, IconInitial, confirm)
}
tpl, err := template.New("").Funcs(tpls.FuncMap).Parse(tpls.Confirm)
if err != nil {
return err
}
tpls.prompt = tpl
} else {
if tpls.Prompt == "" {
tpls.Prompt = fmt.Sprintf("%s {{ . | bold }}%s ", bold(IconInitial), bold(":"))
}
tpl, err := template.New("").Funcs(tpls.FuncMap).Parse(tpls.Prompt)
if err != nil {
return err
}
tpls.prompt = tpl
}
if tpls.Valid == "" {
tpls.Valid = fmt.Sprintf("%s {{ . | bold }}%s ", bold(IconGood), bold(":"))
}
tpl, err := template.New("").Funcs(tpls.FuncMap).Parse(tpls.Valid)
if err != nil {
return err
}
tpls.valid = tpl
if tpls.Invalid == "" {
tpls.Invalid = fmt.Sprintf("%s {{ . | bold }}%s ", bold(IconBad), bold(":"))
}
tpl, err = template.New("").Funcs(tpls.FuncMap).Parse(tpls.Invalid)
if err != nil {
return err
}
tpls.invalid = tpl
if tpls.ValidationError == "" {
tpls.ValidationError = `{{ ">>" | red }} {{ . | red }}`
}
tpl, err = template.New("").Funcs(tpls.FuncMap).Parse(tpls.ValidationError)
if err != nil {
return err
}
tpls.validation = tpl
if tpls.Success == "" {
tpls.Success = `{{ . | faint }}`
}
tpl, err = template.New("").Funcs(tpls.FuncMap).Parse(tpls.Success)
if err != nil {
return err
}
tpls.success = tpl
p.Templates = tpls
return nil
}