3 SLj@sdZdZddlZddlmZddlmZddlmZejZddZd d Z d d Z Gd dde Z ddZ erxejjZne ZddZdS)aJProvides DescriptorPool to use as a container for proto2 descriptors. The DescriptorPool is used in conjection with a DescriptorDatabase to maintain a collection of protocol buffer descriptors for use when dynamically creating message types at runtime. For most applications protocol buffers should be used via modules generated by the protocol buffer compiler tool. This should only be used when the type of protocol buffers used in an application or library cannot be predetermined. Below is a straightforward example on how to use this class: pool = DescriptorPool() file_descriptor_protos = [ ... ] for file_descriptor_proto in file_descriptor_protos: pool.Add(file_descriptor_proto) my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType') The message descriptor can be used in conjunction with the message_factory module in order to create a protocol buffer class that can be encoded and decoded. If you want to get a Python class for the specified proto, use the helper functions inside google.protobuf.message_factory directly instead of this class. z"matthewtoia@google.com (Matt Toia)N) descriptor)descriptor_database) text_encodingcCs |jdS)aLRemove leading period from fully-qualified type name. Due to b/13860351 in descriptor_database.py, types in the root namespace are generated with a leading period. This function removes that prefix. Args: name: A str, the fully-qualified symbol name. Returns: A str, the normalized fully-qualified symbol name. .)lstrip)namer%/usr/lib/python3.6/descriptor_pool.py_NormalizeFullyQualifiedNameFs r cCs|jdr|jSdSdS)zCReturns the value of the field `options`, or None if it is not set.optionsN)HasFieldr )Zdescriptor_protorrr _OptionsOrNoneUs r cCs6|jo4|jjo4|jjjo4|jtjjko4|j tjj kS)N) is_extensioncontaining_typeZ has_optionsZ GetOptionsZmessage_set_wire_formattyperFieldDescriptor TYPE_MESSAGElabelZLABEL_OPTIONAL)fieldrrr _IsMessageSetExtension]s  rc@s&eZdZdZerdFddZdGddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.ZdHd/d0ZdId1d2ZdJd4d5Zd6d7Zd8d9Zd:d;Z dd?Z"d@dAZ#dBdCZ$dDdEZ%dS)KDescriptorPoolzGA collection of protobufs dynamically constructed by descriptor protos.NcCs tjj|S)N)r_messager)cls descriptor_dbrrr __new__jszDescriptorPool.__new__cCsJtj|_||_i|_i|_i|_i|_i|_t j t |_ t j t |_ dS)aInitializes a Pool of proto buffs. The descriptor_db argument to the constructor is provided to allow specialized file descriptor proto lookup code to be triggered on demand. An example would be an implementation which will read and compile a file specified in a call to FindFileByName() and not require the call to Add() at all. Results from this database will be cached internally here as well. Args: descriptor_db: A secondary source of file descriptors. N)rZDescriptorDatabase _internal_db_descriptor_db _descriptors_enum_descriptors_service_descriptors_file_descriptors_toplevel_extensions collections defaultdictdict_extensions_by_name_extensions_by_number)selfrrrr __init__ns  zDescriptorPool.__init__cCs|jj|dS)zAdds the FileDescriptorProto and its types to this pool. Args: file_desc_proto: The FileDescriptorProto to add. N)rAdd)r'file_desc_protorrr r)szDescriptorPool.AddcCs&ddlm}|jj|}|j|dS)zAdds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add. r)descriptor_pb2N)google.protobufr+ZFileDescriptorProtoZ FromStringr))r'Zserialized_file_desc_protor+r*rrr AddSerializedFiles z DescriptorPool.AddSerializedFilecCs0t|tjstd||j|j<|j|jdS)aAdds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor. z+Expected instance of descriptor.Descriptor.N) isinstancer Descriptor TypeErrorr full_name_AddFileDescriptorfile)r'descrrr AddDescriptors  zDescriptorPool.AddDescriptorcCs0t|tjstd||j|j<|j|jdS)zAdds an EnumDescriptor to the pool. This method also registers the FileDescriptor associated with the enum. Args: enum_desc: An EnumDescriptor. z/Expected instance of descriptor.EnumDescriptor.N)r.rEnumDescriptorr0rr1r2r3)r'Z enum_descrrr AddEnumDescriptors  z DescriptorPool.AddEnumDescriptorcCs$t|tjstd||j|j<dS)z^Adds a ServiceDescriptor to the pool. Args: service_desc: A ServiceDescriptor. z2Expected instance of descriptor.ServiceDescriptor.N)r.rServiceDescriptorr0rr1)r'Z service_descrrr AddServiceDescriptors z#DescriptorPool.AddServiceDescriptorcCst|tjo|jstd|jdkr0||j|j<y|j|j |j }Wnt k rZYn(X||k rt d|j|j|j j|j f||j|j |j <||j |j |j<t|r||j |j |jj<dS)a;Adds a FieldDescriptor describing an extension to the pool. Args: extension: A FieldDescriptor. Raises: AssertionError: when another extension with the same number extends the same message. TypeError: when the specified extension is not a descriptor.FieldDescriptor. z!Expected an extension descriptor.NzSExtensions "%s" and "%s" both try to extend message type "%s" with field number %d.)r.rrrr0extension_scoper!r1r&rnumberKeyErrorAssertionErrorr%r message_type)r' extensionZ existing_descrrr AddExtensionDescriptors&   z%DescriptorPool.AddExtensionDescriptorcCs|j|dS)zAdds a FileDescriptor to the pool, non-recursively. If the FileDescriptor contains messages or enums, the caller must explicitly register them. Args: file_desc: A FileDescriptor. N)r2)r' file_descrrr AddFileDescriptors z DescriptorPool.AddFileDescriptorcCs$t|tjstd||j|j<dS)zAdds a FileDescriptor to the pool, non-recursively. If the FileDescriptor contains messages or enums, the caller must explicitly register them. Args: file_desc: A FileDescriptor. z/Expected instance of descriptor.FileDescriptor.N)r.rFileDescriptorr0r r)r'rArrr r2s z!DescriptorPool._AddFileDescriptorcCsy |j|Stk rYnXy|jj|}Wn:tk rj}z|jrV|jj|}n|WYdd}~XnX|s|td||j|S)zGets a FileDescriptor by file name. Args: file_name: The path to the file to get a descriptor for. Returns: A FileDescriptor for the named file. Raises: KeyError: if the file cannot be found in the pool. NzCannot find a file named %s)r r<rFindFileByNamer!_ConvertFileProtoToFileDescriptor)r' file_name file_protoerrorrrr rDs   zDescriptorPool.FindFileByNamec3Cst|}y |j|jStk r(YnXy |j|jStk rJYnXy |j|jStk rlYnXy |j|Stk rYnXy |j|jStk rYnX|jd\}}}y|j |}|j |st |jStk rtd|YnXdS)aGets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the pool. rz Cannot find a file containing %sN) r rr3r<rr_FindFileContainingSymbolInDbr! rpartitionFindMessageTypeByNameextensions_by_namer=)r'symbol message_name_extension_namemessagerrr FindFileContainingSymbol+s8       z'DescriptorPool.FindFileContainingSymbolcCs&t|}||jkr|j||j|S)zLoads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type. Raises: KeyError: if the message cannot be found in the pool. )r rrI)r'r1rrr rK[s   z$DescriptorPool.FindMessageTypeByNamecCs&t|}||jkr|j||j|S)zLoads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. Raises: KeyError: if the enum cannot be found in the pool. )r rrI)r'r1rrr FindEnumTypeByNamems   z!DescriptorPool.FindEnumTypeByNamecCs,t|}|jd\}}}|j|}|j|S)aLoads the named field descriptor from the pool. Args: full_name: The full name of the field descriptor to load. Returns: The field descriptor for the named field. Raises: KeyError: if the field cannot be found in the pool. r)r rJrKZfields_by_name)r'r1rNrOZ field_namemessage_descriptorrrr FindFieldByNames  zDescriptorPool.FindFieldByNamecCs,t|}|jd\}}}|j|}|j|S)aLoads the named oneof descriptor from the pool. Args: full_name: The full name of the oneof descriptor to load. Returns: The oneof descriptor for the named oneof. Raises: KeyError: if the oneof cannot be found in the pool. r)r rJrKZoneofs_by_name)r'r1rNrOZ oneof_namerTrrr FindOneofByNames  zDescriptorPool.FindOneofByNamecCspt|}y |j|Stk r&YnX|jd\}}}y|j|}Wntk rd|j|}YnX|j|S)aLoads the named extension descriptor from the pool. Args: full_name: The full name of the extension descriptor to load. Returns: A FieldDescriptor, describing the named extension. Raises: KeyError: if the extension cannot be found in the pool. r)r r!r<rJrKrIrL)r'r1rNrOrPscoperrr FindExtensionByNames  z"DescriptorPool.FindExtensionByNamecCs|j||S)aGets the extension of the specified message with the specified number. Extensions have to be registered to this pool by calling AddExtensionDescriptor. Args: message_descriptor: descriptor of the extended message. number: integer, number of the extension field. Returns: A FieldDescriptor describing the extension. Raises: KeyError: when no extension with the given number is known for the specified message. )r&)r'rTr;rrr FindExtensionByNumbersz$DescriptorPool.FindExtensionByNumbercCst|j|jS)a!Gets all the known extension of a given message. Extensions have to be registered to this pool by calling AddExtensionDescriptor. Args: message_descriptor: descriptor of the extended message. Returns: A list of FieldDescriptor describing the extensions. )listr&values)r'rTrrr FindAllExtensionss z DescriptorPool.FindAllExtensionscCs&t|}||jkr|j||j|S)aLoads the named service descriptor from the pool. Args: full_name: The full name of the service descriptor to load. Returns: The service descriptor for the named service. Raises: KeyError: if the service cannot be found in the pool. )r rrI)r'r1rrr FindServiceByNames   z DescriptorPool.FindServiceByNamecCsfy|jj|}Wn:tk rJ}z|jr6|jj|}n|WYdd}~XnX|s\td||j|S)a"Finds the file in descriptor DB containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the descriptor database. Nz Cannot find a file containing %s)rrRr<rrE)r'rMrGrHrrr rIs  z,DescriptorPool._FindFileContainingSymbolInDbc s0|jjkr$tj|j}fdd|jDfdd|jD}tj|j|j|j t ||j |d}i}x<|D]4}|j j |jj|j dd|jjDqxWx0|jD]&}j||j|||j }||j|j<qWx*|jD] } j| |j|d||j| j<qWx`t|jD]R\} } j| |j| |dd } j|j| j|| _j| | |j|| |j| j<qWx |jD]} j|j| |qxW|jrt|j}nd }x,|jD]"} j|| j|}||j| j<qWx4t|jD]&\} }j || ||j||j!|j<qWj"||j|j<j|jS) aDCreates a FileDescriptor from a proto or returns a cached copy. This method also has the side effect of loading all the symbols found in the file into the appropriate dictionaries in the pool. Args: file_proto: The proto to convert. Returns: A FileDescriptor matching the passed in proto. csg|]}j|qSr)rD).0n)r'rr szDDescriptorPool._ConvertFileProtoToFileDescriptor..csg|] }|qSrr)r^i) direct_depsrr r`s)Zpoolrpackagesyntaxr Z serialized_pb dependenciesZpublic_dependenciescss|]}t|j|fVqdS)N)_PrefixWithDotr1)r^enumrrr ,szCDescriptorPool._ConvertFileProtoToFileDescriptor..NT)r)#rr rZ_GetDeps dependencyZpublic_dependencyrrCrcrdr ZSerializeToStringupdate_ExtractSymbolsZmessage_types_by_namer[Zenum_types_by_namer>_ConvertMessageDescriptor enum_type_ConvertEnumDescriptor enumerater?_MakeFieldDescriptor_GetTypeFromScopeextendeer _SetFieldTyperL_SetAllFieldTypesrfZservice_MakeServiceDescriptorZservices_by_namer))r'rGZ built_depsZ public_depsZfile_descriptorrWrkr>Z message_descroindexextension_protoextension_desc desc_protoZdesc_proto_prefixr4 service_protor)rbr'r rEsf                z0DescriptorPool._ConvertFileProtoToFileDescriptorcs|rdj||jfn|jdkr*d}nj}dkr\}}|jd rL|j}| |jj| || || |_qLW|t<|j<|S)aAdds the proto to the pool in the specified package. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: The package the proto should be located in. file_desc: The file containing this message. scope: Dict mapping short and full symbols to message and enum types. syntax: string indicating syntax of the file ("proto2" or "proto3") Returns: The added descriptor. rNcsg|]}j|qSr)rn)r^nested) desc_namerArWr'rdrr r`zsz.csg|]}j|dqS)N)rp)r^rg)r~rArWr'rr r`~scs g|]\}}j||qSr)rr)r^rxr)r~rAr'rr r`sc s$g|]\}}j||ddqS)T)r)rr)r^rxr?)r~rAr'rr r`sc s4g|],\}}tj|jdj|jf|dg|jqS)rN)rZOneofDescriptorrjoinr )r^rxr4)r~rr r`scSsg|]}|j|jfqSr)startend)r^rrrr r`sTF)rr1filenamerfieldsoneofs nested_types enum_types extensionsr is_extendableextension_rangesr3Zserialized_startZserialized_endrd oneof_index)rr nested_typerorqrr?Z oneof_declZextension_rangerr/r rrrr rrappendZcontaining_oneofrfr)r'r{rcrArWrdrFr}Zenumsrrrrrr4rgZ field_index field_descrr)r~rArWr'rdr rn]sf          z(DescriptorPool._ConvertMessageDescriptorc s|rdj||jf}n|j}|dkr*d}n|j}fddt|jD}tj|j|||||t|d} | |d|<| j|<| S)aMake a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. Args: enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the enum descriptor. containing_type: The type containing this enum. scope: Scope containing available types. Returns: The added descriptor rNcsg|]\}}j||qSr)_MakeEnumValueDescriptor)r^rxvalue)r'rr r`sz9DescriptorPool._ConvertEnumDescriptor..)rr1rr3r[rr z.%s)rrrqrrr6r r) r'Z enum_protorcrArrWZ enum_namerFr[r4r)r'r rps$    z%DescriptorPool._ConvertEnumDescriptorFcCsR|rdj||jf}n|j}tj|j|||j|jdddd|jdd|dt||dS)aCreates a field descriptor from a FieldDescriptorProto. For message and enum type fields, this method will do a look up in the pool for the appropriate descriptor for that type. If it is unavailable, it will fall back to the _source function to create it. If this type is still unavailable, construction will fail. Args: field_proto: The proto describing the field. message_name: The name of the containing message. index: Index of the field file_desc: The file containing the field descriptor. is_extension: Indication that this field is for an extension. Returns: An initialized FieldDescriptor object rNF)rr1rxr;rcpp_typer>rorrhas_default_value default_valuerr:r r3)rrrrr;rrr )r' field_protorNrxrArr1rrr rrs(z#DescriptorPool._MakeFieldDescriptorc Cst|}|j||j|}|dkr,t|j}ndj||jg}x*t|j|jD]\}}|j||||qLWxtjj|_n tjj |_tjj |j|_ |jtjjkst|jtjj krz||_ |jtjj kr||_|jtjjkrd|_g|_nh|jdrvd|_|jtjjks|jtjjkrt|j|_n|jtjjkr|j|_nr|jtjjkr$|jjdk|_nP|jtjj krH|jj|jj|_n,|jtjjkrhtj|j|_n t|j|_nd|_|jtjjks|jtjjkrd|_np|jtjjkrd|_nX|jtjjkrd|_n@|jtjj kr|jjd j|_n|jtjjkrd |_nd |_|j|_dS) aSets the field's type, cpp_type, message_type and enum_type. Args: field_proto: Data about the field in proto format. field_desc: The descriptor to modiy. package: The package the field's container is in. scope: Enclosing scope of available types. NrFrTtruegrir) type_namersr r.rr/rrrZ TYPE_ENUMZProtoTypeToCppProtoTyperZ TYPE_GROUPr>rorZLABEL_REPEATEDrrZ TYPE_DOUBLEZ TYPE_FLOATfloatZ TYPE_STRINGZ TYPE_BOOLlowerZvalues_by_namer;Z TYPE_BYTESrZ CUnescapeintr[)r'rrrcrWr4rrr ru s^          zDescriptorPool._SetFieldTypecCstj|j||jt|ddS)zCreates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object. N)rrxr;r r)rZEnumValueDescriptorrr;r )r'Z value_protorxrrr rfs z'DescriptorPool._MakeEnumValueDescriptorcsdrdj|jfn|jfddt|jD}tj|j||t||d}|j<|S)aMake a protobuf ServiceDescriptor given a ServiceDescriptorProto. Args: service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message. service_index: The index of the service in the File. scope: Dict mapping short and full symbols to message and enum types. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the service descriptor. Returns: The added descriptor. rcs"g|]\}}j||qSr)_MakeMethodDescriptor)r^rx method_proto)rcrWr' service_namerr r`sz9DescriptorPool._MakeServiceDescriptor..)rr1rxmethodsr r3)rrrqmethodrr8r r)r'r|Z service_indexrWrcrArr4r)rcrWr'rr rwxs z%DescriptorPool._MakeServiceDescriptorc CsNdj||jf}|j||j|}|j||j|}tj|j||d||t|dS)aCreates a method descriptor from a MethodDescriptorProto. Args: method_proto: The proto describing the method. service_name: The name of the containing service. package: Optional package name to look up for types. scope: Scope containing available types. index: Index of the method in the service. Returns: An initialized MethodDescriptor object. rN)rr1rxZcontaining_service input_type output_typer )rrrsrrrZMethodDescriptorr ) r'rrrcrWrxr1rrrrr rs  z$DescriptorPool._MakeMethodDescriptorccs^xX|D]P}t|j|fVx|j|jD] }|Vq(Wx|jD]}t|j|fVq>WqWdS)zPulls out all the symbols from descriptor protos. Args: descriptors: The messages to extract descriptors from. Yields: A two element tuple of the type name and descriptor object. N)rfr1rmrr)r'Z descriptorsr4rMrgrrr rms   zDescriptorPool._ExtractSymbolsccs8x2|D]*}|j|}|Vx|jD] }|Vq"WqWdS)zRecursively finds dependencies for file protos. Args: dependencies: The names of the files being depended on. Yields: Each direct and indirect dependency. N)rDre)r'rerkZdep_descZ parent_deprrr rjs   zDescriptorPool._GetDepscCsR||krJt|jd}x2|rHdj||g}||kr<|}Pq|jdqW||S)a?Finds a given type name in the current scope. Args: package: The package the proto should be located in. type_name: The name of the type to be found in the scope. scope: Dict mapping short and full symbols to message and enum types. Returns: The descriptor for the requested type. r)rfsplitrpop)r'rcrrWZ componentsZpossible_matchrrr rss z DescriptorPool._GetTypeFromScope)N)N)NNNN)NNNN)F)&__name__ __module__ __qualname____doc___USE_C_DESCRIPTORSrr(r)r-r5r7r9r@rBr2rDrRrKrSrUrVrXrYr\r]rIrErnrprrrvrurrwrrmrjrsrrrr resJ    * 0U P & + F rcCs|jdr|Sd|S)Nrz.%s) startswith)rrrr rfsrfcCstS)N)_DEFAULTrrrr Defaultsr)r __author__r"r,rrrrr r robjectrrfrZ default_poolrrrrrr 8s,