forked from GoogleCloudPlatform/protoc-gen-bq-schema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
378 lines (340 loc) · 10.8 KB
/
main.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Copyright 2014 Google Inc. 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.
// protoc plugin which converts .proto to schema for BigQuery.
// It is spawned by protoc and generates schema for BigQuery, encoded in JSON.
//
// usage:
// $ bin/protoc --bq-schema_out=path/to/outdir foo.proto
//
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strings"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
)
var (
globalPkg = &ProtoPackage{
name: "",
parent: nil,
children: make(map[string]*ProtoPackage),
types: make(map[string]*descriptor.DescriptorProto),
}
)
// Field describes the schema of a field in BigQuery.
type Field struct {
Name string `json:"name"`
Type string `json:"type"`
Mode string `json:"mode"`
Fields []*Field `json:"fields,omitempty"`
}
// ProtoPackage describes a package of Protobuf, which is an container of message types.
type ProtoPackage struct {
name string
parent *ProtoPackage
children map[string]*ProtoPackage
types map[string]*descriptor.DescriptorProto
}
func registerType(pkgName *string, msg *descriptor.DescriptorProto) {
pkg := globalPkg
if pkgName != nil {
for _, node := range strings.Split(*pkgName, ".") {
if pkg == globalPkg && node == "" {
// Skips leading "."
continue
}
child, ok := pkg.children[node]
if !ok {
child = &ProtoPackage{
name: pkg.name + "." + node,
parent: pkg,
children: make(map[string]*ProtoPackage),
types: make(map[string]*descriptor.DescriptorProto),
}
pkg.children[node] = child
}
pkg = child
}
}
pkg.types[msg.GetName()] = msg
}
func (pkg *ProtoPackage) lookupType(name string) (*descriptor.DescriptorProto, bool) {
if strings.HasPrefix(name, ".") {
return globalPkg.relativelyLookupType(name[1:len(name)])
}
for ; pkg != nil; pkg = pkg.parent {
if desc, ok := pkg.relativelyLookupType(name); ok {
return desc, ok
}
}
return nil, false
}
func relativelyLookupNestedType(desc *descriptor.DescriptorProto, name string) (*descriptor.DescriptorProto, bool) {
components := strings.Split(name, ".")
componentLoop:
for _, component := range components {
for _, nested := range desc.GetNestedType() {
if nested.GetName() == component {
desc = nested
continue componentLoop
}
}
glog.Infof("no such nested message %s in %s", component, desc.GetName())
return nil, false
}
return desc, true
}
func (pkg *ProtoPackage) relativelyLookupType(name string) (*descriptor.DescriptorProto, bool) {
components := strings.SplitN(name, ".", 2)
switch len(components) {
case 0:
glog.V(1).Info("empty message name")
return nil, false
case 1:
found, ok := pkg.types[components[0]]
return found, ok
case 2:
glog.Infof("looking for %s in %s at %s (%v)", components[1], components[0], pkg.name, pkg)
if child, ok := pkg.children[components[0]]; ok {
found, ok := child.relativelyLookupType(components[1])
return found, ok
}
if msg, ok := pkg.types[components[0]]; ok {
found, ok := relativelyLookupNestedType(msg, components[1])
return found, ok
}
glog.V(1).Infof("no such package nor message %s in %s", components[0], pkg.name)
return nil, false
default:
glog.Fatal("not reached")
return nil, false
}
}
func (pkg *ProtoPackage) relativelyLookupPackage(name string) (*ProtoPackage, bool) {
components := strings.Split(name, ".")
for _, c := range components {
var ok bool
pkg, ok = pkg.children[c]
if !ok {
return nil, false
}
}
return pkg, true
}
var (
typeFromWKT = map[string]string{
".google.protobuf.Int32Value": "INTEGER",
".google.protobuf.Int64Value": "INTEGER",
".google.protobuf.UInt32Value": "INTEGER",
".google.protobuf.UInt64Value": "INTEGER",
".google.protobuf.DoubleValue": "FLOAT",
".google.protobuf.FloatValue": "FLOAT",
".google.protobuf.BoolValue": "BOOLEAN",
".google.protobuf.StringValue": "STRING",
".google.protobuf.BytesValue": "BYTES",
".google.protobuf.Duration": "STRING",
".google.protobuf.Timestamp": "TIMESTAMP",
}
typeFromFieldType = map[descriptor.FieldDescriptorProto_Type]string{
descriptor.FieldDescriptorProto_TYPE_DOUBLE: "FLOAT",
descriptor.FieldDescriptorProto_TYPE_FLOAT: "FLOAT",
descriptor.FieldDescriptorProto_TYPE_INT64: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_UINT64: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_INT32: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_UINT32: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_FIXED64: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_FIXED32: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_SFIXED32: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_SFIXED64: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_SINT32: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_SINT64: "INTEGER",
descriptor.FieldDescriptorProto_TYPE_STRING: "STRING",
descriptor.FieldDescriptorProto_TYPE_BYTES: "BYTES",
descriptor.FieldDescriptorProto_TYPE_ENUM: "STRING",
descriptor.FieldDescriptorProto_TYPE_BOOL: "BOOLEAN",
descriptor.FieldDescriptorProto_TYPE_GROUP: "RECORD",
descriptor.FieldDescriptorProto_TYPE_MESSAGE: "RECORD",
}
modeFromFieldLabel = map[descriptor.FieldDescriptorProto_Label]string{
descriptor.FieldDescriptorProto_LABEL_OPTIONAL: "NULLABLE",
descriptor.FieldDescriptorProto_LABEL_REQUIRED: "REQUIRED",
descriptor.FieldDescriptorProto_LABEL_REPEATED: "REPEATED",
}
)
func convertField(curPkg *ProtoPackage, desc *descriptor.FieldDescriptorProto, msg *descriptor.DescriptorProto) (*Field, error) {
field := &Field{
Name: desc.GetName(),
}
var ok bool
field.Mode, ok = modeFromFieldLabel[desc.GetLabel()]
if !ok {
return nil, fmt.Errorf("unrecognized field label: %s", desc.GetLabel().String())
}
field.Type, ok = typeFromFieldType[desc.GetType()]
if !ok {
return nil, fmt.Errorf("unrecognized field type: %s", desc.GetType().String())
}
if field.Type != "RECORD" {
return field, nil
}
if t, ok := typeFromWKT[desc.GetTypeName()]; ok {
field.Type = t
return field, nil
}
recordType, ok := curPkg.lookupType(desc.GetTypeName())
if !ok {
return nil, fmt.Errorf("no such message type named %s", desc.GetTypeName())
}
var err error
field.Fields, err = convertMessageType(curPkg, recordType)
if err != nil {
return nil, err
}
return field, nil
}
func convertMessageType(curPkg *ProtoPackage, msg *descriptor.DescriptorProto) (schema []*Field, err error) {
if glog.V(4) {
glog.Info("Converting message: ", proto.MarshalTextString(msg))
}
for _, fieldDesc := range msg.GetField() {
field, err := convertField(curPkg, fieldDesc, msg)
if err != nil {
glog.Errorf("Failed to convert field %s in %s: %v", fieldDesc.GetName(), msg.GetName(), err)
return nil, err
}
schema = append(schema, field)
}
return
}
func convertFile(file *descriptor.FileDescriptorProto) ([]*plugin.CodeGeneratorResponse_File, error) {
name := path.Base(file.GetName())
pkg, ok := globalPkg.relativelyLookupPackage(file.GetPackage())
if !ok {
return nil, fmt.Errorf("no such package found: %s", file.GetPackage())
}
response := []*plugin.CodeGeneratorResponse_File{}
for _, msg := range file.GetMessageType() {
options := msg.GetOptions()
if options == nil {
continue
}
if !proto.HasExtension(options, E_TableName) {
continue
}
optionValue, err := proto.GetExtension(options, E_TableName)
if err != nil {
return nil, err
}
tableName := *optionValue.(*string)
if len(tableName) == 0 {
return nil, fmt.Errorf("table name of %s cannot be empty", msg.GetName())
}
glog.V(2).Info("Generating schema for a message type ", msg.GetName())
schema, err := convertMessageType(pkg, msg)
if err != nil {
glog.Errorf("Failed to convert %s: %v", name, err)
return nil, err
}
jsonSchema, err := json.Marshal(schema)
if err != nil {
glog.Error("Failed to encode schema", err)
return nil, err
}
resFile := &plugin.CodeGeneratorResponse_File{
Name: proto.String(fmt.Sprintf("%s/%s.schema", strings.Replace(file.GetPackage(), ".", "/", -1), tableName)),
Content: proto.String(string(jsonSchema)),
}
response = append(response, resFile)
}
return response, nil
}
func convert(req *plugin.CodeGeneratorRequest) (*plugin.CodeGeneratorResponse, error) {
generateTargets := make(map[string]bool)
for _, file := range req.GetFileToGenerate() {
generateTargets[file] = true
}
res := &plugin.CodeGeneratorResponse{}
for _, file := range req.GetProtoFile() {
for _, msg := range file.GetMessageType() {
glog.V(1).Infof("Loading a message type %s from package %s", msg.GetName(), file.GetPackage())
registerType(file.Package, msg)
}
}
for _, file := range req.GetProtoFile() {
if _, ok := generateTargets[file.GetName()]; ok {
glog.V(1).Info("Converting ", file.GetName())
converted, err := convertFile(file)
if err != nil {
res.Error = proto.String(fmt.Sprintf("Failed to convert %s: %v", file.GetName(), err))
return res, err
}
res.File = append(res.File, converted...)
}
}
return res, nil
}
func convertFrom(rd io.Reader) (*plugin.CodeGeneratorResponse, error) {
glog.V(1).Info("Reading code generation request")
input, err := ioutil.ReadAll(rd)
if err != nil {
glog.Error("Failed to read request:", err)
return nil, err
}
req := &plugin.CodeGeneratorRequest{}
err = proto.Unmarshal(input, req)
if err != nil {
glog.Error("Can't unmarshal input:", err)
return nil, err
}
glog.V(1).Info("Converting input")
return convert(req)
}
func main() {
flag.Parse()
ok := true
glog.Info("Processing code generator request")
res, err := convertFrom(os.Stdin)
if err != nil {
ok = false
if res == nil {
message := fmt.Sprintf("Failed to read input: %v", err)
res = &plugin.CodeGeneratorResponse{
Error: &message,
}
}
}
glog.Info("Serializing code generator response")
data, err := proto.Marshal(res)
if err != nil {
glog.Fatal("Cannot marshal response", err)
}
_, err = os.Stdout.Write(data)
if err != nil {
glog.Fatal("Failed to write response", err)
}
if ok {
glog.Info("Succeeded to process code generator request")
} else {
glog.Info("Failed to process code generator but successfully sent the error to protoc")
os.Exit(1)
}
}