o
    Q `e                     @   s  d Z ddlmZmZ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mZ ddlmZmZ ddlZddlZddlmZmZmZmZmZmZmZmZ ddlmZ dd	lmZ dd
l m!Z!m"Z"m#Z# ddl
m$Z$ ddlm%Z% ej&rddl'm'Z' ddl	m(Z( ddlm)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z> ddl?m@Z@ ddlAmBZB ddlmCZC ejDdddZEejDdddZFe+eFe4ge@eF f ZGdgZHdd ZIeJejKG dd deLZMdS )zPyFilesystem base class.

The filesystem base class is common to all filesystems. If you
familiarize yourself with this (rather straightforward) API, you
can work with any of the supported filesystems.

    )absolute_importprint_functionunicode_literalsN)closing)partialwraps   )copyerrorsfsencodeiotoolsmovetoolswalkwildcardBoundGlobber)validate_open_mode)abspathjoinnormpath)datetime_to_epoch)Walker)datetime)RLock)AnyBinaryIOCallable
CollectionDictIOIterableIteratorListMappingOptionalTextTupleTypeUnion)TracebackType)ResourceType)InfoRawInfoSubFS)Permissions)BoundWalker_FFS)Zbound_Tc                    sD   t   fdd}d j}t|dddur | j|7  _|S )z+Return a method with a deprecation warning.c                     s$   t d jt  | i |S )Nz6method '{}' has been deprecated, please rename to '{}')warningswarnformat__name__DeprecationWarning)argskwargsmethodold_name )/usr/lib/python3/dist-packages/fs/base.py_methodF   s   z_new_name.<locals>._methodzR
        Note:
            .. deprecated:: 2.2.0
                Please use `~{}`
__doc__N)r   r7   r8   getattrrB   )r=   r>   rA   Zdeprecated_msgr?   r<   r@   	_new_nameB   s   	rD   c                       s  e Zd ZdZi ZeZdZ fddZdd Z	dd Z
d	d
 Zedd Zedd ZejdddZejdd Zej		dddZej		dddZejdd Zejdd Zejdd Zd d! Z	"		#dd$d%Zd&d' Zdd(d)Zdd*d+Zdd,d-Zd.d/ Zd0d1 Z						dd2d3Z d4d5 Z!e"e!d6Z#dd7d8Z$e"e$d9Z%			#dd:d;Z&e"e&d<Z'dd>d?Z(d@dA Z)dBdC Z*dDdE Z+dFdG Z,ddIdJZ-dKdL Z.ddMdNZ/dOdP Z0dQdR Z1dSdT Z2dUdV Z3dWdX Z4dYdZ Z5dd[d\Z6		dd]d^Z7dd_d`Z8					#ddadbZ9	ddcddZ:dedf Z;		ddgdhZ<didj Z=e"e=dkZ>ddldmZ?e"e?dnZ@			#ddodpZAe"eAdqZBddrdsZC	"		#ddtduZDe"eDdvZEdwdx ZFdydz ZGd{d| ZHd}d~ ZIdd ZJdd ZKdd ZLdd ZM  ZNS )r3   zBase class for FS objects.
    Nc                    s"   d| _ t | _tt|   dS )zJCreate a filesystem. See help(type(self)) for accurate signature.
        FN)_closed	threadingr   _locksuperr3   __init__self	__class__r?   r@   rI   k   s   
zFS.__init__c                 C      |    dS )z"Auto-close the filesystem on exit.NcloserJ   r?   r?   r@   __del__s   s   z
FS.__del__c                 C   s   | S )z6Allow use of filesystem as a context manager.
        r?   rJ   r?   r?   r@   	__enter__w   s   zFS.__enter__c                 C   rN   )z"Close filesystem on exit.
        NrO   )rK   exc_type	exc_value	tracebackr?   r?   r@   __exit__}   s   	zFS.__exit__c                 C   s   t | S )z4`~fs.glob.BoundGlobber`: a globber object..
        r   rJ   r?   r?   r@   glob   s   zFS.globc                 C   s   | j | S )zC`~fs.walk.BoundWalker`: a walker bound to this filesystem.
        )walker_classZbindrJ   r?   r?   r@   r      s   zFS.walkc                 C      dS )a  Get information about a resource on a filesystem.

        Arguments:
            path (str): A path to a resource on the filesystem.
            namespaces (list, optional): Info namespaces to query
                (defaults to *[basic]*).

        Returns:
            ~fs.info.Info: resource information object.

        For more information regarding resource information, see :ref:`info`.

        Nr?   )rK   path
namespacesr?   r?   r@   getinfo       z
FS.getinfoc                 C   rY   )a0  Get a list of the resource names in a directory.

        This method will return a list of the resources in a directory.
        A *resource* is a file, directory, or one of the other types
        defined in `~fs.enums.ResourceType`.

        Arguments:
            path (str): A path to a directory on the filesystem

        Returns:
            list: list of names, relative to ``path``.

        Raises:
            fs.errors.DirectoryExpected: If ``path`` is not a directory.
            fs.errors.ResourceNotFound: If ``path`` does not exist.

        Nr?   rK   rZ   r?   r?   r@   listdir   r]   z
FS.listdirFc                 C   rY   )ah  Make a directory.

        Arguments:
            path (str): Path to directory from root.
            permissions (~fs.permissions.Permissions, optional): a
                `Permissions` instance, or `None` to use default.
            recreate (bool): Set to `True` to avoid raising an error if
                the directory already exists (defaults to `False`).

        Returns:
            ~fs.subfs.SubFS: a filesystem whose root is the new directory.

        Raises:
            fs.errors.DirectoryExists: If the path already exists.
            fs.errors.ResourceNotFound: If the path is not found.

        Nr?   )rK   rZ   permissionsrecreater?   r?   r@   makedir   r]   z
FS.makedirrc                 K   rY   )a  Open a binary file-like object.

        Arguments:
            path (str): A path on the filesystem.
            mode (str): Mode to open file (must be a valid non-text mode,
                defaults to *r*). Since this method only opens binary files,
                the ``b`` in the mode string is implied.
            buffering (int): Buffering policy (-1 to use default buffering,
                0 to disable buffering, or any positive integer to indicate
                a buffer size).
            **options: keyword arguments for any additional information
                required by the filesystem (if any).

        Returns:
            io.IOBase: a *file-like* object.

        Raises:
            fs.errors.FileExpected: If the path is not a file.
            fs.errors.FileExists: If the file exists, and *exclusive mode*
                is specified (``x`` in the mode).
            fs.errors.ResourceNotFound: If the path does not exist.

        Nr?   )rK   rZ   mode	bufferingoptionsr?   r?   r@   openbin   r]   z
FS.openbinc                 C   rY   )a	  Remove a file from the filesystem.

        Arguments:
            path (str): Path of the file to remove.

        Raises:
            fs.errors.FileExpected: If the path is a directory.
            fs.errors.ResourceNotFound: If the path does not exist.

        Nr?   r^   r?   r?   r@   remove   r]   z	FS.removec                 C   rY   )a  Remove a directory from the filesystem.

        Arguments:
            path (str): Path of the directory to remove.

        Raises:
            fs.errors.DirectoryNotEmpty: If the directory is not empty (
                see `~fs.base.FS.removetree` for a way to remove the
                directory contents.).
            fs.errors.DirectoryExpected: If the path does not refer to
                a directory.
            fs.errors.ResourceNotFound: If no resource exists at the
                given path.
            fs.errors.RemoveRootError: If an attempt is made to remove
                the root directory (i.e. ``'/'``)

        Nr?   r^   r?   r?   r@   	removedir	  r]   zFS.removedirc                 C   rY   )a  Set info on a resource.

        This method is the complement to `~fs.base.FS.getinfo`
        and is used to set info values on a resource.

        Arguments:
            path (str): Path to a resource on the filesystem.
            info (dict): Dictionary of resource info.

        Raises:
            fs.errors.ResourceNotFound: If ``path`` does not exist
                on the filesystem

        The ``info`` dict should be in the same format as the raw
        info returned by ``getinfo(file).raw``.

        Example:
            >>> details_info = {"details": {
            ...     "modified": time.time()
            ... }}
            >>> my_fs.setinfo('file.txt', details_info)

        Nr?   )rK   rZ   infor?   r?   r@   setinfo  r]   z
FS.setinfoc              	   C   s   t |ts	td| j, | |d}|| W d   n1 s#w   Y  W d   dS W d   dS 1 s;w   Y  dS )ac  Append bytes to the end of a file, creating it if needed.

        Arguments:
            path (str): Path to a file.
            data (bytes): Bytes to append.

        Raises:
            TypeError: If ``data`` is not a `bytes` instance.
            fs.errors.ResourceNotFound: If a parent directory of
                ``path`` does not exist.

        zmust be bytesabN)
isinstancebytes	TypeErrorrG   openwrite)rK   rZ   dataappend_filer?   r?   r@   appendbytes>  s   
"zFS.appendbytesutf-8 c              	   C   s   t |tjs
td| j0 | j|d|||d}|| W d   n1 s(w   Y  W d   dS W d   dS 1 s@w   Y  dS )a_  Append text to the end of a file, creating it if needed.

        Arguments:
            path (str): Path to a file.
            text (str): Text to append.
            encoding (str): Encoding for text files (defaults to ``utf-8``).
            errors (str, optional): What to do with unicode decode errors
                (see `codecs` module for more information).
            newline (str): Newline parameter.

        Raises:
            TypeError: if ``text`` is not an unicode string.
            fs.errors.ResourceNotFound: if a parent directory of
                ``path`` does not exist.

        zmust be unicode stringZat)encodingr
   newlineN)rn   six	text_typerp   rG   rq   rr   )rK   rZ   textrx   r
   ry   rt   r?   r?   r@   
appendtextS  s   
"zFS.appendtextc                 C   s
   d| _ dS )a  Close the filesystem and release any resources.

        It is important to call this method when you have finished
        working with the filesystem. Some filesystems may not finalize
        changes until they are closed (archives for example). You may
        call this method explicitly (it is safe to call close multiple
        times), or you can use the filesystem as a context manager to
        automatically close.

        Example:
            >>> with OSFS('~/Desktop') as desktop_fs:
            ...    desktop_fs.writetext(
            ...        'note.txt',
            ...        "Don't forget to tape Game of Thrones"
            ...    )

        If you attempt to use a filesystem that has been closed, a
        `~fs.errors.FilesystemClosed` exception will be thrown.

        TN)rE   rJ   r?   r?   r@   rP   t  s   
zFS.closec              	   C   s   | j ; |s| |rt|t| |d}| || W d   n1 s)w   Y  W d   dS W d   dS 1 sAw   Y  dS )a$  Copy file contents from ``src_path`` to ``dst_path``.

        Arguments:
            src_path (str): Path of source file.
            dst_path (str): Path to destination file.
            overwrite (bool): If `True`, overwrite the destination file
                if it exists (defaults to `False`).

        Raises:
            fs.errors.DestinationExists: If ``dst_path`` exists,
                and ``overwrite`` is `False`.
            fs.errors.ResourceNotFound: If a parent directory of
                ``dst_path`` does not exist.

        rbN)rG   existsr
   DestinationExistsr   rq   upload)rK   src_pathdst_path	overwrite	read_filer?   r?   r@   r	     s   
"zFS.copyc                 C   sj   | j ( |s| |st|| |jst|t| || | W d   dS 1 s.w   Y  dS )a  Copy the contents of ``src_path`` to ``dst_path``.

        Arguments:
            src_path (str): Path of source directory.
            dst_path (str): Path to destination directory.
            create (bool): If `True`, then ``dst_path`` will be created
                if it doesn't exist already (defaults to `False`).

        Raises:
            fs.errors.ResourceNotFound: If the ``dst_path``
                does not exist, and ``create`` is not `True`.

        N)	rG   r   r
   ResourceNotFoundr\   is_dirDirectoryExpectedr	   Zcopy_dirrK   r   r   creater?   r?   r@   copydir  s   

"z
FS.copydirc              	   C   s~   | j 2 |s| |r	 W d   dS t| |d W d   n1 s'w   Y  	 W d   dS 1 s8w   Y  dS )a  Create an empty file.

        The default behavior is to create a new file if one doesn't
        already exist. If ``wipe`` is `True`, any existing file will
        be truncated.

        Arguments:
            path (str): Path to a new file in the filesystem.
            wipe (bool): If `True`, truncate any existing
                file to 0 bytes (defaults to `False`).

        Returns:
            bool: `True` if a new file had to be created.

        NFwbT)rG   r   r   rq   )rK   rZ   Zwiper?   r?   r@   r     s   $z	FS.createc              	   C   sL   |  |s
t|z| |}W |S  tjtjfy%   d||  Y S w )zReturn a short descriptive text regarding a path.

        Arguments:
            path (str): A path to a resource on the filesystem.

        Returns:
            str: a short description of the path.

        z{} on {})r   r
   r   
getsyspath	NoSysPathr7   )rK   rZ   syspathr?   r?   r@   desc  s   

zFS.descc                 C   s(   z|  | W dS  tjy   Y dS w )zCheck if a path maps to a resource.

        Arguments:
            path (str): Path to a resource.

        Returns:
            bool: `True` if a resource exists at the given path.

        FT)r\   r
   r   r^   r?   r?   r@   r     s   z	FS.existsc                    s   j ||d}g  fdd}	fdd}
fdd}fdd	}|r+ t|
| |r5 t|	| |r? t|| |rI t||  rT fd
d|D }t|}|durg|\}}t|||}|S )a  Get an iterator of resource info, filtered by patterns.

        This method enhances `~fs.base.FS.scandir` with additional
        filtering functionality.

        Arguments:
            path (str): A path to a directory on the filesystem.
            files (list, optional): A list of UNIX shell-style patterns
                to filter file names, e.g. ``['*.py']``.
            dirs (list, optional): A list of UNIX shell-style patterns
                to filter directory names.
            exclude_dirs (list, optional): A list of patterns used
                to exclude directories.
            exclude_files (list, optional): A list of patterns used
                to exclude files.
            namespaces (list, optional): A list of namespaces to include
                in the resource information, e.g. ``['basic', 'access']``.
            page (tuple, optional): May be a tuple of ``(<start>, <end>)``
                indexes to return an iterator of a subset of the resource
                info, or `None` to iterate over the entire directory.
                Paging a directory scan may be necessary for very large
                directories.

        Returns:
            ~collections.abc.Iterator: an iterator of `Info` objects.

        r[   c                       |j p	 | |jS z%Pattern match info.name.
            is_filematchnamepatternsrk   rJ   r?   r@   	match_dir!     zFS.filterdir.<locals>.match_dirc                    r   r   r   r   r   r   rJ   r?   r@   
match_file'  r   z FS.filterdir.<locals>.match_filec                       |j p
 | |j S r   r   r   rJ   r?   r@   exclude_dir-     z!FS.filterdir.<locals>.exclude_dirc                    r   r   r   r   rJ   r?   r@   exclude_file3  r   z"FS.filterdir.<locals>.exclude_filec                 3   s*    | ] t  fd dD r V  qdS )c                 3   s    | ]}| V  qd S Nr?   ).0Z_filterrk   r?   r@   	<genexpr>D  s    z)FS.filterdir.<locals>.<genexpr>.<genexpr>N)all)r   )filtersr   r@   r   C  s    
zFS.filterdir.<locals>.<genexpr>N)scandirappendr   iter	itertoolsislice)rK   rZ   filesdirsZexclude_dirsZexclude_filesr[   pageZ	resourcesr   r   r   r   	iter_infostartendr?   )r   rK   r@   	filterdir  s.   &
zFS.filterdirc                 C   s@   t | j|dd}| }W d   |S 1 sw   Y  |S )a  Get the contents of a file as bytes.

        Arguments:
            path (str): A path to a readable file on the filesystem.

        Returns:
            bytes: the file contents.

        Raises:
            fs.errors.ResourceNotFound: if ``path`` does not exist.

        r~   re   Nr   rq   read)rK   rZ   r   contentsr?   r?   r@   	readbytesM  s   

zFS.readbytesgetbytesc              	   K   s~   | j 2 | j|fi |}tj|||d W d   n1 s w   Y  W d   dS W d   dS 1 s8w   Y  dS )a  Copies a file from the filesystem to a file-like object.

        This may be more efficient that opening and copying files
        manually if the filesystem supplies an optimized method.

        Arguments:
            path (str): Path to a resource.
            file (file-like): A file-like object open for writing in
                binary mode.
            chunk_size (int, optional): Number of bytes to read at a
                time, if a simple copy is used, or `None` to use
                sensible default.
            **options: Implementation specific options required to open
                the source file.

        Note that the file object ``file`` will *not* be closed by this
        method. Take care to close it after this method completes
        (ideally with a context manager).

        Example:
            >>> with open('starwars.mov', 'wb') as write_file:
            ...     my_fs.download('/movies/starwars.mov', write_file)

        
chunk_sizeNrG   rh   r   copy_file_data)rK   rZ   filer   rg   r   r?   r?   r@   downloada  s   "zFS.downloadgetfilec                 C   sF   t | j|d|||d}| }W d   |S 1 sw   Y  |S )a  Get the contents of a file as a string.

        Arguments:
            path (str): A path to a readable file on the filesystem.
            encoding (str, optional): Encoding to use when reading contents
                in text mode (defaults to `None`, reading in binary mode).
            errors (str, optional): Unicode errors parameter.
            newline (str): Newlines parameter.

        Returns:
            str: file contents.

        Raises:
            fs.errors.ResourceNotFound: If ``path`` does not exist.

        Zrtre   rx   r
   ry   Nr   )rK   rZ   rx   r
   ry   r   r   r?   r?   r@   readtext  s   


zFS.readtextgettextstandardc                 C   s   |dkr| j  }|S i }|S )aj  Get meta information regarding a filesystem.

        Arguments:
            namespace (str): The meta namespace (defaults
                to ``"standard"``).

        Returns:
            dict: the meta information.

        Meta information is associated with a *namespace* which may be
        specified with the ``namespace`` parameter. The default namespace,
        ``"standard"``, contains common information regarding the
        filesystem's capabilities. Some filesystems may provide other
        namespaces which expose less common or implementation specific
        information. If a requested namespace is not supported by
        a filesystem, then an empty dictionary will be returned.

        The ``"standard"`` namespace supports the following keys:

        =================== ============================================
        key                 Description
        ------------------- --------------------------------------------
        case_insensitive    `True` if this filesystem is case
                            insensitive.
        invalid_path_chars  A string containing the characters that
                            may not be used on this filesystem.
        max_path_length     Maximum number of characters permitted in
                            a path, or `None` for no limit.
        max_sys_path_length Maximum number of characters permitted in
                            a sys path, or `None` for no limit.
        network             `True` if this filesystem requires a
                            network.
        read_only           `True` if this filesystem is read only.
        supports_rename     `True` if this filesystem supports an
                            `os.rename` operation.
        =================== ============================================

        Most builtin filesystems will provide all these keys, and third-
        party filesystems should do so whenever possible, but a key may
        not be present if there is no way to know the value.

        Note:
            Meta information is constant for the lifetime of the
            filesystem, and may be cached.

        r   )_metar	   )rK   	namespacemetar?   r?   r@   getmeta  s
   0
z
FS.getmetac                 C      |  |j}|S )a  Get the size (in bytes) of a resource.

        Arguments:
            path (str): A path to a resource.

        Returns:
            int: the *size* of the resource.

        The *size* of a file is the total number of readable bytes,
        which may not reflect the exact number of bytes of reserved
        disk space (or other storage medium).

        The size of a directory is the number of bytes of overhead
        use to store the directory entry.

        )
getdetailssize)rK   rZ   r   r?   r?   r@   getsize  s   z
FS.getsizec                 C   s   t j|d)a  Get the *system path* of a resource.

        Parameters:
            path (str): A path on the filesystem.

        Returns:
            str: the *system path* of the resource, if any.

        Raises:
            fs.errors.NoSysPath: If there is no corresponding system path.

        A system path is one recognized by the OS, that may be used
        outside of PyFilesystem (in an application or a shell for
        example). This method will get the corresponding system path
        that would be referenced by ``path``.

        Not all filesystems have associated system paths. Network and
        memory based filesystems, for example, may not physically store
        data anywhere the OS knows about. It is also possible for some
        paths to have a system path, whereas others don't.

        This method will always return a str on Py3.* and unicode
        on Py2.7. See `~getospath` if you need to encode the path as
        bytes.

        If ``path`` doesn't have a system path, a `~fs.errors.NoSysPath`
        exception will be thrown.

        Note:
            A filesystem may return a system path even if no
            resource is referenced by that path -- as long as it can
            be certain what that system path would be.

        rZ   )r
   r   r^   r?   r?   r@   r     s   $zFS.getsyspathc                 C   s   |  |}t|}|S )as  Get a *system path* to a resource, encoded in the operating
        system's prefered encoding.

        Parameters:
            path (str): A path on the filesystem.

        Returns:
            str: the *system path* of the resource, if any.

        Raises:
            fs.errors.NoSysPath: If there is no corresponding system path.

        This method takes the output of `~getsyspath` and encodes it to
        the filesystem's prefered encoding. In Python3 this step is
        not required, as the `os` module will do it automatically. In
        Python2.7, the encoding step is required to support filenames
        on the filesystem that don't encode correctly.

        Note:
            If you want your code to work in Python2.7 and Python3 then
            use this method if you want to work will the OS filesystem
            outside of the OSFS interface.

        )r   r   )rK   rZ   r   Zospathr?   r?   r@   	getospath  s   
zFS.getospathc                 C   r   )a\  Get the type of a resource.

        Parameters:
            path (str): A path on the filesystem.

        Returns:
            ~fs.enums.ResourceType: the type of the resource.

        A type of a resource is an integer that identifies the what
        the resource references. The standard type integers may be one
        of the values in the `~fs.enums.ResourceType` enumerations.

        The most common resource types, supported by virtually all
        filesystems are ``directory`` (1) and ``file`` (2), but the
        following types are also possible:

        ===================   ======
        ResourceType          value
        -------------------   ------
        unknown               0
        directory             1
        file                  2
        character             3
        block_special_file    4
        fifo                  5
        socket                6
        symlink               7
        ===================   ======

        Standard resource types are positive integers, negative values
        are reserved for implementation specific resource types.

        )r   type)rK   rZ   Zresource_typer?   r?   r@   gettype2  s   #z
FS.gettyper   c                 C   s   t ||)a5  Get the URL to a given resource.

        Parameters:
            path (str): A path on the filesystem
            purpose (str): A short string that indicates which URL
                to retrieve for the given path (if there is more than
                one). The default is ``'download'``, which should return
                a URL that serves the file. Other filesystems may support
                other values for ``purpose``.

        Returns:
            str: a URL.

        Raises:
            fs.errors.NoURL: If the path does not map to a URL.

        )r
   NoURL)rK   rZ   purposer?   r?   r@   geturlX  s   z	FS.geturlc                 C   s0   d}z|  | W |S  tjy   d}Y |S w )zCheck if a path maps to a system path.

        Parameters:
            path (str): A path on the filesystem.

        Returns:
            bool: `True` if the resource at ``path`` has a *syspath*.

        TF)r   r
   r   )rK   rZ   Zhas_sys_pathr?   r?   r@   
hassyspathm  s   zFS.hassyspathc                 C   s4   d}z
| j ||d W |S  tjy   d}Y |S w )a.  Check if a path has a corresponding URL.

        Parameters:
            path (str): A path on the filesystem.
            purpose (str): A purpose parameter, as given in
                `~fs.base.FS.geturl`.

        Returns:
            bool: `True` if an URL for the given purpose exists.

        T)r   F)r   r
   r   )rK   rZ   r   Zhas_urlr?   r?   r@   hasurl  s   z	FS.hasurlc                 C   s   t | ddS )z+Check if the filesystem is closed.
        rE   F)rC   rJ   r?   r?   r@   isclosed  s   zFS.isclosedc                 C   s&   z|  |jW S  tjy   Y dS w )zCheck if a path maps to an existing directory.

        Parameters:
            path (str): A path on the filesystem.

        Returns:
            bool: `True` if ``path`` maps to a directory.

        Fr\   r   r
   r   r^   r?   r?   r@   isdir  s
   zFS.isdirc                 C   s   t t| |ddu S )a  Check if a directory is empty.

        A directory is considered empty when it does not contain
        any file or any directory.

        Parameters:
            path (str): A path to a directory on the filesystem.

        Returns:
            bool: `True` if the directory is empty.

        Raises:
            errors.DirectoryExpected: If ``path`` is not a directory.
            errors.ResourceNotFound: If ``path`` does not exist.

        N)nextr   r   r^   r?   r?   r@   isempty  s   z
FS.isemptyc                 C   s(   z|  |j W S  tjy   Y dS w )zCheck if a path maps to an existing file.

        Parameters:
            path (str): A path on the filesystem.

        Returns:
            bool: `True` if ``path`` maps to a file.

        Fr   r^   r?   r?   r@   isfile  s
   z	FS.isfilec                 C   s   |  | dS )zCheck if a path maps to a symlink.

        Parameters:
            path (str): A path on the filesystem.

        Returns:
            bool: `True` if ``path`` maps to a symlink.

        Fr\   r^   r?   r?   r@   islink  s   
z	FS.islinkc                 C   s   | j S )aN  Get a context manager that *locks* the filesystem.

        Locking a filesystem gives a thread exclusive access to it.
        Other threads will block until the threads with the lock has
        left the context manager.

        Returns:
            threading.RLock: a lock specific to the filesystem instance.

        Example:
            >>> with my_fs.lock():  # May block
            ...    # code here has exclusive access to the filesystem

        It is a good idea to put a lock around any operations that you
        would like to be *atomic*. For instance if you are copying
        files, and you don't want another thread to delete or modify
        anything while the copy is in progress.

        Locking with this method is only required for code that calls
        multiple filesystem methods. Individual methods are thread safe
        already, and don't need to be locked.

        Note:
            This only locks at the Python level. There is nothing to
            prevent other processes from modifying the filesystem
            outside of the filesystem instance.

        )rG   rJ   r?   r?   r@   lock  s   zFS.lockc                 C   sT   | j  |s| |st|t| || | W d   dS 1 s#w   Y  dS )a  Move directory ``src_path`` to ``dst_path``.

        Parameters:
            src_path (str): Path of source directory on the filesystem.
            dst_path (str): Path to destination directory.
            create (bool): If `True`, then ``dst_path`` will be created
                if it doesn't exist already (defaults to `False`).

        Raises:
            fs.errors.ResourceNotFound: if ``dst_path`` does not exist,
                and ``create`` is `False`.

        N)rG   r   r
   r   r   Zmove_dirr   r?   r?   r@   movedir  s
   
"z
FS.movedirc              
   C   s   |    | jE t| |}|D ]}z	| j||d W q tjy(   |s& Y qw z	| j||d W n tjy?   |s= Y nw | |W  d   S 1 sOw   Y  dS )a  Make a directory, and any missing intermediate directories.

        Arguments:
            path (str): Path to directory from root.
            permissions (~fs.permissions.Permissions, optional): Initial
                permissions, or `None` to use defaults.
            recreate (bool):  If `False` (the default), attempting to
                create an existing directory will raise an error. Set
                to `True` to ignore existing directories.

        Returns:
            ~fs.subfs.SubFS: A sub-directory filesystem.

        Raises:
            fs.errors.DirectoryExists: if the path is already
                a directory, and ``recreate`` is `False`.
            fs.errors.DirectoryExpected: if one of the ancestors
                in the path is not a directory.

        )r`   N)checkrG   r   Zget_intermediate_dirsrb   r
   ZDirectoryExistsopendir)rK   rZ   r`   ra   Z	dir_pathsdir_pathr?   r?   r@   makedirs  s(   $zFS.makedirsc              	   C   s   |s|  |rt|| |jrt||  ddrIz| |}| |}W n
 tj	y5   Y nw z	t
|| W dS  tyH   Y nw | j* | |d}| || W d   n1 sdw   Y  | | W d   dS 1 syw   Y  dS )a  Move a file from ``src_path`` to ``dst_path``.

        Arguments:
            src_path (str): A path on the filesystem to move.
            dst_path (str): A path on the filesystem where the source
                file will be written to.
            overwrite (bool): If `True`, destination path will be
                overwritten if it exists.

        Raises:
            fs.errors.FileExpected: If ``src_path`` maps to a
                directory instead of a file.
            fs.errors.DestinationExists: If ``dst_path`` exists,
                and ``overwrite`` is `False`.
            fs.errors.ResourceNotFound: If a parent directory of
                ``dst_path`` does not exist.

        Zsupports_renameFNr~   )r   r
   r   r\   r   ZFileExpectedr   getr   r   osrenameOSErrorrG   rq   r   ri   )rK   r   r   r   Zsrc_sys_pathZdst_sys_pathr   r?   r?   r@   r   :  s.   


"zFS.movec                 K   sL   t | |dd}| j|||d}	tj||	f|||pd||d|}
|
S )a  Open a file.

        Arguments:
            path (str): A path to a file on the filesystem.
            mode (str): Mode to open the file object with
                (defaults to *r*).
            buffering (int): Buffering policy (-1 to use
                default buffering, 0 to disable buffering, 1 to select
                line buffering, of any positive integer to indicate
                a buffer size).
            encoding (str): Encoding for text files (defaults to
                ``utf-8``)
            errors (str, optional): What to do with unicode decode errors
                (see `codecs` module for more information).
            newline (str): Newline parameter.
            **options: keyword arguments for any additional information
                required by the filesystem (if any).

        Returns:
            io.IOBase: a *file-like* object.

        Raises:
            fs.errors.FileExpected: If the path is not a file.
            fs.errors.FileExists: If the file exists, and *exclusive mode*
                is specified (``x`` in the mode).
            fs.errors.ResourceNotFound: If the path does not exist.

        trw   )re   rf   rv   )re   rf   rx   r
   ry   )r   replacerh   r   Zmake_stream)rK   rZ   re   rf   rx   r
   ry   rg   Zbin_modeZbin_fileZ	io_streamr?   r?   r@   rq   e  s    '
zFS.openc                 C   s<   ddl m} |p| jp|}| |jstj|d|| |S )a  Get a filesystem object for a sub-directory.

        Arguments:
            path (str): Path to a directory on the filesystem.
            factory (callable, optional): A callable that when invoked
                with an FS instance and ``path`` will return a new FS object
                representing the sub-directory contents. If no ``factory``
                is supplied then `~fs.subfs_class` will be used.

        Returns:
            ~fs.subfs.SubFS: A filesystem representing a sub-directory.

        Raises:
            fs.errors.DirectoryExpected: If ``dst_path`` does not
                exist or is not a directory.

        r   r.   r   )subfsr/   subfs_classgetbasicr   r
   r   )rK   rZ   factoryr/   Z_factoryr?   r?   r@   r     s
   
z
FS.opendirc                 C   s   t t|}| j; tjdd}|| |}|D ]\}}|jr%| | q| | q|dkr<| | W d   dS W d   dS 1 sGw   Y  dS )a  Recursively remove the contents of a directory.

        This method is similar to `~fs.base.removedir`, but will
        remove the contents of the directory if it is not empty.

        Arguments:
            dir_path (str): Path to a directory on the filesystem.

        depth)search/N)	r   r   rG   r   r   rk   r   rj   ri   )rK   r   Z	_dir_pathZwalkerZgen_info_pathrk   r?   r?   r@   
removetree  s   "zFS.removetreec                    sZ   pdt t|  fdd|D }t|}|dur+|\}}t|||}|S )aJ  Get an iterator of resource info.

        Arguments:
            path (str): A path to a directory on the filesystem.
            namespaces (list, optional): A list of namespaces to include
                in the resource information, e.g. ``['basic', 'access']``.
            page (tuple, optional): May be a tuple of ``(<start>, <end>)``
                indexes to return an iterator of a subset of the resource
                info, or `None` to iterate over the entire directory.
                Paging a directory scan may be necessary for very large
                directories.

        Returns:
            ~collections.abc.Iterator: an iterator of `Info` objects.

        Raises:
            fs.errors.DirectoryExpected: If ``path`` is not a directory.
            fs.errors.ResourceNotFound: If ``path`` does not exist.

        r?   c                 3   s$    | ]}j t |d V  qdS )r   N)r\   r   )r   r   r   r[   rK   r?   r@   r     s
    
zFS.scandir.<locals>.<genexpr>N)r   r   r_   r   r   r   )rK   rZ   r[   r   rk   r   r   r   r?   r   r@   r     s   z
FS.scandirc                 C   sT   t |ts	tdt| j|dd}|| W d   dS 1 s#w   Y  dS )zCopy binary data to a file.

        Arguments:
            path (str): Destination path on the filesystem.
            contents (bytes): Data to be written.

        Raises:
            TypeError: if contents is not bytes.

        zcontents must be bytesr   r   N)rn   ro   rp   r   rq   rr   )rK   rZ   r   
write_filer?   r?   r@   
writebytes  s
   
"zFS.writebytessetbytesc              	   K   s   | j 4 | j|fddi|}tj|||d W d   n1 s"w   Y  W d   dS W d   dS 1 s:w   Y  dS )a  Set a file to the contents of a binary file object.

        This method copies bytes from an open binary file to a file on
        the filesystem. If the destination exists, it will first be
        truncated.

        Arguments:
            path (str): A path on the filesystem.
            file (io.IOBase): a file object open for reading in
                binary mode.
            chunk_size (int, optional): Number of bytes to read at a
                time, if a simple copy is used, or `None` to use
                sensible default.
            **options: Implementation specific options required to open
                the source file.

        Note that the file object ``file`` will *not* be closed by this
        method. Take care to close it after this method completes
        (ideally with a context manager).

        Example:
            >>> with open('~/movies/starwars.mov', 'rb') as read_file:
            ...     my_fs.upload('starwars.mov', read_file)

        re   r   r   Nr   )rK   rZ   r   r   rg   dst_filer?   r?   r@   r     s   "z	FS.upload
setbinfilec              	   C   s   |du rdnd}| j 1 | j|||||d}t|| W d   n1 s'w   Y  W d   dS W d   dS 1 s?w   Y  dS )a*  Set a file to the contents of a file object.

        Arguments:
            path (str): A path on the filesystem.
            file (io.IOBase): A file object open for reading.
            encoding (str, optional): Encoding of destination file,
                defaults to `None` for binary.
            errors (str, optional): How encoding errors should be treated
                (same as `io.open`).
            newline (str): Newline parameter (same as `io.open`).

        This method is similar to `~FS.upload`, in that it copies data from a
        file-like object to a resource on the filesystem, but unlike ``upload``,
        this method also supports creating files in text-mode (if the ``encoding``
        argument is supplied).

        Note that the file object ``file`` will *not* be closed by this
        method. Take care to close it after this method completes
        (ideally with a context manager).

        Example:
            >>> with open('myfile.txt') as read_file:
            ...     my_fs.writefile('myfile.txt', read_file)

        Nr   wtr   )rG   rq   r   r   )rK   rZ   r   rx   r
   ry   re   r   r?   r?   r@   	writefile/  s   "
"zFS.writefilesetfilec                 C   sT   i }d|i}|du rt   nt||d< |du r|d nt||d< | || dS )a  Set the accessed and modified time on a resource.

        Arguments:
            path: A path to a resource on the filesystem.
            accessed (datetime, optional): The accessed time, or
                `None` (the default) to use the current time.
            modified (datetime, optional): The modified time, or
                `None` (the default) to use the same time as the
                ``accessed`` parameter.

        detailsNaccessedmodified)timer   rl   )rK   rZ   r   r   r   raw_infor?   r?   r@   settimes[  s   zFS.settimesc                 C   s\   t |tjs
tdt| j|d|||d}|| W d   dS 1 s'w   Y  dS )a  Create or replace a file with text.

        Arguments:
            path (str): Destination path on the filesystem.
            contents (str): Text to be written.
            encoding (str, optional): Encoding of destination file
                (defaults to ``'utf-8'``).
            errors (str, optional): How encoding errors should be treated
                (same as `io.open`).
            newline (str): Newline parameter (same as `io.open`).

        Raises:
            TypeError: if ``contents`` is not a unicode string.

        zcontents must be unicoder   r   N)rn   rz   r{   rp   r   rq   rr   )rK   rZ   r   rx   r
   ry   r   r?   r?   r@   	writetextu  s   
"zFS.writetextsettextc                 C   sh   | j ' t }| |s"d||di}| || W d   dS W d   dS 1 s-w   Y  dS )a[  Touch a file on the filesystem.

        Touching a file means creating a new file if ``path`` doesn't
        exist, or update accessed and modified times if the path does
        exist. This method is similar to the linux command of the same
        name.

        Arguments:
            path (str): A path to a file on the filesystem.

        r   )r   r   N)rG   r   r   rl   )rK   rZ   Znowr   r?   r?   r@   touch  s   
"zFS.touchc                 C   s   |    t|trttjrdd|  }ttj	|
d}|r/t||r/t|tt|
dd}|dkrdz| |}W n
 tjyN   Y nw t||krdd}|j|d}tj||dtt|}|S )	a  Check if a path is valid, returning a normalized absolute
        path.

        Many filesystems have restrictions on the format of paths they
        support. This method will check that ``path`` is valid on the
        underlaying storage mechanism and throw a
        `~fs.errors.InvalidPath` exception if it is not.

        Arguments:
            path (str): A path.

        Returns:
            str: A normalized, absolute path.

        Raises:
            fs.errors.InvalidCharsInPath: If the path contains
                invalid characters.
            fs.errors.InvalidPath: If the path is invalid.
            fs.errors.FilesystemClosed: if the filesystem
                is closed.

        zpaths must be unicode (not str)zpaths must be str (not bytes)Zinvalid_path_charsmax_sys_path_lengthrd   z6path too long (max {max_chars} characters in sys path))Z	max_chars)msg)r   rn   ro   rp   rz   ZPY2r   typingcastr{   r   setintersectionr
   ZInvalidCharsInPathintr   r   lenr7   ZInvalidPathr   r   )rK   rZ   r   Zinvalid_charsr  Zsys_pathZ_msgr  r?   r?   r@   validatepath  s4   

zFS.validatepathc                 C      | j |dgdS )a/  Get the *basic* resource info.

        This method is shorthand for the following::

            fs.getinfo(path, namespaces=['basic'])

        Arguments:
            path (str): A path on the filesystem.

        Returns:
            ~fs.info.Info: Resource information object for ``path``.

        Zbasicr   r   r^   r?   r?   r@   r        zFS.getbasicc                 C   r  )a3  Get the *details* resource info.

        This method is shorthand for the following::

            fs.getinfo(path, namespaces=['details'])

        Arguments:
            path (str): A path on the filesystem.

        Returns:
            ~fs.info.Info: Resource information object for ``path``.

        r   r   r   r^   r?   r?   r@   r     r  zFS.getdetailsc                 C   s   |   rt dS )zCheck if a filesystem may be used.

        Raises:
            fs.errors.FilesystemClosed: if the filesystem is closed.

        N)r   r
   ZFilesystemClosedrJ   r?   r?   r@   r     s   zFS.checkc                 C   sN   |du rdS t |tjrtdtt|  dd }t	
||}||S )az  Check if a name matches any of a list of wildcards.

        Arguments:
            patterns (list): A list of patterns, e.g. ``['*.py']``
            name (str): A file or directory name (not a path)

        Returns:
            bool: `True` if ``name`` matches any of the patterns.

        If a filesystem is case *insensitive* (such as Windows) then
        this method will perform a case insensitive match (i.e. ``*.py``
        will match the same names as ``*.PY``). Otherwise the match will
        be case sensitive (``*.py`` and ``*.PY`` will match different
        names).

        Example:
            >>> home_fs.match(['*.py'], '__init__.py')
            True
            >>> home_fs.match(['*.jpg', '*.png'], 'foo.gif')
            False

        Note:
            If ``patterns`` is `None` (or ``['*']``), then this
            method will always return `True`.

        NTz#patterns must be a list or sequenceZcase_insensitiveF)rn   rz   r{   rp   r  r  boolr   r   r   Zget_matcher)rK   r   r   Zcase_sensitiveZmatcherr?   r?   r@   r     s   zFS.matchc                 K   s    ddl m} || fi | dS )a  Render a tree view of the filesystem to stdout or a file.

        The parameters are passed to :func:`~fs.tree.render`.

        Keyword Arguments:
            path (str): The path of the directory to start rendering
                from (defaults to root folder, i.e. ``'/'``).
            file (io.IOBase): An open file-like object to render the
                tree, or `None` for stdout.
            encoding (str): Unicode encoding, or `None` to
                auto-detect.
            max_levels (int): Maximum number of levels to
                display, or `None` for no maximum.
            with_color (bool): Enable terminal color output,
                or `None` to auto-detect terminal.
            dirs_first (bool): Show directories first.
            exclude (list): Option list of directory patterns
                to exclude from the tree render.
            filter (list): Optional list of files patterns to
                match in the tree render.

        r   )renderN)treer  )rK   r;   r  r?   r?   r@   r  9  s   zFS.treec                 C   s   |  | zt|}W n ty   td|w | |}	 |d}|s+n|	| q#W d   |
 S 1 s>w   Y  |
 S )a{  Get the hash of a file's contents.

        Arguments:
            path(str): A path on the filesystem.
            name(str):
                One of the algorithms supported by the hashlib module, e.g. `"md5"`

        Returns:
            str: The hex digest of the hash.

        Raises:
            fs.errors.UnsupportedHash: If the requested hash is not supported.

        zhash '{}' is not supportedTi   N)r  hashlibnew
ValueErrorr
   ZUnsupportedHashr7   rh   r   updateZ	hexdigest)rK   rZ   r   Zhash_objectbinary_filechunkr?   r?   r@   hashU  s$   



zFS.hashr   )NF)rc   rd   )rv   Nrw   )F)NNNNNN)NNrw   )r   )r   )rc   rd   NNrw   )NN)Or8   
__module____qualname__rB   r   r   rX   r   rI   rQ   rR   rV   propertyrW   r   abcabstractmethodr\   r_   rb   rh   ri   rj   rl   ru   r}   rP   r	   r   r   r   r   r   r   rD   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rq   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r   r   r   r   r  r  __classcell__r?   r?   rL   r@   r3   ]   s    


 



!



U




 
6&
&

 

+.
9
 
(




*


!;&)NrB   Z
__future__r   r   r   r  r  r   r   rF   r   r  
contextlibr   	functoolsr   r   r5   rz   rw   r	   r
   r   r   r   r   r   r   rW   r   re   r   rZ   r   r   r   r   r   ZTYPE_CHECKINGr   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   typesr*   Zenumsr+   rk   r,   r-   r   r/   r`   r0   r1   TypeVarr2   r4   Z_OpendirFactory__all__rD   Zadd_metaclassABCMetaobjectr3   r?   r?   r?   r@   <module>   sH    (D
