descriptor_pool.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. """Provides DescriptorPool to use as a container for proto2 descriptors.
  31. The DescriptorPool is used in conjection with a DescriptorDatabase to maintain
  32. a collection of protocol buffer descriptors for use when dynamically creating
  33. message types at runtime.
  34. For most applications protocol buffers should be used via modules generated by
  35. the protocol buffer compiler tool. This should only be used when the type of
  36. protocol buffers used in an application or library cannot be predetermined.
  37. Below is a straightforward example on how to use this class:
  38. pool = DescriptorPool()
  39. file_descriptor_protos = [ ... ]
  40. for file_descriptor_proto in file_descriptor_protos:
  41. pool.Add(file_descriptor_proto)
  42. my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType')
  43. The message descriptor can be used in conjunction with the message_factory
  44. module in order to create a protocol buffer class that can be encoded and
  45. decoded.
  46. If you want to get a Python class for the specified proto, use the
  47. helper functions inside google.protobuf.message_factory
  48. directly instead of this class.
  49. """
  50. __author__ = 'matthewtoia@google.com (Matt Toia)'
  51. import sys
  52. from google.protobuf import descriptor
  53. from google.protobuf import descriptor_database
  54. from google.protobuf import text_encoding
  55. _USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS
  56. def _NormalizeFullyQualifiedName(name):
  57. """Remove leading period from fully-qualified type name.
  58. Due to b/13860351 in descriptor_database.py, types in the root namespace are
  59. generated with a leading period. This function removes that prefix.
  60. Args:
  61. name: A str, the fully-qualified symbol name.
  62. Returns:
  63. A str, the normalized fully-qualified symbol name.
  64. """
  65. return name.lstrip('.')
  66. class DescriptorPool(object):
  67. """A collection of protobufs dynamically constructed by descriptor protos."""
  68. def __init__(self, descriptor_db=None):
  69. """Initializes a Pool of proto buffs.
  70. The descriptor_db argument to the constructor is provided to allow
  71. specialized file descriptor proto lookup code to be triggered on demand. An
  72. example would be an implementation which will read and compile a file
  73. specified in a call to FindFileByName() and not require the call to Add()
  74. at all. Results from this database will be cached internally here as well.
  75. Args:
  76. descriptor_db: A secondary source of file descriptors.
  77. """
  78. self._internal_db = descriptor_database.DescriptorDatabase()
  79. self._descriptor_db = descriptor_db
  80. self._descriptors = {}
  81. self._enum_descriptors = {}
  82. self._file_descriptors = {}
  83. def Add(self, file_desc_proto):
  84. """Adds the FileDescriptorProto and its types to this pool.
  85. Args:
  86. file_desc_proto: The FileDescriptorProto to add.
  87. """
  88. self._internal_db.Add(file_desc_proto)
  89. def AddSerializedFile(self, serialized_file_desc_proto):
  90. """Adds the FileDescriptorProto and its types to this pool.
  91. Args:
  92. serialized_file_desc_proto: A bytes string, serialization of the
  93. FileDescriptorProto to add.
  94. """
  95. # pylint: disable=g-import-not-at-top
  96. from google.protobuf import descriptor_pb2
  97. file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
  98. serialized_file_desc_proto)
  99. self.Add(file_desc_proto)
  100. def AddDescriptor(self, desc):
  101. """Adds a Descriptor to the pool, non-recursively.
  102. If the Descriptor contains nested messages or enums, the caller must
  103. explicitly register them. This method also registers the FileDescriptor
  104. associated with the message.
  105. Args:
  106. desc: A Descriptor.
  107. """
  108. if not isinstance(desc, descriptor.Descriptor):
  109. raise TypeError('Expected instance of descriptor.Descriptor.')
  110. self._descriptors[desc.full_name] = desc
  111. self.AddFileDescriptor(desc.file)
  112. def AddEnumDescriptor(self, enum_desc):
  113. """Adds an EnumDescriptor to the pool.
  114. This method also registers the FileDescriptor associated with the message.
  115. Args:
  116. enum_desc: An EnumDescriptor.
  117. """
  118. if not isinstance(enum_desc, descriptor.EnumDescriptor):
  119. raise TypeError('Expected instance of descriptor.EnumDescriptor.')
  120. self._enum_descriptors[enum_desc.full_name] = enum_desc
  121. self.AddFileDescriptor(enum_desc.file)
  122. def AddFileDescriptor(self, file_desc):
  123. """Adds a FileDescriptor to the pool, non-recursively.
  124. If the FileDescriptor contains messages or enums, the caller must explicitly
  125. register them.
  126. Args:
  127. file_desc: A FileDescriptor.
  128. """
  129. if not isinstance(file_desc, descriptor.FileDescriptor):
  130. raise TypeError('Expected instance of descriptor.FileDescriptor.')
  131. self._file_descriptors[file_desc.name] = file_desc
  132. def FindFileByName(self, file_name):
  133. """Gets a FileDescriptor by file name.
  134. Args:
  135. file_name: The path to the file to get a descriptor for.
  136. Returns:
  137. A FileDescriptor for the named file.
  138. Raises:
  139. KeyError: if the file can not be found in the pool.
  140. """
  141. try:
  142. return self._file_descriptors[file_name]
  143. except KeyError:
  144. pass
  145. try:
  146. file_proto = self._internal_db.FindFileByName(file_name)
  147. except KeyError:
  148. _, error, _ = sys.exc_info() #PY25 compatible for GAE.
  149. if self._descriptor_db:
  150. file_proto = self._descriptor_db.FindFileByName(file_name)
  151. else:
  152. raise error
  153. if not file_proto:
  154. raise KeyError('Cannot find a file named %s' % file_name)
  155. return self._ConvertFileProtoToFileDescriptor(file_proto)
  156. def FindFileContainingSymbol(self, symbol):
  157. """Gets the FileDescriptor for the file containing the specified symbol.
  158. Args:
  159. symbol: The name of the symbol to search for.
  160. Returns:
  161. A FileDescriptor that contains the specified symbol.
  162. Raises:
  163. KeyError: if the file can not be found in the pool.
  164. """
  165. symbol = _NormalizeFullyQualifiedName(symbol)
  166. try:
  167. return self._descriptors[symbol].file
  168. except KeyError:
  169. pass
  170. try:
  171. return self._enum_descriptors[symbol].file
  172. except KeyError:
  173. pass
  174. try:
  175. file_proto = self._internal_db.FindFileContainingSymbol(symbol)
  176. except KeyError:
  177. _, error, _ = sys.exc_info() #PY25 compatible for GAE.
  178. if self._descriptor_db:
  179. file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
  180. else:
  181. raise error
  182. if not file_proto:
  183. raise KeyError('Cannot find a file containing %s' % symbol)
  184. return self._ConvertFileProtoToFileDescriptor(file_proto)
  185. def FindMessageTypeByName(self, full_name):
  186. """Loads the named descriptor from the pool.
  187. Args:
  188. full_name: The full name of the descriptor to load.
  189. Returns:
  190. The descriptor for the named type.
  191. """
  192. full_name = _NormalizeFullyQualifiedName(full_name)
  193. if full_name not in self._descriptors:
  194. self.FindFileContainingSymbol(full_name)
  195. return self._descriptors[full_name]
  196. def FindEnumTypeByName(self, full_name):
  197. """Loads the named enum descriptor from the pool.
  198. Args:
  199. full_name: The full name of the enum descriptor to load.
  200. Returns:
  201. The enum descriptor for the named type.
  202. """
  203. full_name = _NormalizeFullyQualifiedName(full_name)
  204. if full_name not in self._enum_descriptors:
  205. self.FindFileContainingSymbol(full_name)
  206. return self._enum_descriptors[full_name]
  207. def _ConvertFileProtoToFileDescriptor(self, file_proto):
  208. """Creates a FileDescriptor from a proto or returns a cached copy.
  209. This method also has the side effect of loading all the symbols found in
  210. the file into the appropriate dictionaries in the pool.
  211. Args:
  212. file_proto: The proto to convert.
  213. Returns:
  214. A FileDescriptor matching the passed in proto.
  215. """
  216. if file_proto.name not in self._file_descriptors:
  217. built_deps = list(self._GetDeps(file_proto.dependency))
  218. direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
  219. file_descriptor = descriptor.FileDescriptor(
  220. name=file_proto.name,
  221. package=file_proto.package,
  222. syntax=file_proto.syntax,
  223. options=file_proto.options,
  224. serialized_pb=file_proto.SerializeToString(),
  225. dependencies=direct_deps)
  226. if _USE_C_DESCRIPTORS:
  227. # When using C++ descriptors, all objects defined in the file were added
  228. # to the C++ database when the FileDescriptor was built above.
  229. # Just add them to this descriptor pool.
  230. def _AddMessageDescriptor(message_desc):
  231. self._descriptors[message_desc.full_name] = message_desc
  232. for nested in message_desc.nested_types:
  233. _AddMessageDescriptor(nested)
  234. for enum_type in message_desc.enum_types:
  235. _AddEnumDescriptor(enum_type)
  236. def _AddEnumDescriptor(enum_desc):
  237. self._enum_descriptors[enum_desc.full_name] = enum_desc
  238. for message_type in file_descriptor.message_types_by_name.values():
  239. _AddMessageDescriptor(message_type)
  240. for enum_type in file_descriptor.enum_types_by_name.values():
  241. _AddEnumDescriptor(enum_type)
  242. else:
  243. scope = {}
  244. # This loop extracts all the message and enum types from all the
  245. # dependencies of the file_proto. This is necessary to create the
  246. # scope of available message types when defining the passed in
  247. # file proto.
  248. for dependency in built_deps:
  249. scope.update(self._ExtractSymbols(
  250. dependency.message_types_by_name.values()))
  251. scope.update((_PrefixWithDot(enum.full_name), enum)
  252. for enum in dependency.enum_types_by_name.values())
  253. for message_type in file_proto.message_type:
  254. message_desc = self._ConvertMessageDescriptor(
  255. message_type, file_proto.package, file_descriptor, scope,
  256. file_proto.syntax)
  257. file_descriptor.message_types_by_name[message_desc.name] = (
  258. message_desc)
  259. for enum_type in file_proto.enum_type:
  260. file_descriptor.enum_types_by_name[enum_type.name] = (
  261. self._ConvertEnumDescriptor(enum_type, file_proto.package,
  262. file_descriptor, None, scope))
  263. for index, extension_proto in enumerate(file_proto.extension):
  264. extension_desc = self._MakeFieldDescriptor(
  265. extension_proto, file_proto.package, index, is_extension=True)
  266. extension_desc.containing_type = self._GetTypeFromScope(
  267. file_descriptor.package, extension_proto.extendee, scope)
  268. self._SetFieldType(extension_proto, extension_desc,
  269. file_descriptor.package, scope)
  270. file_descriptor.extensions_by_name[extension_desc.name] = (
  271. extension_desc)
  272. for desc_proto in file_proto.message_type:
  273. self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
  274. if file_proto.package:
  275. desc_proto_prefix = _PrefixWithDot(file_proto.package)
  276. else:
  277. desc_proto_prefix = ''
  278. for desc_proto in file_proto.message_type:
  279. desc = self._GetTypeFromScope(
  280. desc_proto_prefix, desc_proto.name, scope)
  281. file_descriptor.message_types_by_name[desc_proto.name] = desc
  282. self.Add(file_proto)
  283. self._file_descriptors[file_proto.name] = file_descriptor
  284. return self._file_descriptors[file_proto.name]
  285. def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
  286. scope=None, syntax=None):
  287. """Adds the proto to the pool in the specified package.
  288. Args:
  289. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  290. package: The package the proto should be located in.
  291. file_desc: The file containing this message.
  292. scope: Dict mapping short and full symbols to message and enum types.
  293. Returns:
  294. The added descriptor.
  295. """
  296. if package:
  297. desc_name = '.'.join((package, desc_proto.name))
  298. else:
  299. desc_name = desc_proto.name
  300. if file_desc is None:
  301. file_name = None
  302. else:
  303. file_name = file_desc.name
  304. if scope is None:
  305. scope = {}
  306. nested = [
  307. self._ConvertMessageDescriptor(
  308. nested, desc_name, file_desc, scope, syntax)
  309. for nested in desc_proto.nested_type]
  310. enums = [
  311. self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope)
  312. for enum in desc_proto.enum_type]
  313. fields = [self._MakeFieldDescriptor(field, desc_name, index)
  314. for index, field in enumerate(desc_proto.field)]
  315. extensions = [
  316. self._MakeFieldDescriptor(extension, desc_name, index,
  317. is_extension=True)
  318. for index, extension in enumerate(desc_proto.extension)]
  319. oneofs = [
  320. descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)),
  321. index, None, [])
  322. for index, desc in enumerate(desc_proto.oneof_decl)]
  323. extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
  324. if extension_ranges:
  325. is_extendable = True
  326. else:
  327. is_extendable = False
  328. desc = descriptor.Descriptor(
  329. name=desc_proto.name,
  330. full_name=desc_name,
  331. filename=file_name,
  332. containing_type=None,
  333. fields=fields,
  334. oneofs=oneofs,
  335. nested_types=nested,
  336. enum_types=enums,
  337. extensions=extensions,
  338. options=desc_proto.options,
  339. is_extendable=is_extendable,
  340. extension_ranges=extension_ranges,
  341. file=file_desc,
  342. serialized_start=None,
  343. serialized_end=None,
  344. syntax=syntax)
  345. for nested in desc.nested_types:
  346. nested.containing_type = desc
  347. for enum in desc.enum_types:
  348. enum.containing_type = desc
  349. for field_index, field_desc in enumerate(desc_proto.field):
  350. if field_desc.HasField('oneof_index'):
  351. oneof_index = field_desc.oneof_index
  352. oneofs[oneof_index].fields.append(fields[field_index])
  353. fields[field_index].containing_oneof = oneofs[oneof_index]
  354. scope[_PrefixWithDot(desc_name)] = desc
  355. self._descriptors[desc_name] = desc
  356. return desc
  357. def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,
  358. containing_type=None, scope=None):
  359. """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
  360. Args:
  361. enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
  362. package: Optional package name for the new message EnumDescriptor.
  363. file_desc: The file containing the enum descriptor.
  364. containing_type: The type containing this enum.
  365. scope: Scope containing available types.
  366. Returns:
  367. The added descriptor
  368. """
  369. if package:
  370. enum_name = '.'.join((package, enum_proto.name))
  371. else:
  372. enum_name = enum_proto.name
  373. if file_desc is None:
  374. file_name = None
  375. else:
  376. file_name = file_desc.name
  377. values = [self._MakeEnumValueDescriptor(value, index)
  378. for index, value in enumerate(enum_proto.value)]
  379. desc = descriptor.EnumDescriptor(name=enum_proto.name,
  380. full_name=enum_name,
  381. filename=file_name,
  382. file=file_desc,
  383. values=values,
  384. containing_type=containing_type,
  385. options=enum_proto.options)
  386. scope['.%s' % enum_name] = desc
  387. self._enum_descriptors[enum_name] = desc
  388. return desc
  389. def _MakeFieldDescriptor(self, field_proto, message_name, index,
  390. is_extension=False):
  391. """Creates a field descriptor from a FieldDescriptorProto.
  392. For message and enum type fields, this method will do a look up
  393. in the pool for the appropriate descriptor for that type. If it
  394. is unavailable, it will fall back to the _source function to
  395. create it. If this type is still unavailable, construction will
  396. fail.
  397. Args:
  398. field_proto: The proto describing the field.
  399. message_name: The name of the containing message.
  400. index: Index of the field
  401. is_extension: Indication that this field is for an extension.
  402. Returns:
  403. An initialized FieldDescriptor object
  404. """
  405. if message_name:
  406. full_name = '.'.join((message_name, field_proto.name))
  407. else:
  408. full_name = field_proto.name
  409. return descriptor.FieldDescriptor(
  410. name=field_proto.name,
  411. full_name=full_name,
  412. index=index,
  413. number=field_proto.number,
  414. type=field_proto.type,
  415. cpp_type=None,
  416. message_type=None,
  417. enum_type=None,
  418. containing_type=None,
  419. label=field_proto.label,
  420. has_default_value=False,
  421. default_value=None,
  422. is_extension=is_extension,
  423. extension_scope=None,
  424. options=field_proto.options)
  425. def _SetAllFieldTypes(self, package, desc_proto, scope):
  426. """Sets all the descriptor's fields's types.
  427. This method also sets the containing types on any extensions.
  428. Args:
  429. package: The current package of desc_proto.
  430. desc_proto: The message descriptor to update.
  431. scope: Enclosing scope of available types.
  432. """
  433. package = _PrefixWithDot(package)
  434. main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)
  435. if package == '.':
  436. nested_package = _PrefixWithDot(desc_proto.name)
  437. else:
  438. nested_package = '.'.join([package, desc_proto.name])
  439. for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):
  440. self._SetFieldType(field_proto, field_desc, nested_package, scope)
  441. for extension_proto, extension_desc in (
  442. zip(desc_proto.extension, main_desc.extensions)):
  443. extension_desc.containing_type = self._GetTypeFromScope(
  444. nested_package, extension_proto.extendee, scope)
  445. self._SetFieldType(extension_proto, extension_desc, nested_package, scope)
  446. for nested_type in desc_proto.nested_type:
  447. self._SetAllFieldTypes(nested_package, nested_type, scope)
  448. def _SetFieldType(self, field_proto, field_desc, package, scope):
  449. """Sets the field's type, cpp_type, message_type and enum_type.
  450. Args:
  451. field_proto: Data about the field in proto format.
  452. field_desc: The descriptor to modiy.
  453. package: The package the field's container is in.
  454. scope: Enclosing scope of available types.
  455. """
  456. if field_proto.type_name:
  457. desc = self._GetTypeFromScope(package, field_proto.type_name, scope)
  458. else:
  459. desc = None
  460. if not field_proto.HasField('type'):
  461. if isinstance(desc, descriptor.Descriptor):
  462. field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE
  463. else:
  464. field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM
  465. field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(
  466. field_proto.type)
  467. if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE
  468. or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):
  469. field_desc.message_type = desc
  470. if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  471. field_desc.enum_type = desc
  472. if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  473. field_desc.has_default_value = False
  474. field_desc.default_value = []
  475. elif field_proto.HasField('default_value'):
  476. field_desc.has_default_value = True
  477. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  478. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  479. field_desc.default_value = float(field_proto.default_value)
  480. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  481. field_desc.default_value = field_proto.default_value
  482. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  483. field_desc.default_value = field_proto.default_value.lower() == 'true'
  484. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  485. field_desc.default_value = field_desc.enum_type.values_by_name[
  486. field_proto.default_value].number
  487. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  488. field_desc.default_value = text_encoding.CUnescape(
  489. field_proto.default_value)
  490. else:
  491. field_desc.default_value = int(field_proto.default_value)
  492. else:
  493. field_desc.has_default_value = False
  494. field_desc.default_value = None
  495. field_desc.type = field_proto.type
  496. def _MakeEnumValueDescriptor(self, value_proto, index):
  497. """Creates a enum value descriptor object from a enum value proto.
  498. Args:
  499. value_proto: The proto describing the enum value.
  500. index: The index of the enum value.
  501. Returns:
  502. An initialized EnumValueDescriptor object.
  503. """
  504. return descriptor.EnumValueDescriptor(
  505. name=value_proto.name,
  506. index=index,
  507. number=value_proto.number,
  508. options=value_proto.options,
  509. type=None)
  510. def _ExtractSymbols(self, descriptors):
  511. """Pulls out all the symbols from descriptor protos.
  512. Args:
  513. descriptors: The messages to extract descriptors from.
  514. Yields:
  515. A two element tuple of the type name and descriptor object.
  516. """
  517. for desc in descriptors:
  518. yield (_PrefixWithDot(desc.full_name), desc)
  519. for symbol in self._ExtractSymbols(desc.nested_types):
  520. yield symbol
  521. for enum in desc.enum_types:
  522. yield (_PrefixWithDot(enum.full_name), enum)
  523. def _GetDeps(self, dependencies):
  524. """Recursively finds dependencies for file protos.
  525. Args:
  526. dependencies: The names of the files being depended on.
  527. Yields:
  528. Each direct and indirect dependency.
  529. """
  530. for dependency in dependencies:
  531. dep_desc = self.FindFileByName(dependency)
  532. yield dep_desc
  533. for parent_dep in dep_desc.dependencies:
  534. yield parent_dep
  535. def _GetTypeFromScope(self, package, type_name, scope):
  536. """Finds a given type name in the current scope.
  537. Args:
  538. package: The package the proto should be located in.
  539. type_name: The name of the type to be found in the scope.
  540. scope: Dict mapping short and full symbols to message and enum types.
  541. Returns:
  542. The descriptor for the requested type.
  543. """
  544. if type_name not in scope:
  545. components = _PrefixWithDot(package).split('.')
  546. while components:
  547. possible_match = '.'.join(components + [type_name])
  548. if possible_match in scope:
  549. type_name = possible_match
  550. break
  551. else:
  552. components.pop(-1)
  553. return scope[type_name]
  554. def _PrefixWithDot(name):
  555. return name if name.startswith('.') else '.%s' % name