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)Zordered_pairsZmdictr   valuer   r   r   	multidict_   s   
r#   )Z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   
!r.   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   r2   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&   r4   locationpointer	TypeError	operation)selfr9   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	frozensetr9   r!   r:   r   r   r   __hash__   s   zPatchOperation.__hash__c                 C      t |tsdS | j|jkS NF)r&   r3   r9   r:   otherr   r   r   __eq__      
zPatchOperation.__eq__c                 C   
   | |k S r@   r   rG   r   r   r   __ne__      
zPatchOperation.__ne__c                 C   s   d | jjd d S )N/)joinr7   partsrC   r   r   r   r4      s   zPatchOperation.pathc                 C   s2   z	t | jjd W S  ty   | jjd  Y S w )NrO   )intr7   rQ   
ValueErrorrC   r   r   r   r      s
   zPatchOperation.keyc                 C   s*   t || jjd< | jj| _| j| jd< d S )NrO   r4   )strr7   rQ   r4   r6   r9   )r:   r"   r   r   r   r      s   
N)r   r   r   r   r   r<   r*   rD   rI   rL   propertyr4   r   setterr   r   r   r   r3      s    

r3   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}')r7   to_lastKeyError
IndexErrorformatr   )r:   r>   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   r4   r   r:   r4   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 r`   ra   rb   r   r   r   _on_undo_add   rd   zRemoveOperation._on_undo_addNr   r   r   r   r*   rc   re   r   r   r   r   rX      s
    
rX   c                   @   rW   )	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})r9   rZ   r   r7   rY   r&   r   r   r   r   insertr   r8   r\   typer6   )r:   r>   r"   r;   r]   r^   r   r   r   r*   	  s4   


	zAddOperation.applyc                 C   s2   | j |kr| j|kr|  jd7  _|S |d7 }|S r`   ra   rb   r   r   r   rc   )  rd   zAddOperation._on_undo_removec                 C   s2   | j |kr| j|kr|  jd8  _|S |d7 }|S r`   ra   rb   r   r   r   re   1  rd   zAddOperation._on_undo_addNrf   r   r   r   r   rg     s
     rg   c                   @   rW   )	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"   rh   ri   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}'rj   rk   )r9   rZ   r   r7   rY   r&   r   r   r   r   r\   r8   rm   r6   )r:   r>   r"   r;   r]   r^   r_   r   r   r   r*   =  s6   


zReplaceOperation.applyc                 C      |S r@   r   rb   r   r   r   rc   ]     z ReplaceOperation._on_undo_removec                 C   ro   r@   r   rb   r   r   r   re   `  rp   zReplaceOperation._on_undo_addNrf   r   r   r   r   rn   :  s
     rn   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opr4   r$   addrv   r4   r"   )r&   r9   r%   rZ   r   rY   r[   r   rT   r7   r   containsrX   r*   rg   r6   r:   r>   from_ptrr;   r]   r^   r"   r   r   r   r*   g  sT   


zMoveOperation.applyc                 C   s$   |  | jd }d|jd d S )Nrr   rN   rO   )r%   r9   rP   rQ   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 Nrr   rO   )r%   r9   rR   rQ   r8   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%   r9   rT   rQ   r4   )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 r`   r}   r   r4   r   rb   r   r   r   rc        



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 r`   r   rb   r   r   r   re     r   zMoveOperation._on_undo_addN)r   r   r   r   r*   rU   r}   r   rV   rc   re   r   r   r   r   rq   d  s    %


rq   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"   rh   z0{0} ({1}) is not equal to tested value {2} ({3}))r7   rY   walkr   r   rT   r9   rZ   r   r\   rm   )r:   r>   r]   r^   valr;   r"   r_   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 )Nrr   rs   rw   rx   r$   )r%   r9   rZ   r   rY   copydeepcopyr[   r   rT   rg   r6   r*   rz   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(   )rt   rw   replacemovetestr   c                 C   s&   || _ || _| j D ]}| | q	d S r@   )r,   r%   _get_operation)r:   r,   r%   rv   r   r   r   r<   (  s
   
zJsonPatch.__init__c                 C   s   |   S )zstr(self) -> self.to_string())	to_stringrC   r   r   r   __str__3  r?   zJsonPatch.__str__c                 C   
   t | jS r@   )boolr,   rC   r   r   r   __bool__7  rM   zJsonPatch.__bool__c                 C   r   r@   )iterr,   rC   r   r   r   __iter__<  rM   zJsonPatch.__iter__c                 C   s   t t| jS r@   )rA   tuple_opsrC   r   r   r   rD   ?  s   zJsonPatch.__hash__c                 C   rE   rF   )r&   r(   r   rG   r   r   r   rI   B  rJ   zJsonPatch.__eq__c                 C   rK   r@   r   rG   r   r   r   rL   G  rM   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)clsZ	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   r0   r1   optimizationdumpsr%   r   Zbuilderopsr   r   r   r/   ^  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 r@   )r   mapr   r,   rC   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:   r>   r-   r9   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 )Nrv   z&Operation does not contain 'op' memberzOperation must be a stringzUnknown operation {0!r}r$   )r   r&   r'   
operationsr\   r%   )r:   r9   rv   r   r   r   r   r     s   


zJsonPatch._get_operationr@   )F)"r   r   r   staticmethodjsonr   r   
_jsonloadsr   r   rX   rg   rn   rq   r   r   r   r   r<   r   r   Z__nonzero__r   rD   rI   rL   classmethodr)   r/   r   rU   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 r@   )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 r@   )rm   r   getr   r8   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   rO   r   )rm   r   r   popr8   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:   rv   r   Zlastr   r   r   rl     s   zDiffBuilder.insertc                 C   s*   |\}}}||d< ||d< g |d d < d S )Nr   r   r   )r:   r   Z	link_prevZ	link_next_r   r   r   rt     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"   rx   r$   )r   r6   rm   rX   rg   rn   r9   r%   )r:   r   r   Zop_firstZ	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   rv   rr   r4   r$   rw   rx   )r   
_ST_REMOVErm   r   rR   r   rc   r4   rt   r6   
_path_joinrq   r%   rl   rg   r   _ST_ADD)	r:   r4   r   itemr   rv   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 )Nrt   ru   r$   r   r   r   r   )rX   r   r%   r   r   rl   r7   rY   r   rm   r   r   re   r4   r   rt   r6   rq   r   r   )
r:   r4   r   r   r   r   r   rv   Z
added_itemr   r   r   r   _item_removed  s4   

zDiffBuilder._item_removedc                 C   s&   |  tdt|||d| jd d S )Nr   rx   r$   )rl   rn   r   r%   )r:   r4   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 r@   )setkeysr   rT   r   r   )	r:   r4   r0   r1   Zsrc_keysZdst_keysZ
added_keysZ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 r@   )r   maxminr   r&   r   r   r   r   _compare_listsr   r   )r:   r4   r0   r1   Zlen_srcZlen_dstZmax_lenZ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 r@   )r&   r   r   r   r   r   r   r   )r:   r4   r   r0   r1   r   r   r   r   q  s   

	zDiffBuilder._compare_valuesN)r   r   r   r   r   r   r<   r   r   rl   rt   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 )NrN   ~z~0z~1)rT   r   ra   r   r   r   r     s    r   )4r   Z
__future__r   r   r   	functoolsr   systypesr   ImportErrorr    Zjsonpointerr   r   r   r   Zcollections.abcr   r   ZunicoderT   
__author____version__Z__website__Z__license__version_infobytesr'   	Exceptionr   r   r   AssertionErrorr   r#   partialr   r   r.   r2   objectr3   rX   rg   rn   rq   r   r   r(   r   r   r   r   r   r   <module>   s^    
	(64*V D X