U
    ڲg;                     @   s  d dl Z d dlZ d dlZd dlZd dlmZmZmZmZm	Z	 d dl
Z
d dlZd dlmZ d dlmZ d dlmZmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ ej j!Z"e Z#G dd de$Z%G dd de%dZ&G dd dZ'dZ(dS )    N)AnyDictListOptionalType)descriptor_pb2)message)MessageToDictMessageToJsonParse)
_file_info)_package_info)Field)MapField)RepeatedField)Marshal)	ProtoType)has_upbc                       s(  e Zd ZdZ fddZedd Zedd Zdd	 Z	d-dde
dddZ fddZedddZeddddZee
 d
dddZee
 ee
 d
dddZee
 ee
 e
dddZd d
ddd!d
d
d"edd#d$Zdd%ddd&d'Zd d d
d
d
d(eeef dd)d*Zd+d, Z  ZS ).MessageMetaz<A metaclass for building and registering Message subclasses.c              	      s  |st  | |||S t||\}}t|d|d d krn d} d |d   |d d    d|f  	d}i }|
 D ]\}	}
t|
tsqdjtddd |	|	d	 |	d	  dd
}t|dd dj|d||dddid}t|
jdd|d< t|
jd|
j|
jd|d< t|tf|||< ttj|
j|| d||	< q|| g }i }t }t  }d	}|
 D ]
\}	}
t|
ts|
||	< q|	|||d|
_!|"|
 |
j#r|$|
j#t%| ||
j# |
j&_'|
jrBt|
jt(sB|
j}t)|dr*t*|j+r*|+ }|r|,|j-j.j/ nJ|
jrt|
jt(st)|
jdrp|
jj0j+n|
jj-}|r|,|j.j/ |d7 }qi }|D ]>}
|
j1rd|
j/|
_#t%| |
j&_'||
j#< |
j/||
j/< q|rt2d| f|} t3j45|d|6 }t3j47||}|D ]"}||j&j8kr|j&j8"| qt9j:f |;di }t9j<|dd |D dd |= D |d } fd!d|j>= D }|D ]}|j?, @|j>;| q fd"d|jA= D }|D ]}|jB, @|jA;| qt% dkr|j&jC, @| n
||j> < tD|||||d#|d< t  | |||}||j0_E|j0jFG D ]}
||
_Eq`||jH|< |jI|d$r|jJ||d% |S )&N__qualname__.z<locals>   z{pascal_key}Entryz_\wc                 S   s   |   dd   S )Nr   )groupupper)m r   1/tmp/pip-unpacked-wheel-zasgy6sz/proto/message.py<lambda>O       z%MessageMeta.__new__.<locals>.<lambda>r   )Z
pascal_key
__module__z{prefix}.{name})prefixnameZ	map_entryT)r   r   _pb_optionsnumberkey   )r$   enumr   value)r$   r   )r!   parent_nameindexpackagepb_metaz_{}Z	AttrsMetar"   c                 S   s   g | ]
}|j qS r   )
descriptor.0ir   r   r   
<listcomp>   s     z'MessageMeta.__new__.<locals>.<listcomp>c                 S   s   g | ]}t j|d qS )r!   )r   ZOneofDescriptorProtor/   r   r   r   r2      s    )r!   fieldZ
oneof_decloptionsc                    s    g | ]} |d d kr|qS Nr   r0   p
local_pathr   r   r2      s      c                    s    g | ]} |d d kr|qS r6   r   r8   r:   r   r   r2      s      )fields	full_namemarshalr5   r+   )	new_class)r?   Zfallback_salt)Ksuper__new__r   compiletuplegetsplitr*   joinlstripitems
isinstancer   formatresubreplacer   collectionsOrderedDictr   Zmap_key_typeZ
proto_typer'   r   r   Messager   r   ZMESSAGEr$   updatesetZ	mcls_dataappendZoneof
setdefaultlenr.   Zoneof_indexstrhasattrcallabler,   add
DESCRIPTORfiler!   r-   optionaltyper   Z	_FileInfoZproto_file_namelowerZmaybe_add_descriptor
dependencyr   MessageOptionspopZDescriptorProtokeysnestedZnested_type	MergeFromZnested_enumZ	enum_typeZmessage_type_MessageInfoparentr<   valuesmessagesreadyZgenerate_file_pb)mclsr!   basesattrsr+   r>   ixr=   Z
map_fieldsr%   r4   Zmsg_nameZentry_attrsr<   Z	new_attrsZoneofsZproto_importsr*   Z	field_msgZ
field_enumZ	opt_attrsfilename	file_infoZproto_importoptsdescZchild_pathsZ
child_pathcls	__class__r:   r   rA   -   s    
 
 
 








	

zMessageMeta.__new__c                 K   s   t  S N)rN   rO   )rj   r!   rk   kwargsr   r   r   __prepare__  s    zMessageMeta.__prepare__c                 C   s   | j S ru   )r-   )rr   r   r   r   meta   s    zMessageMeta.metac                 C   st   zRt tt}|d |  j}|dd |jD  |dd |jD  |W S  tk
rn   tt Y S X d S )N)	rx   r,   wrap	serializedeserializeto_json	from_jsonto_dict	copy_fromc                 s   s   | ]}|j V  qd S ru   r3   )r0   tr   r   r   	<genexpr>5  s     z&MessageMeta.__dir__.<locals>.<genexpr>c                 s   s   | ]}|j V  qd S ru   r3   r0   er   r   r   r   6  s     )	rR   dirr]   rQ   r,   rZ   nested_types
enum_typesAttributeError)selfnamesrq   r   r   r   __dir__$  s    
zMessageMeta.__dir__NFcoercec                C   s@   |dkr| j jS t|| s:|r(| |}ntd|| jf |jS )aH  Return the underlying protobuf Message class or instance.

        Args:
            obj: If provided, and an instance of ``cls``, return the
                underlying protobuf instance.
            coerce (bool): If provided, will attempt to coerce ``obj`` to
                ``cls`` if it is not already an instance.
        Nz%r is not an instance of %s)rx   r,   rI   	TypeError__name___pb)rr   objr   r   r   r   r,   <  s    	

zMessageMeta.pbc                    s    |  | }t| |d| |S )zReturn a Message object that shallowly wraps the descriptor.

        Args:
            pb: A protocol buffer object, such as would be returned by
                :meth:`pb`.
        r   )rA   r@   __setattr__)rr   r,   instancers   r   r   ry   T  s    
zMessageMeta.wrapreturnc                 C   s   | j |dd S )a  Return the serialized proto.

        Args:
            instance: An instance of this message type, or something
                compatible (accepted by the type's constructor).

        Returns:
            bytes: The serialized representation of the protocol buffer.
        Tr   )r,   SerializeToString)rr   r   r   r   r   rz   `  s    
zMessageMeta.serializerP   )payloadr   c                 C   s   |  |  |S )a  Given a serialized proto, deserialize it into a Message instance.

        Args:
            payload (bytes): The serialized proto.

        Returns:
            ~.Message: An instance of the message class against which this
            method was called.
        )ry   r,   
FromString)rr   r   r   r   r   r{   l  s    
zMessageMeta.deserialize)including_default_value_fieldsr   c                 C   s$   t d dkr |dk	r tdt dS )z
        Warn Protobuf 5.x+ users that `including_default_value_fields` is deprecated if it is set.

        Args:
            including_default_value_fields (Optional(bool)): The value of `including_default_value_fields` set by the user.
        r   34NzThe argument `including_default_value_fields` has been removed from
                Protobuf 5.x. Please use `always_print_fields_with_no_presence` instead.
                )PROTOBUF_VERSIONwarningswarnDeprecationWarning)rr   r   r   r   r   :_warn_if_including_default_value_fields_is_used_protobuf_5x  s    

zFMessageMeta._warn_if_including_default_value_fields_is_used_protobuf_5)$always_print_fields_with_no_presencer   r   c                 C   s$   |dk	r |dk	r ||kr t ddS )a  
        Raise Exception if both `always_print_fields_with_no_presence` and `including_default_value_fields` are set
            and the values differ.

        Args:
            always_print_fields_with_no_presence (Optional(bool)): The value of `always_print_fields_with_no_presence` set by the user.
            including_default_value_fields (Optional(bool)): The value of `including_default_value_fields` set by the user.
        Returns:
            None
        Raises:
            ValueError: if both `always_print_fields_with_no_presence` and `including_default_value_fields` are set and
                the values differ.
        Nz`Arguments `always_print_fields_with_no_presence` and `including_default_value_fields` must match)
ValueErrorrr   r   r   r   r   r   0_raise_if_print_fields_values_are_set_and_differ  s    z<MessageMeta._raise_if_print_fields_values_are_set_and_differc                 C   s.   |  | | || |dkr&|dkp,|p,|S )a  
        Return true if fields with no presence should be included in the results.
        By default, fields with no presence will be included in the results
        when both `always_print_fields_with_no_presence` and
        `including_default_value_fields` are not set

        Args:
            always_print_fields_with_no_presence (Optional(bool)): The value of `always_print_fields_with_no_presence` set by the user.
            including_default_value_fields (Optional(bool)): The value of `including_default_value_fields` set by the user.
        Returns:
            None
        Raises:
            ValueError: if both `always_print_fields_with_no_presence` and `including_default_value_fields` are set and
                the values differ.
        N)r   r   r   r   r   r   (_normalize_print_fields_without_presence  s     z4MessageMeta._normalize_print_fields_without_presenceTr&   )use_integers_for_enumsr   preserving_proto_field_name	sort_keysindentfloat_precisionr   c          
   	   C   sT   |  ||}	td dkr4t| |||	||||dS t| |||	||||dS dS )aD  Given a message instance, serialize it to json

        Args:
            instance: An instance of this message type, or something
                compatible (accepted by the type's constructor).
            use_integers_for_enums (Optional(bool)): An option that determines whether enum
                values should be represented by strings (False) or integers (True).
                Default is True.
            including_default_value_fields (Optional(bool)): Deprecated. Use argument
                `always_print_fields_with_no_presence` instead. An option that
                determines whether the default field values should be included in the results.
                This value must match `always_print_fields_with_no_presence`,
                if both arguments are explicitly set.
            preserving_proto_field_name (Optional(bool)): An option that
                determines whether field name representations preserve
                proto case (snake_case) or use lowerCamelCase. Default is False.
            sort_keys (Optional(bool)): If True, then the output will be sorted by field names.
                Default is False.
            indent (Optional(int)): The JSON object will be pretty-printed with this indent level.
                An indent level of 0 or negative will only insert newlines.
                Pass None for the most compact representation without newlines.
            float_precision (Optional(int)): If set, use this to specify float field valid digits.
                Default is None.
            always_print_fields_with_no_presence (Optional(bool)): If True, fields without
                presence (implicit presence scalars, repeated fields, and map fields) will
                always be serialized. Any field that supports presence is not affected by
                this option (including singular message fields and oneof fields).
                This value must match `including_default_value_fields`,
                if both arguments are explicitly set.
        Returns:
            str: The json string representation of the protocol buffer.
        r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   N)r   r   r
   r,   )
rr   r   r   r   r   r   r   r   r   print_fieldsr   r   r   r|     s.    - zMessageMeta.to_jsonignore_unknown_fieldsc                C   s   |  }t ||j|d |S )a  Given a json string representing an instance,
        parse it into a message.

        Args:
            payload: A json string representing a message.
            ignore_unknown_fields (Optional(bool)): If True, do not raise errors
                for unknown fields.

        Returns:
            ~.Message: An instance of the message class against which this
            method was called.
        r   )r   r   )rr   r   r   r   r   r   r   r}     s    zMessageMeta.from_json)r   r   r   r   r   c                C   sL   |  ||}td dkr0t| |||||dS t| |||||dS dS )a\  Given a message instance, return its representation as a python dict.

        Args:
            instance: An instance of this message type, or something
                compatible (accepted by the type's constructor).
            use_integers_for_enums (Optional(bool)): An option that determines whether enum
                values should be represented by strings (False) or integers (True).
                Default is True.
            preserving_proto_field_name (Optional(bool)): An option that
                determines whether field name representations preserve
                proto case (snake_case) or use lowerCamelCase. Default is True.
            including_default_value_fields (Optional(bool)): Deprecated. Use argument
                `always_print_fields_with_no_presence` instead. An option that
                determines whether the default field values should be included in the results.
                This value must match `always_print_fields_with_no_presence`,
                if both arguments are explicitly set.
            float_precision (Optional(int)): If set, use this to specify float field valid digits.
                Default is None.
            always_print_fields_with_no_presence (Optional(bool)): If True, fields without
                presence (implicit presence scalars, repeated fields, and map fields) will
                always be serialized. Any field that supports presence is not affected by
                this option (including singular message fields and oneof fields). This value
                must match `including_default_value_fields`, if both arguments are explicitly set.

        Returns:
            dict: A representation of the protocol buffer using pythonic data structures.
                  Messages and map fields are represented as dicts,
                  repeated fields are represented as lists.
        r   r   )r   r   r   r   )r   r   r   r   N)r   r   r	   r,   )rr   r   r   r   r   r   r   r   r   r   r   r~   (  s&    ( zMessageMeta.to_dictc                 C   sn   t || rt|}nDt ||  r&n4t |tjjrD| jjf |}ntd| j	|j
j	| || dS )zEquivalent for protobuf.Message.CopyFrom

        Args:
            instance: An instance of this message type
            other: (Union[dict, ~.Message):
                A dictionary or message to reinitialize the values for this message.
        z'invalid argument type to copy to {}: {}N)rI   rP   r,   rN   abcMappingr-   r   rJ   r   rt   ZCopyFrom)rr   r   otherr   r   r   r   j  s    
 
zMessageMeta.copy_from)N)r   r   r   __doc__rA   classmethodrw   propertyrx   r   boolr,   ry   bytesrz   r{   r   r   r   r   rV   r|   r}   r   r   r~   r   __classcell__r   r   rs   r   r   *   sV    p

)K	
Br   c                       s   e Zd ZdZddd fddZdd Zd	d
 Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Z fddZdd Z fddZ  ZS ) rP   a  The abstract base class for a message.

    Args:
        mapping (Union[dict, ~.Message]): A dictionary or message to be
            used to determine the values for this message.
        ignore_unknown_fields (Optional(bool)): If True, do not raise errors for
            unknown fields. Only applied if `mapping` is a mapping type or there
            are keyword parameters.
        kwargs (dict): Keys and values corresponding to the fields of the
            message.
    NFr   c          
         sV  |d kr*|s$t  d| j  d S |}nt|| jjrlt|}|rZ|| jjf | t  d| d S t|t| r| j	f d|j
i| d S t|tjjrt|}|| ntd| jj|f i }| jj}| D ]X\}}| |\}}|d kr|rqtd| jj||||}	|	d k	r|	||< qt  d| jjf | d S )Nr   mappingz$Invalid constructor input for %s: %rUnknown field for {}: {})r@   r   r-   r,   rI   copydeepcopyrd   r]   __init__r   rN   r   r   rQ   r   rt   r   r>   rH   _get_pb_type_from_keyr   rJ   to_proto)
r   r   r   rv   paramsr>   r%   r(   pb_typepb_valuers   r   r   r     sL    



zMessage.__init__c                 C   s^   d}z| j j| j}W n> tk
rT   | d| j jkrP| d}| j j| j}Y nX ||fS )aY  Given a key, return the corresponding pb_type.

        Args:
            key(str): The name of the field.

        Returns:
            A tuple containing a key and pb_type. The pb_type will be
            the composite type of the field, or the primitive type if a primitive.
            If no corresponding field exists, return None.
        N_)r-   r<   r   KeyError)r   r%   r   r   r   r   r     s    
zMessage._get_pb_type_from_keyc                 C   sn   t |  j}dd | jj D }|dd |jD  |dd |jD  |t	t
  |d |S )Nc                 S   s   h | ]}|qS r   r   )r0   f_namer   r   r   	<setcomp>   s     z"Message.__dir__.<locals>.<setcomp>c                 s   s   | ]}|j V  qd S ru   r3   )r0   r   r   r   r   r     s     z"Message.__dir__.<locals>.<genexpr>c                 s   s   | ]}|j V  qd S ru   r3   r   r   r   r   r     s     )__bool____contains____dict____getattr____getstate__r   __setstate____weakref__)r]   r,   rZ   r-   r<   rb   rQ   r   r   r   object)r   rq   r   r   r   r   r     s    zMessage.__dir__c                    s   t  fdd jj D S )z4Return True if any field is truthy, False otherwise.c                 3   s    | ]}| kot  |V  qd S ru   )getattr)r0   kr   r   r   r     s     z#Message.__bool__.<locals>.<genexpr>)anyr-   r<   rb   r   r   r   r   r     s    zMessage.__bool__c                 C   s<   t | j|}z| j|W S  tk
r6   t| Y S X dS )aR  Return True if this field was set to something non-zero on the wire.

        In most cases, this method will return True when ``__getattr__``
        would return a truthy value and False when it would return a falsy
        value, so explicitly calling this is not useful.

        The exception case is empty messages explicitly set on the wire,
        which are falsy from ``__getattr__``. This method allows to
        distinguish between an explicitly provided empty message and the
        absence of that message, which is useful in some edge cases.

        The most common edge case is the use of ``google.protobuf.BoolValue``
        to get a boolean that distinguishes between ``False`` and ``None``
        (or the same for a string, int, etc.). This library transparently
        handles that case for you, but this method remains available to
        accommodate cases not automatically covered.

        Args:
            key (str): The name of the field.

        Returns:
            bool: Whether the field's value corresponds to a non-empty
                wire serialization.
        N)r   r   ZHasFieldr   r   )r   r%   r   r   r   r   r     s
    zMessage.__contains__c                 C   s   | j | dS )zmDelete the value on the given field.

        This is generally equivalent to setting a falsy value.
        N)r   
ClearField)r   r%   r   r   r   __delattr__?  s    zMessage.__delattr__c                 C   s6   t |t| r| j|jkS t || jjr2| j|kS tS )z7Return True if the messages are equal, False otherwise.)rI   r]   r   r-   r,   NotImplementedr   r   r   r   r   __eq__F  s
    
zMessage.__eq__c                 C   sR   |  |\}}|dkr*td| jj|t| j|}| jj}|j	|||| kdS )a  Retrieve the given field's value.

        In protocol buffers, the presence of a field on a message is
        sufficient for it to always be "present".

        For primitives, a value of the correct type will always be returned
        (the "falsy" values in protocol buffers consistently match those
        in Python). For repeated fields, the falsy value is always an empty
        sequence.

        For messages, protocol buffers does distinguish between an empty
        message and absence, but this distinction is subtle and rarely
        relevant. Therefore, this method always returns an empty message
        (following the official implementation). To check for message
        presence, use ``key in self`` (in other words, ``__contains__``).

        .. note::

            Some well-known protocol buffer types
            (e.g. ``google.protobuf.Timestamp``) will be converted to
            their Python equivalents. See the ``marshal`` module for
            more details.
        Nr   )Zabsent)
r   r   rJ   rt   r   r   r   r-   r>   Z	to_python)r   r%   r   r   r>   r   r   r   r   S  s    zMessage.__getattr__c                 C   s
   | |k S )z9Return True if the messages are unequal, False otherwise.r   r   r   r   r   __ne__t  s    zMessage.__ne__c                 C   s
   t | jS ru   )reprr   r   r   r   r   __repr__x  s    zMessage.__repr__c                    s   |d dkrt  ||S | jj}| |\}}|dkrLtd| jj||	||}| j
| |dk	r| j
| jjf ||i dS )zSet the value on the given field.

        For well-known protocol buffer types which are marshalled, either
        the protocol buffer object or the Python equivalent is accepted.
        r   r   Nr   )r@   r   r-   r>   r   r   rJ   rt   r   r   r   r   rd   r,   )r   r%   r(   r>   r   r   rs   r   r   r   {  s    zMessage.__setattr__c                 C   s
   | j  S )zSerialize for pickling.)r   r   r   r   r   r   r     s    zMessage.__getstate__c                    s"   | j  |}t d| dS )zDeserialization for pickling.r   N)r-   r,   r   r@   r   )r   r(   Znew_pbrs   r   r   r     s    zMessage.__setstate__)N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rs   r   rP     s"    J&!rP   )	metaclassc                   @   sF   e Zd ZdZee eeeej	ddddZ
eeej dddZdS )	re   a%  Metadata about a message.

    Args:
        fields (Tuple[~.fields.Field]): The fields declared on the message.
        package (str): The proto package.
        full_name (str): The full name of the message.
        file_info (~._FileInfo): The file descriptor and messages for the
            file containing this message.
        marshal (~.Marshal): The marshal instance to which this message was
            automatically registered.
        options (~.descriptor_pb2.MessageOptions): Any options that were
            set on the message.
    N)r<   r+   r=   r>   r5   r   c                C   sN   || _ || _|| _tdd |D | _tdd |D | _|| _d | _d S )Nc                 s   s   | ]}|j |fV  qd S ru   r3   r/   r   r   r   r     s     z(_MessageInfo.__init__.<locals>.<genexpr>c                 s   s   | ]}|j |fV  qd S ru   r#   r/   r   r   r   r     s     )	r+   r=   r5   rN   rO   r<   Zfields_by_numberr>   r   )r   r<   r+   r=   r>   r5   r   r   r   r     s    	z_MessageInfo.__init__r   c                 C   s   | j S )zReturn the protobuf message type for this descriptor.

        If a field on the message references another message which has not
        loaded, then this method returns None.
        )r   r   r   r   r   r,     s    z_MessageInfo.pb)r   r   r   r   r   r   rV   r   r   r`   r   r   r   r   rP   r,   r   r   r   r   re     s   re   )rP   ))rN   collections.abcr   rK   typingr   r   r   r   r   r   Zgoogle.protobufZgoogler   r   Zgoogle.protobuf.json_formatr	   r
   r   protor   r   Zproto.fieldsr   r   r   Zproto.marshalr   Zproto.primitivesr   Zproto.utilsr   Zprotobuf__version__r   Z_upbr]   r   rP   re   __all__r   r   r   r   <module>   s:       c  *