-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
80 lines (67 loc) · 1.58 KB
/
graph.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
package codegraph
import (
"context"
"io"
"github.com/cayleygraph/cayley"
"github.com/cayleygraph/cayley/graph"
_ "github.com/cayleygraph/cayley/graph/kv/bolt"
"github.com/cayleygraph/cayley/quad/nquads"
)
const (
defaultKV = "bolt"
)
// Graph is a opaque type for cayley graph database handler.
type Graph struct {
store *cayley.Handle
}
// Open opens git graph database
func Open(dbpath string) (*Graph, error) {
err := graph.InitQuadStore(defaultKV, dbpath, nil)
if err != nil && err != graph.ErrDatabaseExists {
return nil, err
}
store, err := cayley.NewGraph(defaultKV, dbpath, nil)
if err != nil {
return nil, err
}
return &Graph{store}, nil
}
// Import imports git repository into graph database
// Returns number of imported commits
func (g *Graph) Import(_ context.Context, gitpath string, opts *ExportOptions) error {
w := graph.NewWriter(g.store)
defer w.Close()
exp, err := NewExporter(w, opts)
if err != nil {
return err
}
err = exp.ExportRepoPath(gitpath)
if cerr := exp.Close(); err == nil {
err = cerr
}
return err
}
// Export exports quads in raw format
// Returns number of exported quads
func (g *Graph) Export(ctx context.Context, w io.Writer) (int, error) {
qw := nquads.NewWriter(w)
defer qw.Close()
it, _ := g.store.QuadsAllIterator().Optimize()
defer it.Close()
n := 0
for it.Next(ctx) {
q := g.store.Quad(it.Result())
if err := qw.WriteQuad(q); err != nil {
return 0, err
}
n++
}
return n, nil
}
// Close implements io.Closer
func (g *Graph) Close() error {
if g != nil && g.store != nil {
return g.store.Close()
}
return nil
}