forked from milvus-io/birdwatcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
95 lines (83 loc) · 2.12 KB
/
main.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
package main
import (
"errors"
"flag"
"fmt"
"os"
"strings"
"github.com/c-bata/go-prompt"
"github.com/congqixia/birdwatcher/states"
"github.com/manifoldco/promptui"
)
var (
simple = flag.Bool("simple", false, "use simple ui without suggestion and history")
)
func main() {
app := states.Start()
//run(app)
runPrompt(app)
}
// run start BirdWatcher with promptui. (disable suggestion and history)
func run(app states.State) {
for {
p := promptui.Prompt{
Label: app.Label(),
Validate: func(input string) error {
return nil
},
}
line, err := p.Run()
if err == nil {
app, err = app.Process(line)
if errors.Is(err, states.ExitErr) {
break
}
}
}
}
// promptApp model wraps states to provide function for go-prompt.
type promptApp struct {
currentState states.State
}
// promptExecute actual execution logic entry.
func (a *promptApp) promptExecute(in string) {
in = strings.TrimSpace(in)
var err error
a.currentState, err = a.currentState.Process(in)
if errors.Is(err, states.ExitErr) {
os.Exit(0)
}
}
// completeInput auto-complete logic entry.
func (a *promptApp) completeInput(d prompt.Document) []prompt.Suggest {
input := d.CurrentLineBeforeCursor()
if input == "" {
return nil
}
r := a.currentState.Suggestions(input)
s := make([]prompt.Suggest, 0, len(r))
for usage, short := range r {
s = append(s, prompt.Suggest{
Text: usage,
Description: short,
})
}
return prompt.FilterHasPrefix(s, input, true)
}
// livePrefix implements dynamic change prefix.
func (a *promptApp) livePrefix() (string, bool) {
return fmt.Sprintf("%s > ", a.currentState.Label()), true
}
// runPrompt start BirdWatcher with go-prompt.
func runPrompt(app states.State) {
pa := &promptApp{currentState: app}
p := prompt.New(pa.promptExecute, pa.completeInput,
prompt.OptionTitle("BirdWatcher"),
prompt.OptionHistory([]string{""}),
prompt.OptionLivePrefix(pa.livePrefix),
prompt.OptionPrefixTextColor(prompt.Yellow),
prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
prompt.OptionSuggestionBGColor(prompt.DarkGray))
p.Run()
}