-
Notifications
You must be signed in to change notification settings - Fork 69
/
proteus.go
80 lines (68 loc) · 1.81 KB
/
proteus.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 proteus
import (
"gopkg.in/src-d/proteus.v1/protobuf"
"gopkg.in/src-d/proteus.v1/resolver"
"gopkg.in/src-d/proteus.v1/rpc"
"gopkg.in/src-d/proteus.v1/scanner"
)
// Options are all the available options to configure proto generation.
type Options struct {
BasePath string
Packages []string
}
type generator func(*scanner.Package, *protobuf.Package) error
func transformToProtobuf(packages []string, generate generator) error {
scanner, err := scanner.New(packages...)
if err != nil {
return err
}
pkgs, err := scanner.Scan()
if err != nil {
return err
}
r := resolver.New()
r.Resolve(pkgs)
t := protobuf.NewTransformer()
t.SetStructSet(createStructTypeSet(pkgs))
t.SetEnumSet(createEnumTypeSet(pkgs))
for _, p := range pkgs {
pkg := t.Transform(p)
if err := generate(p, pkg); err != nil {
return err
}
}
return nil
}
func createStructTypeSet(pkgs []*scanner.Package) protobuf.TypeSet {
ts := protobuf.NewTypeSet()
for _, p := range pkgs {
for _, s := range p.Structs {
ts.Add(p.Path, s.Name)
}
}
return ts
}
func createEnumTypeSet(pkgs []*scanner.Package) protobuf.TypeSet {
ts := protobuf.NewTypeSet()
for _, p := range pkgs {
for _, e := range p.Enums {
ts.Add(p.Path, e.Name)
}
}
return ts
}
// GenerateProtos generates proto files for the given options.
func GenerateProtos(options Options) error {
g := protobuf.NewGenerator(options.BasePath)
return transformToProtobuf(options.Packages, func(_ *scanner.Package, pkg *protobuf.Package) error {
return g.Generate(pkg)
})
}
// GenerateRPCServer generates the gRPC server implementation of the given
// packages.
func GenerateRPCServer(packages []string) error {
g := rpc.NewGenerator()
return transformToProtobuf(packages, func(p *scanner.Package, pkg *protobuf.Package) error {
return g.Generate(pkg, p.Path)
})
}