U
    ڲg;                     @   s,   d Z ddlZddlmZ G dd deZdS )z*Docker-style file variable support module.    N)MutableMappingc                   @   sB   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S )FileAwareMappinga  
    A mapping that wraps os.environ, first checking for the existence of a key
    appended with ``_FILE`` whenever reading a value. If a matching file key is
    found then the value is instead read from the file system at this location.

    By default, values read from the file system are cached so future lookups
    do not hit the disk again.

    A ``_FILE`` key has higher precedence than a value is set directly in the
    environment, and an exception is raised if the file can not be found.
    NTc                 C   s$   |dk	r|nt j| _|| _i | _dS )a  
        Initialize the mapping.

        :param env:
            where to read environment variables from (defaults to
            ``os.environ``)
        :param cache:
            cache environment variables read from the file system (defaults to
            ``True``)
        N)osenvironenvcachefiles_cache)selfr   r    r
   =/tmp/pip-unpacked-wheel-fcyglivv/environ/fileaware_mapping.py__init__   s    zFileAwareMapping.__init__c              	   C   sl   | j r|| jkr| j| S | j|d }|rbt|dd}| }W 5 Q R X | j r^|| j|< |S | j| S )N_FILEzutf-8)encoding)r   r   r   getopenread)r	   keykey_filefvaluer
   r
   r   __getitem__+   s    

zFileAwareMapping.__getitem__c                 c   s@   | j D ]4}|V  |dr|dd }|r|| j kr|V  qdS )zp
        Iterate all keys, also always including the shortened key if ``_FILE``
        keys are found.
        r   N)r   endswith)r	   r   no_file_keyr
   r
   r   __iter__7   s    

zFileAwareMapping.__iter__c                 C   s   t tt| S )zy
        Return the length of the file, also always counting shortened keys for
        any ``_FILE`` key found.
        )lentupleiter)r	   r
   r
   r   __len__C   s    zFileAwareMapping.__len__c                 C   s@   || j |< | jr<|dr<|d d }|r<|| jkr<| j|= d S Nr   r   r   r   r   r   )r	   r   r   r   r
   r
   r   __setitem__J   s
    
zFileAwareMapping.__setitem__c                 C   sl   |d }|| j kr.| |= || j kr*| j |= d S | jr`|dr`|d d }|r`|| jkr`| j|= | j |= d S r   r    )r	   r   Zfile_keyr   r
   r
   r   __delitem__Q   s    

zFileAwareMapping.__delitem__)NT)
__name__
__module____qualname____doc__r   r   r   r   r!   r"   r
   r
   r
   r   r      s   
r   )r&   r   collections.abcr   r   r
   r
   r
   r   <module>	   s   