U
    /eO                     @  sx  U 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d dlZd dlZd dl	Z	d dl
Z
d dlmZmZ d dlmZmZ d dlZdZdd Ze Zdejkrejd Znejejd	d
dZi Zded< eZe	 Zg Zded< ddddddZ dbdddddddZ!dddddZ"ddddd Z#efd!d"d#d$d%Z$dcd&dd'd(d)Z%dddd+d,d-d.d/d0Z&G d1d2 d2Z'edfd3d&dd4d5d6Z(eefddd-d7d8d9Z)eedfdd:dd;d:d<d=d>Z*efddd-d?d@dAZ+eefdddd-dBdCdDZ,d:d:dEdFdGZ-dHdIdJdKdLdMdNdOdPdQdRdSdTdUdVZ.e.fddddWdXdYZ/d:ddZd[d\Z0dd:dZd]d^Z1d-d_d`daZ2e)  e2  dS )e    )annotationsN)MappingSequence)AnyLiteralZ__no_default__c                  C  s~   t ddt jtjddfdd tjD t jt jdddf} d	t j	kr`| 
t j	d	  ttttt| } | S )
z~Get locations to search for YAML configuration files.

    This logic exists as a separate function for testing purposes.
    ZDASK_ROOT_CONFIGz	/etc/dasketcdaskc                 S  s   g | ]}t j|d dqS )r   r   )ospathjoin).0prefix r   //tmp/pip-unpacked-wheel-dbjnr7gq/dask/config.py
<listcomp>   s     z_get_paths.<locals>.<listcomp>~.configDASK_CONFIG)r	   getenvr
   r   sysr   sitePREFIXES
expanduserenvironappendlistreverseddictfromkeyspathsr   r   r   
_get_paths   s    

r!   r   r   r   r   r   configzlist[Mapping]defaultsstr)kr"   returnc                 C  s\   z| |kr| W S W n t k
r*   |  Y S X d| kr@| ddn
| dd}||krX|S | S )a@  Return the canonical name for a key.

    Handles user choice of '-' or '_' conventions by standardizing on whichever
    version was set first. If a key already exists in either hyphen or
    underscore form, the existing version is the canonical name. If neither
    version exists the original key is used as is.
    _-)	TypeErrorreplace)r%   r"   Zaltkr   r   r   canonical_name;   s    

 r+   newr   zLiteral[('old', 'new')])oldr,   priorityr&   c                 C  sr   |  D ]d\}}t|| }t|trT|| ks8| | dkr@i | |< t| | ||d q|dksd|| kr|| |< q| S )a  Update a nested dictionary with values from another

    This is like dict.update except that it smoothly merges nested values

    This operates in-place and modifies old

    Parameters
    ----------
    priority: string {'old', 'new'}
        If new (default) then the new dictionary has preference.
        Otherwise the old dictionary does.

    Examples
    --------
    >>> a = {'x': 1, 'y': {'a': 2}}
    >>> b = {'x': 2, 'y': {'b': 3}}
    >>> update(a, b)  # doctest: +SKIP
    {'x': 2, 'y': {'a': 2, 'b': 3}}

    >>> a = {'x': 1, 'y': {'a': 2}}
    >>> b = {'x': 2, 'y': {'b': 3}}
    >>> update(a, b, priority='old')  # doctest: +SKIP
    {'x': 1, 'y': {'a': 2, 'b': 3}}

    See Also
    --------
    dask.config.merge
    Nr.   r,   )itemsr+   
isinstancer   update)r-   r,   r.   r%   vr   r   r   r2   R   s    


r2   )dictsr&   c                  G  s   i }| D ]}t || q|S )aS  Update a sequence of nested dictionaries

    This prefers the values in the latter dictionaries to those in the former

    Examples
    --------
    >>> a = {'x': 1, 'y': {'a': 2}}
    >>> b = {'y': {'b': 3}}
    >>> merge(a, b)  # doctest: +SKIP
    {'x': 1, 'y': {'a': 2, 'b': 3}}

    See Also
    --------
    dask.config.update
    )r2   )r4   resultdr   r   r   merge}   s    r7   zdict | None)r
   r&   c              
   C  s   z&t | }t| }W 5 Q R X W nL tk
r<   Y dS  tk
rr } ztd| d| dW 5 d}~X Y nX |dk	rt|tstd| dt	|j
 d|S )zhA helper for loading a config file from a path, and erroring
    appropriately if the file is malformed.NzA dask config file at z( is malformed, original error message:

zM is malformed - config files must have a dict as the top level object, got a z instead)openyaml	safe_loadreadOSError	Exception
ValueErrorr1   r   type__name__)r
   fr"   excr   r   r   _load_config_file   s     
rC   Sequence[str]z
list[dict])r    r&   c              	     s   g }| D ]d t j rt j rbz&|t fddt  D  W ql tk
r^   Y qlX q|  qg }|D ] t	 }|dk	rv|| qv|S )zCollect configuration from yaml files

    This searches through a list of paths, expands to find all yaml or json
    files, and then parses each file.
    c                 3  s4   | ],}t j|d   dkrt j |V  qdS )   )z.jsonz.yamlz.ymlN)r	   r
   splitextlowerr   )r   pr
   r   r   	<genexpr>   s
   zcollect_yaml.<locals>.<genexpr>N)
r	   r
   existsisdirextendsortedlistdirr<   r   rC   )r    Z
file_pathsconfigsr"   r   rI   r   collect_yaml   s&    rQ   zMapping[str, str] | None)envr&   c              
   C  s   | dkrt j} d| kr$t| d }ni }|  D ]^\}}|dr0|dd  dd}zt|||< W q0 t	t
fk
r   |||< Y q0X q0i }t||d |S )a  Collect config from environment variables

    This grabs environment variables of the form "DASK_FOO__BAR_BAZ=123" and
    turns these into config variables of the form ``{"foo": {"bar-baz": 123}}``
    It transforms the key and value in the following way:

    -  Lower-cases the key text
    -  Treats ``__`` (double-underscore) as nested access
    -  Calls ``ast.literal_eval`` on the value

    Any serialized config passed via ``DASK_INTERNAL_INHERIT_CONFIG`` is also set here.

    NZDASK_INTERNAL_INHERIT_CONFIGZDASK_   __.r"   )r	   r   deserializer0   
startswithrG   r*   astliteral_evalSyntaxErrorr>   set)rR   r6   namevaluevarnamer5   r   r   r   collect_env   s    
r`   Tz
str | NoneboolNone)sourcedestinationcommentr&   c              	   C  s  |dkrt }tj|rdS |}tj|tj| }ztj|stj|dd d|t f }t	| }t
|}W 5 Q R X |rdd |D }t	|d}|d| W 5 Q R X zt|| W n tk
r   t| Y nX W n tk
r   Y nX dS )	a   
    Copy file to default location if it does not already exist

    This tries to move a default configuration file to a default location if
    if does not already exist.  It also comments out that file by default.

    This is to be used by downstream modules (like dask.distributed) that may
    have default configuration files that they wish to include in the default
    configuration path.

    Parameters
    ----------
    source : string, filename
        Source configuration file, typically within a source directory.
    destination : string, directory
        Destination directory. Configurable by ``DASK_CONFIG`` environment
        variable, falling back to ~/.config/dask.
    comment : bool, True by default
        Whether or not to comment out the config file when copying.
    NT)exist_okz	%s.tmp.%dc                 S  s*   g | ]"}|  r"|d s"d| n|qS )#z# )striprX   )r   liner   r   r   r   !  s   zensure_file.<locals>.<listcomp>w )PATHr	   r
   isfiler   basenamerK   makedirsgetpidr8   r   writerenamer<   remove)rc   rd   re   	directorytmprA   linesr   r   r   ensure_file   s0    
rw   c                   @  sf   e Zd ZU dZded< ded< deefdddd	d
dZdd Zdd Z	ddddddddddZ
dS )r\   a  Temporarily set configuration values within a context manager

    Parameters
    ----------
    arg : mapping or None, optional
        A mapping of configuration key-value pairs to set.
    **kwargs :
        Additional key-value pairs to set. If ``arg`` is provided, values set
        in ``arg`` will be applied before those in ``kwargs``.
        Double-underscores (``__``) in keyword arguments will be replaced with
        ``.``, allowing nested values to be easily set.

    Examples
    --------
    >>> import dask

    Set ``'foo.bar'`` in a context, by providing a mapping.

    >>> with dask.config.set({'foo.bar': 123}):
    ...     pass

    Set ``'foo.bar'`` in a context, by providing a keyword argument.

    >>> with dask.config.set(foo__bar=123):
    ...     pass

    Set ``'foo.bar'`` globally.

    >>> dask.config.set(foo__bar=123)  # doctest: +SKIP

    See Also
    --------
    dask.config.get
    r   r"   zAlist[tuple[Literal[('insert', 'replace')], tuple[str, ...], Any]]_recordNzMapping | Nonezthreading.Lock)argr"   lockc              	   K  s   | || _ g | _|d k	rH| D ]$\}}t|}| |d|| q"|r| D ]0\}}|dd}t|}| |d|| qTW 5 Q R X d S )NrU   rT   )r"   rx   r0   check_deprecations_assignsplitr*   )selfry   r"   rz   kwargskeyr^   r   r   r   __init__Y  s    zset.__init__c                 C  s   | j S NrV   )r~   r   r   r   	__enter__n  s    zset.__enter__c              
   C  s   t | jD ]\}}}| j}|dkrN|d d D ]}||i }q.|||d < q
|d d D ],}z|| }W qZ tk
r   Y  q
Y qZX qZ||d d  q
d S )Nr*   )r   rx   r"   
setdefaultKeyErrorpop)r~   r?   r^   	tracebackopr
   r6   r   r   r   r   __exit__q  s    zset.__exit__r   TrD   r   ztuple[str, ...]ra   rb   )keysr^   r6   r
   recordr&   c                 C  s   t |d |}||f }t|dkrd|rZ||krH| jd||| f n| jd|df |||< nJ||kr|r| jd|df i ||< d}| j|dd ||| ||d dS )a  Assign value into a nested configuration dictionary

        Parameters
        ----------
        keys : Sequence[str]
            The nested path of keys to assign the value.
        value : object
        d : dict
            The part of the nested dictionary into which we want to assign the
            value
        path : tuple[str], optional
            The path history up to this point.
        record : bool, optional
            Whether this operation needs to be recorded to allow for rollback.
        r   rE   r*   insertNF)r   )r+   lenrx   r   r|   )r~   r   r^   r6   r
   r   r   r   r   r   r|     s    

zset._assign)r   T)r@   
__module____qualname____doc____annotations__r"   config_lockr   r   r   r|   r   r   r   r   r\   1  s   
#  r\   z	list[str])r    rR   r&   c                 C  s0   |dkrt j}t| d}|t|d t| S )a  
    Collect configuration from paths and environment variables

    Parameters
    ----------
    paths : list[str]
        A list of paths to search for yaml config files

    env : Mapping[str, str]
        The system environment variables

    Returns
    -------
    config: dict

    See Also
    --------
    dask.config.refresh: collect configuration and update into primary config
    Nr   )rR   )r	   r   rQ   r   r`   r7   )r    rR   rP   r   r   r   collect  s
    
r   )r"   r#   r&   c                 K  s4   |    |D ]}t| |dd qt| tf | dS )a  
    Update configuration by re-reading yaml files and env variables

    This mutates the global dask.config.config, or the config parameter if
    passed in.

    This goes through the following stages:

    1.  Clearing out all old configuration
    2.  Updating from the stored defaults from downstream libraries
        (see update_defaults)
    3.  Updating from yaml files and environment variables

    Note that some functionality only checks configuration once at startup and
    may not change behavior, even if configuration changes.  It is recommended
    to restart your python process if convenient to ensure that new
    configuration changes take place.

    See Also
    --------
    dask.config.collect: for parameters
    dask.config.update_defaults
    r-   r/   N)clearr2   r   )r"   r#   r   r6   r   r   r   refresh  s    r   r   z
Any | None)r   defaultr"   override_withr&   c                 C  sp   |dk	r|S |  d}|}|D ]L}t||}z|| }W q tttfk
rh   |tk	rb| Y   S  Y qX q|S )a  
    Get elements from global config

    If ``override_with`` is not None this value will be passed straight back.
    Useful for getting kwarg defaults from Dask config.

    Use '.' for nested access

    Examples
    --------
    >>> from dask import config
    >>> config.get('foo')  # doctest: +SKIP
    {'x': 1, 'y': 2}

    >>> config.get('foo.x')  # doctest: +SKIP
    1

    >>> config.get('foo.x.y', default=123)  # doctest: +SKIP
    123

    >>> config.get('foo.y', override_with=None)  # doctest: +SKIP
    2

    >>> config.get('foo.y', override_with=3)  # doctest: +SKIP
    3

    See Also
    --------
    dask.config.set
    NrU   )r}   r+   r)   
IndexErrorr   
no_default)r   r   r"   r   r   r5   r%   r   r   r   get  s    $


r   )aliasesr"   r&   c                 C  sh   g }i }|   D ]0\}}t|d|d}|dk	r|| |||< q|D ]}|t||= qFt||d dS )z_Rename old keys to new keys

    This helps migrate older configuration versions over time
    NrV   )r0   r   r   r+   r\   )r   r"   r-   r,   onr^   r%   r   r   r   rr      s    

rr   )r,   r"   r#   r&   c                 C  s   | |  t|| dd dS )a  Add a new set of defaults to the configuration

    It does two things:

    1.  Add the defaults to a global collection to be used by refresh later
    2.  Updates the global config with the new configuration
        prioritizing older values over newer ones
    r-   r/   N)r   r2   )r,   r"   r#   r   r   r   update_defaults3  s    
r   )r"   r&   c                 C  sb   t | trdd |  D S t | tr2tj| S t | ttt	j
frZt| dd | D S | S dS )a  Expand environment variables in a nested config dictionary

    This function will recursively search through any nested dictionaries
    and/or lists.

    Parameters
    ----------
    config : dict, iterable, or str
        Input object to search for environment variables

    Returns
    -------
    config : same type as input

    Examples
    --------
    >>> expand_environment_variables({'x': [1, 2, '$USER']})  # doctest: +SKIP
    {'x': [1, 2, 'my-username']}
    c                 S  s   i | ]\}}|t |qS r   expand_environment_variables)r   r%   r3   r   r   r   
<dictcomp>W  s      z0expand_environment_variables.<locals>.<dictcomp>c                 s  s   | ]}t |V  qd S r   r   )r   r3   r   r   r   rJ   [  s     z/expand_environment_variables.<locals>.<genexpr>N)r1   r   r0   r$   r	   r
   
expandvarsr   tuplebuiltinsr\   r?   rV   r   r   r   r   B  s    

r   zoptimization.fuse.ave-widthzoptimization.fuse.max-heightzoptimization.fuse.max-widthzoptimization.fuse.subgraphszoptimization.fuse.rename-keysz%optimization.fuse.max-depth-new-edgeszdistributed.ucx.cuda_copyzdistributed.ucx.tcpzdistributed.ucx.nvlinkzdistributed.ucx.infinibandzdistributed.ucx.rdmacmzdistributed.ucx.net-deviceszdistributed.ucx.reuse-endpointszdistributed.rmm.pool-size)Zfuse_ave_widthZfuse_max_heightZfuse_max_widthZfuse_subgraphsZfuse_rename_keysZfuse_max_depth_new_edgeszucx.cuda_copyzucx.tcpz
ucx.nvlinkzucx.infinibandz
ucx.rdmacmzucx.net-deviceszucx.reuse-endpointszrmm.pool-size)r   deprecationsr&   c                 C  sD   | |kr<||  }|r*t d| | |S td|  dn| S dS )an  Check if the provided value has been renamed or removed

    Parameters
    ----------
    key : str
        The configuration key to check
    deprecations : Dict[str, str]
        The mapping of aliases

    Examples
    --------
    >>> deprecations = {"old_key": "new_key", "invalid": None}
    >>> check_deprecations("old_key", deprecations=deprecations)  # doctest: +SKIP
    UserWarning: Configuration key "old_key" has been deprecated. Please use "new_key" instead.

    >>> check_deprecations("invalid", deprecations=deprecations)
    Traceback (most recent call last):
        ...
    ValueError: Configuration value "invalid" has been removed

    >>> check_deprecations("another_key", deprecations=deprecations)
    'another_key'

    Returns
    -------
    new: str
        The proper key, whether the original (if no deprecation) or the aliased
        value
    zCConfiguration key "{}" has been deprecated. Please use "{}" insteadzConfiguration value "z" has been removedN)warningswarnformatr>   )r   r   r,   r   r   r   r{   s  s     r{   )datar&   c                 C  s   t t|   S )aF  Serialize config data into a string.

    Typically used to pass config via the ``DASK_INTERNAL_INHERIT_CONFIG`` environment variable.

    Parameters
    ----------
    data: json-serializable object
        The data to serialize

    Returns
    -------
    serialized_data: str
        The serialized data as a string

    )base64urlsafe_b64encodejsondumpsencodedecoder   r   r   r   	serialize  s    r   c                 C  s   t t|   S )aW  De-serialize config data into the original object.

    Typically when receiving config via the ``DASK_INTERNAL_INHERIT_CONFIG`` environment variable.

    Parameters
    ----------
    data: str
        String serialized by :func:`dask.config.serialize`

    Returns
    -------
    deserialized_data: obj
        The de-serialized data

    )r   loadsr   urlsafe_b64decoder   r   r   r   r   r   rW     s    rW   )r&   c               	   C  s@   t jt jtd} t| }t|}W 5 Q R X t| d S )Nz	dask.yaml)	r	   r
   r   dirname__file__r8   r9   r:   r   )fnrA   	_defaultsr   r   r   _initialize  s    
r   )r,   )N)NT)3
__future__r   rY   r   r   r   r	   r   r   	threadingr   collections.abcr   r   typingr   r   r9   r   r!   r    r   rl   r
   r   r   r"   r   Zglobal_configLockr   r#   r+   r2   r7   rC   rQ   r`   rw   r\   r   r   r   rr   r   r   r   r{   r   rW   r   r   r   r   r   <module>   s    
+%%   ?| $4 ,	