proto_builder.py 3.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Dynamic Protobuf class creator."""
  31. import hashlib
  32. import os
  33. from google.protobuf import descriptor_pb2
  34. from google.protobuf import message_factory
  35. def _GetMessageFromFactory(factory, full_name):
  36. """Get a proto class from the MessageFactory by name.
  37. Args:
  38. factory: a MessageFactory instance.
  39. full_name: str, the fully qualified name of the proto type.
  40. Returns:
  41. a class, for the type identified by full_name.
  42. Raises:
  43. KeyError, if the proto is not found in the factory's descriptor pool.
  44. """
  45. proto_descriptor = factory.pool.FindMessageTypeByName(full_name)
  46. proto_cls = factory.GetPrototype(proto_descriptor)
  47. return proto_cls
  48. def MakeSimpleProtoClass(fields, full_name, pool=None):
  49. """Create a Protobuf class whose fields are basic types.
  50. Note: this doesn't validate field names!
  51. Args:
  52. fields: dict of {name: field_type} mappings for each field in the proto.
  53. full_name: str, the fully-qualified name of the proto type.
  54. pool: optional DescriptorPool instance.
  55. Returns:
  56. a class, the new protobuf class with a FileDescriptor.
  57. """
  58. factory = message_factory.MessageFactory(pool=pool)
  59. try:
  60. proto_cls = _GetMessageFromFactory(factory, full_name)
  61. return proto_cls
  62. except KeyError:
  63. # The factory's DescriptorPool doesn't know about this class yet.
  64. pass
  65. # Use a consistent file name that is unlikely to conflict with any imported
  66. # proto files.
  67. fields_hash = hashlib.sha1()
  68. for f_name, f_type in sorted(fields.items()):
  69. fields_hash.update(f_name.encode('utf8'))
  70. fields_hash.update(str(f_type).encode('utf8'))
  71. proto_file_name = fields_hash.hexdigest() + '.proto'
  72. package, name = full_name.rsplit('.', 1)
  73. file_proto = descriptor_pb2.FileDescriptorProto()
  74. file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name)
  75. file_proto.package = package
  76. desc_proto = file_proto.message_type.add()
  77. desc_proto.name = name
  78. for f_number, (f_name, f_type) in enumerate(sorted(fields.items()), 1):
  79. field_proto = desc_proto.field.add()
  80. field_proto.name = f_name
  81. field_proto.number = f_number
  82. field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
  83. field_proto.type = f_type
  84. factory.pool.Add(file_proto)
  85. return _GetMessageFromFactory(factory, full_name)