o
    M`p                     @   s  d Z ddlmZ ddlZddlZddlZddlZddlZzddlm	Z	 W n e
y/   eZ	Y nw ddlmZmZ dZdZz
ddlmZmZ W n e
yY   ddlmZmZ eZY nw dZd	Zd
ZdZejdkrkeefZG dd deZG dd deZG dd deZ G dd dee!Z"dd Z#ej$ej%e#dZ&defddZ'efddZ(G dd de)Z*G dd  d e*Z+G d!d" d"e*Z,G d#d$ d$e*Z-G d%d& d&e*Z.G d'd( d(e*Z/G d)d* d*e*Z0G d+d, d,e)Z1G d-d. d.e)Z2d/d0 Z3dS )1z Apply JSON-Patches (RFC 6902)     )unicode_literalsN)MappingProxyType)JsonPointerJsonPointerException   )MutableMappingMutableSequenceu    Stefan Kögl <stefan@skoegl.net>z1.32z0https://github.com/stefankoegl/python-json-patchzModified BSD License)   r   c                   @      e Zd ZdZdS )JsonPatchExceptionzBase Json Patch exceptionN__name__
__module____qualname____doc__ r   r   +/usr/lib/python3/dist-packages/jsonpatch.pyr   J       r   c                   @   r
   )InvalidJsonPatchz, Raised if an invalid JSON Patch is created Nr   r   r   r   r   r   N   r   r   c                   @   r
   )JsonPatchConflicta
  Raised if patch could not be applied due to conflict situation such as:
    - attempt to add object key when it already exists;
    - attempt to operate with nonexistence object key;
    - attempt to insert value to array at position beyond its size;
    - etc.
    Nr   r   r   r   r   r   R   r   r   c                   @   r
   )JsonPatchTestFailedz A Test operation failed Nr   r   r   r   r   r   [   r   r   c                 C   s<   t t}| D ]\}}|| | qtdd | D S )z'Convert duplicate keys values to lists.c                 s   s0    | ]\}}|t |d kr|d n|fV  qdS )r   r   N)len).0keyvaluesr   r   r   	<genexpr>f   s
    
zmultidict.<locals>.<genexpr>)collectionsdefaultdictlistappenddictitems)ordered_pairsmdictr   valuer   r   r   	multidict_   s   
r%   )object_pairs_hookFc                 C   s2   t |trtj||d}nt||d}|| |S )a  Apply list of patches to specified json document.

    :param doc: Document object.
    :type doc: dict

    :param patch: JSON patch as list of dicts or raw JSON-encoded string.
    :type patch: list or str

    :param in_place: While :const:`True` patch will modify target document.
                     By default patch will be applied to document copy.
    :type in_place: bool

    :param pointer_cls: JSON pointer class to use.
    :type pointer_cls: Type[JsonPointer]

    :return: Patched document object.
    :rtype: dict

    >>> doc = {'foo': 'bar'}
    >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}]
    >>> other = apply_patch(doc, patch)
    >>> doc is not other
    True
    >>> other == {'foo': 'bar', 'baz': 'qux'}
    True
    >>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}]
    >>> apply_patch(doc, patch, in_place=True) == {'foo': 'bar', 'baz': 'qux'}
    True
    >>> doc == other
    True
    pointer_cls)
isinstance
basestring	JsonPatchfrom_stringapply)docpatchin_placer(   r   r   r   apply_patchr   s   
!r1   c                 C   s   t j| ||dS )a!  Generates patch by comparing two document objects. Actually is
    a proxy to :meth:`JsonPatch.from_diff` method.

    :param src: Data source document object.
    :type src: dict

    :param dst: Data source document object.
    :type dst: dict

    :param pointer_cls: JSON pointer class to use.
    :type pointer_cls: Type[JsonPointer]

    >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
    >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
    >>> patch = make_patch(src, dst)
    >>> new = patch.apply(src)
    >>> new == dst
    True
    r'   )r+   	from_diff)srcdstr(   r   r   r   
make_patch   s   r5   c                   @   sb   e Zd ZdZefddZdd Zdd Zdd	 Zd
d Z	e
dd Ze
dd Zejdd ZdS )PatchOperationz'A single operation inside a JSON Patch.c              
   C   s   || _ |dstdt|d | j r |d j| _|d | _n|d | _z	|  | j| _W n ty> } ztdd }~ww || _d S )Npathz#Operation must have a 'path' memberzInvalid 'path')	r(   __contains__r   r)   r7   locationpointer	TypeError	operation)selfr<   r(   exr   r   r   __init__   s   


zPatchOperation.__init__c                 C   s   t d)zGAbstract method that applies a patch operation to the specified object.z%should implement the patch operation.)NotImplementedError)r=   objr   r   r   r-         zPatchOperation.applyc                 C   s   t t| j S N)hash	frozensetr<   r!   r=   r   r   r   __hash__   s   zPatchOperation.__hash__c                 C      t |tsdS | j|jkS NF)r)   r6   r<   r=   otherr   r   r   __eq__      
zPatchOperation.__eq__c                 C   
   | |k S rC   r   rJ   r   r   r   __ne__      
zPatchOperation.__ne__c                 C   s   d | jjd d S )N/)joinr:   partsrF   r   r   r   r7      s   zPatchOperation.pathc                 C   s2   z	t | jjd W S  ty   | jjd  Y S w )NrR   )intr:   rT   
ValueErrorrF   r   r   r   r      s
   zPatchOperation.keyc                 C   s*   t || jjd< | jj| _| j| jd< d S )NrR   r7   )strr:   rT   r7   r9   r<   )r=   r$   r   r   r   r      s   
N)r   r   r   r   r   r?   r-   rG   rL   rO   propertyr7   r   setterr   r   r   r   r6      s    

r6   c                   @   (   e Zd ZdZdd Zdd Zdd ZdS )	RemoveOperationz/Removes an object property or an array element.c              
   C   sL   | j |\}}z||= W |S  ttfy% } z	d|}t|d }~ww )Nz(can't remove a non-existent object '{0}')r:   to_lastKeyError
IndexErrorformatr   )r=   rA   subobjpartr>   msgr   r   r   r-      s   
zRemoveOperation.applyc                 C   s2   | j |kr| j|kr|  jd7  _|S |d8 }|S Nr   r7   r   r=   r7   r   r   r   r   _on_undo_remove      

zRemoveOperation._on_undo_removec                 C   s2   | j |kr| j|kr|  jd8  _|S |d8 }|S rc   rd   re   r   r   r   _on_undo_add   rg   zRemoveOperation._on_undo_addNr   r   r   r   r-   rf   rh   r   r   r   r   r[      s
    
r[   c                   @   rZ   )	AddOperationz,Adds an object property or an array element.c              
   C   s   z| j d }W n ty } ztdd }~ww | j|\}}t|trF|dkr0|| |S |t|ks:|dk r>t	d|
|| |S t|trY|d u rS|}|S |||< |S |d u rftdt|t	d| j|)Nr$   /The operation does not contain a 'value' member-r   zcan't insert outside of listinvalid document type {0}2unable to fully resolve json pointer {0}, part {1})r<   r]   r   r:   r\   r)   r   r   r   r   insertr   r;   r_   typer9   )r=   rA   r$   r>   r`   ra   r   r   r   r-   	  s4   


	zAddOperation.applyc                 C   s2   | j |kr| j|kr|  jd7  _|S |d7 }|S rc   rd   re   r   r   r   rf   )  rg   zAddOperation._on_undo_removec                 C   s2   | j |kr| j|kr|  jd8  _|S |d7 }|S rc   rd   re   r   r   r   rh   1  rg   zAddOperation._on_undo_addNri   r   r   r   r   rj     s
     rj   c                   @   rZ   )	ReplaceOperationz?Replaces an object property or an array element by a new value.c              
   C   s   z| j d }W n ty } ztdd }~ww | j|\}}|d u r&|S |dkr.tdt|trB|t|ks=|dk rAtdn)t|t	rU||vrTd
|}t|n|d u rbtd
t|td	
| j||||< |S )
Nr$   rk   rl   z7'path' with '-' can't be applied to 'replace' operationr   zcan't replace outside of listz)can't replace a non-existent object '{0}'rm   rn   )r<   r]   r   r:   r\   r)   r   r   r   r   r_   r;   rp   r9   )r=   rA   r$   r>   r`   ra   rb   r   r   r   r-   =  s6   


zReplaceOperation.applyc                 C      |S rC   r   re   r   r   r   rf   ]     z ReplaceOperation._on_undo_removec                 C   rr   rC   r   re   r   r   r   rh   `  rs   zReplaceOperation._on_undo_addNri   r   r   r   r   rq   :  s
     rq   c                   @   sN   e Zd ZdZdd Zedd Zedd Zejdd Zd	d
 Z	dd Z
dS )MoveOperationz?Moves an object property or an array element to a new location.c              
   C   s  zt | jd | jr| jd }n| | jd }W n ty) } ztdd }~ww ||\}}z|| }W n ttfyK } ztt|d }~ww | j	|krS|S t |t
rb| j	|rbtdtd| jd d| jd|}td| j|d| jd|}|S )	Nfrom.The operation does not contain a 'from' memberz*Cannot move values into their own childrenremoveopr7   r'   addry   r7   r$   )r)   r<   r(   r]   r   r\   r^   r   rW   r:   r   containsr[   r-   rj   r9   r=   rA   from_ptrr>   r`   ra   r$   r   r   r   r-   g  sT   


zMoveOperation.applyc                 C   s$   |  | jd }d|jd d S )Nru   rQ   rR   )r(   r<   rS   rT   r=   r~   r   r   r   	from_path  s   zMoveOperation.from_pathc                 C   s>   |  | jd }zt|jd W S  ty   |jd  Y S w Nru   rR   )r(   r<   rU   rT   r;   r   r   r   r   from_key  s   zMoveOperation.from_keyc                 C   s.   |  | jd }t||jd< |j| jd< d S r   )r(   r<   rW   rT   r7   )r=   r$   r~   r   r   r   r     s   c                 C   s^   | j |kr| j|kr|  jd7  _n|d8 }| j|kr-| j|kr)|  jd7  _|S |d7 }|S rc   r   r   r7   r   re   r   r   r   rf        



zMoveOperation._on_undo_removec                 C   s^   | j |kr| j|kr|  jd8  _n|d8 }| j|kr-| j|kr)|  jd8  _|S |d7 }|S rc   r   re   r   r   r   rh     r   zMoveOperation._on_undo_addN)r   r   r   r   r-   rX   r   r   rY   rf   rh   r   r   r   r   rt   d  s    %


rt   c                   @      e Zd ZdZdd ZdS )TestOperationz!Test value by specified location.c              
   C   s   z| j |\}}|d u r|}n| j ||}W n ty* } ztt|d }~ww z| jd }W n tyB } ztdd }~ww ||krWd}t|	|t
||t
||S )Nr$   rk   z0{0} ({1}) is not equal to tested value {2} ({3}))r:   r\   walkr   r   rW   r<   r]   r   r_   rp   )r=   rA   r`   ra   valr>   r$   rb   r   r   r   r-     s0   zTestOperation.applyNr   r   r   r   r-   r   r   r   r   r         r   c                   @   r   )CopyOperationzA Copies an object property or an array element to a new location c              
   C   s   z
|  | jd }W n ty } ztdd }~ww ||\}}z	t|| }W n ttfy? } ztt	|d }~ww t
d| j|d| j d|}|S )Nru   rv   rz   r{   r'   )r(   r<   r]   r   r\   copydeepcopyr^   r   rW   rj   r9   r-   r}   r   r   r   r-     s2   zCopyOperation.applyNr   r   r   r   r   r     r   r   c                   @   s   e Zd ZeejZeeZe	e
eeeeedZ	 efddZdd Zdd ZeZdd	 Zd
d Zdd Zdd ZedefddZeddefddZdddZedd Zd ddZ dd Z!dS )!r+   )rw   rz   replacemovetestr   c                 C   s&   || _ || _| j D ]}| | q	d S rC   )r/   r(   _get_operation)r=   r/   r(   ry   r   r   r   r?   (  s
   
zJsonPatch.__init__c                 C   s   |   S )zstr(self) -> self.to_string())	to_stringrF   r   r   r   __str__3  rB   zJsonPatch.__str__c                 C   
   t | jS rC   )boolr/   rF   r   r   r   __bool__7  rP   zJsonPatch.__bool__c                 C   r   rC   )iterr/   rF   r   r   r   __iter__<  rP   zJsonPatch.__iter__c                 C   s   t t| jS rC   )rD   tuple_opsrF   r   r   r   rG   ?  s   zJsonPatch.__hash__c                 C   rH   rI   )r)   r+   r   rJ   r   r   r   rL   B  rM   zJsonPatch.__eq__c                 C   rN   rC   r   rJ   r   r   r   rO   G  rP   zJsonPatch.__ne__Nc                 C   s   |p| j }||}| ||dS )a  Creates JsonPatch instance from string source.

        :param patch_str: JSON patch as raw string.
        :type patch_str: str

        :param loads: A function of one argument that loads a serialized
                      JSON string.
        :type loads: function

        :param pointer_cls: JSON pointer class to use.
        :type pointer_cls: Type[JsonPointer]

        :return: :class:`JsonPatch` instance.
        r'   )json_loader)cls	patch_strloadsr(   r   r/   r   r   r   r,   J  s   
zJsonPatch.from_stringTc           	      C   sB   |p| j }t||||d}|dd|| t| }| ||dS )aC  Creates JsonPatch instance based on comparison of two document
        objects. Json patch would be created for `src` argument against `dst`
        one.

        :param src: Data source document object.
        :type src: dict

        :param dst: Data source document object.
        :type dst: dict

        :param dumps: A function of one argument that produces a serialized
                      JSON string.
        :type dumps: function

        :param pointer_cls: JSON pointer class to use.
        :type pointer_cls: Type[JsonPointer]

        :return: :class:`JsonPatch` instance.

        >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
        >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
        >>> patch = JsonPatch.from_diff(src, dst)
        >>> new = patch.apply(src)
        >>> new == dst
        True
        r'    N)json_dumperDiffBuilder_compare_valuesr   execute)	r   r3   r4   optimizationdumpsr(   r   builderopsr   r   r   r2   ^  s
   
zJsonPatch.from_diffc                 C   s   |p| j }|| jS )z!Returns patch set as JSON string.)r   r/   )r=   r   r   r   r   r   r     s   

zJsonPatch.to_stringc                 C   s   t t| j| jS rC   )r   mapr   r/   rF   r   r   r   r     s   zJsonPatch._opsFc                 C   s(   |st |}| jD ]}||}q
|S )a5  Applies the patch to a given object.

        :param obj: Document object.
        :type obj: dict

        :param in_place: Tweaks the way how patch would be applied - directly to
                         specified `obj` or to its copy.
        :type in_place: bool

        :return: Modified `obj`.
        )r   r   r   r-   )r=   rA   r0   r<   r   r   r   r-     s
   

zJsonPatch.applyc                 C   sZ   d|vrt d|d }t|tst d|| jvr!t d|| j| }||| jdS )Nry   z&Operation does not contain 'op' memberzOperation must be a stringzUnknown operation {0!r}r'   )r   r)   r*   
operationsr_   r(   )r=   r<   ry   r   r   r   r   r     s   


zJsonPatch._get_operationrC   )F)"r   r   r   staticmethodjsonr   r   
_jsonloadsr   r   r[   rj   rq   rt   r   r   r   r   r?   r   r   __nonzero__r   rG   rL   rO   classmethodr,   r2   r   rX   r   r-   r   r   r   r   r   r+     s>    
	-
$

r+   c                   @   s   e Zd Zeje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dd Zdd Zdd Zdd ZdS )r   c                 C   sL   || _ || _i i g| _g g g| _g  | _}|| _|| _||d g|d d < d S rC   )r   r(   index_storageindex_storage2_DiffBuilder__rootsrc_docdst_doc)r=   r   r   r   r(   rootr   r   r   r?     s   


zDiffBuilder.__init__c                 C   sv   |t |f}z | j| }||}|d u r|g||< W d S || | W d S  ty:   | j| ||f Y d S w rC   )rp   r   getr   r;   r   )r=   r$   indexst	typed_keystoragestoredr   r   r   store_index  s   

zDiffBuilder.store_indexc                 C   s   |t |f}z| j| |}|r| W S W d S  tyG   | j| }tt|d ddD ]}|| d |krC||d    Y S q.Y d S w )Nr   rR   r   )rp   r   r   popr;   r   ranger   )r=   r$   r   r   r   r   ir   r   r   
take_index  s   

zDiffBuilder.take_indexc                 C   s,   | j }|d }|||g |d< |d< |d S )Nr   r   r   )r=   ry   r   lastr   r   r   ro     s   zDiffBuilder.insertc                 C   s*   |\}}}||d< ||d< g |d d < d S )Nr   r   r   )r=   r   	link_prev	link_next_r   r   r   rw     s   
zDiffBuilder.removec                 c   s:    | j }|d }||ur|d V  |d }||usd S d S Nr      r   )r=   startr   currr   r   r   	iter_from     
zDiffBuilder.iter_fromc                 c   s:    | j }|d }||ur|d V  |d }||usd S d S r   r   )r=   r   r   r   r   r   r     r   zDiffBuilder.__iter__c                 c   s    | j }|d }||urW|d |urG|d |d d }}|j|jkrGt|tkrGt|tkrGtd|j|jd d| jdjV  |d d }q|d jV  |d }||usd S d S )Nr   r   r   r$   r{   r'   )r   r9   rp   r[   rj   rq   r<   r(   )r=   r   r   op_first	op_secondr   r   r   r     s2   

zDiffBuilder.executec           	      C   s   |  |t}|d urQ|d }t|jtkr,t|tkr,| |D ]}||j|j|_q | | |j	t
||krOtd|j	t
||d| jd}| | d S d S tdt
|||d| jd}| |}| ||t d S )Nr   r   ry   ru   r7   r'   rz   r{   )r   
_ST_REMOVErp   r   rU   r   rf   r7   rw   r9   
_path_joinrt   r(   ro   rj   r   _ST_ADD)	r=   r7   r   itemr   ry   vnew_op	new_indexr   r   r   _item_added  s4   

zDiffBuilder._item_addedc           
      C   s   t dt||d| jd}| |t}| |}|d ure|d }|j| jd }t	|t
kr@| |D ]}	|	|j|j|_q4| | |j|jkr^td|j|jd| jd}||d< d S | | d S | ||t d S )Nrw   rx   r'   r   r   r   r   )r[   r   r(   r   r   ro   r:   r\   r   rp   r   r   rh   r7   r   rw   r9   rt   r   r   )
r=   r7   r   r   r   r   r   ry   
added_itemr   r   r   r   _item_removed  s4   

zDiffBuilder._item_removedc                 C   s&   |  tdt|||d| jd d S )Nr   r{   r'   )ro   rq   r   r(   )r=   r7   r   r   r   r   r   _item_replaced?  s   zDiffBuilder._item_replacedc           	      C   s   t | }t | }|| }|| }|D ]}| |t|||  q|D ]}| |t|||  q&||@ D ]}| |||| ||  q8d S rC   )setkeysr   rW   r   r   )	r=   r7   r3   r4   src_keysdst_keys
added_keysremoved_keysr   r   r   r   _compare_dictsF  s   zDiffBuilder._compare_dictsc                 C   s   t |t |}}t||}t||}t|D ]d}||k rd|| || }	}
|	|
kr+qt|	tr@t|
tr@| t|||	|
 qt|	trUt|
trU| 	t|||	|
 q| 
|||	 | |||
 q||krr| 
||||  q| ||||  qd S rC   )r   maxminr   r)   r   r   r   r   _compare_listsr   r   )r=   r7   r3   r4   len_srclen_dstmax_lenmin_lenr   oldnewr   r   r   r   U  s,   



zDiffBuilder._compare_listsc                 C   s   t |trt |tr| t|||| d S t |tr,t |tr,| t|||| d S | || |kr8d S | ||| d S rC   )r)   r   r   r   r   r   r   r   )r=   r7   r   r3   r4   r   r   r   r   q  s   

	zDiffBuilder._compare_valuesN)r   r   r   r   r   r   r?   r   r   ro   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s    
!r   c                 C   s,   |d u r| S | d t |dddd S )NrQ   ~z~0z~1)rW   r   rd   r   r   r   r     s    r   )4r   
__future__r   r   r   	functoolsr   systypesr   ImportErrorr    jsonpointerr   r   r   r   collections.abcr   r   unicoderW   
__author____version____website____license__version_infobytesr*   	Exceptionr   r   r   AssertionErrorr   r%   partialr   r   r1   r5   objectr6   r[   rj   rq   rt   r   r   r+   r   r   r   r   r   r   <module>   s^    
	(64*V D X