OLD | NEW |
(Empty) | |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 """Converts proto messages from JSONPB.""" |
| 6 |
| 7 from google.protobuf import descriptor |
| 8 |
| 9 |
| 10 SCALAR_TYPES = { |
| 11 descriptor.FieldDescriptor.TYPE_BOOL, |
| 12 descriptor.FieldDescriptor.TYPE_BYTES, |
| 13 descriptor.FieldDescriptor.TYPE_DOUBLE, |
| 14 descriptor.FieldDescriptor.TYPE_FIXED32, |
| 15 descriptor.FieldDescriptor.TYPE_FIXED64, |
| 16 descriptor.FieldDescriptor.TYPE_FLOAT, |
| 17 descriptor.FieldDescriptor.TYPE_INT32, |
| 18 descriptor.FieldDescriptor.TYPE_INT64, |
| 19 descriptor.FieldDescriptor.TYPE_SFIXED32, |
| 20 descriptor.FieldDescriptor.TYPE_SFIXED64, |
| 21 descriptor.FieldDescriptor.TYPE_SINT32, |
| 22 descriptor.FieldDescriptor.TYPE_SINT64, |
| 23 descriptor.FieldDescriptor.TYPE_STRING, |
| 24 descriptor.FieldDescriptor.TYPE_UINT32, |
| 25 descriptor.FieldDescriptor.TYPE_UINT64, |
| 26 } |
| 27 |
| 28 |
| 29 def merge_dict(data, msg): |
| 30 """Merges |data| dict into |msg|, recursively. |
| 31 |
| 32 Raises: |
| 33 TypeError if a field in |data| is not defined in |msg| or has an |
| 34 unsupported type. |
| 35 """ |
| 36 if not isinstance(data, dict): |
| 37 raise TypeError('data is not a dict') |
| 38 for name, value in data.iteritems(): |
| 39 f = msg.DESCRIPTOR.fields_by_name.get(name) |
| 40 if not f: |
| 41 raise TypeError('unexpected property %r' % name) |
| 42 scalar_f = f.type in SCALAR_TYPES |
| 43 msg_f = f.type == descriptor.FieldDescriptor.TYPE_MESSAGE |
| 44 if not scalar_f and not msg_f: # pragma: no cover |
| 45 raise TypeError('field %s has unsupported type %r', name, f.type) |
| 46 |
| 47 try: |
| 48 if f.label == descriptor.FieldDescriptor.LABEL_REPEATED: |
| 49 container = getattr(msg, name) |
| 50 for v in value: |
| 51 if scalar_f: |
| 52 container.append(v) |
| 53 else: |
| 54 submsg = container.add() |
| 55 merge_dict(v, submsg) |
| 56 else: |
| 57 if scalar_f: |
| 58 setattr(msg, name, value) |
| 59 else: |
| 60 merge_dict(value, getattr(msg, name)) |
| 61 except TypeError as ex: |
| 62 raise TypeError('%s: %s' % (name, ex)) |
OLD | NEW |