1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/cli/repl.go

135 lines
2.1 KiB
Go
Raw Normal View History

2018-09-26 03:49:42 +02:00
package cli
2018-09-18 22:42:38 +02:00
import (
"context"
"fmt"
"github.com/MontFerret/ferret/pkg/compiler"
"github.com/MontFerret/ferret/pkg/runtime"
2018-09-28 06:28:33 +02:00
"github.com/MontFerret/ferret/pkg/runtime/logging"
2018-09-18 22:42:38 +02:00
"github.com/chzyer/readline"
2018-09-28 06:28:33 +02:00
"os"
"os/signal"
2018-09-18 22:42:38 +02:00
"strings"
2018-09-28 06:28:33 +02:00
"syscall"
2018-09-18 22:42:38 +02:00
)
func Repl(version string, opts Options) {
2018-09-18 22:42:38 +02:00
ferret := compiler.New()
fmt.Printf("Welcome to Ferret REPL %s\n", version)
fmt.Println("Please use `exit` or `Ctrl-D` to exit this program.")
rl, err := readline.NewEx(&readline.Config{
Prompt: "> ",
InterruptPrompt: "^C",
EOFPrompt: "exit",
})
if err != nil {
panic(err)
}
defer rl.Close()
var commands []string
2018-09-23 08:28:26 +02:00
var multiline bool
var timer *Timer
if opts.ShowTime {
timer = NewTimer()
}
2018-09-18 22:42:38 +02:00
2018-09-28 06:28:33 +02:00
l := NewLogger()
ctx, cancel := context.WithCancel(context.Background())
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
exit := func() {
cancel()
l.Close()
}
2018-09-28 06:28:33 +02:00
go func() {
for {
<-c
exit()
2018-09-28 06:28:33 +02:00
}
}()
2018-09-18 22:42:38 +02:00
for {
line, err := rl.Readline()
if err != nil {
break
}
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
2018-09-23 08:28:26 +02:00
if strings.HasPrefix(line, "%") {
line = line[1:]
multiline = !multiline
}
if multiline {
commands = append(commands, line)
2018-09-18 22:42:38 +02:00
continue
}
commands = append(commands, line)
2018-09-23 08:28:26 +02:00
query := strings.TrimSpace(strings.Join(commands, "\n"))
2018-09-18 22:42:38 +02:00
commands = make([]string, 0, 10)
2018-09-23 08:28:26 +02:00
if query == "" {
continue
}
if query == "exit" {
exit()
os.Exit(0)
return
}
2018-09-18 22:42:38 +02:00
program, err := ferret.Compile(query)
if err != nil {
fmt.Println("Failed to parse the query")
fmt.Println(err)
continue
}
if opts.ShowTime {
timer.Start()
}
2018-09-18 22:42:38 +02:00
out, err := program.Run(
2018-09-28 06:28:33 +02:00
ctx,
runtime.WithBrowser(opts.Cdp),
2018-09-28 06:28:33 +02:00
runtime.WithLog(l),
runtime.WithLogLevel(logging.DebugLevel),
2018-09-29 03:04:16 +02:00
runtime.WithParams(opts.Params),
runtime.WithProxy(opts.Proxy),
runtime.WithUserAgent(opts.UserAgent),
)
2018-09-18 22:42:38 +02:00
if err != nil {
fmt.Println("Failed to execute the query")
fmt.Println(err)
continue
}
fmt.Println(string(out))
if opts.ShowTime {
timer.Stop()
fmt.Println(timer.Print())
}
2018-09-18 22:42:38 +02:00
}
}