a
    ߙfb>?                 	   @   s&  d 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
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mZmZ ddlmZ zddlZW n ey   dZY n0 ddlZddlmZ ddl m!Z! ddl"m#Z#m$Z$ g dZ%i Z&G d	d
 d
ej'Z(G dd dej)Z*G dd dej+Z,e, Z-G dd de!Z.dd Z/e/Z0dd Z1ej2ddddZ3dd Z4ej2deddZ5dfddZ6dgdd Z7dhd"d#Z8did$d%Z9d&d' Z:dd(d)d*Z;djd,d-Z<dkd.d/Z=d0d1 Z>G d2d3 d3ej?j@ZAG d4d5 d5ej?jBZCeD dld6d7ZEdmd8d9ZFdnd:d;ZGdod<d=ZHdpd>d?ZIdqd@dAZJdBdC ZKdrdEdFZLg aMejNdGdH ZOdsdIdJZPdtdKdLZQdMdN ZRG dOdP dPeSZTeTi ZUG dQdR dReVZWdudSdTZXej2dvdUdVZYdwdWdXZZdxddYdZd[Z[dyd\d]Z\dzd^d_Z]d{d`daZ^d|dbdcZ_dS )}z=Functions for accessing, downloading, and caching data files.    N)NamedTemporaryFile
gettempdirTemporaryDirectorymkdtemp)warn)config)AstropyWarning)find_current_moduleresolve_name)Confconfdownload_filedownload_files_in_parallelget_readable_fileobjget_pkg_data_fileobjget_pkg_data_filenameget_pkg_data_contentsget_pkg_data_fileobjsget_pkg_data_filenamesget_pkg_data_pathis_urlis_url_in_cacheget_cached_urlscache_total_sizecache_contentsexport_download_cacheimport_download_cacheimport_file_to_cachecheck_download_cacheclear_download_cachecompute_hashget_free_space_in_dircheck_free_space_in_dirget_file_contentsCacheMissingWarningCacheDamagedc                   @   s   e Zd Zdd ZdS )_NonClosingBufferedReaderc                 C   s$   z|    W n ty   Y n0 d S Ndetach	Exceptionself r-   1lib/python3.9/site-packages/astropy/utils/data.py__del__B   s    z!_NonClosingBufferedReader.__del__N__name__
__module____qualname__r/   r-   r-   r-   r.   r&   A   s   r&   c                   @   s   e Zd Zdd ZdS )_NonClosingTextIOWrapperc                 C   s$   z|    W n ty   Y n0 d S r'   r(   r+   r-   r-   r.   r/   L   s    z _NonClosingTextIOWrapper.__del__Nr0   r-   r-   r-   r.   r4   K   s   r4   c                   @   sv   e Zd ZdZeddZeddZeddZejdd	d
gdZ	eddZ
eddZeddZeddZdS )r   z<
    Configuration parameters for `astropy.utils.data`.
    zhttp://data.astropy.org/z)Primary URL for astropy remote data site.z$http://www.astropy.org/astropy-data/z(Mirror URL for astropy remote data site.astropyzDefault User-Agent for HTTP request headers. This can be overwritten for a particular call via http_headers option, where available. This only provides the default value when not set by https_headers.g      $@z2Time to wait for remote data queries (in seconds).z5astropy.coordinates.name_resolve.name_resolve_timeout)aliasesTz9If False, prevents any attempt to download from Internet.i   z%Block size for computing file hashes.z4Number of bytes of remote data to download per step.zzIf True, temporary download files created when the cache is inaccessible will be deleted at the end of the python session.N)r1   r2   r3   __doc___configZ
ConfigItemdataurldataurl_mirrordefault_http_user_agentremote_timeoutallow_internetcompute_hash_block_sizedownload_block_size"delete_temporary_downloads_at_exitr-   r-   r-   r.   r   U   sD   r   c                   @   s   e Zd ZdZdS )r$   a1  
    This warning indicates the standard cache directory is not accessible, with
    the first argument providing the warning message. If args[1] is present, it
    is a filename indicating the path to a temporary file that was created to
    store a remote data download in the absence of the cache.
    N)r1   r2   r3   r7   r-   r-   r-   r.   r$   {   s   r$   c                 C   s   t j| }|j dv S )z
    Test whether a string is a valid URL for :func:`download_file`.

    Parameters
    ----------
    string : str
        The string to test.

    Returns
    -------
    status : bool
        String is URL or not.

    )httphttpsftpZsftpZsshfile)urllibparseurlparseschemelower)stringurlr-   r-   r.   r      s    r   c                 C   s4   t j| t j|p2t j| t j|S r'   )ospathabspath
startswithrealpath)rM   parent_pathr-   r-   r.   
_is_inside   s    rR   FTc              
   c   s  g }g }|du rt j}t| tjr,t| } t| trt| }	|	rVt| |||||d} t	
| d}
|	rt|st||
 ||
 n| }
t|
dszt	|
 }
W n  ty   t	|
 }
Y n0 |
d}|
d |dd dkrVddl}z$ddl}|j|
d	d
}|d W n. tt|jfyB   |
d |  Y n0 |d |}
n|dd dkrJzddl}W n0 ty   |D ]}|  qtdY n0 zbtddd6}||
  |  |j|jd	d}W d   n1 s0    Y  |d W n& ty.   |
d |  Y n0 |d || |}
n|dd dkrz$ddl }|j!|
d	d}|d W nX ty   |D ]}|  qtdY n8 ttfy   |
d |  Y n0 |d |}
|dk}|rzddl}W n ty   Y nX0 t|
|jrntddd}|
 }|| |  || t	
|jd}
||
 t"|
}
t#|
|d}
|
d z6|
V  W |D ]}|  q|D ]}t$|j qn.|D ]}|  q|D ]}t$|j q0 dS )a  Yield a readable, seekable file-like object from a file or URL.

    This supports passing filenames, URLs, and readable file-like objects,
    any of which can be compressed in gzip, bzip2 or lzma (xz) if the
    appropriate compression libraries are provided by the Python installation.

    Notes
    -----

    This function is a context manager, and should be used for example
    as::

        with get_readable_fileobj('file.dat') as f:
            contents = f.read()

    If a URL is provided and the cache is in use, the provided URL will be the
    name used in the cache. The contents may already be stored in the cache
    under this URL provided, they may be downloaded from this URL, or they may
    be downloaded from one of the locations listed in ``sources``. See
    `~download_file` for details.

    Parameters
    ----------
    name_or_obj : str or file-like
        The filename of the file to access (if given as a string), or
        the file-like object to access.

        If a file-like object, it must be opened in binary mode.

    encoding : str, optional
        When `None` (default), returns a file-like object with a
        ``read`` method that returns `str` (``unicode``) objects, using
        `locale.getpreferredencoding` as an encoding.  This matches
        the default behavior of the built-in `open` when no ``mode``
        argument is provided.

        When ``'binary'``, returns a file-like object where its ``read``
        method returns `bytes` objects.

        When another string, it is the name of an encoding, and the
        file-like object's ``read`` method will return `str` (``unicode``)
        objects, decoded from binary using the given encoding.

    cache : bool or "update", optional
        Whether to cache the contents of remote URLs. If "update",
        check the remote URL for a new version but store the result
        in the cache.

    show_progress : bool, optional
        Whether to display a progress bar if the file is downloaded
        from a remote server.  Default is `True`.

    remote_timeout : float
        Timeout for remote requests in seconds (default is the configurable
        `astropy.utils.data.Conf.remote_timeout`).

    sources : list of str, optional
        If provided, a list of URLs to try to obtain the file from. The
        result will be stored under the original URL. The original URL
        will *not* be tried unless it is in this list; this is to prevent
        long waits for a primary server that is known to be inaccessible
        at the moment.

    http_headers : dict or None
        HTTP request headers to pass into ``urlopen`` if needed. (These headers
        are ignored if the protocol for the ``name_or_obj``/``sources`` entry
        is not a remote HTTP URL.) In the default case (None), the headers are
        ``User-Agent: some_value`` and ``Accept: */*``, where ``some_value``
        is set by ``astropy.utils.data.conf.default_http_user_agent``.

    Returns
    -------
    file : readable file-like
    N)cacheshow_progresstimeoutsourceshttp_headersrseek   r      s   rb)fileobjmode   s   BZhz9This Python installation does not provide the bz2 module.wbF)delete)r^   s   7zz:This Python installation does not provide the lzma module.Zbinaryencoding)%r   r<   
isinstancerL   PathLikefspathstr_is_urlr   ioFileIOappendhasattrBytesIOZread_binaryAttributeErrorreadrY   structgzipZGzipFileOSErrorEOFErrorerrorclosebz2ImportErrorModuleNotFoundErrorr   writeZBZ2FilenamelzmaZLZMAFiler&   r4   remove)Zname_or_objrc   rS   rT   r<   rV   rW   Z	close_fdsZ
delete_fdsr   r]   Z	signaturerp   rq   Zfileobj_newrv   fdtmpr{   Zneeds_textio_wrapperdatar-   r-   r.   r      s    V








0








r   c                  O   s:   t | i |}| W  d   S 1 s,0    Y  dS )z
    Retrieves the contents of a filename or file-like object.

    See  the `get_readable_fileobj` docstring for details on parameters.

    Returns
    -------
    object
        The content of the file (as requested by ``encoding``).
    N)r   ro   )argskwargsfr-   r-   r.   r#     s    r#   c                 c   s   t | |d}tj|r"tdntj|rbt||d}|V  W d   q1 sV0    Y  n`ttj|  ||tj|  tj	|  gd*}|
d |d |V  W d   n1 s0    Y  dS )a  
    Retrieves a data file from the standard locations for the package and
    provides the file as a file-like object that reads bytes.

    Parameters
    ----------
    data_name : str
        Name/location of the desired data file.  One of the following:

            * The name of a data file included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data/file.dat'`` to get the
              file in ``astropy/pkgname/data/file.dat``.  Double-dots
              can be used to go up a level.  In the same example, use
              ``'../data/file.dat'`` to get ``astropy/data/file.dat``.
            * If a matching local file does not exist, the Astropy
              data server will be queried for the file.
            * A hash like that produced by `compute_hash` can be
              requested, prefixed by 'hash/'
              e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'.  The hash
              will first be searched for locally, and if not found,
              the Astropy data server will be queried.

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.

    encoding : str, optional
        When `None` (default), returns a file-like object with a
        ``read`` method returns `str` (``unicode``) objects, using
        `locale.getpreferredencoding` as an encoding.  This matches
        the default behavior of the built-in `open` when no ``mode``
        argument is provided.

        When ``'binary'``, returns a file-like object where its ``read``
        method returns `bytes` objects.

        When another string, it is the name of an encoding, and the
        file-like object's ``read`` method will return `str` (``unicode``)
        objects, decoded from binary using the given encoding.

    cache : bool
        If True, the file will be downloaded and saved locally or the
        already-cached local copy will be accessed. If False, the
        file-like object will directly access the resource (e.g. if a
        remote URL is accessed, an object like that from
        `urllib.request.urlopen` is returned).

    Returns
    -------
    fileobj : file-like
        An object with the contents of the data file available via
        ``read`` function.  Can be used as part of a ``with`` statement,
        automatically closing itself after the ``with`` block.

    Raises
    ------
    urllib.error.URLError
        If a remote file cannot be found.
    OSError
        If problems occur writing or reading a local file.

    Examples
    --------

    This will retrieve a data file and its contents for the `astropy.wcs`
    tests::

        >>> from astropy.utils.data import get_pkg_data_fileobj
        >>> with get_pkg_data_fileobj('data/3d_cd.hdr',
        ...                           package='astropy.wcs.tests') as fobj:
        ...     fcontents = fobj.read()
        ...

    This next example would download a data file from the astropy data server
    because the ``allsky/allsky_rosat.fits`` file is not present in the
    source distribution.  It will also save the file locally so the
    next time it is accessed it won't need to be downloaded.::

        >>> from astropy.utils.data import get_pkg_data_fileobj
        >>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits',
        ...                           encoding='binary') as fobj:  # doctest: +REMOTE_DATA +IGNORE_OUTPUT
        ...     fcontents = fobj.read()
        ...
        Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]

    This does the same thing but does *not* cache it locally::

        >>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits',
        ...                           encoding='binary', cache=False) as fobj:  # doctest: +REMOTE_DATA +IGNORE_OUTPUT
        ...     fcontents = fobj.read()
        ...
        Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]

    See Also
    --------
    get_pkg_data_contents : returns the contents of a file or url as a bytes object
    get_pkg_data_filename : returns a local name for a file containing the data
    packageDTried to access a data file that's actually a package data directoryrb   N)rc   rS   rV   r_   r   )r   rL   rM   isdirrr   isfiler   r   r9   r:   ro   rY   )	data_namer   rc   rS   datafnr]   r-   r-   r.   r     s$    g
&

r   c                 C   s   |du rt j}| dr^t| dd }|du rXtt j|  d||t j|  t j|  gdS |S nftj	| }t
||d}tj|rtdn8tj|r|S tt j|  d||t j|  t j|  gdS dS )a  
    Retrieves a data file from the standard locations for the package and
    provides a local filename for the data.

    This function is similar to `get_pkg_data_fileobj` but returns the
    file *name* instead of a readable file-like object.  This means
    that this function must always cache remote files locally, unlike
    `get_pkg_data_fileobj`.

    Parameters
    ----------
    data_name : str
        Name/location of the desired data file.  One of the following:

            * The name of a data file included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data/file.dat'`` to get the
              file in ``astropy/pkgname/data/file.dat``.  Double-dots
              can be used to go up a level.  In the same example, use
              ``'../data/file.dat'`` to get ``astropy/data/file.dat``.
            * If a matching local file does not exist, the Astropy
              data server will be queried for the file.
            * A hash like that produced by `compute_hash` can be
              requested, prefixed by 'hash/'
              e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'.  The hash
              will first be searched for locally, and if not found,
              the Astropy data server will be queried.

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.

    show_progress : bool, optional
        Whether to display a progress bar if the file is downloaded
        from a remote server.  Default is `True`.

    remote_timeout : float
        Timeout for the requests in seconds (default is the
        configurable `astropy.utils.data.Conf.remote_timeout`).

    Raises
    ------
    urllib.error.URLError
        If a remote file cannot be found.
    OSError
        If problems occur writing or reading a local file.

    Returns
    -------
    filename : str
        A file path on the local file system corresponding to the data
        requested in ``data_name``.

    Examples
    --------

    This will retrieve the contents of the data file for the `astropy.wcs`
    tests::

        >>> from astropy.utils.data import get_pkg_data_filename
        >>> fn = get_pkg_data_filename('data/3d_cd.hdr',
        ...                            package='astropy.wcs.tests')
        >>> with open(fn) as f:
        ...     fcontents = f.read()
        ...

    This retrieves a data file by hash either locally or from the astropy data
    server::

        >>> from astropy.utils.data import get_pkg_data_filename
        >>> fn = get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28')  # doctest: +SKIP
        >>> with open(fn) as f:
        ...     fcontents = f.read()
        ...

    See Also
    --------
    get_pkg_data_contents : returns the contents of a file or url as a bytes object
    get_pkg_data_fileobj : returns a file-like object with the data
    Nzhash/   T)rS   rT   rU   rV   r   r   )r   r<   rO   _find_hash_fnr   r9   r:   rL   rM   normpathr   r   rr   r   )r   r   rT   r<   ZhashfnZfs_pathr   r-   r-   r.   r   "  s4    T

r   c                 C   s<   t | |||d}| }W d   n1 s.0    Y  |S )a
  
    Retrieves a data file from the standard locations and returns its
    contents as a bytes object.

    Parameters
    ----------
    data_name : str
        Name/location of the desired data file.  One of the following:

            * The name of a data file included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data/file.dat'`` to get the
              file in ``astropy/pkgname/data/file.dat``.  Double-dots
              can be used to go up a level.  In the same example, use
              ``'../data/file.dat'`` to get ``astropy/data/file.dat``.
            * If a matching local file does not exist, the Astropy
              data server will be queried for the file.
            * A hash like that produced by `compute_hash` can be
              requested, prefixed by 'hash/'
              e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'.  The hash
              will first be searched for locally, and if not found,
              the Astropy data server will be queried.
            * A URL to some other file.

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.


    encoding : str, optional
        When `None` (default), returns a file-like object with a
        ``read`` method that returns `str` (``unicode``) objects, using
        `locale.getpreferredencoding` as an encoding.  This matches
        the default behavior of the built-in `open` when no ``mode``
        argument is provided.

        When ``'binary'``, returns a file-like object where its ``read``
        method returns `bytes` objects.

        When another string, it is the name of an encoding, and the
        file-like object's ``read`` method will return `str` (``unicode``)
        objects, decoded from binary using the given encoding.

    cache : bool
        If True, the file will be downloaded and saved locally or the
        already-cached local copy will be accessed. If False, the
        file-like object will directly access the resource (e.g. if a
        remote URL is accessed, an object like that from
        `urllib.request.urlopen` is returned).

    Returns
    -------
    contents : bytes
        The complete contents of the file as a bytes object.

    Raises
    ------
    urllib.error.URLError
        If a remote file cannot be found.
    OSError
        If problems occur writing or reading a local file.

    See Also
    --------
    get_pkg_data_fileobj : returns a file-like object with the data
    get_pkg_data_filename : returns a local name for a file containing the data
    )r   rc   rS   N)r   ro   )r   r   rc   rS   r}   contentsr-   r-   r.   r     s    F&r   *c                 c   sh   t | |d}tj|r"tdnBtj|r\t|D ] }t||r8tj||V  q8ntddS )a  
    Returns the path of all of the data files in a given directory
    that match a given glob pattern.

    Parameters
    ----------
    datadir : str
        Name/location of the desired data files.  One of the following:

            * The name of a directory included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data'`` to get the
              files in ``astropy/pkgname/data``.
            * Remote URLs are not currently supported.

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.

    pattern : str, optional
        A UNIX-style filename glob pattern to match files.  See the
        `glob` module in the standard library for more information.
        By default, matches all files.

    Returns
    -------
    filenames : iterator of str
        Paths on the local filesystem in *datadir* matching *pattern*.

    Examples
    --------
    This will retrieve the contents of the data file for the `astropy.wcs`
    tests::

        >>> from astropy.utils.data import get_pkg_data_filenames
        >>> for fn in get_pkg_data_filenames('data/maps', 'astropy.wcs.tests',
        ...                                  '*.hdr'):
        ...     with open(fn) as f:
        ...         fcontents = f.read()
        ...
    r   zDTried to access a data directory that's actually a package data filezPath not foundN)	r   rL   rM   r   rr   r   listdirfnmatchjoin)datadirr   patternrM   filenamer-   r-   r.   r     s    ,r   c              	   c   sJ   t | ||dD ]6}t||d}|V  W d   q1 s:0    Y  qdS )a  
    Returns readable file objects for all of the data files in a given
    directory that match a given glob pattern.

    Parameters
    ----------
    datadir : str
        Name/location of the desired data files.  One of the following:

            * The name of a directory included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data'`` to get the
              files in ``astropy/pkgname/data``
            * Remote URLs are not currently supported

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.

    pattern : str, optional
        A UNIX-style filename glob pattern to match files.  See the
        `glob` module in the standard library for more information.
        By default, matches all files.

    encoding : str, optional
        When `None` (default), returns a file-like object with a
        ``read`` method that returns `str` (``unicode``) objects, using
        `locale.getpreferredencoding` as an encoding.  This matches
        the default behavior of the built-in `open` when no ``mode``
        argument is provided.

        When ``'binary'``, returns a file-like object where its ``read``
        method returns `bytes` objects.

        When another string, it is the name of an encoding, and the
        file-like object's ``read`` method will return `str` (``unicode``)
        objects, decoded from binary using the given encoding.

    Returns
    -------
    fileobjs : iterator of file object
        File objects for each of the files on the local filesystem in
        *datadir* matching *pattern*.

    Examples
    --------
    This will retrieve the contents of the data file for the `astropy.wcs`
    tests::

        >>> from astropy.utils.data import get_pkg_data_filenames
        >>> for fd in get_pkg_data_fileobjs('data/maps', 'astropy.wcs.tests',
        ...                                 '*.hdr'):
        ...     fcontents = fd.read()
        ...
    )r   r   rb   N)r   r   )r   r   r   rc   fnr}   r-   r-   r.   r     s
    :
r   c                 C   sb   t | d@}t }|tj}|r<|| |tj}q W d   n1 sP0    Y  | S )am   Computes the MD5 hash for a file.

    The hash for a data file is used for looking up data files in a unique
    fashion. This is of particular use for tests; a test may require a
    particular version of a particular file, in which case it can be accessed
    via hash to get the appropriate version.

    Typically, if you wish to write a test that requires a particular data
    file, you will want to submit that file to the astropy data servers, and
    use
    e.g. ``get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28')``,
    but with the hash for your file in place of the hash in the example.

    Parameters
    ----------
    localfn : str
        The path to the file for which the hash should be generated.

    Returns
    -------
    hash : str
        The hex digest of the cryptographic hash for the contents of the
        ``localfn`` file.
    r\   N)openhashlibmd5ro   r   r>   update	hexdigest)Zlocalfnr   hblockr-   r-   r.   r    [  s    
,r    r   c                 G   s   | du rht dddgd}|du r,tjj| S t|dr<|js`d|jv rX|jdd } qf|j} qp|j} nt| }tj	|j
}tjj|g|R  }| dd }t|}tj	|j
}t||std	| d
|S )a  Get path from source-included data directories.

    Parameters
    ----------
    *path : str
        Name/location of the desired data file/directory.
        May be a tuple of strings for ``os.path`` joining.

    package : str or None, optional, keyword-only
        If specified, look for a file relative to the given package, rather
        than the calling module's package.

    Returns
    -------
    path : str
        Name/location of the desired data file/directory.

    Raises
    ------
    ImportError
        Given package or module is not importable.
    RuntimeError
        If the local data file is outside of the package's tree.

    Nr_   zastropy.utils.data
contextlib)Zfinddiff__package__.r   z2attempted to get a local data file outside of the z tree.)r	   rL   rM   r   rl   r   r1   
rpartitionr
   dirname__file__	partitionrR   RuntimeError)r   rM   moduleZmodule_path	full_pathZrootpkgnameZrootpkgZroot_dirr-   r-   r.   r   ~  s(    


r   r5   c                 C   s,   t |d D ]}t|| kr|  S qdS )zs
    Looks for a local file by hash - returns file name if found and a valid
    file, otherwise returns None.
    pkgnameN)r   valuesr    )r   r   vr-   r-   r.   r     s    
r   c                 C   sV   t j| stdt| j}|rRddlm} |du r>|j	}|
||j	|}|S )aB  
    Given a path to a directory, returns the amount of free space
    on that filesystem.

    Parameters
    ----------
    path : str
        The path to a directory.

    unit : bool or `~astropy.units.Unit`
        Return the amount of free space as Quantity in the given unit,
        if provided. Default is `False` for backward-compatibility.

    Returns
    -------
    free_space : int or `~astropy.units.Quantity`
        The amount of free space on the partition that the directory is on.
        If ``unit=False``, it is returned as plain integer (in bytes).

    zECan only determine free space associated with directories, not files.r   )unitsT)rL   rM   r   rr   shutilZ
disk_usageZfreer5   r   ZbyteZQuantityto)rM   unitZ
free_spaceur-   r-   r.   r!     s    r!   c                 C   sP   t | t|ddd}||k rLddlm} td|  d|| d|| d	d
S )ax  
    Determines if a given directory has enough space to hold a file of
    a given size.

    Parameters
    ----------
    path : str
        The path to a directory.

    size : int or `~astropy.units.Quantity`
        A proposed filesize. If not a Quantity, assume it is in bytes.

    Raises
    ------
    OSError
        There is not enough room on the filesystem.
    r   F)r   r   )human_file_sizezNot enough free space in z to download a z file, only z leftN)r!   getattrastropy.utils.consoler   rr   )rM   sizeZspacer   r-   r-   r.   r"     s    
r"   c                   @   s   e Zd Zdd ZdS )_ftptlswrapperc                 C   s^   d| _ t | _| j| j| j| j | j| j	| j
 | j  d| j}| j| d S )Nr   /)ZbusyftplibZFTP_TLSrC   ZconnecthostportrU   ZloginuserpasswdZprot_pr   dirscwd)r,   Z_targetr-   r-   r.   init  s    

z_ftptlswrapper.initN)r1   r2   r3   r   r-   r-   r-   r.   r     s   r   c                   @   s   e Zd Zdd ZdS )_FTPTLSHandlerc              	   C   s   t ||||||ddS )NF)Z
persistent)r   )r,   r   r   r   r   r   rU   r-   r-   r.   connect_ftp  s    z_FTPTLSHandler.connect_ftpN)r1   r2   r3   r   r-   r-   r-   r.   r     s   r   c                 C   s   ddl }|rtdd |D ni }i }d|v rX||d|dd|ddd nd|v shd|v rptd	d
|vrtdurt |d
< |jf i |}|rd|_|j	|_
|r|jf i | tjj|d}| rtjt |}ntj|}|S )zT
    Helper for building a `urllib.request.build_opener` which handles TLS/SSL.
    r   Nc                 s   s   | ]
}|V  qd S r'   r-   ).0itr-   r-   r.   	<genexpr>      z#_build_urlopener.<locals>.<genexpr>certfilekeyfilepassword)r   r   r   z_passing 'keyfile' or 'password' in the ssl_context argument requires passing 'certfile' as wellZcafileF)context)ssldictr   pop
ValueErrorcertifiwhereZcreate_default_contextZcheck_hostnameZ	CERT_NONEZverify_modeZload_cert_chainrE   requestZHTTPSHandlerZbuild_openerr   )ftp_tlsssl_contextallow_insecurer   Z
cert_chainZhttps_handler	urlopenerr-   r-   r.   _build_urlopener  s4    


r   c              
   C   s   ddl }t|r| ng }t||dd}tjj| |d}z|j||dW S  tjj	y }	 z|	j
}
t|
|jr|
j
dkrd|  d	}|s|d
|
 7 }tj	|n:|d7 }t|t t||dd}|j||dW  Y d}	~	S  W Y d}	~	n
d}	~	0 0 dS )zDHelper for opening a URL while handling TLS/SSL verification issues.r   NF)r   r   r   )Zheaders)rU   ZCERTIFICATE_VERIFY_FAILEDz'Verification of TLS/SSL certificate at a   failed: this can mean either the server is misconfigured or your local root CA certificates are out-of-date; in the latter case this can usually be addressed by installing the Python package "certifi" (see the documentation for astropy.utils.data.download_url)z or in both cases you can work around this by passing allow_insecure=True, but only if you understand the implications; the original error was: z%. Re-trying with allow_insecure=True.T)r   	frozensetitemsr   rE   r   ZRequestr   rt   URLErrorreasonrd   ZSSLErrorr   r   )
source_urlrU   rW   r   r   r   r   r   Zreqexcr   msgr-   r-   r.   _try_url_openB  s4    
r   c
                 C   s  ddl m}
 tjs.tjd| dtj d|d u r:| }|d u rFi }|d u rtj|j	dkrzt
| ||||||ddW S  tjjy } z$t|jd	rd
}n W Y d }~n
d }~0 0 t| |||||	d$}| }zt|d }W n tttfy
   d }Y n0 |d ur:tt | |r:t|}t|| |rTtj rTtj}nt }| |krrd| }nd| d|  }|
|||dD}tdt  ddd}zd}|tj }|r&|!| |t"|7 }|#| |tj }|d ur||krtjd| d| dq|d urX||k rXtjj$d| d| dd dW nL t%y   tj&'|j(rzt)|j( W n t*y   Y n0  Y n0 W d    n1 s0    Y  W d    n1 s0    Y  W d    n1 s0    Y  |j(S )Nr   )ProgressBarOrSpinnerURL z5 was supposed to be downloaded but allow_internet is zP; if this is unexpected check the astropy.cfg file for the option allow_internetrC   F)rT   rU   
remote_urlrS   r   rW   r   zftp error: error_permT)rU   rW   r   r   r   zContent-LengthzDownloading z from )rD   zastropy-download--)prefixra   zFile was supposed to be z* bytes but server provides more, at least z bytes. Download failed.z bytes but we only got )Zcontent)+r   r   r   r=   rE   rt   r   rF   rG   rH   _download_file_from_sourcerg   r   rO   r   infointKeyErrorr   	TypeErrorr"   r   _get_download_cache_locsysstdoutisattyri   StringIOr   rL   getpidro   r?   ry   lenr   ZContentTooShortErrorBaseExceptionrM   existsrz   r|   rr   )r   rT   rU   r   rS   r   rW   r   r   r   r   eZremoter   r   dldirZprogress_streamZdlmsgpr   Z
bytes_readr   r-   r-   r.   r   m  s    






hr   c	                 C   s  |du rt j}|du r| g}|du r0t jdd}d}	| }
|rzt|}W n4 ty| } zd}d| d}	W Y d}~n\d}~0 0 |dkrnHt|trtd	| d
n,tj	
|t|
d}tj	|rtj	|S i }|D ]}z&t||||| ||||d	}W  qW q tjjy } zdt|drht|jdrh|jjdkrh|jjd |  |j_|jj|jjf|j_|||< W Y d}~qd}~0  tjy } z|||< W Y d}~qd}~0 0 q|std|  dn8t|dkr||d  ntjd| ||d  |r^zt|
|d|dk|dW S  ty\ } zd| d| d}	W Y d}~n
d}~0 0 |	rrtt|	| t jrt !| tj	|S )a  Downloads a URL and optionally caches the result.

    It returns the filename of a file containing the URL's contents.
    If ``cache=True`` and the file is present in the cache, just
    returns the filename; if the file had to be downloaded, add it
    to the cache. If ``cache="update"`` always download and add it
    to the cache.

    The cache is effectively a dictionary mapping URLs to files; by default the
    file contains the contents of the URL that is its key, but in practice
    these can be obtained from a mirror (using ``sources``) or imported from
    the local filesystem (using `~import_file_to_cache` or
    `~import_download_cache`).  Regardless, each file is regarded as
    representing the contents of a particular URL, and this URL should be used
    to look them up or otherwise manipulate them.

    The files in the cache directory are named according to a cryptographic
    hash of their URLs (currently MD5, so hackers can cause collisions).
    The modification times on these files normally indicate when they were
    last downloaded from the Internet.

    Parameters
    ----------
    remote_url : str
        The URL of the file to download

    cache : bool or "update", optional
        Whether to cache the contents of remote URLs. If "update",
        always download the remote URL in case there is a new version
        and store the result in the cache.

    show_progress : bool, optional
        Whether to display a progress bar during the download (default
        is `True`). Regardless of this setting, the progress bar is only
        displayed when outputting to a terminal.

    timeout : float, optional
        Timeout for remote requests in seconds (default is the configurable
        `astropy.utils.data.Conf.remote_timeout`).

    sources : list of str, optional
        If provided, a list of URLs to try to obtain the file from. The
        result will be stored under the original URL. The original URL
        will *not* be tried unless it is in this list; this is to prevent
        long waits for a primary server that is known to be inaccessible
        at the moment. If an empty list is passed, then ``download_file``
        will not attempt to connect to the Internet, that is, if the file
        is not in the cache a KeyError will be raised.

    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.

    http_headers : dict or None
        HTTP request headers to pass into ``urlopen`` if needed. (These headers
        are ignored if the protocol for the ``name_or_obj``/``sources`` entry
        is not a remote HTTP URL.) In the default case (None), the headers are
        ``User-Agent: some_value`` and ``Accept: */*``, where ``some_value``
        is set by ``astropy.utils.data.conf.default_http_user_agent``.

    ssl_context : dict, optional
        Keyword arguments to pass to `ssl.create_default_context` when
        downloading from HTTPS or TLS+FTP sources.  This can be used provide
        alternative paths to root CA certificates.  Additionally, if the key
        ``'certfile'`` and optionally ``'keyfile'`` and ``'password'`` are
        included, they are passed to `ssl.SSLContext.load_cert_chain`.  This
        can be used for performing SSL/TLS client certificate authentication
        for servers that require it.

    allow_insecure : bool, optional
        Allow downloading files over a TLS/SSL connection even when the server
        certificate verification failed.  When set to `True` the potentially
        insecure download is allowed to proceed, but an
        `~astropy.utils.exceptions.AstropyWarning` is issued.  If you are
        frequently getting certificate verification warnings, consider
        installing or upgrading `certifi`_ package, which provides frequently
        updated certificates for common root CAs (i.e., a set similar to those
        used by web browsers).  If installed, Astropy will use it
        automatically.

        .. _certifi: https://pypi.org/project/certifi/

    Returns
    -------
    local_path : str
        Returns the local path that the file was download to.

    Raises
    ------
    urllib.error.URLError
        Whenever there's a problem getting the remote file.
    KeyError
        When a file was requested from the cache but is missing and no
        sources were provided to obtain it from the Internet.

    Notes
    -----
    Because this function returns a filename, another process could run
    `clear_download_cache` before you actually open the file, leaving
    you with a filename that no longer points to a usable file.
    Nz*/*)z
User-AgentZAccept Fz+Cache directory cannot be read or created (z,), providing data in temporary file instead.r   zCache value 'zS' was requested but 'update' is the only recognized string; otherwise use a booleanr   )rU   rT   rS   r   r   rW   r   r   r   errno   z. requested URL: zNo sources listed and file ze not in cache! Please include primary URL in sources if you want it to be included as a valid source.r_   r   z+Unable to open any source! Exceptions were T)remove_originalreplacer   z)Cache directory appears to be read-only (zF), unable to import downloaded file, providing data in temporary file z	 instead.)"r   r<   r;   r   rr   rd   rg   r   rL   rM   r   _url_to_dirnamer   rN   r   rE   rt   r   rl   r   r   strerrorr   socketrU   r   r   r   PermissionErrorr   r$   r@   _tempfilestodelrk   )r   rS   rT   rU   rV   r   rW   r   r   Zmissing_cacheurl_keyr   r   r   errorsr   Zf_namer-   r-   r.   r     s    i



 


r   c                 C   sB   zt |}W n ty    Y dS 0 tj|t| d}tj|S )a.  Check if a download for ``url_key`` is in the cache.

    The provided ``url_key`` will be the name used in the cache. The contents
    may have been downloaded from this URL or from a mirror or they may have
    been provided by the user. See `~download_file` for details.

    Parameters
    ----------
    url_key : str
        The URL retrieved
    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.


    Returns
    -------
    in_cache : bool
        `True` if a download for ``url_key`` is in the cache, `False` if not
        or if the cache does not exist at all.

    See Also
    --------
    cache_contents : obtain a dictionary listing everything in the cache
    Fr   )r   rr   rL   rM   r   r   r   )r   r   r   r   r-   r-   r.   r     s    r   c                    sB   d}t | d}t|D ]$\ }}|t fdd|D 7 }q|S )z9Return the total size in bytes of all files in the cache.r   r   c                 3   s$   | ]}t jt j |V  qd S r'   )rL   rM   getsizer   )r   rz   rootr-   r.   r     r   z#cache_total_size.<locals>.<genexpr>)r   rL   walksum)r   r   r   r   filesr-   r   r.   r     s
    
r   c              	   C   s   t jj| d` t jj| d, tf i | W  d    W  d    S 1 s\0    Y  W d    n1 sz0    Y  d S )Ntemp_config
temp_cache)r5   r   pathsset_temp_configr   set_temp_cacher   )r   r-   r-   r.   _do_download_files_in_parallel  s    r	  r   c                    s   ddl m} du rtjdu r&i  s8tdt d |rDtj}nt	 }t
t| }	|jt fdd|	D |d|d	}
g }| D ]}||
|	|  q|S )
a
  Download multiple files in parallel from the given URLs.

    Blocks until all files have downloaded.  The result is a list of
    local file paths corresponding to the given urls.

    The results will be stored in the cache under the values in ``urls`` even
    if they are obtained from some other location via ``sources``. See
    `~download_file` for details.

    Parameters
    ----------
    urls : list of str
        The URLs to retrieve.

    cache : bool or "update", optional
        Whether to use the cache (default is `True`). If "update",
        always download the remote URLs to see if new data is available
        and store the result in cache.

        .. versionchanged:: 4.0
            The default was changed to ``"update"`` and setting it to
            ``False`` will print a Warning and set it to ``"update"`` again,
            because the function will not work properly without cache. Using
            ``True`` will work as expected.

        .. versionchanged:: 3.0
            The default was changed to ``True`` and setting it to ``False``
            will print a Warning and set it to ``True`` again, because the
            function will not work properly without cache.

    show_progress : bool, optional
        Whether to display a progress bar during the download (default
        is `True`)

    timeout : float, optional
        Timeout for each individual requests in seconds (default is the
        configurable `astropy.utils.data.Conf.remote_timeout`).

    sources : dict, optional
        If provided, for each URL a list of URLs to try to obtain the
        file from. The result will be stored under the original URL.
        For any URL in this dictionary, the original URL will *not* be
        tried unless it is in this list; this is to prevent long waits
        for a primary server that is known to be inaccessible at the
        moment.

    multiprocessing_start_method : str, optional
        Useful primarily for testing; if in doubt leave it as the default.
        When using multiprocessing, certain anomalies occur when starting
        processes with the "spawn" method (the only option on Windows);
        other anomalies occur with the "fork" method (the default on
        Linux).

    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.

    Returns
    -------
    paths : list of str
        The local file paths corresponding to the downloaded URLs.

    Notes
    -----
    If a URL is unreachable, the downloading will grind to a halt and the
    exception will propagate upward, but an unpredictable number of
    files will have been successfully downloaded and will remain in
    the cache.
    r_   )ProgressBarNzDisabling the cache does not work because of multiprocessing, it will be set to ``"update"``. You may need to manually remove the cached files with clear_download_cache() afterwards.r   c                    s<   g | ]4}t | d |dtjjjjtjjjjdqS )FN)r   rS   rT   rU   rV   r   r  r  )r   getr5   r   r  r  Z
_temp_pathr  )r   r   rS   r   rV   rU   r-   r.   
<listcomp>0  s   


z.download_files_in_parallel.<locals>.<listcomp>T)rD   Zmultiprocessmultiprocessing_start_method)Zconsoler
  r   r<   r   r   r   r   ri   rm   listsetmapr	  rk   index)urlsrS   rT   rU   rV   r  r   r
  ZprogressZcombined_urlsZcombined_pathsr  rK   r-   r  r.   r     s6    M	r   c                  C   s   t d ur|tt dkr|t  } tj| rLzt|  W qz tyH   Y qz0 qtj| rzt	
|  W q tyx   Y q0 qd S )Nr   )r   r   r   rL   rM   r   r|   rr   r   r   rmtree)r   r-   r-   r.   	_deltempsH  s    r  c              
   C   s  zt |}W n` tyl } zHd}t|jdk r2dn
dt| }tt||jj |  W Y d}~dS d}~0 0 z| du rt	| nt
| rtj|t| }t	| ntj|| }tj||}|drtd| d| tj|\}}	|r|	d	v rtj||}tj|r&t	| n@t| d
t j krftd| rft| }
|
durft|
 W nb ty } zHd}t|jdk rdn
dt| }tt||jj |  W Y d}~n
d}~0 0 dS )a  Clears the data file cache by deleting the local file(s).

    If a URL is provided, it will be the name used in the cache. The contents
    may have been downloaded from this URL or from a mirror or they may have
    been provided by the user. See `~download_file` for details.

    For the purposes of this function, a file can also be identified by a hash
    of its contents or by the filename under which the data is stored (as
    returned by `~download_file`, for example).

    Parameters
    ----------
    hashorurl : str or None
        If None, the whole cache is cleared.  Otherwise, specify
        a hash for the cached file that is supposed to be deleted,
        the full path to a file in the cache that should be deleted,
        or a URL that should be removed from the cache if present.

    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.
    z4Not clearing data cache - cache inaccessible due to r_   r   : Nz..z2attempted to use clear_download_cache on the path z" outside the data cache directory )r   rK      z	[0-9a-f]+z-Not clearing data from cache - problem arose )r   rr   r   r   rg   r   r$   	__class__r1   _rmtreerh   rL   rM   r   r   relpathrO   r   splitr   r   r   Zdigest_sizerematchr   r   )Z	hashorurlr   r   r   r   estrfilepathZrpdr   r   r-   r-   r.   r   `  sL    





 r   c              
   C   s   zzt jtjj| dd}t j|sZzt | W qv t	yV   t j|sR Y qv0 nt j
|svt	d| d|W S  t	y } zHd}t|jdk rdn
dt| }tt||jj |   W Y d	}~n
d	}~0 0 d	S )
a  Finds the path to the cache directory and makes them if they don't exist.

    Parameters
    ----------
    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.

    Returns
    -------
    datadir : str
        The path to the data cache directory.
    ZdownloadrK   zData cache directory z is not a directoryz/Remote data cache could not be accessed due to r_   r   r  N)rL   rM   r   r5   r   r  Zget_cache_dirr   makedirsrr   r   r   r   rg   r   r$   r  r1   )r   r   r   r   r  r-   r-   r.   r     s     
r   c                 C   s   t | std|  dttj| }|d  |d< |d  dv rd|d rd|d dkrdd|d< tj|}t	|
d	 S )
NzMalformed URL: ''r_   r   )rA   rB   r  r   r   utf-8)rh   r   r  rE   rF   ZurlsplitrI   Z
urlunsplitr   r   encoder   )rK   ZurlobjZurl_cr-   r-   r.   r     s    $r   c                   @   s   e Zd Zdd ZdS )ReadOnlyDictc                 C   s   t dd S )NzThis object is read-only.)r   )r,   keyvaluer-   r-   r.   __setitem__  s    zReadOnlyDict.__setitem__N)r1   r2   r3   r(  r-   r-   r-   r.   r%    s   r%  c                       s(   e Zd ZdZddd fdd
Z  ZS )r%   zRecord the URL or file that was a problem.
    Using clear_download_cache on the .bad_file or .bad_url attribute,
    whichever is not None, should resolve this particular problem.
    N)bad_urls	bad_filesc                   s:   t  j|i | |d ur|ng | _|d ur0|ng | _d S r'   )super__init__r)  r*  )r,   r)  r*  r   r   r  r-   r.   r,    s    zCacheDamaged.__init__)r1   r2   r3   r7   r,  __classcell__r-   r-   r-  r.   r%     s   r%   c              	   C   s"  t  }t  }t| d}t|}|D ]}tjtj||j}|jdrz|t	vrx|
| |
d|j d q(| rt|D ]6}|dv rqtj||}|
| |
d|  qtj|d}d}	tj|s|
| |
d	|  nht|d
d}	t|	s4|
| |
d|	  n6t|	}
|j|
krj|
| |
d|
 d|j  tjtj|ds|
| |	du r|
d|j d n|
d|	 d|j d q(|
| |
d| d q(W d   n1 s0    Y  |rtd||ddS )aI  Do a consistency check on the cache.

    .. note::

        Since v5.0, this function no longer returns anything.

    Because the cache is shared by all versions of ``astropy`` in all virtualenvs
    run by your user, possibly concurrently, it could accumulate problems.
    This could lead to hard-to-debug problems or wasted space. This function
    detects a number of incorrect conditions, including nonexistent files that
    are indexed, files that are indexed but in the wrong place, and, if you
    request it, files whose content does not match the hash that is indexed.

    This function also returns a list of non-indexed files. A few will be
    associated with the shelve object; their exact names depend on the backend
    used but will probably be based on ``urlmap``. The presence of other files
    probably indicates that something has gone wrong and inaccessible files
    have accumulated in the cache. These can be removed with
    :func:`clear_download_cache`, either passing the filename returned here, or
    with no arguments to empty the entire cache and return it to a
    reasonable, if empty, state.

    Parameters
    ----------
    pkgname : str, optional
        The package name to use to locate the download cache, i.e., for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.

    Raises
    ------
    `~astropy.utils.data.CacheDamaged`
        To indicate a problem with the cache contents; the exception contains
        a ``.bad_files`` attribute containing a set of filenames to allow the
        user to use :func:`clear_download_cache` to remove the offending items.
    OSError, RuntimeError
        To indicate some problem with the cache structure. This may need a full
        :func:`clear_download_cache` to resolve, or may indicate some kind of
        misconfiguration.
    r   rmtree-zCache entry z not scheduled for deletion)rK   r   zUnexpected file frK   NzProblem with URL file fr#  rb   zMalformed URL: zURL hashes to z but is stored in r   zHash z is missing contentsr   z with hash zLeft-over non-directory z	 in cache
)r*  )r  r   rL   scandirrM   rN   r   rz   rO   r   addis_dirr   r   r#   rh   r   r%   )r   r*  Zmessagesr   r   entryr   ZsfZurlfrK   Zhashnamer-   r-   r.   r     sN    )











4r   c                 c   sd   t | ||d}z,|V  W zt| W q` ty8   Y q`0 n$zt| W n ty\   Y n0 0 dS )av  Temporary directory context manager

    This will not raise an exception if the temporary directory goes away
    before it's supposed to be deleted. Specifically, what is deleted will
    be the directory *name* produced; if no such directory exists, no
    exception will be raised.

    It would be safer to delete it only if it's really the same directory
    - checked by file descriptor - and if it's still called the same thing.
    But that opens a platform-specific can of worms.

    It would also be more robust to use ExitStack and TemporaryDirectory,
    which is more aggressive about removing readonly things.
    )suffixr   dirN)r   r   r  rr   )r5  r   r6  r   r-   r-   r.   _SafeTemporaryDirectory=  s    r7  c                 C   s   t dtjtj| d}zt| tj|d W n: tyJ   Y n* tyr   t	t
d|  d|   Y n0 |durzt||  W nD ty   Y n4 ty } z|jtjkrn W Y d}~n
d}~0 0 W d   n1 s0    Y  dS )z.More-atomic rmtree. Ignores missing directory.r/  r   r6  zto-zapzUnable to remove directory z6 because a file in it is in use and you are on WindowsN)r   rL   rM   r   rN   renamer   FileNotFoundErrorr   r   r$   FileExistsErrorrr   r   	ENOTEMPTY)rM   r   r   r   r-   r-   r.   r  W  s.    
r  r   c                C   s<  t |d}t| }tj||}tj|d}td|d}	tj|	d}
t||
 ttj|	dddd}|	|  W d	   n1 s0    Y  |rt
||	d
 nVzt|	| W nD ty   Y n4 ty } z|jtjkrn W Y d	}~n
d	}~0 0 W d	   n1 s0    Y  |r0t| tj|S )ap  Import the on-disk file specified by filename to the cache.

    The provided ``url_key`` will be the name used in the cache. The file
    should contain the contents of this URL, at least notionally (the URL may
    be temporarily or permanently unavailable). It is using ``url_key`` that
    users will request these contents from the cache. See :func:`download_file` for
    details.

    If ``url_key`` already exists in the cache, it will be updated to point to
    these imported contents, and its old contents will be deleted from the
    cache.

    Parameters
    ----------
    url_key : str
        The key to index the file under. This should probably be
        the URL where the file was located, though if you obtained
        it from a mirror you should use the URL of the primary
        location.
    filename : str
        The file whose contents you want to import.
    remove_original : bool
        Whether to remove the original file (``filename``) once import is
        complete.
    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.
    replace : boolean, optional
        Whether or not to replace an existing object in the cache, if one exists.
        If replacement is not requested but the object exists, silently pass.
    r   r   temp_dirr8  rK   Zwtr#  rb   Nr=  )r   r   rL   rM   r   r7  r   copyr   ry   r  r9  r;  rr   r   r<  r|   rN   )r   r   r   r   r   Z	cache_dirZcache_dirnameZlocal_dirnameZlocal_filenamer>  Ztemp_filenamer   r   r-   r-   r.   r   r  s,    %
(8
r   c                 C   s   t t| d S )a  
    Get the list of URLs in the cache. Especially useful for looking up what
    files are stored in your cache when you don't have internet access.

    The listed URLs are the keys programs should use to access the file
    contents, but those contents may have actually been obtained from a mirror.
    See `~download_file` for details.

    Parameters
    ----------
    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.

    Returns
    -------
    cached_urls : list
        List of cached URLs.

    See Also
    --------
    cache_contents : obtain a dictionary listing everything in the cache
    r   )sortedr   keysr   r-   r-   r.   r     s    r   c              	   C   s   i }zt | d}W n ty(   t Y S 0 t|X}|D ]B}|jr:ttj||j	ddd}tj
tj||j	d||< q:W d   n1 s0    Y  t|S )a  Obtain a dict mapping cached URLs to filenames.

    This dictionary is a read-only snapshot of the state of the cache when this
    function was called. If other processes are actively working with the
    cache, it is possible for them to delete files that are listed in this
    dictionary. Use with some caution if you are working on a system that is
    busy with many running astropy processes, although the same issues apply to
    most functions in this module.
    r   rK   r#  rb   r   N)r   rr   _NOTHINGrL   r1  r3  r#   rM   r   rz   rN   r%  )r   rX   r   r   r4  rK   r-   r-   r.   r     s    

>r   c                 C   s~   |du rt |}t| |rdndF}|D ]0}t|dg |d}tjj|dd}||| q*W d   n1 sp0    Y  dS )a  Exports the cache contents as a ZIP file.

    Parameters
    ----------
    filename_or_obj : str or file-like
        Where to put the created ZIP file. Must be something the zipfile
        module can write to.
    urls : iterable of str or None
        The URLs to include in the exported cache. The default is all
        URLs currently in the cache. If a URL is included in this list
        but is not currently in the cache, a KeyError will be raised.
        To ensure that all are in the cache use `~download_file`
        or `~download_files_in_parallel`.
    overwrite : bool, optional
        If filename_or_obj is a filename that exists, it will only be
        overwritten if this is True.
    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.

    See Also
    --------
    import_download_cache : import the contents of such a ZIP file
    import_file_to_cache : import a single file directly
    NwxT)rS   rV   r   r   )Zsafe)r   zipfileZipFiler   rE   rF   Zquotery   )filename_or_objr  Z	overwriter   zr   r   Zz_fnr-   r-   r.   r     s    r   c                 C   sB  t | d}t }t| D ]\}}tj|j}|durL||vrLq$|s^t	||dr^q$t
j|t|}	||b}
t|	d8}|
tj}|r|| |
tj}qW d   n1 s0    Y  W d   n1 s0    Y  t||	d|d q$W d   n1 s0    Y  W d   n1 s40    Y  dS )a6  Imports the contents of a ZIP file into the cache.

    Each member of the ZIP file should be named by a quoted version of the
    URL whose contents it stores. These names are decoded with
    :func:`~urllib.parse.unquote`.

    Parameters
    ----------
    filename_or_obj : str or file-like
        Where the stored ZIP file is. Must be something the :mod:`~zipfile`
        module can read from.
    urls : set of str or list of str or None
        The URLs to import from the ZIP file. The default is all
        URLs in the file.
    update_cache : bool, optional
        If True, any entry in the ZIP file will overwrite the value in the
        cache; if False, leave untouched any entry already in the cache.
    pkgname : `str`, optional
        The package name to use to locate the download cache. i.e. for
        ``pkgname='astropy'`` the default cache location is
        ``~/.astropy/cache``.

    See Also
    --------
    export_download_cache : export the contents the cache to of such a ZIP file
    import_file_to_cache : import a single file directly
    rX   Nr   r`   T)r   r   )rE  rF  r   	enumerateZinfolistrE   rF   Zunquoter   r   rL   rM   r   rg   r   ro   r   r?   ry   r   )rG  r  Zupdate_cacher   rH  r   iZzfrK   Zf_temp_nameZf_zipZf_tempr   r-   r-   r.   r     s"    
Jr   )NFTNNN)NNT)NTN)NNT)Nr   )Nr   N)r5   )F)FNF)NNFNF)	TNNFr5   NNNF)FTNNr5   NNF)r5   )r5   )r   TNNNr5   )Nr5   )r5   )r5   )NNN)N)Fr5   )r5   )r5   )NFr5   )NFr5   )`r7   atexitr   r   r   	functoolsr   rL   ri   r  r   r   r   Zurllib.requestrE   Zurllib.errorZurllib.parserE  r   Ztempfiler   r   r   r   warningsr   r   rw   Zastropy.config.pathsr5   r   r8   Zastropy.utils.exceptionsr   Zastropy.utils.introspectionr	   r
   __all__Z_dataurls_to_aliasBufferedReaderr&   TextIOWrapperr4   ZConfigNamespacer   r   r$   r   rh   rR   contextmanagerr   r#   r   r   r   r   r   r    r   r   r!   r"   r   Z
ftpwrapperr   Z
FTPHandlerr   	lru_cacher   r   r   r   r   r   r	  r   r   registerr  r   r   r   r   r%  rB  r   r%   r   r7  r  r   r   r   r   r   r-   r-   r-   r.   <module>   s   


#		    p{  
t
L
9
@#>

%*  
+    
Z   
 O
#
	      
~

D
#
V
  C


&