-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt.go
81 lines (71 loc) · 1.78 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
package rline
import (
"strings"
"sync"
)
//go:generate stringer -type=Prompt
// Prompt is the prompt implementation type.
type Prompt int
// Prompt implementation values.
const (
Default Prompt = iota
Readline
Replxx
)
// PromptFromString returns a prompt based on the type given.
func PromptFromString(typ string) (Prompt, error) {
switch strings.ToLower(typ) {
case "", "default":
return Default, nil
case "readline":
return Readline, nil
case "replxx":
return Replxx, nil
}
return Prompt(-1), &ErrInvalidPromptType{typ}
}
// prompt contains initializer for a prompt.
type prompt struct {
init func(string, ...Option) (Prompter, error)
prompter Prompter
once sync.Once
}
// prompts are the set of prompts.
var prompts = [...]prompt{
Default: {init: NewDefaultPrompt},
Readline: {},
Replxx: {},
}
// Available returns whether or not the prompt is available.
func (prompt Prompt) Available() bool {
return prompts[prompt].init != nil
}
// Init initializes the prompt with the specified options.
func (prompt Prompt) Init(app string, opts ...Option) (Prompter, error) {
p := prompts[prompt]
if p.init == nil {
return nil, &ErrPromptNotAvailable{prompt.String()}
}
var err error
(&p.once).Do(func() {
p.prompter, err = p.init(app, opts...)
})
if err != nil {
return nil, err
}
if p.prompter == nil {
return nil, &ErrPromptNotAvailable{prompt.String()}
}
return p.prompter, nil
}
// Initialized returns whether or not the specified prompt has already been
// initialized.
func (prompt Prompt) Initialized() (bool, error) {
switch {
case int(prompt) >= len(prompts):
return false, &ErrInvalidPromptType{prompt.String()}
case prompts[prompt].init == nil:
return false, &ErrPromptNotAvailable{prompt.String()}
}
return prompts[prompt].prompter != nil, nil
}