forked from milvus-io/birdwatcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
185 lines (164 loc) · 4.09 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
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
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"os/exec"
"strings"
"github.com/c-bata/go-prompt"
"github.com/manifoldco/promptui"
_ "github.com/milvus-io/birdwatcher/asap"
"github.com/milvus-io/birdwatcher/states"
)
var (
simple = flag.Bool("simple", false, "use simple ui without suggestion and history")
logger *log.Logger
)
func main() {
defer handleExit()
app := states.Start()
// open file and create if non-existent
file, err := os.OpenFile("bw_debug.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
logger = log.New(file, "Custom Log", log.LstdFlags)
runPrompt(app)
}
func handleExit() {
rawModeOff := exec.Command("/bin/stty", "-raw", "echo")
rawModeOff.Stdin = os.Stdin
_ = rawModeOff.Run()
rawModeOff.Wait()
}
// 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 {
exited bool
currentState states.State
}
// promptExecute actual execution logic entry.
func (a *promptApp) promptExecute(in string) {
in = strings.TrimSpace(in)
// try to get $PAGER env
pager := os.Getenv("PAGER")
pagerSig := make(chan struct{})
stdout := os.Stdout
var writer *os.File
if pager != "" {
var args []string
// refine less behavior
if pager == "less" {
args = append(args,
"-F", // don't page if content can fix in one screen
"--no-init", // don't clean screen when start paging
)
}
// #nosec args audit for less
cmd := exec.Command(pager, args...)
r, w, err := os.Pipe()
if err != nil {
fmt.Println("failed to create os pipeline", err.Error())
return
}
// Capture STDOUT for the Pager. Keep the old
// value so we can restore it later.
writer = w
os.Stdout = w
cmd.Stdin = r
cmd.Stdout = stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
fmt.Printf("[WARNING] Cannot use %%PAGER(%s), set output back to stdout\n", pager)
close(pagerSig)
} else {
go func() {
// wait here in case of pager exit early
cmd.Wait()
logger.Printf("[DEBUG] wait pager done, state: %#v", cmd.ProcessState)
// set to /dev/null to discard not wanted output
os.Stdout, _ = os.Open(os.DevNull)
w.Close()
close(pagerSig)
}()
}
} else {
close(pagerSig)
}
a.currentState, _ = a.currentState.Process(in)
if writer != nil {
writer.Close()
}
<-pagerSig
// recovery normal output
os.Stdout = stdout
if a.currentState.IsEnding() {
fmt.Println("Bye!")
a.exited = true
}
}
// 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 s
}
// livePrefix implements dynamic change prefix.
func (a *promptApp) livePrefix() (string, bool) {
if a.exited {
return "", false
}
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),
prompt.OptionSetExitCheckerOnInput(func(in string, breakline bool) bool {
// setup exit command
if strings.ToLower(in) == "exit" && breakline {
return true
}
return false
}),
)
p.Run()
}