-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprompter.go
75 lines (64 loc) · 1.37 KB
/
prompter.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
package bubbly
import (
"context"
"errors"
"fmt"
)
type PromptReader interface {
Response(ctx context.Context) (string, error)
}
type PromptWriter interface {
IsSensitive() bool
PromptMessage() string
Respond(string) error
Validate(string) error
}
type Prompter struct {
message string
value *string
responses chan string // prompt responses come from the prompt writer
validators []func(string) error
sensitive bool
}
func NewPrompter(message string, sensitive bool, validators ...func(string) error) *Prompter {
return &Prompter{
message: message,
responses: make(chan string, 1),
validators: validators,
sensitive: sensitive,
}
}
func (p Prompter) PromptMessage() string {
return p.message
}
func (p Prompter) IsSensitive() bool {
return p.sensitive
}
func (p *Prompter) Validate(value string) error {
for _, validator := range p.validators {
if err := validator(value); err != nil {
return err
}
}
return nil
}
func (p *Prompter) Respond(value string) error {
if p.value != nil {
return fmt.Errorf("prompt cannot take another value")
}
p.value = &value
p.responses <- value
close(p.responses)
return nil
}
func (p *Prompter) Response(ctx context.Context) (string, error) {
if p.value != nil {
return *p.value, nil
}
select {
case v := <-p.responses:
return v, nil
case <-ctx.Done():
return "", errors.New("timeout")
}
}