3
(h                 @   s  d Z dZyddlmZ W n  ek
r8   ddlmZ Y nX ddlZddlZddlZddl	m
Z
 ddlZddlZddlZddlmZ ddlmZ ddlmZ d	ZeejjejjejjejjgZeejjejjgZeejjejjgZd
ZdZ dZ!ej"ej#dZ$ej"dZ%G dd de&Z'G dd de'Z(G dd de'Z)d>ddZ*d?ddZ+dd Z,G dd de-Z.dd  Z/d!d" Z0d#d$ Z1d@d%d&Z2dAd'd(Z3ej4e5f Z6G d)d* d*e-Z7dBd+d,Z8d-d. Z9d/d0 Z:d1d2 Z;d3d4gd5d6gd5d6gd7d8gd9d:gd5d6gd;d<gd=Z<dS )Cat  Contains routines for printing protocol messages in JSON format.

Simple usage example:

  # Create a proto object and serialize it to a json format string.
  message = my_proto_pb2.MyMessage(foo='bar')
  json_string = json_format.MessageToJson(message)

  # Parse a json format string to proto object.
  message = json_format.Parse(json_string, my_proto_pb2.MyMessage())
zjieluo@google.com (Jie Luo)    )OrderedDictN)methodcaller)type_checkers)
descriptor)symbol_databasez%Y-%m-%dT%H:%M:%SInfinityz	-InfinityNaNzF[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]z\[[a-zA-Z0-9\._]*\]$c               @   s   e Zd ZdZdS )Errorz'Top-level module error for json_format.N)__name__
__module____qualname____doc__ r   r   A/tmp/pip-install-q3hcpn_q/protobuf/google/protobuf/json_format.pyr	   X   s   r	   c               @   s   e Zd ZdZdS )SerializeToJsonErrorz&Thrown if serialization to JSON fails.N)r
   r   r   r   r   r   r   r   r   \   s   r   c               @   s   e Zd ZdZdS )
ParseErrorz Thrown in case of parsing error.N)r
   r   r   r   r   r   r   r   r   `   s   r   F   c       	      C   s    t |||||d}|j| ||S )aR  Converts protobuf message to JSON format.

  Args:
    message: The protocol buffers message instance to serialize.
    including_default_value_fields: If True, singular primitive fields,
        repeated fields, and map fields will always be serialized.  If
        False, only serialize non-empty fields.  Singular message fields
        and oneof fields are not affected by this option.
    preserving_proto_field_name: If True, use the original proto field
        names as defined in the .proto file. If False, convert the field
        names to lowerCamelCase.
    indent: The JSON object will be pretty-printed with this indent level.
        An indent level of 0 or negative will only insert newlines.
    sort_keys: If True, then the output will be sorted by field names.
    use_integers_for_enums: If true, print integers instead of enum names.
    descriptor_pool: A Descriptor Pool for resolving types. If None use the
        default.
    float_precision: If set, use this to specify float field valid digits.

  Returns:
    A string containing the JSON formatted protocol buffer message.
  )float_precision)_PrinterToJsonString)	messageincluding_default_value_fieldspreserving_proto_field_nameindent	sort_keysuse_integers_for_enumsdescriptor_poolr   printerr   r   r   MessageToJsond   s    r   c             C   s   t |||||d}|j| S )a  Converts protobuf message to a dictionary.

  When the dictionary is encoded to JSON, it conforms to proto3 JSON spec.

  Args:
    message: The protocol buffers message instance to serialize.
    including_default_value_fields: If True, singular primitive fields,
        repeated fields, and map fields will always be serialized.  If
        False, only serialize non-empty fields.  Singular message fields
        and oneof fields are not affected by this option.
    preserving_proto_field_name: If True, use the original proto field
        names as defined in the .proto file. If False, convert the field
        names to lowerCamelCase.
    use_integers_for_enums: If true, print integers instead of enum names.
    descriptor_pool: A Descriptor Pool for resolving types. If None use the
        default.
    float_precision: If set, use this to specify float field valid digits.

  Returns:
    A dict representation of the protocol buffer message.
  )r   )r   _MessageToJsonObject)r   r   r   r   r   r   r   r   r   r   MessageToDict   s    r    c             C   s"   | j tjjko | jjo | jj jS )N)typer   FieldDescriptorZTYPE_MESSAGEmessage_typeZhas_optionsZ
GetOptionsZ	map_entry)fieldr   r   r   _IsMapEntry   s    r%   c               @   sj   e Zd ZdZd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dd ZdS )r   z)JSON format printer for protocol message.FNc             C   s4   || _ || _|| _|| _|r*dj|| _nd | _d S )Nz.{}g)r   r   r   r   formatfloat_format)selfr   r   r   r   r   r   r   r   __init__   s    z_Printer.__init__c             C   s   | j |}tj|||dS )N)r   r   )r   jsondumps)r(   r   r   r   jsr   r   r   r      s    
z_Printer.ToJsonStringc             C   sL   |j }|j}t|r| j|S |tkr<tt| d || S i }| j||S )zEConverts message to an object according to Proto3 JSON Specification.r   )
DESCRIPTOR	full_name_IsWrapperMessage_WrapperMessageToJsonObject_WKTJSONMETHODSr   _RegularMessageToJsonObject)r(   r   message_descriptorr.   r,   r   r   r   r      s    
z_Printer._MessageToJsonObjectc                s  |j  }yx|D ]\ }jr( j}n j}t r jjd }i }x>|D ]6}t|trj|rdd}	qnd}	n|}	j	||| ||	< qLW |||< q j
tjjkr fdd|D ||< q jrd j }j	 |||< qj	 |||< qW jr|j}
x|
jD ]  j
tjjkr( jtjjks jr4qjrD j}n j}||krXqt rli ||< n, j
tjjkrg ||< nj	  j||< qW W n6 tk
r } ztdj j|W Y dd}~X nX |S )	z?Converts normal message according to Proto3 JSON Specification.valuetruefalsec                s   g | ]}j  |qS r   )_FieldToJsonObject).0k)r$   r(   r   r   
<listcomp>   s   z8_Printer._RegularMessageToJsonObject.<locals>.<listcomp>z[%s]z#Failed to serialize {0} field: {1}.N)
ListFieldsr   name	json_namer%   r#   fields_by_name
isinstanceboolr7   labelr   r"   LABEL_REPEATEDis_extensionr.   r   r-   fieldscpp_typeCPPTYPE_MESSAGEcontaining_oneofdefault_value
ValueErrorr   r&   )r(   r   r,   rD   r4   r<   Zv_fieldZjs_mapkeyZrecorded_keyr3   er   )r$   r(   r   r2      s\    







"z$_Printer._RegularMessageToJsonObjectc             C   sB  |j tjjkr| j|S |j tjjkrx| jr0|S |jjdkr@dS |jj	j
|d}|dk	r^|jS |jjdkrn|S tdn|j tjjkr|jtjjkrtj|jdS |S n|j tjjkrt|S |j tkrt|S |j tkr>tj| r|dk  rtS tS tj|rtS |j tjj kr>| j!r4t"t#|| j!S t$j%|S |S )z<Converts field value according to Proto3 JSON Specification.zgoogle.protobuf.NullValueNproto3zKEnum field contains an integer value which can not mapped to an enum value.zutf-8g        )&rE   r   r"   rF   r   CPPTYPE_ENUMr   	enum_typer.   values_by_numbergetr<   filesyntaxr   CPPTYPE_STRINGr!   
TYPE_BYTESbase64	b64encodedecodeCPPTYPE_BOOLr@   _INT64_TYPESstr_FLOAT_TYPESmathisinf_NEG_INFINITY	_INFINITYisnan_NANCPPTYPE_FLOATr'   floatr&   r   ZToShortestFloat)r(   r$   r4   
enum_valuer   r   r   r7     sB    




z_Printer._FieldToJsonObjectc             C   s   |j  si S t }|j}||d< t|| j}|j|j |j}|j}t	|r^| j
||d< |S |tkrtt| d || |d< |S | j||S )z<Converts Any message according to Proto3 JSON Specification.z@typer4   r   )r;   r   type_url_CreateMessageFromTypeUrlr   ZParseFromStringr4   r-   r.   r/   r0   r1   r   r2   )r(   r   r,   re   sub_messager3   r.   r   r   r   _AnyMessageToJsonObjectE  s"    z _Printer._AnyMessageToJsonObjectc             C   s   |j  S )z8Converts message according to Proto3 JSON Specification.)r   )r(   r   r   r   r   _GenericMessageToJsonObjectZ  s    z$_Printer._GenericMessageToJsonObjectc             C   sd   |j d}|dks|dkrdS |dkr2| j|jS |dkrB|j}n
t||}|jj| }| j||S )z>Converts Value message according to Proto3 JSON Specification.kindN
null_value
list_valuestruct_value)Z
WhichOneof_ListValueMessageToJsonObjectrl   rm   getattrr-   r>   r7   )r(   r   whichr4   Zoneof_descriptorr   r   r   _ValueMessageToJsonObject`  s    

z"_Printer._ValueMessageToJsonObjectc                s    fdd|j D S )zBConverts ListValue message according to Proto3 JSON Specification.c                s   g | ]} j |qS r   )rq   )r8   r4   )r(   r   r   r:   r  s   z:_Printer._ListValueMessageToJsonObject.<locals>.<listcomp>)values)r(   r   r   )r(   r   rn   p  s    
z&_Printer._ListValueMessageToJsonObjectc             C   s.   |j }i }x|D ]}| j|| ||< qW |S )z?Converts Struct message according to Proto3 JSON Specification.)rD   rq   )r(   r   rD   retrJ   r   r   r   _StructMessageToJsonObjectu  s
    
z#_Printer._StructMessageToJsonObjectc             C   s   | j |jjd |jS )Nr4   )r7   r-   r>   r4   )r(   r   r   r   r   r0   }  s    z$_Printer._WrapperMessageToJsonObject)FFFNN)r
   r   r   r   r)   r   r   r2   r7   rh   ri   rq   rn   rt   r0   r   r   r   r   r      s        

@+r   c             C   s   | j jdkS )Nzgoogle/protobuf/wrappers.proto)rQ   r<   )r3   r   r   r   r/     s    r/   c             C   s8   i }x.| D ]&\}}||kr(t dj||||< q
W |S )Nz'Failed to load JSON: duplicate key {0}.)r   r&   )r,   resultr<   r4   r   r   r   _DuplicateChecker  s    rv   c             C   sj   t j }|dkr|jn|}| jdd }y|j|}W n" tk
rX   tdj| Y nX |j|}| S )z"Creates a message from a type URL.N/   z1Can not find message descriptor by type_url: {0}.)	r   ZDefaultpoolsplitZFindMessageTypeByNameKeyError	TypeErrorr&   ZGetPrototype)re   r   dbrz   	type_namer3   Zmessage_classr   r   r   rf     s    
rf   c             C   sl   t | tjs| jd} ytj| td}W n4 tk
r\ } ztdj	t
|W Y dd}~X nX t||||S )a  Parses a JSON representation of a protocol message into a message.

  Args:
    text: Message JSON representation.
    message: A protocol buffer message to merge into.
    ignore_unknown_fields: If True, do not raise errors for unknown fields.
    descriptor_pool: A Descriptor Pool for resolving types. If None use the
        default.

  Returns:
    The same message passed as argument.

  Raises::
    ParseError: On JSON parsing problems.
  zutf-8)object_pairs_hookzFailed to load JSON: {0}.N)r?   six	text_typerW   r*   loadsrv   rI   r   r&   rZ   	ParseDict)textr   ignore_unknown_fieldsr   r,   rK   r   r   r   Parse  s     
$r   c             C   s   t ||}|j| | |S )a  Parses a JSON dictionary representation into a message.

  Args:
    js_dict: Dict representation of a JSON message.
    message: A protocol buffer message to merge into.
    ignore_unknown_fields: If True, do not raise errors for unknown fields.
    descriptor_pool: A Descriptor Pool for resolving types. If None use the
      default.

  Returns:
    The same message passed as argument.
  )_ParserConvertMessage)Zjs_dictr   r   r   parserr   r   r   r     s    
r   c               @   s`   e Zd Z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dd ZdS )r   z(JSON format parser for protocol message.c             C   s   || _ || _d S )N)r   r   )r(   r   r   r   r   r   r)     s    z_Parser.__init__c             C   sT   |j }|j}t|r"| j|| n.|tkrDtt| d |||  n| j|| dS )zConvert a JSON object into a message.

    Args:
      value: A JSON object.
      message: A WKT or regular protocol message to record the data.

    Raises:
      ParseError: In case of convert problems.
    rx   N)r-   r.   r/   _ConvertWrapperMessager1   r   _ConvertFieldValuePair)r(   r4   r   r3   r.   r   r   r   r     s    
z_Parser.ConvertMessagec             C   s  g }|j }tdd |jD }x|D ]}y|j|d}|sN|jj|d}| rtj|r|jsttdj	|j
|dd }|jj|}|sdj|jddd }|jj|}|s| jrw&tdj	|j
|dd	 |jD ||k rtd
j	|j j
||j| |jdk	rD|jj}	|	|kr:tdj	|j j
|	|j|	 || }
|
dkr|jtjjkr|jj
dkrt||j}d|_n:|jtjjkr|jj
dkrt||jd n|j|j w&t|r|j|j | j|
|| nF|j tjj!kr|j|j t"|
t#s$tdj	||
|jtjjkrx|
D ]B}t||jj$ }|dkrn|j j
dkrntd| j%|| q:W n:x|
D ]0}|dkrtdt||jjt&|| qW nt|jtjjkr|j'r|j| }nt||j}|j(  | j%|
| n.|j'rt&|
||j|< nt||jt&|
| W q& tk
r } z6|rl|jdkrltdj	||ntt)|W Y dd}~X q& t*k
r } ztdj	||W Y dd}~X q& t+k
r } ztdj	||W Y dd}~X q&X q&W dS )zConvert field value pairs into regular message.

    Args:
      js: A JSON object to convert the field value pairs.
      message: A regular protocol message to record the data.

    Raises:
      ParseError: In case of problems converting.
    c             s   s   | ]}|j |fV  qd S )N)r=   )r8   fr   r   r   	<genexpr>  s   z1_Parser._ConvertFieldValuePair.<locals>.<genexpr>Nz)Message type {0} does not have extensionsrx   .zVMessage type "{0}" has no field named "{1}".
 Available Fields(except extensions): {2}c             S   s   g | ]
}|j qS r   )r=   )r8   r   r   r   r   r:     s    z2_Parser._ConvertFieldValuePair.<locals>.<listcomp>z9Message type "{0}" should not have multiple "{1}" fields.z?Message type "{0}" should not have multiple "{1}" oneof fields.zgoogle.protobuf.Valuer   zgoogle.protobuf.NullValuez.repeated field {0} must be in [] which is {1}.zAnull is not allowed to be used as an element in a repeated field.zFailed to parse {0} field: {1}.ry   ry   ),r-   dictrD   rP   r>   _VALID_EXTENSION_NAMEmatchZis_extendabler   r&   r.   Z
ExtensionsZ_FindExtensionByNamejoinr{   r   appendrG   r<   rE   r   r"   rF   r#   ro   rk   rM   rN   setattr
ClearFieldr%   _ConvertMapFieldValuerA   rB   r?   listaddr   _ConvertScalarFieldValuerC   ZSetInParentrZ   rI   r}   )r(   r,   r   namesr3   Zfields_by_json_namer<   r$   
identifierZ
oneof_namer4   rg   itemrK   r   r   r   r     s    












 z_Parser._ConvertFieldValuePairc             C   s   t |tr| rdS y|d }W n tk
r<   tdY nX t|| j}|j}|j}t|rp| j	|d | n@|t
krtt
| d |d ||  n|d= | j|| ||d< |j |_||_dS )z/Convert a JSON representation into Any message.Nz@typez*@type is missing when parsing any message.r4   rx   )r?   r   r|   r   rf   r   r-   r.   r/   r   r1   r   r   ZSerializeToStringr4   re   )r(   r4   r   re   rg   r3   r.   r   r   r   _ConvertAnyMessage]  s&    
z_Parser._ConvertAnyMessagec             C   s>   y|j | W n* tk
r8 } zt|W Y dd}~X nX dS )z?Convert a JSON representation into message with FromJsonString.N)ZFromJsonStringrI   r   )r(   r4   r   rK   r   r   r   _ConvertGenericMessagev  s    z_Parser._ConvertGenericMessagec             C   s   t |tr| j||j nvt |tr4| j||j n\|dkrDd|_nLt |trV||_	n:t |t
jrj||_n&t |tr|||_ntdj|t|dS )z1Convert a JSON representation into Value message.Nr   z"Value {0} has unexpected type {1}.)r?   r   _ConvertStructMessagerm   r   _ConvertListValueMessagerl   rk   r@   Z
bool_valuer   string_typesZstring_value_INT_OR_FLOATZnumber_valuer   r&   r!   )r(   r4   r   r   r   r   _ConvertValueMessage  s    



z_Parser._ConvertValueMessagec             C   sF   t |tstdj||jd x|D ]}| j||jj  q(W dS )z5Convert a JSON representation into ListValue message.z%ListValue must be in [] which is {0}.rr   N)r?   r   r   r&   r   r   rr   r   )r(   r4   r   r   r   r   r   r     s    


z _Parser._ConvertListValueMessagec             C   sH   t |tstdj||j  x"|D ]}| j|| |j|  q&W dS )z2Convert a JSON representation into Struct message.z&Struct must be in a dict which is {0}.N)r?   r   r   r&   ZClearr   rD   )r(   r4   r   rJ   r   r   r   r     s    

z_Parser._ConvertStructMessagec             C   s"   |j jd }t|dt|| dS )z3Convert a JSON representation into Wrapper message.r4   N)r-   r>   r   r   )r(   r4   r   r$   r   r   r   r     s    z_Parser._ConvertWrapperMessagec             C   s   t |tstdj|j||jjd }|jjd }x^|D ]V}t||d}|jt	j
jkrv| j|| t||j|  q:t|| |t||j|< q:W dS )a5  Convert map field value for a message map field.

    Args:
      value: A JSON object to convert the map field value.
      message: A protocol message to record the converted data.
      field: The descriptor of the map field to be converted.

    Raises:
      ParseError: In case of convert problems.
    z-Map field {0} must be in a dict which is {1}.rJ   r4   TN)r?   r   r   r&   r<   r#   r>   r   rE   r   r"   rF   r   ro   )r(   r4   r   r$   Z	key_fieldZvalue_fieldrJ   	key_valuer   r   r   r     s    

z_Parser._ConvertMapFieldValueN)r
   r   r   r   r)   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s   v		r   c             C   s\  |j tkrt| S |j tkr&t| |S |j tjjkr>t| |S |j tjj	kr|j
tjjkrt| tjrr| jd}n| }|ddt|d    }tj|S tj| rtd| S n|j tjjkrX|jjj| d}|dkrRyt| }|jjj|d}W n* tk
r    tdj| |jjY nX |dkrR|jj dkr>|S tdj| |jj|j!S dS )aB  Convert a single scalar field value.

  Args:
    value: A scalar value to convert the scalar field value.
    field: The descriptor of the field to convert.
    require_str: If True, the field value must be a str.

  Returns:
    The converted scalar field value

  Raises:
    ParseError: In case of convert problems.
  zutf-8   =   zUnpaired surrogateNz)Invalid enum value {0} for enum type {1}.rL   )"rE   
_INT_TYPES_ConvertIntegerr[   _ConvertFloatr   r"   rX   _ConvertBoolrS   r!   rT   r?   r   r   encodelenrU   urlsafe_b64decode_UNPAIRED_SURROGATE_PATTERNsearchr   rM   rN   Zvalues_by_namerP   intrO   rI   r&   r.   rQ   rR   number)r4   r$   require_strencodedZpadded_valuerd   r   r   r   r   r     s>    







r   c             C   sj   t | tr"| j  r"tdj| t | tjrJ| jddkrJtdj| t | trbtdj| t	| S )zConvert an integer.

  Args:
    value: A scalar value to convert.

  Returns:
    The integer value.

  Raises:
    ParseError: If an integer couldn't be consumed.
  zCouldn't parse integer: {0}. rx   zCouldn't parse integer: "{0}".z3Bool value {0} is not acceptable for integer field.ry   )
r?   rc   
is_integerr   r&   r   r   findr@   r   )r4   r   r   r   r     s    
r   c             C   s   t | trrtj| rtdtj| r@| dkr8tdntd|jtjj	krr| t
jkr`td| t
jk rrtd| dkrtdyt| S  tk
r   | tkrtd	S | tkrtd
S | tkrtdS tdj| Y nX dS )z!Convert an floating point number.z-Couldn't parse NaN, use quoted "NaN" instead.r   zJCouldn't parse Infinity or value too large, use quoted "Infinity" instead.zLCouldn't parse -Infinity or value too small, use quoted "-Infinity" instead.zFloat value too largezFloat value too smallnanz.Couldn't parse float "nan", use "NaN" instead.z-infinfzCouldn't parse float: {0}.N)r?   rc   r\   r`   r   r]   rE   r   r"   rb   r   Z
_FLOAT_MAXZ
_FLOAT_MINrI   r^   r_   ra   r&   )r4   r$   r   r   r   r     s0    





r   c             C   s@   |r*| dkrdS | dkrdS t dj| t| ts<t d| S )zConvert a boolean value.

  Args:
    value: A scalar value to convert.
    require_str: If True, value must be a str.

  Returns:
    The bool parsed.

  Raises:
    ParseError: If a boolean value couldn't be consumed.
  r5   Tr6   Fz$Expected "true" or "false", not {0}.z&Expected true or false without quotes.)r   r&   r?   r@   )r4   r   r   r   r   r   9  s    
r   rh   r   ri   r   rn   r   rt   r   rq   r   )zgoogle.protobuf.Anyzgoogle.protobuf.Durationzgoogle.protobuf.FieldMaskzgoogle.protobuf.ListValuezgoogle.protobuf.Structzgoogle.protobuf.Timestampzgoogle.protobuf.Value)FFr   FFNN)FFFNN)FN)FN)F)=r   
__author__collectionsr   ImportErrorZordereddictrU   r*   r\   operatorr   resysr   Zgoogle.protobuf.internalr   Zgoogle.protobufr   r   Z_TIMESTAMPFOMAT	frozensetr"   ZCPPTYPE_INT32ZCPPTYPE_UINT32ZCPPTYPE_INT64ZCPPTYPE_UINT64r   rY   rb   ZCPPTYPE_DOUBLEr[   r_   r^   ra   compileur   r   	Exceptionr	   r   r   r   r    r%   objectr   r/   rv   rf   r   r   integer_typesrc   r   r   r   r   r   r   r1   r   r   r   r   <module>)   s   
      
"    
  K	
 
 z
6$