o
    h )                    @  s"  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
 d dlmZ d dlmZ d dlmZmZ ddlmZ dd	lmZmZ d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" e#dZ$dd Z%G dd de&Z'G dd de'dZ(G dd dej)Z*dd Z+dS )    )annotationsN)ESPIPE)	has_magic)sha256)AnyClassVar   )DEFAULT_CALLBACK)apply_configconf)DirCache)Transaction)_unstrip_protocolglob_translate
isfilelikeother_paths
read_blockstringify_pathtokenizefsspecc                 C  s   | |i |S N clsargskwargsr   r   _/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/fsspec/spec.pymake_instance    s   r   c                      s,   e Zd ZdZ fddZ fddZ  ZS )_Cacheda  
    Metaclass for caching file system instances.

    Notes
    -----
    Instances are cached according to

    * The values of the class attributes listed in `_extra_tokenize_attributes`
    * The arguments passed to ``__init__``.

    This creates an additional reference to the filesystem, which prevents the
    filesystem from being garbage collected when all *user* references go away.
    A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also*
    be made for a filesystem instance to be garbage collected.
    c                   s<   t  j|i | tdrt | _ni | _t | _	d S )Nweakref_instance_cache)
super__init__r   getweakrefWeakValueDictionary_cacheosgetpid_pidr   	__class__r   r   r!   5   s
   
z_Cached.__init__c                   s   t  |}t fdd jD }t  jt g||R i |}|dd}t	  jkr: j
  t	  _|sL jrL| j
v rL| _ j
| S t j|i |}||_||_||_|jrn|jrnddlm} ||  jr{|s{| _| j
|< |S )Nc                 3  s    | ]	}t  |d V  qd S r   getattr).0attrr   r   r   	<genexpr>C   s    
z#_Cached.__call__.<locals>.<genexpr>skip_instance_cacheFr   )mirror_sync_methods)r
   tuple_extra_tokenize_attributesr   r(   	threading	get_identpopr&   r'   r%   clearcachable_latestr    __call__
_fs_token_storage_argsstorage_options
async_implr2   asyn)r   r   r   extra_tokenstokenskipobjr2   r)   r/   r   r;   A   s>   





z_Cached.__call__)__name__
__module____qualname____doc__r!   r;   __classcell__r   r   r)   r   r   $   s    r   c                   @  s  e Zd ZU dZdZdZdZdZdZde	d< d	Z
dZdZd
ZeZdZde	d< de	d< dd Zedd Zedd Zdd Zdd Zdd Zdd Zedd Zdd#d$Zed%d& Zed'd( Zed)d* Zd+d, Z d-d. Z!dd/d0Z"dd1d2Z#dd3d4Z$d5d6 Z%dd7d8Z&d9d: Z'dd<d=Z(dd>d?Z)dd@dAZ*ddBdCZ+dDdE Z,dFdG Z-dHdI Z.dJdK Z/dLdM Z0dNdO Z1dPdQ Z2dRdS Z3ddTdUZ4		ddVdWZ5ddXdYZ6dd[d\Z7dd]d^Z8	"dd_d`Z9ddbdcZ:e;d	fdddeZ<de;d	fdfdgZ=e;dZfdhdiZ>de;d	fdjdkZ?ddmdnZ@ddodpZAdqdr ZB		ddsdtZCddudvZDddwdxZEdydz ZFd{d| ZGdd}d~ZHedd ZI						dddZJ							dddZKdddZLdd ZMdddZNdddddZOedddZPdddddZQedddZRdd ZSdddZTedd ZUdd ZVdd ZW					
			ddddZXdddZYdd ZZdddZ[dddZ\dddZ]dd Z^dd Z_dd Z`dddZaddĄ ZbdddƄZcdddȄZddddʄZeddd̈́Zfddτ Zgd	S )AbstractFileSystemz
    An abstract super-class for pythonic file-systems

    Implementations are expected to be compatible with or, better, subclass
    from here.
    TFi  @ /abstractzClassVar[str | tuple[str, ...]]protocolN r   ztuple[Any, ...]r=   dict[str, Any]r>   c                 O  sl   | j rdS d| _ d| _d| _g | _tdi || _|ddr%tdt	 |ddr1tdt	 d| _
dS )	a  Create and configure file-system instance

        Instances may be cachable, so if similar enough arguments are seen
        a new instance is not required. The token attribute exists to allow
        implementations to cache instances if they wish.

        A reasonable default should be provided if there are no arguments.

        Subclasses should call this method.

        Parameters
        ----------
        use_listings_cache, listings_expiry_time, max_paths:
            passed to ``DirCache``, if the implementation supports
            directory listing caching. Pass use_listings_cache=False
            to disable such caching.
        skip_instance_cache: bool
            If this is a cachable implementation, pass True here to force
            creating a new instance even if a matching instance exists, and prevent
            storing this instance.
        asynchronous: bool
        loop: asyncio-compatible IOLoop or None
        NTFadd_docsz add_docs is no longer supported.add_aliaseszadd_aliases has been removed.r   )_cached_intrans_transaction"_invalidated_caches_in_transactionr   dircacher7   warningswarnFutureWarningr<   )selfr   r>   r   r   r   r!   {   s   
zAbstractFileSystem.__init__c                 C     t )zbPersistent filesystem id that can be used to compare filesystems
        across sessions.
        NotImplementedErrorrZ   r   r   r   fsid      zAbstractFileSystem.fsidc                 C     | j S r   )r<   r^   r   r   r   	_fs_token      zAbstractFileSystem._fs_tokenc                 C  ra   r   )rb   r^   r   r   r   __dask_tokenize__   s   z$AbstractFileSystem.__dask_tokenize__c                 C  s   t | jdS )N   )intrb   r^   r   r   r   __hash__      zAbstractFileSystem.__hash__c                 C  s   t |t| o| j|jkS r   )
isinstancetyperb   rZ   otherr   r   r   __eq__   s   zAbstractFileSystem.__eq__c                 C  s   t t| | j| jffS r   )r   rj   r=   r>   r^   r   r   r   
__reduce__   s   zAbstractFileSystem.__reduce__c                   s   t |tr fdd|D S t|}t  jtr jfn j}|D ]%}||d r5|t|d d }q!||d rF|t|d d }q!|d}|pP jS )	zTurn path from fully-qualified to file-system-specific

        May require FS-specific handling, e.g., for relative paths or links.
        c                      g | ]}  |qS r   _strip_protocolr-   pr/   r   r   
<listcomp>       z6AbstractFileSystem._strip_protocol.<locals>.<listcomp>://   Nz::   rK   )	ri   listr   rM   str
startswithlenrstriproot_marker)r   pathprotosrM   r   r/   r   rq      s   


z"AbstractFileSystem._strip_protocolnamerz   returnc                 C  sN   t | jtr
| jfn| j}|D ]}|| dr|  S q|d  d| S )z6Format FS-specific path to generic, including protocolrv   r   )ri   rM   rz   r{   )rZ   r   r   rM   r   r   r   unstrip_protocol   s   z#AbstractFileSystem.unstrip_protocolc                 C  s   i S )af  If kwargs can be encoded in the paths, extract them here

        This should happen before instantiation of the class; incoming paths
        then should be amended to strip the options in methods.

        Examples may look like an sftp path "sftp://user@host:/my/path", where
        the user and host should become kwargs and later get stripped.
        r   r   r   r   r   _get_kwargs_from_urls   s   z(AbstractFileSystem._get_kwargs_from_urlsc                 C  s   | j | jv r| j| j  S |  S )zReturn the most recently instantiated FileSystem

        If no instance has been created, then create one with defaults
        )r:   r%   r/   r   r   r   current   s   zAbstractFileSystem.currentc                 C  s   | j du r| | | _ | j S )zA context within which files are committed together upon exit

        Requires the file class to implement `.commit()` and `.discard()`
        for the normal and exception cases.
        N)rT   transaction_typer^   r   r   r   transaction   s   
zAbstractFileSystem.transactionc                 C  s   d| _ | | | _| jS )z@Begin write transaction for deferring files, non-context versionT)rS   r   rT   r   r^   r   r   r   start_transaction   s   z$AbstractFileSystem.start_transactionc                 C  s4   | j   d| _| jD ]}| | q| j  dS )z-Finish write transaction, non-context versionN)r   completerT   rU   invalidate_cacher8   rZ   r   r   r   r   end_transaction   s
   

z"AbstractFileSystem.end_transactionc                 C  s   | j r| j| dS dS )z
        Discard any cached directory information

        Parameters
        ----------
        path: string or None
            If None, clear all listings cached else listings at or under given
            path.
        N)rS   rU   appendr   r   r   r   r     s   z#AbstractFileSystem.invalidate_cachec                 K     dS )a  
        Create directory entry at path

        For systems that don't have true directories, may create an for
        this instance only and not touch the real filesystem

        Parameters
        ----------
        path: str
            location
        create_parents: bool
            if True, this is equivalent to ``makedirs``
        kwargs:
            may be permissions, etc.
        Nr   rZ   r   create_parentsr   r   r   r   mkdir  s   zAbstractFileSystem.mkdirc                 C  r   )a  Recursively make directories

        Creates directory at path and any intervening required directories.
        Raises exception if, for instance, the path already exists but is a
        file.

        Parameters
        ----------
        path: str
            leaf directory name
        exist_ok: bool (False)
            If False, will error if the target already exists
        Nr   rZ   r   exist_okr   r   r   makedirs*  s   zAbstractFileSystem.makedirsc                 C  r   )zRemove a directory, if emptyNr   r   r   r   r   rmdir:     zAbstractFileSystem.rmdirc                 K  r[   )ap  List objects at path.

        This should include subdirectories and files at that location. The
        difference between a file and a directory must be clear when details
        are requested.

        The specific keys, or perhaps a FileInfo class, or similar, is TBD,
        but must be consistent across implementations.
        Must include:

        - full path to the entry (without protocol)
        - size of the entry, in bytes. If the value cannot be determined, will
          be ``None``.
        - type of entry, "file", "directory" or other

        Additional information
        may be present, appropriate to the file-system, e.g., generation,
        checksum, etc.

        May use refresh=True|False to allow use of self._ls_from_cache to
        check for a saved listing and avoid calling the backend. This would be
        common where listing may be expensive.

        Parameters
        ----------
        path: str
        detail: bool
            if True, gives a list of dictionaries, where each is the same as
            the result of ``info(path)``. If False, gives a list of paths
            (str).
        kwargs: may have additional backend-specific options, such as version
            information

        Returns
        -------
        List of strings if detail is False, or list of directory information
        dicts if detail is True.
        r\   rZ   r   detailr   r   r   r   ls>  s   'zAbstractFileSystem.lsc                   sx   |   }z	| j d W S  ty   Y nw z fdd| j| D }t|dkr/t |W S  ty;   Y dS w )zCheck cache for listing

        Returns listing, if found (may be empty list for a directly that exists
        but contains nothing), None if not in cache.
        rK   c                   s:   g | ]}|d   ks|d    dkr|d dkr|qS )r   rK   rj   	directoryr}   )r-   fr   r   r   rt   s  s    z5AbstractFileSystem._ls_from_cache.<locals>.<listcomp>r   N)_parentrV   r}   KeyErrorr|   FileNotFoundError)rZ   r   parentfilesr   r   r   _ls_from_cacheg  s    

z!AbstractFileSystem._ls_from_cacheomitc              
   k  s   |dur|dk rt d| |}i }i }i }|dd}	z| j|fddi|}
W n" ttfyM } z|dkr: t|rB|| W Y d}~dS d}~ww |
D ]1}|d d	}|d	dd
 }|d dkrt||krt|||< |||< qP||kr}||d< qP|||< qP|	st	|}t	|}|r|||fV  |dur|d8 }|dk r|s|||fV  dS |D ]}| j
|| f||	|d|E dH  q|s|||fV  dS dS )a  Return all files under the given path.

        List all files, recursing into subdirectories; output is iterator-style,
        like ``os.walk()``. For a simple list of files, ``find()`` is available.

        When topdown is True, the caller can modify the dirnames list in-place (perhaps
        using del or slice assignment), and walk() will
        only recurse into the subdirectories whose names remain in dirnames;
        this can be used to prune the search, impose a specific order of visiting,
        or even to inform walk() about directories the caller creates or renames before
        it resumes walk() again.
        Modifying dirnames when topdown is False has no effect. (see os.walk)

        Note that the "files" outputted will include anything that is not
        a directory, such as links.

        Parameters
        ----------
        path: str
            Root to recurse into
        maxdepth: int
            Maximum recursion depth. None means limitless, but not recommended
            on link-based file-systems.
        topdown: bool (True)
            Whether to walk the directory tree from the top downwards or from
            the bottom upwards.
        on_error: "omit", "raise", a callable
            if omit (default), path with exception will simply be empty;
            If raise, an underlying exception will be raised;
            if callable, it will be called with a single OSError instance as argument
        kwargs: passed to ``ls``
        Nr   maxdepth must be at least 1r   FTraiser   rK   rj   r   rN   )maxdepthr   topdown)
ValueErrorrq   r7   r   r   OSErrorcallabler}   rsplitry   walk)rZ   r   r   r   on_errorr   	full_dirsdirsr   r   listingeinfopathnamer   dr   r   r   r     sf   !



zAbstractFileSystem.walkc           
        s   |  |}i  |r|dkr| |r| | |< | j||fddi|D ]\}}}|r1||  dd | D  q% sI| |rIi  |< t }	|sQ|	S  fdd|	D S )a  List all files below path.

        Like posix ``find`` command without conditions

        Parameters
        ----------
        path : str
        maxdepth: int or None
            If not None, the maximum number of levels to descend
        withdirs: bool
            Whether to include directory paths in the output. This is True
            when used by glob, but users usually only want files.
        kwargs are passed to ``ls``.
        rN   r   Tc                 S  s   i | ]	\}}|d  |qS )r   r   )r-   r   r   r   r   r   
<dictcomp>      z+AbstractFileSystem.find.<locals>.<dictcomp>c                   s   i | ]}| | qS r   r   )r-   r   outr   r   r     ru   )rq   isdirr   r   updateitemsisfilesorted)
rZ   r   r   withdirsr   r   _r   r   namesr   r   r   find  s   
"
zAbstractFileSystem.findc           	      K  sx   i }|r|  |r| |}|d ||d < | j|f||d|D ]}| |}|d ||d < q"|r:t| S |S )as  Space used by files and optionally directories within a path

        Directory size does not include the size of its contents.

        Parameters
        ----------
        path: str
        total: bool
            Whether to sum all the file sizes
        maxdepth: int or None
            Maximum number of directory levels to descend, None for unlimited.
        withdirs: bool
            Whether to include directory paths in the output.
        kwargs: passed to ``find``

        Returns
        -------
        Dict of {path: size} if total=False, or int otherwise, where numbers
        refer to bytes used.
        sizer   )r   r   )r   r   r   sumvalues)	rZ   r   totalr   r   r   sizesr   r   r   r   r   du  s   

zAbstractFileSystem.duc                   sF  |dur|dk rt dddl}tjjrtjjtjjfntjjf}||}| |}|p8|tdd |D  |	ddkrE|	dnt
|}|	ddkrU|	dnt
|}|	d	dkre|	d	nt
|}	t|||	}
|d
d}t|s| j|fi |r|s|gS || j|fi |iS |sg S i S d|d|
 v r|d|
 d}
|d|
d  }||
d d dd }nd}||
d d dd }d|v r|dur|	d}||d dd }|| | }nd}| j	|f|ddd|}t||rdnd | fddt| D }|r|S t|S )aJ  
        Find files by glob-matching.

        If the path ends with '/', only folders are returned.

        We support ``"**"``,
        ``"?"`` and ``"[..]"``. We do not support ^ for pattern negation.

        The `maxdepth` option is applied on the first `**` found in the path.

        kwargs are passed to ``ls``.
        Nr   r   r   c                 s  s    | ]}|d  V  qdS )**Nr   )r-   sepr   r   r   r0   <      z*AbstractFileSystem.glob.<locals>.<genexpr>*?[r   FrK   rN   r   Tr   r   r   c                   s8   i | ]\}}  r|d  dkr|d n|r||qS )rj   r   rK   )match)r-   rs   r   append_slash_to_dirnamepatternr   r   r   f  s    z+AbstractFileSystem.glob.<locals>.<dictcomp>)r   rer&   r   altsepr   endswithrq   r3   r   r|   minr7   r   existsr   rindexcountr   compiler   r   ry   )rZ   r   r   r   r   sepsends_with_sepidx_star	idx_qmark	idx_bracemin_idxr   rootdepthidx_double_starsdepth_double_starsallpathsr   r   r   r   glob&  sV   "

   



zAbstractFileSystem.globc                 K  s&   z| j |fi | W dS    Y dS )z!Is there a file at the given pathTFr   rZ   r   r   r   r   r   r   u  s
   zAbstractFileSystem.existsc                 K  
   |  |S )zEIf there is a file at the given path (including
        broken links))r   r   r   r   r   lexists~  s   
zAbstractFileSystem.lexistsc                   s   |    | j|  fddi|} fdd|D }|r"|d S | j fddi|} d  fdd|D }t|dkrQd	|d vrMd
|d d	< |d S t|dksY|r_ dddS t )a`  Give details of entry at path

        Returns a single dictionary, with exactly the same information as ``ls``
        would with ``detail=True``.

        The default implementation calls ls and could be overridden by a
        shortcut. kwargs are passed on to ```ls()``.

        Some file systems might not be able to measure the file's size, in
        which case, the returned dict will include ``'size': None``.

        Returns
        -------
        dict with keys: name (full path in the FS), size (in bytes), type (file,
        directory, or something else) and other FS-specific keys.
        r   Tc                   "   g | ]}|d   d kr|qS r   rK   r   r-   or   r   r   rt        " z+AbstractFileSystem.info.<locals>.<listcomp>r   rK   c                   r   r   r   r   r   r   r   rt     r   r   r   Nr   )r   r   rj   )rq   r   r   r}   r|   r   )rZ   r   r   r   out1r   r   r   r     s   

zAbstractFileSystem.infoc                 C  s   t t| |dS )a  Unique value for current version of file

        If the checksum is the same from one moment to another, the contents
        are guaranteed to be the same. If the checksum changes, the contents
        *might* have changed.

        This should normally be overridden; default will probably capture
        creation/modification timestamp (which would be good) or maybe
        access timestamp (which would be bad)
        re   )rf   r   r   r   r   r   r   checksum  s   zAbstractFileSystem.checksumc                 C  s   |  |ddS )zSize in bytes of filer   N)r   r"   r   r   r   r   r        zAbstractFileSystem.sizec                   s    fdd|D S )z-Size in bytes of each file in a list of pathsc                   ro   r   )r   rr   r^   r   r   rt     ru   z,AbstractFileSystem.sizes.<locals>.<listcomp>r   )rZ   pathsr   r^   r   r     r   zAbstractFileSystem.sizesc                 C  s*   z
|  |d dkW S  ty   Y dS w )zIs this entry directory-like?rj   r   F)r   r   r   r   r   r   r     s
   zAbstractFileSystem.isdirc                 C  s"   z
|  |d dkW S    Y dS )zIs this entry file-like?rj   fileFr   r   r   r   r   r     s   zAbstractFileSystem.isfilec                 K  sH   | j |fd|||d|}| W  d   S 1 sw   Y  dS )zGet the contents of the file as a string.

        Parameters
        ----------
        path: str
            URL of file on this filesystems
        encoding, errors, newline: same as `open`.
        rmodeencodingerrorsnewlineNopenread)rZ   r   r   r   r   r   r   r   r   r   	read_text  s   	$zAbstractFileSystem.read_textc                 K  sJ   | j |fd|||d|}||W  d   S 1 sw   Y  dS )a  Write the text to the given file.

        An existing file will be overwritten.

        Parameters
        ----------
        path: str
            URL of file on this filesystems
        value: str
            Text to write.
        encoding, errors, newline: same as `open`.
        wr   N)r   write)rZ   r   valuer   r   r   r   r   r   r   r   
write_text  s   $zAbstractFileSystem.write_textc                 K  s   | j |dfi |B}|dur$|dkr|| n|td|j|  |durA|dk r1|j| }|||  W  d   S | W  d   S 1 sOw   Y  dS )ah  Get the content of a file

        Parameters
        ----------
        path: URL of file on this filesystems
        start, end: int
            Bytes limits of the read. If negative, backwards from end,
            like usual python slices. Either can be None for start or
            end of file, respectively
        kwargs: passed to ``open()``.
        rbNr   )r   seekmaxr   r   tell)rZ   r   startendr   r   r   r   r   cat_file  s   

$zAbstractFileSystem.cat_file	overwritec                 K  sZ   |dkr|  |rt| j|dfi |}|| W d   dS 1 s&w   Y  dS )zSet the bytes of given filecreatewbN)r   FileExistsErrorr   r  )rZ   r   r  r   r   r   r   r   r   	pipe_file  s
   "zAbstractFileSystem.pipe_filec                 K  sj   t |tr| j| ||fi | dS t |tr1| D ]\}}| j| ||fi | qdS td)a  Put value into path

        (counterpart to ``cat``)

        Parameters
        ----------
        path: string or dict(str, bytes)
            If a string, a single remote location to put ``value`` bytes; if a dict,
            a mapping of {path: bytesvalue}.
        value: bytes, optional
            If using a single path, these are the bytes to put there. Ignored if
            ``path`` is a dict
        zpath must be str or dictN)ri   rz   r  rq   dictr   r   )rZ   r   r  r   kvr   r   r   pipe  s   

zAbstractFileSystem.pipec                 K  s   |durt t|tstt|ts|gt| }t|ts%|gt| }t|t|ks5t|t|kr7tg }t|||D ].\}}	}
z|| ||	|
 W q? t	ym }
 z|dkrb||
 n W Y d}
~
q?d}
~
ww |S )aY  Get the contents of byte ranges from one or more files

        Parameters
        ----------
        paths: list
            A list of of filepaths on this filesystems
        starts, ends: int or list
            Bytes limits of the read. If using a single int, the same value will be
            used to read all the specified files.
        Nr   )
r]   ri   ry   	TypeErrorr|   r   zipr   r  	Exception)rZ   r   startsendsmax_gapr   r   r   rs   sr   r   r   r   
cat_ranges,  s,   


 zAbstractFileSystem.cat_rangesr   c                 K  s   | j ||d}t|dkst|ts|d | |krPi }|D ].}z| j|fi |||< W q tyM } z|dkr; |dkrC|||< W Y d}~qd}~ww |S | j|d fi |S )a  Fetch (potentially multiple) paths' contents

        Parameters
        ----------
        recursive: bool
            If True, assume the path(s) are directories, and get all the
            contained files
        on_error : "raise", "omit", "return"
            If raise, an underlying exception will be raised (converted to KeyError
            if the type is in self.missing_exceptions); if omit, keys with exception
            will simply not be included in the output; if "return", all keys are
            included in the output, but the value will be bytes or an exception
            instance.
        kwargs: passed to cat_file

        Returns
        -------
        dict of {path: contents} if there are multiple paths
        or the path has been otherwise expanded
        	recursiver   r   r   r   N)expand_pathr|   ri   ry   rq   r  r  )rZ   r   r  r   r   r   r   r   r   r   r   catN  s$   zAbstractFileSystem.catc              	   K  s  ddl m} t|r|}n| |rtj|dd dS |dd}|j||dd | j|dfi |N}|du r>t|d}z1|t	|d	d d}	|	rf|
| j}	||	}
|
du r_t|	}
||
 |	sLW t|so|  n
t|sy|  w w W d   dS 1 sw   Y  dS )
z Copy single remote file to localr   )LocalFileSystemTr   N)
auto_mkdirr  r  r   )implementations.localr!  r   r   r&   r   r   r   set_sizer,   r   	blocksizer  r|   relative_updateclose)rZ   rpathlpathcallbackoutfiler   r!  fsf1datasegment_lenr   r   r   get_filev  s<   





"zAbstractFileSystem.get_filec              	     s^  t |trt |tr|}|}nhddlm}	m}
m t |t} j|||d}|r<|r.|dur< fdd|D }|s<dS t |trE|
|}t|dk}t |toY|pY|	 	|}|omt
|rb|pmt
| om|om| }t|||| d}|t| |t||D ]&\}}|||} j||fd|i| W d   n1 sw   Y  qdS )	aT  Copy file(s) to local.

        Copies a specific file or tree of files (if recursive=True). If lpath
        ends with a "/", it will be assumed to be a directory, and target files
        will go within. Can submit a list of paths, which may be glob-patterns
        and will be expanded.

        Calls get_file for each source.
        r   r!  make_path_posixtrailing_sepr  r   Nc                   "   g | ]}|s  |s|qS r   r   rr   rZ   r4  r   r   rt     r   z*AbstractFileSystem.get.<locals>.<listcomp>r   flattenr+  )ri   ry   r$  r!  r3  r4  rz   r  r|   r   r   r   r%  wrapr  branchedr1  )rZ   r)  r*  r  r+  r   r   rpathslpathsr!  r3  source_is_strsource_is_filedest_is_dirr   childr   r8  r   r"     sB   


zAbstractFileSystem.getc              	   K  s*  |dkr|  |rttj|r| j|dd dS t|dl}|dd}|| |d | j	| 
t|dd | j|dfi |,}| |k rl|| j}	||	}
|
du rat|	}
||
 | |k sNW d   n1 svw   Y  W d   dS W d   dS 1 sw   Y  dS )	zCopy single file to remoter  Tr"  Nr  r   rx   r  )r   r  r&   r   r   r   r   r  r%  mkdirsr   fspathr  r   r&  r  r|   r'  )rZ   r*  r)  r+  r   r   r.  r   f2r/  r0  r   r   r   put_file  s.   



"zAbstractFileSystem.put_filec              	     s  t |trt |tr|}|}nzddlm}	m}
m t |t}|r$|
|}|	   j|||d}|rE|r7|durE fdd|D }|sEdS t|dk}t |toX|pX	|}t |trc
|nfdd|D }|ot|rt|pt| o|o| }t|||| d}|t| |t||D ]&\}}|||}j||fd	|i| W d   n1 sw   Y  qdS )
a  Copy file(s) from local.

        Copies a specific file or tree of files (if recursive=True). If rpath
        ends with a "/", it will be assumed to be a directory, and target files
        will go within.

        Calls put_file for each source.
        r   r2  r5  Nc                   r6  r   r7  rr   )r-  r4  r   r   rt     r   z*AbstractFileSystem.put.<locals>.<listcomp>c                   ro   r   rp   rr   r^   r   r   rt     ru   r9  r+  )ri   ry   r$  r!  r3  r4  rz   r  r|   r   rq   r   r   r%  r;  r  r<  rF  )rZ   r*  r)  r  r+  r   r   r=  r>  r!  r3  r?  r@  rA  r   rB  r   )r-  rZ   r4  r   put  sL   

zAbstractFileSystem.put   c                 C  s:   |  |d}||W  d   S 1 sw   Y  dS )z&Get the first ``size`` bytes from filer  Nr   rZ   r   r   r   r   r   r   head,  s   $zAbstractFileSystem.headc                 C  sP   |  |d}|t| |j d | W  d   S 1 s!w   Y  dS )z%Get the last ``size`` bytes from filer  rx   N)r   r  r  r   r   rI  r   r   r   tail1  s   $zAbstractFileSystem.tailc                 K  r[   r   r\   rZ   path1path2r   r   r   r   cp_file7     zAbstractFileSystem.cp_filec              	     s<  |du r	|r	d}n|du rd}t |trt |tr|}|}nZddlm t |t}	 j|||d}|	rG|r9|durG fdd|D }|sGdS t|dk}
t |toZ|pZ |}|	ont|rc|
pnt| on|on| }t	||||	 d	}t
||D ]\}}z j||fi | W q} ty   |dkr Y q}w dS )
a?  Copy within two locations in the filesystem

        on_error : "raise", "ignore"
            If raise, any not-found exceptions will be raised; if ignore any
            not-found exceptions will cause the path to be skipped; defaults to
            raise unless recursive is true, where the default is ignore
        Nignorer   r   )r4  r5  c                   r6  r   r7  rr   r8  r   r   rt   U  r   z+AbstractFileSystem.copy.<locals>.<listcomp>r9  )ri   ry   r$  r4  rz   r  r|   r   r   r   r  rO  r   )rZ   rM  rN  r  r   r   r   paths1paths2r?  r@  rA  r   p1p2r   r8  r   copy:  sJ   


zAbstractFileSystem.copyc           	        s4  |dur|dk rt dt|ttjfr |g||}nst } fdd|D }|D ]d}t|rht j|fd|i|}||O }|rg|durM|dkrMq+|t jt	|f||dur^|d ndd|O }q+|r}t j
|f|dd	d
|}||O }||vr|d	u s |r|| q+|st|t|S )zTurn one or more globs or directories into a list of all matching paths
        to files or directories.

        kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls``
        Nr   r   c                   ro   r   rp   rr   r^   r   r   rt   ~  ru   z2AbstractFileSystem.expand_path.<locals>.<listcomp>r   r5  TFr   )r   ri   rz   r&   PathLiker  setr   r   ry   r   r   addr   r   )	rZ   r   r  r   r   r   rs   bitrecr   r^   r   r  p  sR   
zAbstractFileSystem.expand_pathc                 K  s>   ||krt d|  dS | j||||dd | j||d dS )z)Move file(s) from one location to anotherz6%s mv: The paths are the same, so no files were moved.r   )r  r   onerrorr  N)loggerdebugrV  rm)rZ   rM  rN  r  r   r   r   r   r   mv  s   
zAbstractFileSystem.mvc                 C  s   |  | dS )zDelete a fileN)_rmr   r   r   r   rm_file     zAbstractFileSystem.rm_filec                 C  r[   )zDelete one filer\   r   r   r   r   ra    s   zAbstractFileSystem._rmc                 C  s,   | j |||d}t|D ]}| | qdS )a  Delete files.

        Parameters
        ----------
        path: str or list of str
            File(s) to delete.
        recursive: bool
            If file(s) are directories, recursively delete contents and then
            also remove the directory
        maxdepth: int or None
            Depth to pass to walk for finding files to delete, if recursive.
            If None, there will be no limit and infinite recursion may be
            possible.
        r5  N)r  reversedrb  )rZ   r   r  r   rs   r   r   r   r_    s   zAbstractFileSystem.rmc                 C  s:   |  |}d|v r|ddd | j}| j| S | jS )NrK   r   r   )rq   r   lstripr~   )r   r   r   r   r   r   r     s
   

zAbstractFileSystem._parentr  c                 K  s   t | ||||fd|i|S )z4Return raw bytes-mode file-like from the file-systemcache_options)AbstractBufferedFile)rZ   r   r   
block_size
autocommitrf  r   r   r   r   _open  s   
zAbstractFileSystem._openc                   s   ddl }| |}d|vr3|ddd } fdddD }|j| j||f|||d	 fi |S  d
| j }	| j|f|||	|d }
|durjddlm	} ddl
m} |||}|| }||
|d d}
|	swd|vrw| jj|
 |
S )a  
        Return a file-like object from the filesystem

        The resultant instance must function correctly in a context ``with``
        block.

        Parameters
        ----------
        path: str
            Target file
        mode: str like 'rb', 'w'
            See builtin ``open()``
            Mode "x" (exclusive write) may be implemented by the backend. Even if
            it is, whether  it is checked up front or on commit, and whether it is
            atomic is implementation-dependent.
        block_size: int
            Some indication of buffering - this is a value in bytes
        cache_options : dict, optional
            Extra arguments to pass through to the cache.
        compression: string or None
            If given, open file using compression codec. Can either be a compression
            name (a key in ``fsspec.compression.compr``) or "infer" to guess the
            compression from the filename suffix.
        encoding, errors, newline: passed on to TextIOWrapper for text mode
        r   NbtrN   c                   s    i | ]}| v r|  |qS r   )r7   )r-   r  r   r   r   r     s
    
z+AbstractFileSystem.open.<locals>.<dictcomp>)r   r   r   )rh  rf  compressionri  )r   rh  ri  rf  )compr)get_compression)r   r   )iorq   replaceTextIOWrapperr   r7   rS   rj  fsspec.compressionro  fsspec.corerp  r   r   r   )rZ   r   r   rh  rf  rn  r   rq  text_kwargsacr   ro  rp  compressr   rm  r   r     sR   "

	
zAbstractFileSystem.openc                 K  sL   |s|  |s$| j|dfi |	 W d   dS 1 sw   Y  dS t)a!  Create empty file, or update timestamp

        Parameters
        ----------
        path: str
            file location
        truncate: bool
            If True, always set file size to 0; if False, update timestamp and
            leave file unchanged, if backend allows this
        r  N)r   r   r]   )rZ   r   truncater   r   r   r   touch2  s
   "zAbstractFileSystem.touchc                 C  s   t t| |  S )z2Hash of file properties, to tell if it has changed)r   rz   r   encode	hexdigestr   r   r   r   ukeyC  s   zAbstractFileSystem.ukeyc                 C  sl   |  |d&}|j}|du r|}|dur|| |kr|| }t||||W  d   S 1 s/w   Y  dS )a  Read a block of bytes from

        Starting at ``offset`` of the file, read ``length`` bytes.  If
        ``delimiter`` is set then we ensure that the read starts and stops at
        delimiter boundaries that follow the locations ``offset`` and ``offset
        + length``.  If ``offset`` is zero then we start at zero.  The
        bytestring returned WILL include the end delimiter string.

        If offset+length is beyond the eof, reads to eof.

        Parameters
        ----------
        fn: string
            Path to filename
        offset: int
            Byte offset to start read
        length: int
            Number of bytes to read. If None, read to end.
        delimiter: bytes (optional)
            Ensure reading starts and stops at delimiter bytestring

        Examples
        --------
        >>> fs.read_block('data/file.csv', 0, 13)  # doctest: +SKIP
        b'Alice, 100\nBo'
        >>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\n')  # doctest: +SKIP
        b'Alice, 100\nBob, 200\n'

        Use ``length=None`` to read to the end of the file.
        >>> fs.read_block('data/file.csv', 0, None, delimiter=b'\n')  # doctest: +SKIP
        b'Alice, 100\nBob, 200\nCharlie, 300'

        See Also
        --------
        :func:`fsspec.utils.read_block`
        r  N)r   r   r   )rZ   fnoffsetlength	delimiterr   r   r   r   r   r   G  s   %$zAbstractFileSystem.read_block)include_passwordr  boolc                C  s(   ddl m} t j| td|fd|idS )a  
        JSON representation of this filesystem instance.

        Parameters
        ----------
        include_password: bool, default True
            Whether to include the password (if any) in the output.

        Returns
        -------
        JSON string with keys ``cls`` (the python location of this class),
        protocol (text name of this class's protocol, first one in case of
        multiple), ``args`` (positional args, usually empty), and all other
        keyword arguments as their own keys.

        Warnings
        --------
        Serialized filesystems may contain sensitive information which have been
        passed to the constructor, such as passwords and tokens. Make sure you
        store and send them in a secure environment!
        r   FilesystemJSONEncoder_FilesystemJSONEncoderr  r/   )jsonr  dumpsrj   )rZ   r  r  r   r   r   to_jsont  s   zAbstractFileSystem.to_jsonblobc                 C  s   ddl m} t j| |dS )a  
        Recreate a filesystem instance from JSON representation.

        See ``.to_json()`` for the expected structure of the input.

        Parameters
        ----------
        blob: str

        Returns
        -------
        file system instance, not necessarily of this particular class.

        Warnings
        --------
        This can import arbitrary modules (as determined by the ``cls`` key).
        Make sure you haven't installed any modules that may execute malicious code
        at import time.
        r   FilesystemJSONDecoderr/   )r  r  loads)r  r  r   r   r   	from_json  s   zAbstractFileSystem.from_jsonc                C  s   ddl m} | }t| }| j}t| j}|s|dd td|j d|j t	|t
tfr2|d n||| jd||S )	a  
        JSON-serializable dictionary representation of this filesystem instance.

        Parameters
        ----------
        include_password: bool, default True
            Whether to include the password (if any) in the output.

        Returns
        -------
        Dictionary with keys ``cls`` (the python location of this class),
        protocol (text name of this class's protocol, first one in case of
        multiple), ``args`` (positional args, usually empty), and all other
        keyword arguments as their own keys.

        Warnings
        --------
        Serialized filesystems may contain sensitive information which have been
        passed to the constructor, such as passwords and tokens. Make sure you
        store and send them in a secure environment!
        r   r  passwordN:r   )r   rM   r   r   )r  r  rj   rM   r  r>   r7   rF   rE   ri   r3   ry   make_serializabler=   )rZ   r  r  json_encoderr   protor>   r   r   r   to_dict  s   

zAbstractFileSystem.to_dictdctc                 C  sn   ddl m} | }t| } || }|du rtd| dd | dd ||| ddi || S )	a  
        Recreate a filesystem instance from dictionary representation.

        See ``.to_dict()`` for the expected structure of the input.

        Parameters
        ----------
        dct: Dict[str, Any]

        Returns
        -------
        file system instance, not necessarily of this particular class.

        Warnings
        --------
        This can import arbitrary modules (as determined by the ``cls`` key).
        Make sure you haven't installed any modules that may execute malicious code
        at import time.
        r   r  Nz#Not a serialized AbstractFileSystemr   rM   r   r   )r  r  r  try_resolve_fs_clsr   r7   unmake_serializable)r  r  json_decoderr   r   r   r   	from_dict  s   
zAbstractFileSystem.from_dictc                 C     | S )zW
        Make a version of the FS instance which will be acceptable to pyarrow
        r   r^   r   r   r   _get_pyarrow_filesystem  r`   z*AbstractFileSystem._get_pyarrow_filesystemc                 C  s   ddl m} ||| |||dS )zCreate key/value store based on this file-system

        Makes a MutableMapping interface to the FS at the given root path.
        See ``fsspec.mapping.FSMap`` for further details.
        r   )FSMap)checkr  missing_exceptions)mappingr  )rZ   r   r  r  r  r  r   r   r   
get_mapper  s   zAbstractFileSystem.get_mapperc                 C  s   | j   dS )a  
        Clear the cache of filesystem instances.

        Notes
        -----
        Unless overridden by setting the ``cachable`` class attribute to False,
        the filesystem class stores a reference to newly created instances. This
        prevents Python's normal rules around garbage collection from working,
        since the instances refcount will not drop to zero until
        ``clear_instance_cache`` is called.
        N)r%   r8   r/   r   r   r   clear_instance_cache  s   z'AbstractFileSystem.clear_instance_cachec                 C  r[   )z=Return the created timestamp of a file as a datetime.datetimer\   r   r   r   r   created#  r   zAbstractFileSystem.createdc                 C  r[   )z>Return the modified timestamp of a file as a datetime.datetimer\   r   r   r   r   modified'  r   zAbstractFileSystem.modifiedrx         r   recursion_limitrf   max_displaydisplay_sizeprefixis_lastfirstindent_sizec	                 C  s  d*dd}	g }
|r|
 | |r]d| }| j|dd	}|jd
d d |dur;t||kr;|d| }t|| }n|}d}t|D ]\}}|t|d koR|dk}|r]dd|d   ndd|d   }|d7 }||rn|ndd|d    }tj|dd}|r|ddkr| j|dddd	}t	dd |D }t	dd |D }|dkr|dkrd}n^|dkrd| d|dkrdnd d }nJ|dkrd| d!|dkrdnd d }n6d| d!|dkrdnd d"| d|dkrdnd d 	}n|r|dd#krd|	|d$d d }nd}|
 | | | |  |ddkr@|dkr@|
 | j
|dd|d ||||d%|d& qC|dkr]| d'}|
 | dd|d    d|  d(d)d |
D S )+a  
        Return a tree-like structure of the filesystem starting from the given path as a string.

        Parameters
        ----------
            path: Root path to start traversal from
            recursion_limit: Maximum depth of directory traversal
            max_display: Maximum number of items to display per directory
            display_size: Whether to display file sizes
            prefix: Current line prefix for visual tree structure
            is_last: Whether current item is last in its level
            first: Whether this is the first call (displays root path)
            indent_size: Number of spaces by indent

        Returns
        -------
            str: A string representing the tree structure.

        Example
        -------
            >>> from fsspec import filesystem

            >>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password')
            >>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10)
            >>> print(tree)
        nrf   r   rz   c                 S  s>   dD ]\}}| d| kr| | dd| d  S q|  dS )zFormat bytes as text.))Pl           )Tl        )Gi   @)Mi   )r  rH  g?z.2f rk  Br   )r  r  r  r   r   r   format_bytesQ  s
   
z-AbstractFileSystem.tree.<locals>.format_bytesr  T)r   c                 S  s   |  ddk|  ddfS )Nrj   r   r   rN   r"   )xr   r   r   <lambda>g  r   z)AbstractFileSystem.tree.<locals>.<lambda>)keyNr   r   u   └u   ─rx   u   ├u   │r   rN   rj   r   c                 s  "    | ]}| d dkrdV  qdS )rj   r   r   Nr  r-   sub_itemr   r   r   r0     s    z*AbstractFileSystem.tree.<locals>.<genexpr>c                 s  r  )rj   r   r   Nr  r  r   r   r   r0     s    z (empty folder)z (z
 subfolderr  )z file, r   r   F)r   r  r  r  r  r  r  r  z more item(s) not displayed.
c                 s  s    | ]}|r|V  qd S r   r   )r-   r   r   r   r   r0     r   )r  rf   r   rz   )r   r   sortr|   	enumerater&   r   basenamer"   r   treejoin)rZ   r   r  r  r  r  r  r  r  r  resultindentcontentsdisplayed_contentsremaining_countiitemis_last_itembranch
new_prefixr   sub_contents	num_filesnum_foldersr   more_messager   r   r   r  +  s   
&
  8


zAbstractFileSystem.treec                 K     | j |f||d|S )z'Alias of `AbstractFileSystem.cat_file`.r	  r
  )r  )rZ   r   r	  r
  r   r   r   r   
read_bytes     zAbstractFileSystem.read_bytesc                 K  s   | j ||fi | dS )z(Alias of `AbstractFileSystem.pipe_file`.N)r  )rZ   r   r  r   r   r   r   write_bytes  r  zAbstractFileSystem.write_bytesc                 K     | j |fd|i|S )z$Alias of `AbstractFileSystem.mkdir`.r   )r   r   r   r   r   makedir     zAbstractFileSystem.makedirc                 C  s   | j ||dS )z'Alias of `AbstractFileSystem.makedirs`.r"  )r   r   r   r   r   rC    rc  zAbstractFileSystem.mkdirsc                 K  r  )z!Alias of `AbstractFileSystem.ls`.r   )r   r   r   r   r   listdir  r  zAbstractFileSystem.listdirc                 K     | j ||fi |S )z#Alias of `AbstractFileSystem.copy`.)rV  rL  r   r   r   cp     zAbstractFileSystem.cpc                 K  r  z!Alias of `AbstractFileSystem.mv`.r`  rL  r   r   r   move  r  zAbstractFileSystem.movec                 K  s   | j |fi |S )z#Alias of `AbstractFileSystem.info`.r   r   r   r   r   stat  r   zAbstractFileSystem.statc                 K  r  )z!Alias of `AbstractFileSystem.du`.)r   r   )r   )rZ   r   r   r   r   r   r   r   
disk_usage  r  zAbstractFileSystem.disk_usagec                 K  r  r  r  rL  r   r   r   rename  r  zAbstractFileSystem.renamec                 C  s   | j |||dS )z!Alias of `AbstractFileSystem.rm`.r5  )r_  )rZ   r   r  r   r   r   r   delete  s   zAbstractFileSystem.deletec                 K     | j ||fd|i|S )z"Alias of `AbstractFileSystem.put`.r  )rG  )rZ   r*  r)  r  r   r   r   r   upload  r  zAbstractFileSystem.uploadc                 K  r  )z"Alias of `AbstractFileSystem.get`.r  r  )rZ   r)  r*  r  r   r   r   r   download  r  zAbstractFileSystem.downloadd   c                 K  s   t d)a  Create a signed URL representing the given path

        Some implementations allow temporary URLs to be generated, as a
        way of delegating credentials.

        Parameters
        ----------
        path : str
             The path on the filesystem
        expiration : int
            Number of seconds to enable the URL for (if supported)

        Returns
        -------
        URL : str
            The signed URL

        Raises
        ------
        NotImplementedError : if method is not implemented for a filesystem
        z+Sign is not implemented for this filesystemr\   )rZ   r   
expirationr   r   r   r   sign  s   zAbstractFileSystem.signc                 C  r   )NFr   r^   r   r   r   _isfilestore  r`   zAbstractFileSystem._isfilestore)r   rz   r   rz   r   )TF)NTr   )NFF)TNF)NNN)NN)r  )Nr   )Fr   )rH  )FNN)FN)r  NTN)r  NNN)r  r  r   rz   )r  rz   r   rJ   )r  r  r   rO   )r  rO   r   rJ   )rN   FFN)rK   rx   r  FrN   TTr  )r   rz   r  rf   r  rf   r  r  r  rz   r  r  r  r  r  rf   r   rz   )TN)r  )hrE   rF   rG   rH   r9   rR   r&  r   rM   __annotations__r:   r?   r2   r~   r   r   r4   r!   propertyr_   rb   rd   rg   rm   rn   classmethodrq   r   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r   r	   r1  r"   rF  rG  rJ  rK  rO  rV  r  r`  rb  ra  r_  r   rj  r   rz  r}  r   r  r  r  r  r  r  r  r  r  r  r  r  r  rC  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   rJ   a   s  
 )





	


	


)

^
&
"O	"




	

"("
?


B


6
0




N
-!(&

 








rJ   )	metaclassc                   @  sd  e Zd ZdZdZdZ						dPdd	Zed
d Zej	dd Zedd Z
edd Zej	dd Zdd Zdd Zdd Zdd Zdd Zdd ZdQdd Zd!d" ZdRd$d%ZdRd&d'Zd(d) Zd*d+ ZdSd-d.Zd/d0 ZdTd2d3Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Zd>d? Z d@dA Z!dBdC Z"dDdE Z#dFdG Z$dHdI Z%dJdK Z&e&Z'dLdM Z(dNdO Z)dS )Urg  a?  Convenient class to derive from to provide buffering

    In the case that the backend does not provide a pythonic file-like object
    already, this class contains much of the logic to build one. The only
    methods that need to be overridden are ``_upload_chunk``,
    ``_initiate_upload`` and ``_fetch_range``.
    i  P Nr  defaultT	readaheadc	                 K  s   ddl m}
 || _|| _|| _|dv r| jn|| _d| _|| _d| _	d| _
d| _|du r.i }d|	v r?tdt |	d|d< |	| _|d	vrJtd
|dkrn|durV|| _n| jd | _|
| | j| j| jfi || _dS t | _d| _d| _d| _dS )a  
        Template for files with buffered reading and writing

        Parameters
        ----------
        fs: instance of FileSystem
        path: str
            location in file-system
        mode: str
            Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file
            systems may be read-only, and some may not support append.
        block_size: int
            Buffer size for reading or writing, 'default' for class default
        autocommit: bool
            Whether to write to final destination; may only impact what
            happens when file is being closed.
        cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead"
            Caching policy in read mode. See the definitions in ``core``.
        cache_options : dict
            Additional options passed to the constructor for the cache specified
            by `cache_type`.
        size: int
            If given and in read mode, suppressed having to look up the file size
        kwargs:
            Gets stored as self.kwargs
        r   )caches)r  Nr   NFtrimzyPassing 'trim' to control the cache behavior has been deprecated. Specify it within the 'cache_options' argument instead.>   abr  r  xbzFile mode not supportedr  r   )corer  r   r-  r   DEFAULT_BLOCK_SIZEr&  locri  r
  r	  closedrW   rX   rY   r7   r   r]   r   details_fetch_rangecacherq  BytesIObufferr  forcedlocation)rZ   r-  r   r   rh  ri  
cache_typerf  r   r   r  r   r   r   r!     sF   &

zAbstractBufferedFile.__init__c                 C  s    | j d u r| j| j| _ | j S r   )_detailsr-  r   r   r^   r   r   r   r  f  s   
zAbstractBufferedFile.detailsc                 C  s   || _ |d | _d S )Nr   )r  r   )rZ   r  r   r   r   r  l  s   c                 C  s   t | j| jS r   )r   r   r-  r^   r   r   r   	full_nameq  rc  zAbstractBufferedFile.full_namec                 C  s   t | ddS )N_closedTr+   r^   r   r   r   r  u  s   zAbstractBufferedFile.closedc                 C  s
   || _ d S r   )r  )rZ   cr   r   r   r  {  s   
c                 C  s"   d| j v r	t| S tt| jdS )Nr  re   )r   idrf   r   r  r^   r   r   r   rg     s   
zAbstractBufferedFile.__hash__c                 C  s>   | |u rdS t |t| o| jdko|jdkot| t|kS )zAFiles are equal if they have the same checksum, only in read modeTr  )ri   rj   r   hashrk   r   r   r   rm     s   zAbstractBufferedFile.__eq__c                 C  r   )z#Move from temp to final destinationNr   r^   r   r   r   commit      zAbstractBufferedFile.commitc                 C  r   )zThrow away temporary fileNr   r^   r   r   r   discard  r  zAbstractBufferedFile.discardc                 C  s   |   r| jS td)z File information about this pathz Info not available while writing)readabler  r   r^   r   r   r   r     s   zAbstractBufferedFile.infoc                 C  ra   )zCurrent file location)r  r^   r   r   r   r    rc   zAbstractBufferedFile.tellr   c                 C  s~   t |}| jdksttd|dkr|}n|dkr| j| }n|dkr)| j| }ntd| d|dk r9td|| _| jS )	zSet current file location

        Parameters
        ----------
        loc: int
            byte location
        whence: {0, 1, 2}
            from start of file, current location or end of file, resp.
        r  z Seek only available in read moder   r   rx   zinvalid whence (z, should be 0, 1 or 2)zSeek before start of file)rf   r   r   r   r  r   r   )rZ   r  whencenlocr   r   r   r    s   


zAbstractBufferedFile.seekc                 C  sb   |   std| jrtd| jrtd| j|}|  j|7  _| j | jkr/| 	  |S )z
        Write data to buffer.

        Buffer only sent on flush() or if buffer is greater than
        or equal to blocksize.

        Parameters
        ----------
        data: bytes
            Set of bytes to be written.
        zFile not in write modeI/O operation on closed file.z0This file has been force-flushed, can only close)
writabler   r  r  r   r  r  r  r&  flush)rZ   r/  r   r   r   r   r    s   zAbstractBufferedFile.writeFc                 C  s   | j rtd|r| jrtd|rd| _|  rdS |s'| j | jk r'dS | jdu r=d| _z|   W n   d| _  | j	|ddurX|  j| j
dd7  _t | _dS dS )	a{  
        Write buffered data to backend store.

        Writes the current buffer, if it is larger than the block-size, or if
        the file is being closed.

        Parameters
        ----------
        force: bool
            When closing, write the last block even if it is smaller than
            blocks are allowed to be. Disallows further writing to this file.
        zFlush on closed filez+Force flush cannot be called more than onceTNr   )finalFrx   )r  r   r  r  r   r  r&  r  _initiate_upload_upload_chunkr  rq  r  )rZ   forcer   r   r   r    s*   

zAbstractBufferedFile.flushc                 C  r   )zWrite one part of a multi-block file upload

        Parameters
        ==========
        final: bool
            This is the last block, so should complete file, if
            self.autocommit is True.
        Nr   )rZ   r  r   r   r   r    r  z"AbstractBufferedFile._upload_chunkc                 C  r   )zCreate remote file/uploadNr   r^   r   r   r   r    r   z%AbstractBufferedFile._initiate_uploadc                 C  s   | j j| j||dS )z*Get the specified set of bytes from remoter  )r-  r  r   )rZ   r	  r
  r   r   r   r    r  z!AbstractBufferedFile._fetch_ranger   c                 C  s   |du rdnt |}| jdkrtd|dk r| j| j }| jr$td|dkr*dS | j| j| j| }t	d| | j| j| | j
  |  jt|7  _|S )	z
        Return data from cache, or fetch pieces as necessary

        Parameters
        ----------
        length: int (-1)
            Number of bytes to read; if <0, all remaining bytes.
        Nr   r  zFile not in read moder   r      z%s read: %i - %i %s)rf   r   r   r   r  r  r  _fetchr]  r^  
_log_statsr|   )rZ   r  r   r   r   r   r     s&   	
zAbstractBufferedFile.readc                 C  s2   t |d}| |j}||dt|< t|S )zxmirrors builtin file's readinto method

        https://docs.python.org/3/library/io.html#io.RawIOBase.readinto
        r  N)
memoryviewcastr   nbytesr|   )rZ   rk  r   r/  r   r   r   readinto/  s   zAbstractBufferedFile.readinto   
c                 C  s   g }	 |   }| |p| j}t|dkrn(||}|dkr8||d|t|   | || t|  n|| qd|S )a  Return data between current position and first occurrence of char

        char is included in the output, except if the end of the tile is
        encountered first.

        Parameters
        ----------
        char: bytes
            Thing to find
        blocks: None or int
            How much to read in each go. Defaults to file blocksize - which may
            mean a new read on every call.
        Tr   r   Nr  )r  r   r&  r|   r   r   r  r  )rZ   charblocksr   r	  partfoundr   r   r   	readuntil9  s   


zAbstractBufferedFile.readuntilc                 C  s
   |  dS )zRead until and including the first occurrence of newline character

        Note that, because of character encoding, this is not necessarily a
        true line ending.
        r  )r#  r^   r   r   r   readlineU  s   
zAbstractBufferedFile.readlinec                 C  s   |   }|r|S tr   )r$  StopIteration)rZ   r   r   r   r   __next__]  s   zAbstractBufferedFile.__next__c                 C  r  r   r   r^   r   r   r   __iter__c  rP  zAbstractBufferedFile.__iter__c                 C  sD   |   }|d}dd |dd D }|dr|S ||d g S )zPReturn all data, split by the newline character, including the newline characterr  c                 S  s   g | ]}|d  qS )r  r   )r-   lr   r   r   rt   j  s    z2AbstractBufferedFile.readlines.<locals>.<listcomp>Nr   )r   splitr   )rZ   r/  linesr   r   r   r   	readlinesf  s   

zAbstractBufferedFile.readlinesc                 C  r   r   )r  )rZ   rk  r   r   r   	readinto1q  s   
zAbstractBufferedFile.readinto1c                 C  s   t | ddrdS | jrdS z;| jdkrd| _n&| js | jdd | jdurC| j| j | j| j	| j W d| _dS W d| _dS W d| _dS d| _w )z=Close file

        Finalizes writes, discards cache
        _unclosableFNr  T)r  )
r,   r  r   r  r  r  r-  r   r   r   r^   r   r   r   r(  t  s"   



	zAbstractBufferedFile.closec                 C  s   d| j v o| j S )zWhether opened for readingr   r   r  r^   r   r   r   r    r   zAbstractBufferedFile.readablec                 C  s   |   S )z'Whether is seekable (only in read mode))r  r^   r   r   r   seekable  s   zAbstractBufferedFile.seekablec                 C  s   | j dv o| j S )zWhether opened for writing>   r  r  r  r.  r^   r   r   r   r    r   zAbstractBufferedFile.writablec              
   C  sJ   | j dkr	tdt| j| j| j | j| j| j| j| j	r| j	j
nd| jf	fS )Nr  z*Pickling a writeable file is not supportednone)r   RuntimeErrorreopenr-  r   r&  r  r   ri  r  r   r   r^   r   r   r   rn     s   
zAbstractBufferedFile.__reduce__c                 C  s   | j s	|   d S d S r   )r  r(  r^   r   r   r   __del__  s   zAbstractBufferedFile.__del__c                 C  s   dt | jj d| j dS )Nz<File-like object r  >)rj   r-  rE   r   r^   r   r   r   __str__  s   zAbstractBufferedFile.__str__c                 C  r  r   r   r^   r   r   r   	__enter__  rP  zAbstractBufferedFile.__enter__c                 G  s   |    d S r   )r(  )rZ   r   r   r   r   __exit__  rh   zAbstractBufferedFile.__exit__)r  r  Tr  NN)r   r  )r   )r  N)*rE   rF   rG   rH   r  r  r!   r  r  setterr  r  rg   rm   r
  r  r   r  r  r  r  r  r  r  r   r  r#  r$  r&  r'  r+  r,  r(  r  r/  r  rn   r3  r5  __repr__r6  r7  r   r   r   r   rg  	  sf    
Q







*


rg  c	           
      C  s4   | j |f|||||d|}	|dkr|	| |	S )N)r   rh  ri  r  r   r   )r   r  )
r-  r   r   r&  r  r   ri  r  r   r   r   r   r   r2    s   	
r2  ),
__future__r   rq  r  loggingr&   r5   rW   r#   errnor   r   r   hashlibr   typingr   r   	callbacksr	   configr
   r   rV   r   r   r   utilsr   r   r   r   r   r   r   	getLoggerr]  r   rj   r   rJ   IOBaserg  r2  r   r   r   r   <module>   sN    $

=             5   0