/
generator.go
67 lines (58 loc) · 1.77 KB
/
generator.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
package gentsrpc
import (
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
)
var (
errNoTargetService = errors.New("no target service defined in the file")
)
// Generator processes proto descriptors and generates flow type definitions.
type Generator struct {
reg *descriptor.Registry
}
// New returns a new generator which generates flowtype type definition files.
func New(reg *descriptor.Registry) *Generator {
return &Generator{reg: reg}
}
// GeneratorOptions describes output parameters
type GeneratorOptions struct {
InputID string
}
func defaultOutputNames(targets []*descriptor.File) []string {
result := []string{}
for _, file := range targets {
name := file.GetName()
ext := filepath.Ext(name)
base := strings.TrimSuffix(name, ext)
result = append(result, fmt.Sprintf("%s.service.ts", base))
}
return result
}
// Generate processes the given proto files and produces flowtype output.
func (g *Generator) Generate(targets []*descriptor.File, opts GeneratorOptions) ([]*plugin.CodeGeneratorResponse_File, error) {
var files []*plugin.CodeGeneratorResponse_File
outputNames := defaultOutputNames(targets)
for i, file := range targets {
glog.V(1).Infof("Processing %s", file.GetName())
code, err := generate(file, g.reg, opts)
if err == errNoTargetService {
glog.V(1).Infof("%s: %v", file.GetName(), err)
continue
}
if err != nil {
return nil, err
}
files = append(files, &plugin.CodeGeneratorResponse_File{
Name: proto.String(outputNames[i]),
Content: proto.String(code),
})
glog.V(1).Infof("Will emit %s", outputNames[i])
}
return files, nil
}