forked from cayleygraph/cayley
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepl.go
243 lines (207 loc) · 5.03 KB
/
repl.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Copyright 2014 The Cayley Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package db
import (
"fmt"
"io"
"os"
"os/signal"
"strconv"
"strings"
"time"
"github.com/peterh/liner"
"github.com/google/cayley/config"
"github.com/google/cayley/graph"
"github.com/google/cayley/quad/cquads"
"github.com/google/cayley/query"
"github.com/google/cayley/query/gremlin"
"github.com/google/cayley/query/mql"
"github.com/google/cayley/query/sexp"
)
func trace(s string) (string, time.Time) {
return s, time.Now()
}
func un(s string, startTime time.Time) {
endTime := time.Now()
fmt.Printf(s, float64(endTime.UnixNano()-startTime.UnixNano())/float64(1E6))
}
func Run(query string, ses query.Session) {
nResults := 0
startTrace, startTime := trace("Elapsed time: %g ms\n\n")
defer func() {
if nResults > 0 {
un(startTrace, startTime)
}
}()
fmt.Printf("\n")
c := make(chan interface{}, 5)
go ses.Execute(query, c, 100)
for res := range c {
fmt.Print(ses.Format(res))
nResults++
}
if nResults > 0 {
fmt.Printf("-----------\n%d Results\n", nResults)
}
}
const (
ps1 = "cayley> "
ps2 = "... "
history = ".cayley_history"
)
func Repl(h *graph.Handle, queryLanguage string, cfg *config.Config) error {
var ses query.Session
switch queryLanguage {
case "sexp":
ses = sexp.NewSession(h.QuadStore)
case "mql":
ses = mql.NewSession(h.QuadStore)
case "gremlin":
fallthrough
default:
ses = gremlin.NewSession(h.QuadStore, cfg.Timeout, true)
}
term, err := terminal(history)
if os.IsNotExist(err) {
fmt.Printf("creating new history file: %q\n", history)
}
defer persist(term, history)
var (
prompt = ps1
code string
)
for {
if len(code) == 0 {
prompt = ps1
} else {
prompt = ps2
}
line, err := term.Prompt(prompt)
if err != nil {
if err == io.EOF {
fmt.Println()
return nil
}
return err
}
term.AppendHistory(line)
line = strings.TrimSpace(line)
if len(line) == 0 || line[0] == '#' {
continue
}
if code == "" {
cmd, args := splitLine(line)
switch cmd {
case ":debug":
args = strings.TrimSpace(args)
var debug bool
switch args {
case "t":
debug = true
case "f":
// Do nothing.
default:
debug, err = strconv.ParseBool(args)
if err != nil {
fmt.Printf("Error: cannot parse %q as a valid boolean - acceptable values: 't'|'true' or 'f'|'false'\n", args)
continue
}
}
ses.Debug(debug)
fmt.Printf("Debug set to %t\n", debug)
continue
case ":a":
quad, err := cquads.Parse(args)
if err != nil {
fmt.Printf("Error: not a valid quad: %v\n", err)
continue
}
h.QuadWriter.AddQuad(quad)
continue
case ":d":
quad, err := cquads.Parse(args)
if err != nil {
fmt.Printf("Error: not a valid quad: %v\n", err)
continue
}
h.QuadWriter.RemoveQuad(quad)
continue
default:
if cmd[0] == ':' {
fmt.Printf("Unknown command: %q\n", cmd)
continue
}
}
}
code += line
result, err := ses.Parse(code)
switch result {
case query.Parsed:
Run(code, ses)
code = ""
case query.ParseFail:
fmt.Println("Error: ", err)
code = ""
case query.ParseMore:
}
}
}
// Splits a line into a command and its arguments
// e.g. ":a b c d ." will be split into ":a" and " b c d ."
func splitLine(line string) (string, string) {
var command, arguments string
line = strings.TrimSpace(line)
// An empty line/a line consisting of whitespace contains neither command nor arguments
if len(line) > 0 {
command = strings.Fields(line)[0]
// A line containing only a command has no arguments
if len(line) > len(command) {
arguments = line[len(command):]
}
}
return command, arguments
}
func terminal(path string) (*liner.State, error) {
term := liner.NewLiner()
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
<-c
err := persist(term, history)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to properly clean up terminal: %v\n", err)
os.Exit(1)
}
os.Exit(0)
}()
f, err := os.Open(path)
if err != nil {
return term, err
}
defer f.Close()
_, err = term.ReadHistory(f)
return term, err
}
func persist(term *liner.State, path string) error {
f, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return fmt.Errorf("could not open %q to append history: %v", path, err)
}
defer f.Close()
_, err = term.WriteHistory(f)
if err != nil {
return fmt.Errorf("could not write history to %q: %v", path, err)
}
return term.Close()
}