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
|
package prompt
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/mimecast/dtail/internal/io/dlog"
)
// Answer is a user input of a prompt question.
type Answer struct {
// Long version of the expected user input
Long string
// Short version of the expected user input
Short string
// Runs when user input matches
Callback func()
// Runs after Callback and after logging resumes
EndCallback func()
// AskAgain can be used to not to ask again about the question.
AskAgain bool
}
// Prompt used for interactive user input.
type Prompt struct {
question string
answers []Answer
}
func (p *Prompt) askString() string {
var sb strings.Builder
sb.WriteString(p.question)
sb.WriteString("? (")
var ax []string
for _, a := range p.answers {
ax = append(ax, fmt.Sprintf("%s=%s", a.Short, a.Long))
}
sb.WriteString(strings.Join(ax, ","))
sb.WriteString("): ")
return sb.String()
}
// New returns a new prompt.
func New(question string) *Prompt {
return &Prompt{question: question}
}
// Add an answer.
func (p *Prompt) Add(answer Answer) {
p.answers = append(p.answers, answer)
}
// Ask a question.
func (p *Prompt) Ask() {
reader := bufio.NewReader(os.Stdin)
dlog.Common.Pause()
for {
fmt.Print(p.askString())
answerStr, _ := reader.ReadString('\n')
if a, ok := p.answer(strings.TrimSpace(answerStr)); ok {
if a.Callback != nil {
a.Callback()
}
if !a.AskAgain {
dlog.Common.Resume()
if a.EndCallback != nil {
a.EndCallback()
}
return
}
}
}
}
func (p *Prompt) answer(answerStr string) (*Answer, bool) {
for _, a := range p.answers {
switch answerStr {
case a.Long:
return &a, true
case a.Short:
return &a, true
default:
}
}
return nil, false
}
|