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

84 lines
1.2 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
"io/ioutil"
"os"
2018-09-28 06:28:33 +02:00
"os/signal"
2018-09-18 22:42:38 +02:00
)
func ExecFile(pathToFile string, opts Options) {
2018-09-18 22:42:38 +02:00
query, err := ioutil.ReadFile(pathToFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
return
}
Exec(string(query), opts)
}
func Exec(query string, opts Options) {
2018-09-18 22:42:38 +02:00
ferret := compiler.New()
prog, err := ferret.Compile(query)
2018-09-18 22:42:38 +02:00
if err != nil {
fmt.Println("Failed to compile the query")
fmt.Println(err)
os.Exit(1)
return
}
2018-09-28 06:28:33 +02:00
l := NewLogger()
2019-04-10 12:20:20 +02:00
ctx, cancel := opts.WithContext(context.Background())
2018-09-28 06:28:33 +02:00
c := make(chan os.Signal, 1)
2019-04-10 12:20:20 +02:00
signal.Notify(c, os.Interrupt)
2018-09-28 06:28:33 +02:00
go func() {
for {
<-c
cancel()
l.Close()
}
}()
var timer *Timer
if opts.ShowTime {
timer = NewTimer()
timer.Start()
}
out, err := prog.Run(
2018-09-28 06:28:33 +02:00
ctx,
runtime.WithLog(l),
runtime.WithLogLevel(logging.DebugLevel),
2018-09-29 03:04:16 +02:00
runtime.WithParams(opts.Params),
)
2018-09-18 22:42:38 +02:00
if opts.ShowTime {
timer.Stop()
}
2018-09-18 22:42:38 +02:00
if err != nil {
fmt.Println("Failed to execute the query")
fmt.Println(err)
os.Exit(1)
return
}
fmt.Println(string(out))
if opts.ShowTime {
fmt.Println(timer.Print())
}
2018-09-18 22:42:38 +02:00
}