U
    M8ca                     @   s   d dl Z d dlZd dlmZmZ d dlmZ d dlmZ e	e
ZeddddgZd Zd	Zd
ZG dd deZdddZG dd dZG dd deZG dd deZG dd dZdS )    N)deque
namedtuple)accepts_kwargs)EVENT_ALIASESNodeListfirstmiddlelast      c                   @   s   e Zd Zdd ZdS )r   c                 C   s4   t  | j}t  | j}t  | j}t|||}|S N)copyr   r   r	   r   )selfZ
first_copyZmiddle_copyZ	last_copycopied r   2/tmp/pip-unpacked-wheel-ozje0y8b/botocore/hooks.py__copy__   s
    zNodeList.__copy__N)__name__
__module____qualname__r   r   r   r   r   r      s   c                 C   s&   | D ]}|d dk	r|d   S q|S )a  Find first non None response in a list of tuples.

    This function can be used to find the first non None response from
    handlers connected to an event.  This is useful if you are interested
    in the returned responses from event handlers. Example usage::

        print(first_non_none_response([(func1, None), (func2, 'foo'),
                                       (func3, 'bar')]))
        # This will print 'foo'

    :type responses: list of tuples
    :param responses: The responses from the ``EventHooks.emit`` method.
        This is a list of tuples, and each tuple is
        (handler, handler_response).

    :param default: If no non-None responses are found, then this default
        value will be returned.

    :return: The first non-None response in the list of tuples.

    r
   Nr   )	responsesdefaultresponser   r   r   first_non_none_response&   s    r   c                   @   sT   e Zd Zdd ZdddZdddZdd	d
Zdd ZdddZdd Z	dd Z
dS )BaseEventHooksc                 K   s   g S )a  Call all handlers subscribed to an event.

        :type event_name: str
        :param event_name: The name of the event to emit.

        :type **kwargs: dict
        :param **kwargs: Arbitrary kwargs to pass through to the
            subscribed handlers.  The ``event_name`` will be injected
            into the kwargs so it's not necesary to add this to **kwargs.

        :rtype: list of tuples
        :return: A list of ``(handler_func, handler_func_return_value)``

        r   r   
event_namekwargsr   r   r   emitC   s    zBaseEventHooks.emitNFc                 C   s   | j |||| j|d dS )a@  Register an event handler for a given event.

        If a ``unique_id`` is given, the handler will not be registered
        if a handler with the ``unique_id`` has already been registered.

        Handlers are called in the order they have been registered.
        Note handlers can also be registered with ``register_first()``
        and ``register_last()``.  All handlers registered with
        ``register_first()`` are called before handlers registered
        with ``register()`` which are called before handlers registered
        with ``register_last()``.

        register_methodunique_id_uses_countN)_verify_and_register	_registerr   r   handler	unique_idr!   r   r   r   registerT   s    zBaseEventHooks.registerc                 C   s   | j |||| j|d dS )zRegister an event handler to be called first for an event.

        All event handlers registered with ``register_first()`` will
        be called before handlers registered with ``register()`` and
        ``register_last()``.

        r   N)r"   _register_firstr$   r   r   r   register_firstl   s    
zBaseEventHooks.register_firstc                 C   s   | j |||| j|d dS )zRegister an event handler to be called last for an event.

        All event handlers registered with ``register_last()`` will be called
        after handlers registered with ``register_first()`` and ``register()``.

        r   N)r"   _register_lastr$   r   r   r   register_last~   s    	zBaseEventHooks.register_lastc                 C   s&   |  | | | ||||| d S r   )_verify_is_callable_verify_accept_kwargs)r   r   r%   r&   r    r!   r   r   r   r"      s    

z#BaseEventHooks._verify_and_registerc                 C   s   dS )zUnregister an event handler for a given event.

        If no ``unique_id`` was given during registration, then the
        first instance of the event handler is removed (if the event
        handler has been registered multiple times).

        Nr   r$   r   r   r   
unregister   s    zBaseEventHooks.unregisterc                 C   s   t |std| d S )Nz"Event handler %s must be callable.)callable
ValueErrorr   funcr   r   r   r,      s    z"BaseEventHooks._verify_is_callablec                 C   s8   zt |std| dW n tk
r2   Y dS X dS )zVerifies a callable accepts kwargs

        :type func: callable
        :param func: A callable object.

        :returns: True, if ``func`` accepts kwargs, otherwise False.

        zEvent handler z) must accept keyword arguments (**kwargs)FN)r   r0   	TypeErrorr1   r   r   r   r-      s    	
z$BaseEventHooks._verify_accept_kwargs)NF)NF)NF)NNF)r   r   r   r   r'   r)   r+   r"   r.   r,   r-   r   r   r   r   r   B   s"      
   
   
   
r   c                   @   sf   e Zd Zdd ZdddZdd Zdd	 ZdddZdddZdddZ	dd Z
dddZdd Zd
S )HierarchicalEmitterc                 C   s   i | _ t | _i | _d S r   )_lookup_cache_PrefixTrie	_handlers_unique_id_handlersr   r   r   r   __init__   s    zHierarchicalEmitter.__init__Fc                 C   s   g }| j |}|dkr0| j|}|| j |< n|s8g S ||d< g }|D ]>}td|| |f |}|||f |rH|dk	rH|  S qH|S )a  
        Emit an event with optional keyword arguments.

        :type event_name: string
        :param event_name: Name of the event
        :type kwargs: dict
        :param kwargs: Arguments to be passed to the handler functions.
        :type stop_on_response: boolean
        :param stop_on_response: Whether to stop on the first non-None
                                response. If False, then all handlers
                                will be called. This is especially useful
                                to handlers which mutate data and then
                                want to stop propagation of the event.
        :rtype: list
        :return: List of (handler, response) tuples from all processed
                 handlers.
        Nr   zEvent %s: calling handler %s)r5   getr7   prefix_searchloggerdebugappend)r   r   r   stop_on_responser   Zhandlers_to_callr%   r   r   r   r   _emit   s     

zHierarchicalEmitter._emitc                 K   s   |  ||S )a;  
        Emit an event by name with arguments passed as keyword args.

            >>> responses = emitter.emit(
            ...     'my-event.service.operation', arg1='one', arg2='two')

        :rtype: list
        :return: List of (handler, response) tuples from all processed
                 handlers.
        rA   r   r   r   r   r      s    zHierarchicalEmitter.emitc                 K   s$   | j ||dd}|r|d S dS dS )a  
        Emit an event by name with arguments passed as keyword args,
        until the first non-``None`` response is received. This
        method prevents subsequent handlers from being invoked.

            >>> handler, response = emitter.emit_until_response(
                'my-event.service.operation', arg1='one', arg2='two')

        :rtype: tuple
        :return: The first (handler, response) tuple where the response
                 is not ``None``, otherwise (``None``, ``None``).
        T)r@   )NNNrB   )r   r   r   r   r   r   r   emit_until_response  s    z'HierarchicalEmitter.emit_until_responseNc                 C   s   | j ||||td d S Nsection)_register_section_MIDDLEr$   r   r   r   r#     s    zHierarchicalEmitter._registerc                 C   s   | j ||||td d S rE   )rH   _FIRSTr$   r   r   r   r(      s    z#HierarchicalEmitter._register_firstc                 C   s   | j ||||td d S rE   )rH   _LASTr$   r   r   r   r*   +  s        z"HierarchicalEmitter._register_lastc                 C   s   |d k	r|| j krf| j | dd }|rR|s:td| qb| j | d  d7  < n|rbtd| d S | jj|||d d|i}|rd|d< || j |< n| jj|||d i | _d S )NcountzInitial registration of  unique id %s was specified to use a counter. Subsequent register calls to unique id must specify use of a counter as well.r
   zInitial registration of unique id %s was specified to not use a counter. Subsequent register calls to unique id must specify not to use a counter as well.rF   r%   )r8   r;   r0   r7   append_itemr5   )r   r   r%   r&   r!   rG   rL   Zunique_id_handler_itemr   r   r   rH   2  s:    
  z%HierarchicalEmitter._register_sectionc                 C   s   |d k	rz| j | dd }W n tk
r4   Y d S X |r|d krPtd| q|dkrj| j |d }q| j | d  d8  < d S n |rtd| | j |d }z| j|| i | _W n tk
r   Y nX d S )NrL   zInitial registration of unique id %s was specified to use a counter. Subsequent unregister calls to unique id must specify use of a counter as well.r
   r%   zInitial registration of unique id %s was specified to not use a counter. Subsequent unregister calls to unique id must specify not to use a counter as well.)r8   r;   KeyErrorr0   popr7   remove_itemr5   )r   r   r%   r&   r!   rL   r   r   r   r.   ^  s<    

zHierarchicalEmitter.unregisterc                 C   s<   |   }| j }t| j|d< t| j|d< ||_|S )Nr7   r8   )	__class____dict__r   r7   r8   )r   Znew_instanceZ	new_stater   r   r   r     s    
zHierarchicalEmitter.__copy__)F)NF)NF)F)NNF)r   r   r   r:   rA   r   rD   r#   r(   r*   rH   r.   r   r   r   r   r   r4      s$   

(   
   
 
/   
+r4   c                   @   sf   e Zd ZdddZdd Zdd Zdd	d
ZdddZdddZdddZ	dd Z
dd Zdd ZdS )EventAliaserNc                 C   s$   || _ |d krt| _ i | _|| _d S r   )_event_aliasesr   _alias_name_cache_emitter)r   Zevent_emitterZevent_aliasesr   r   r   r:     s
    zEventAliaser.__init__c                 K   s   |  |}| jj|f|S r   )_alias_event_namerV   r   r   r   r   aliased_event_namer   r   r   r     s    
zEventAliaser.emitc                 K   s   |  |}| jj|f|S r   )rW   rV   rD   rX   r   r   r   rD     s    
z EventAliaser.emit_until_responseFc                 C   s   |  |}| j||||S r   )rW   rV   r'   r   r   r%   r&   r!   rY   r   r   r   r'     s    
   zEventAliaser.registerc                 C   s   |  |}| j||||S r   )rW   rV   r)   rZ   r   r   r   r)     s    
   zEventAliaser.register_firstc                 C   s   |  |}| j||||S r   )rW   rV   r+   rZ   r   r   r   r+     s    
   zEventAliaser.register_lastc                 C   s   |  |}| j||||S r   )rW   rV   r.   rZ   r   r   r   r.     s    
   zEventAliaser.unregisterc              	   C   s   || j kr| j | S | j D ]\}}|d}d|krfz||||< W q tk
rb   Y qY qX n$||kr|d}| ||| nqd|}t	d| d|  || j |< |  S || j |< |S )N.zChanging event name from z to )
rU   rT   itemssplitindexr0   _replace_subsectionjoinr=   r>   )r   r   Zold_partnew_partZevent_parts	old_partsnew_namer   r   r   rW     s*    






zEventAliaser._alias_event_namec                 C   sZ   t t|D ]H}|| |d kr|||t|  |kr|g|||t| <  d S qd S )Nr   )rangelen)r   sectionsrb   ra   ir   r   r   r_     s    z EventAliaser._replace_subsectionc                 C   s   |  t| jt| jS r   )rQ   r   rV   rT   r9   r   r   r   r     s    
 
zEventAliaser.__copy__)N)NF)NF)NF)NNF)r   r   r   r:   r   rD   r'   r)   r+   r.   rW   r_   r   r   r   r   r   rS     s&   
   
	   
	   
   
&	rS   c                   @   sT   e Zd ZdZdd ZefddZdd Zdd	 Zd
d Z	dd Z
dd Zdd ZdS )r6   aj  Specialized prefix trie that handles wildcards.

    The prefixes in this case are based on dot separated
    names so 'foo.bar.baz' is::

        foo -> bar -> baz

    Wildcard support just means that having a key such as 'foo.bar.*.baz' will
    be matched with a call to ``get_items(key='foo.bar.ANYTHING.baz')``.

    You can think of this prefix trie as the equivalent as defaultdict(list),
    except that it can do prefix searches:

        foo.bar.baz -> A
        foo.bar -> B
        foo -> C

    Calling ``get_items('foo.bar.baz')`` will return [A + B + C], from
    most specific to least specific.

    c                 C   s   d i d d| _ d S )N)chunkchildrenvalues)_rootr9   r   r   r   r:     s    z_PrefixTrie.__init__c                 C   s   | d}| j}|D ]:}||d krB|di d}||d |< |}q|d | }q|d dkrltg g g |d< |d | | dS )zAdd an item to a key.

        If a value is already associated with that key, the new
        value is appended to the list for the key.
        r[   ri   N)rh   rj   ri   rj   )r]   rk   r   r?   )r   keyvaluerG   	key_partscurrentpart	new_childr   r   r   rM     s    
z_PrefixTrie.append_itemc                 C   s*   t  }|d}| j}| |||d |S )zCollect all items that are prefixes of key.

        Prefix in this case are delineated by '.' characters so
        'foo.bar.baz' is a 3 chunk sequence of 3 "prefixes" (
        "foo", "bar", and "baz").

        r[   r   )r   r]   rk   
_get_items)r   rl   	collectedrn   ro   r   r   r   r<   -  s
    
z_PrefixTrie.prefix_searchc                 C   s   ||fg}t |}|r| \}}|d rR|d }	|	j|	j |	j }
|t|
 ||ks|d }||| }|d}|d }|d k	r|||f |d k	r|||f qd S )Nrj   ri   *r
   )	re   rO   r   r   r	   
extendleftreversedr;   r?   )r   Zstarting_nodern   rs   Zstarting_indexstackZkey_parts_lencurrent_noder^   	node_listZcomplete_orderri   ZdirectsZwildcardZ
next_indexr   r   r   rr   ;  s$    

z_PrefixTrie._get_itemsc                 C   s&   | d}| j}| j|||dd dS )zRemove an item associated with a key.

        If the value is not associated with the key a ``ValueError``
        will be raised.  If the key does not exist in the trie, a
        ``ValueError`` will be raised.

        r[   r   )r^   N)r]   rk   _remove_item)r   rl   rm   rn   ro   r   r   r   rP   [  s    
z_PrefixTrie.remove_itemc                 C   s   |d krd S |t |k r|d || }|d k	r| ||||d  |t |d kr|d }||jkrv|j| n.||jkr|j| n||jkr|j| |d s|d s|d || = ntdd| d S )Nri   r
   rj   zkey is not in trie: r[   )	re   r;   rz   r   remover   r	   r0   r`   )r   rx   rn   rm   r^   Z	next_nodery   r   r   r   rz   g  s"    


z_PrefixTrie._remove_itemc                 C   s   |   }| | j}||_|S r   )rQ   _recursive_copyrR   )r   Znew_copyZcopied_attrsr   r   r   r     s    z_PrefixTrie.__copy__c                 C   sV   i }|  D ]D\}}t|tr.t|||< qt|trH| |||< q|||< q|S r   )r\   
isinstancer   r   dictr|   )r   nodeZcopied_noderl   rm   r   r   r   r|     s    


z_PrefixTrie._recursive_copyN)r   r   r   __doc__r:   rI   rM   r<   rr   rP   rz   r   r|   r   r   r   r   r6     s    
r6   )N)r   loggingcollectionsr   r   Zbotocore.compatr   Zbotocore.utilsr   	getLoggerr   r=   Z	_NodeListrJ   rI   rK   r   r   r   r4   rS   r6   r   r   r   r   <module>   s"   
	
  Qi