blob: e4fb065e26afbd59aad2308f5f99af7b77b430f6 [file] [log] [blame]
Brian Silverman9c614bc2016-02-15 20:20:02 -05001# 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
31"""Provides a factory class for generating dynamic messages.
32
33The easiest way to use this class is if you have access to the FileDescriptor
34protos containing the messages you want to create you can just do the following:
35
36message_classes = message_factory.GetMessages(iterable_of_file_descriptors)
37my_proto_instance = message_classes['some.proto.package.MessageName']()
38"""
39
40__author__ = 'matthewtoia@google.com (Matt Toia)'
41
42from google.protobuf import descriptor_pool
43from google.protobuf import message
44from google.protobuf import reflection
45
46
47class MessageFactory(object):
48 """Factory for creating Proto2 messages from descriptors in a pool."""
49
50 def __init__(self, pool=None):
51 """Initializes a new factory."""
52 self.pool = pool or descriptor_pool.DescriptorPool()
53
54 # local cache of all classes built from protobuf descriptors
55 self._classes = {}
56
57 def GetPrototype(self, descriptor):
58 """Builds a proto2 message class based on the passed in descriptor.
59
60 Passing a descriptor with a fully qualified name matching a previous
61 invocation will cause the same class to be returned.
62
63 Args:
64 descriptor: The descriptor to build from.
65
66 Returns:
67 A class describing the passed in descriptor.
68 """
Austin Schuh40c16522018-10-28 20:27:54 -070069 if descriptor not in self._classes:
Brian Silverman9c614bc2016-02-15 20:20:02 -050070 descriptor_name = descriptor.name
71 if str is bytes: # PY2
72 descriptor_name = descriptor.name.encode('ascii', 'ignore')
73 result_class = reflection.GeneratedProtocolMessageType(
74 descriptor_name,
75 (message.Message,),
76 {'DESCRIPTOR': descriptor, '__module__': None})
77 # If module not set, it wrongly points to the reflection.py module.
Austin Schuh40c16522018-10-28 20:27:54 -070078 self._classes[descriptor] = result_class
Brian Silverman9c614bc2016-02-15 20:20:02 -050079 for field in descriptor.fields:
80 if field.message_type:
81 self.GetPrototype(field.message_type)
82 for extension in result_class.DESCRIPTOR.extensions:
Austin Schuh40c16522018-10-28 20:27:54 -070083 if extension.containing_type not in self._classes:
Brian Silverman9c614bc2016-02-15 20:20:02 -050084 self.GetPrototype(extension.containing_type)
Austin Schuh40c16522018-10-28 20:27:54 -070085 extended_class = self._classes[extension.containing_type]
Brian Silverman9c614bc2016-02-15 20:20:02 -050086 extended_class.RegisterExtension(extension)
Austin Schuh40c16522018-10-28 20:27:54 -070087 return self._classes[descriptor]
Brian Silverman9c614bc2016-02-15 20:20:02 -050088
89 def GetMessages(self, files):
90 """Gets all the messages from a specified file.
91
92 This will find and resolve dependencies, failing if the descriptor
93 pool cannot satisfy them.
94
95 Args:
96 files: The file names to extract messages from.
97
98 Returns:
99 A dictionary mapping proto names to the message classes. This will include
100 any dependent messages as well as any messages defined in the same file as
101 a specified message.
102 """
103 result = {}
104 for file_name in files:
105 file_desc = self.pool.FindFileByName(file_name)
Austin Schuh40c16522018-10-28 20:27:54 -0700106 for desc in file_desc.message_types_by_name.values():
107 result[desc.full_name] = self.GetPrototype(desc)
Brian Silverman9c614bc2016-02-15 20:20:02 -0500108
109 # While the extension FieldDescriptors are created by the descriptor pool,
110 # the python classes created in the factory need them to be registered
111 # explicitly, which is done below.
112 #
113 # The call to RegisterExtension will specifically check if the
114 # extension was already registered on the object and either
115 # ignore the registration if the original was the same, or raise
116 # an error if they were different.
117
Austin Schuh40c16522018-10-28 20:27:54 -0700118 for extension in file_desc.extensions_by_name.values():
119 if extension.containing_type not in self._classes:
Brian Silverman9c614bc2016-02-15 20:20:02 -0500120 self.GetPrototype(extension.containing_type)
Austin Schuh40c16522018-10-28 20:27:54 -0700121 extended_class = self._classes[extension.containing_type]
Brian Silverman9c614bc2016-02-15 20:20:02 -0500122 extended_class.RegisterExtension(extension)
123 return result
124
125
126_FACTORY = MessageFactory()
127
128
129def GetMessages(file_protos):
130 """Builds a dictionary of all the messages available in a set of files.
131
132 Args:
Austin Schuh40c16522018-10-28 20:27:54 -0700133 file_protos: Iterable of FileDescriptorProto to build messages out of.
Brian Silverman9c614bc2016-02-15 20:20:02 -0500134
135 Returns:
136 A dictionary mapping proto names to the message classes. This will include
137 any dependent messages as well as any messages defined in the same file as
138 a specified message.
139 """
Austin Schuh40c16522018-10-28 20:27:54 -0700140 # The cpp implementation of the protocol buffer library requires to add the
141 # message in topological order of the dependency graph.
142 file_by_name = {file_proto.name: file_proto for file_proto in file_protos}
143 def _AddFile(file_proto):
144 for dependency in file_proto.dependency:
145 if dependency in file_by_name:
146 # Remove from elements to be visited, in order to cut cycles.
147 _AddFile(file_by_name.pop(dependency))
Brian Silverman9c614bc2016-02-15 20:20:02 -0500148 _FACTORY.pool.Add(file_proto)
Austin Schuh40c16522018-10-28 20:27:54 -0700149 while file_by_name:
150 _AddFile(file_by_name.popitem()[1])
Brian Silverman9c614bc2016-02-15 20:20:02 -0500151 return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos])