1
0
mirror of https://github.com/MontFerret/ferret.git synced 2025-03-05 15:16:07 +02:00
ferret/cli/repl.go

132 lines
2.0 KiB
Go
Raw Normal View History

2018-09-25 21:49:42 -04:00
package cli
2018-09-18 16:42:38 -04:00
import (
"context"
"fmt"
"github.com/MontFerret/ferret/pkg/compiler"
"github.com/MontFerret/ferret/pkg/runtime"
2018-09-28 00:28:33 -04:00
"github.com/MontFerret/ferret/pkg/runtime/logging"
2018-09-18 16:42:38 -04:00
"github.com/chzyer/readline"
2018-09-28 00:28:33 -04:00
"os"
"os/signal"
2018-09-18 16:42:38 -04:00
"strings"
2018-09-28 00:28:33 -04:00
"syscall"
2018-09-18 16:42:38 -04:00
)
func Repl(version string, opts Options) {
2018-09-18 16:42:38 -04: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 02:28:26 -04:00
var multiline bool
var timer *Timer
if opts.ShowTime {
timer = NewTimer()
}
2018-09-18 16:42:38 -04:00
2018-09-28 00:28:33 -04:00
l := NewLogger()
ctx, cancel := context.WithCancel(opts.WithContext(context.Background()))
2018-09-28 00:28:33 -04:00
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
exit := func() {
cancel()
l.Close()
}
2018-09-28 00:28:33 -04:00
go func() {
for {
<-c
exit()
2018-09-28 00:28:33 -04:00
}
}()
2018-09-18 16:42:38 -04:00
for {
line, err := rl.Readline()
if err != nil {
break
}
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
2018-09-23 02:28:26 -04:00
if strings.HasPrefix(line, "%") {
line = line[1:]
multiline = !multiline
}
if multiline {
commands = append(commands, line)
2018-09-18 16:42:38 -04:00
continue
}
commands = append(commands, line)
2018-09-23 02:28:26 -04:00
query := strings.TrimSpace(strings.Join(commands, "\n"))
2018-09-18 16:42:38 -04:00
commands = make([]string, 0, 10)
2018-09-23 02:28:26 -04:00
if query == "" {
continue
}
if query == "exit" {
exit()
os.Exit(0)
return
}
2018-09-18 16:42:38 -04: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 16:42:38 -04:00
out, err := program.Run(
2018-09-28 00:28:33 -04:00
ctx,
runtime.WithLog(l),
runtime.WithLogLevel(logging.DebugLevel),
2018-09-28 21:04:16 -04:00
runtime.WithParams(opts.Params),
)
2018-09-18 16:42:38 -04: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 16:42:38 -04:00
}
}