/
unmarshal.go
394 lines (339 loc) · 11 KB
/
unmarshal.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Copyright 2016 The LUCI Authors.
//
// 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 flagpb
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"strconv"
"strings"
"go.chromium.org/luci/common/proto/google/descutil"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
)
// UnmarshalMessage unmarshals the proto message from flags.
//
// The descriptor set should be obtained from the `cproto` compiled packages'
// FileDescriptorSet() method.
func UnmarshalMessage(flags []string, resolver Resolver, msg proto.Message) error {
// TODO(iannucci): avoid round-trip through parser and jsonpb and populate the
// message directly. This would involve writing some additional reflection
// code that may depend on implementation details of proto's generated Go
// code, which is why this wasn't done initially.
name := proto.MessageName(msg)
dproto, ok := resolver.Resolve(name).(*descriptor.DescriptorProto)
if !ok {
return fmt.Errorf("could not resolve message %q", name)
}
jdata, err := UnmarshalUntyped(flags, dproto, resolver)
if err != nil {
return err
}
jtext, err := json.Marshal(jdata)
if err != nil {
return err
}
return jsonpb.Unmarshal(bytes.NewReader(jtext), msg)
}
// UnmarshalUntyped unmarshals a key-value map from flags
// using a protobuf message descriptor.
func UnmarshalUntyped(flags []string, desc *descriptor.DescriptorProto, resolver Resolver) (map[string]interface{}, error) {
p := parser{resolver}
return p.parse(flags, desc)
}
type message struct {
data map[string]interface{}
desc *descriptor.DescriptorProto
}
type parser struct {
Resolver Resolver
}
func (p *parser) parse(flags []string, desc *descriptor.DescriptorProto) (map[string]interface{}, error) {
if desc == nil {
panic("desc is nil")
}
root := message{map[string]interface{}{}, desc}
for len(flags) > 0 {
var err error
if flags, err = p.parseOneFlag(flags, root); err != nil {
return nil, err
}
}
return root.data, nil
}
func (p *parser) parseOneFlag(flags []string, root message) (flagsRest []string, err error) {
// skip empty flags
for len(flags) > 0 && strings.TrimSpace(flags[0]) == "" {
flags = flags[1:]
}
if len(flags) == 0 {
return flags, nil
}
firstArg := flags[0]
flags = flags[1:]
// Prefix returned errors with flag name verbatim.
defer func() {
if err != nil {
err = fmt.Errorf("%s: %s", firstArg, err)
}
}()
// Trim dashes.
if !strings.HasPrefix(firstArg, "-") {
return nil, fmt.Errorf("a flag was expected")
}
flagName := strings.TrimPrefix(firstArg, "-") // -foo
flagName = strings.TrimPrefix(flagName, "-") // --foo
if strings.HasPrefix(flagName, "-") {
// Triple dash is too much.
return nil, fmt.Errorf("bad flag syntax")
}
// Split key-value pair x=y.
flagName, valueStr, hasValueStr := p.splitKeyValuePair(flagName)
if flagName == "" {
return nil, fmt.Errorf("bad flag syntax")
}
// Split field path "a.b.c" and resolve field names.
fieldPath := strings.Split(flagName, ".")
pathMsgs, err := p.subMessages(root, fieldPath[:len(fieldPath)-1])
if err != nil {
return nil, err
}
// Where to assign the value?
target := &root
if len(pathMsgs) > 0 {
lastMsg := pathMsgs[len(pathMsgs)-1]
target = &lastMsg.message
}
name := fieldPath[len(fieldPath)-1]
// Resolve target field.
var fieldIndex int
if target.desc.GetOptions().GetMapEntry() {
if fieldIndex = descutil.FindField(target.desc, "value"); fieldIndex == -1 {
return nil, fmt.Errorf("map entry type %s does not have value field", target.desc.GetName())
}
} else {
if fieldIndex = descutil.FindField(target.desc, name); fieldIndex == -1 {
return nil, fmt.Errorf("field %s not found in message %s", name, target.desc.GetName())
}
}
field := target.desc.Field[fieldIndex]
var value interface{}
hasValue := false
if !hasValueStr {
switch {
// Boolean and repeated message fields may have no value and ignore
// next argument.
case field.GetType() == descriptor.FieldDescriptorProto_TYPE_BOOL:
value = true
hasValue = true
case field.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE && descutil.Repeated(field):
value = map[string]interface{}{}
hasValue = true
default:
// Read next argument as a value.
if len(flags) == 0 {
return nil, fmt.Errorf("value was expected")
}
valueStr, flags = flags[0], flags[1:]
}
}
// Check if the value is already set.
if target.data[name] != nil && !descutil.Repeated(field) {
repeatedFields := make([]string, 0, len(pathMsgs))
for _, m := range pathMsgs {
if m.repeated {
repeatedFields = append(repeatedFields, "-"+strings.Join(m.path, "."))
}
}
if len(repeatedFields) == 0 {
return nil, fmt.Errorf("value is already set to %v", target.data[name])
}
return nil, fmt.Errorf(
"value is already set to %v. Did you forgot to insert %s in between to declare a new repeated message?",
target.data[name], strings.Join(repeatedFields, " or "))
}
if !hasValue {
value, err = p.parseFieldValue(valueStr, target.desc.GetName(), field)
if err != nil {
return nil, err
}
}
if !descutil.Repeated(field) {
target.data[name] = value
} else {
target.data[name] = append(asSlice(target.data[name]), value)
}
return flags, nil
}
type subMsg struct {
message
path []string
repeated bool
}
// subMessages returns message field values at each component of the path.
// For example, for path ["a", "b", "c"] it will return
// [msg.a, msg.a.b, msg.a.b.c].
// If a field is repeated, returns the last message.
//
// If a field value is nil, initializes it with an empty message or slice.
// If a field is not a message field, returns an error.
func (p *parser) subMessages(root message, path []string) ([]subMsg, error) {
result := make([]subMsg, 0, len(path))
parent := &root
for i, name := range path {
curPath := path[:i+1]
var fieldIndex int
if parent.desc.GetOptions().GetMapEntry() {
if fieldIndex = descutil.FindField(parent.desc, "value"); fieldIndex == -1 {
return nil, fmt.Errorf("map entry type %s does not have value field", parent.desc.GetName())
}
} else {
if fieldIndex = descutil.FindField(parent.desc, name); fieldIndex == -1 {
return nil, fmt.Errorf("field %q not found in message %s", name, parent.desc.GetName())
}
}
f := parent.desc.Field[fieldIndex]
if f.GetType() != descriptor.FieldDescriptorProto_TYPE_MESSAGE {
return nil, fmt.Errorf("field %s is not a message", strings.Join(curPath, "."))
}
subDescInterface, err := p.resolve(f.GetTypeName())
if err != nil {
return nil, err
}
subDesc, ok := subDescInterface.(*descriptor.DescriptorProto)
if !ok {
return nil, fmt.Errorf("%s is not a message", f.GetTypeName())
}
sub := subMsg{
message: message{desc: subDesc},
repeated: descutil.Repeated(f) && !subDesc.GetOptions().GetMapEntry(),
path: curPath,
}
if value, ok := parent.data[name]; !ok {
sub.data = map[string]interface{}{}
if sub.repeated {
parent.data[name] = []interface{}{sub.data}
} else {
parent.data[name] = sub.data
}
} else {
if sub.repeated {
slice := asSlice(value)
value = slice[len(slice)-1]
}
sub.data = value.(map[string]interface{})
}
result = append(result, sub)
parent = &sub.message
}
return result, nil
}
// parseFieldValue parses a field value according to the field type.
// Types: https://developers.google.com/protocol-buffers/docs/proto?hl=en#scalar
func (p *parser) parseFieldValue(s string, msgName string, field *descriptor.FieldDescriptorProto) (interface{}, error) {
switch field.GetType() {
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
return strconv.ParseFloat(s, 64)
case descriptor.FieldDescriptorProto_TYPE_FLOAT:
x, err := strconv.ParseFloat(s, 32)
return float32(x), err
case
descriptor.FieldDescriptorProto_TYPE_INT32,
descriptor.FieldDescriptorProto_TYPE_SFIXED32,
descriptor.FieldDescriptorProto_TYPE_SINT32:
x, err := strconv.ParseInt(s, 10, 32)
return int32(x), err
case descriptor.FieldDescriptorProto_TYPE_INT64,
descriptor.FieldDescriptorProto_TYPE_SFIXED64,
descriptor.FieldDescriptorProto_TYPE_SINT64:
return strconv.ParseInt(s, 10, 64)
case descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_FIXED32:
x, err := strconv.ParseUint(s, 10, 32)
return uint32(x), err
case descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_FIXED64:
return strconv.ParseUint(s, 10, 64)
case descriptor.FieldDescriptorProto_TYPE_BOOL:
return strconv.ParseBool(s)
case descriptor.FieldDescriptorProto_TYPE_STRING:
return s, nil
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
return nil, fmt.Errorf(
"%s.%s is a message field. Specify its field values, not the message itself",
msgName, field.GetName())
case descriptor.FieldDescriptorProto_TYPE_BYTES:
return hex.DecodeString(s)
case descriptor.FieldDescriptorProto_TYPE_ENUM:
obj, err := p.resolve(field.GetTypeName())
if err != nil {
return nil, err
}
enum, ok := obj.(*descriptor.EnumDescriptorProto)
if !ok {
return nil, fmt.Errorf(
"field %s.%s is declared as of type enum %s, but %s is not an enum",
msgName, field.GetName(),
field.GetTypeName(), field.GetTypeName(),
)
}
return parseEnum(enum, s)
default:
return nil, fmt.Errorf("field type %s is not supported", field.GetType())
}
}
func (p *parser) resolve(name string) (interface{}, error) {
if p.Resolver == nil {
panic(fmt.Errorf("cannot resolve type %q. Resolver is not set", name))
}
name = strings.TrimPrefix(name, ".")
obj := p.Resolver.Resolve(name)
if obj == nil {
return nil, fmt.Errorf("cannot resolve type %q", name)
}
return obj, nil
}
// splitKeyValuePair splits a key value pair key=value if there is equals sign.
func (p *parser) splitKeyValuePair(s string) (key, value string, hasValue bool) {
parts := strings.SplitN(s, "=", 2)
switch len(parts) {
case 1:
key = s
case 2:
key = parts[0]
value = parts[1]
hasValue = true
}
return
}
// parseEnum returns the number of an enum member, which can be name or number.
func parseEnum(enum *descriptor.EnumDescriptorProto, member string) (int32, error) {
i := descutil.FindEnumValue(enum, member)
if i < 0 {
// Is member the number?
if number, err := strconv.ParseInt(member, 10, 32); err == nil {
i = descutil.FindValueByNumber(enum, int32(number))
}
}
if i < 0 {
return 0, fmt.Errorf("invalid value %q for enum %s", member, enum.GetName())
}
return enum.Value[i].GetNumber(), nil
}
func asSlice(x interface{}) []interface{} {
if x == nil {
return nil
}
return x.([]interface{})
}