
    OOIdA                        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 d dlmZ dZd!dZd!d	Zi Zd
 Zd Zd Zd"dZd Zd Zd Zd Zd"dZd Zd Zd Zd Z d Z!d#dZ"d Z#d Z$ed             Z%d$dZ&d  Z'dS )%    N)contextmanager)partial)md5)version)urlspliti  P c                    t          j        d|           st          j        d|           d| dS t          |           }|j        pd}|j        r"d                    |j        |j        g          }n|j        }|dk    r.t          j        d|          }|rd|                                z  }|d	v r|| dS ||d}|j        r|j        	                    d
d          d         	                    dd          d         |d<   |dv r|d         |d         z   |d<   n|d         |d<   |j
        r
|j
        |d<   |j        r
|j        |d<   |j        r
|j        |d<   |j        r
|j        |d<   |j        r
|j        |d<   |rt          ||           |S )a  Infer storage options from URL path and merge it with existing storage
    options.

    Parameters
    ----------
    urlpath: str or unicode
        Either local absolute file path or URL (hdfs://namenode:8020/file.csv)
    inherit_storage_options: dict (optional)
        Its contents will get merged with the inferred information from the
        given path

    Returns
    -------
    Storage options dict.

    Examples
    --------
    >>> infer_storage_options('/mnt/datasets/test.csv')  # doctest: +SKIP
    {"protocol": "file", "path", "/mnt/datasets/test.csv"}
    >>> infer_storage_options(
    ...     'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1',
    ...     inherit_storage_options={'extra': 'value'},
    ... )  # doctest: +SKIP
    {"protocol": "hdfs", "username": "username", "password": "pwd",
    "host": "node", "port": 123, "path": "/mnt/datasets/test.csv",
    "url_query": "q=1", "extra": "value"}
    z^[a-zA-Z]:[\\/]z^[a-zA-Z0-9]+://Nfile)protocolpath#z^/([a-zA-Z])[:|]([\\/].*)$z%s:%s)httphttps@   :r   host)s3s3agcsgsr   portusernamepassword	url_queryurl_fragment)rematchr   schemefragmentjoinr   groupsnetlocrsplitr   r   r   queryupdate_storage_options)urlpathinherit_storage_optionsparsed_pathr
   r   windows_pathoptionss          ,lib/python3.11/site-packages/fsspec/utils.pyinfer_storage_optionsr-      s   < 	#W--58'119"G4447##K!+VH  xx);+?@AA6 x =tDD 	3\00222D$$$$g666#T22G 7 &,33C;;B?FFsANNqQ111%fo?GFOO%foGFO 	/).GFO 	7"-"6GJ 	7"-"6GJ 1*0 7"-"6 Aw(?@@@N    c                     |si }t          |           t          |          z  }|rC|D ]@}|                     |          |                    |          k    rt          d|z            A|                     |           d S )Nz;Collision between inferred and specified storage option:
%s)setgetKeyErrorupdate)r+   	inherited
collisions	collisions       r,   r&   r&   b   s     	WI.J # 	 	I{{9%%y)A)AAA"$-.   B
 NN9r.   c                     t           j                            |           d                             d                                          }|t
          v rt
          |         S dS )a  Infer compression, if available, from filename.

    Infer a named compression type, if registered and available, from filename
    extension. This includes builtin (gz, bz2, zip) compressions, as well as
    optional compressions. See fsspec.compression.register_compression.
    r   .N)osr   splitextstriplowercompressions)filename	extensions     r,   infer_compressionr@   t   sV       **2.44S99??AAIL  I&& ! r.   c                     | dz  } t          t          j        t          j        |                               fd}|S )a  Returns a function that receives a single integer
    and returns it as a string padded by enough zero characters
    to align with maximum possible integer

    >>> name_f = build_name_function(57)

    >>> name_f(7)
    '07'
    >>> name_f(31)
    '31'
    >>> build_name_function(1000)(42)
    '0042'
    >>> build_name_function(999)(42)
    '042'
    >>> build_name_function(0)(0)
    '0'
    g:0yE>c                 H    t          |                                         S N)strzfill)i
pad_lengths    r,   name_functionz*build_name_function.<locals>.name_function   s    1vv||J'''r.   )intmathceillog10)max_intrH   rG   s     @r,   build_name_functionrN      sP    & tOGTYtz'223344J( ( ( ( ( r.   c                    |                                  dk    rdS d}	 |                     |          }|sdS |r||z   n|}	 ||v ra|                    |          }|                     |                                  t	          |          |z
  z
  t	          |          z              dS t	          |          |k     rdS n# t
          t          f$ r Y nw xY w|t	          |           d         })a  Seek current file to file start, file end, or byte after delimiter seq.

    Seeks file to next chunk delimiter, where chunks are defined on file start,
    a delimiting sequence, and file end. Use file.tell() to see location afterwards.
    Note that file start is a valid split, so must be at offset > 0 to seek for
    delimiter.

    Parameters
    ----------
    file: a file
    delimiter: bytes
        a delimiter like ``b'\n'`` or message sentinel, matching file .read() type
    blocksize: int
        Number of bytes to read from the file at once.


    Returns
    -------
    Returns True if a delimiter was found, False if at file start or end.

    r   FNT)tellreadindexseeklenOSError
ValueError)r	   	delimiter	blocksizelastcurrentfullrF   s          r,   seek_delimiterr\      s   . yy{{au D'))I&& 	5!%2tg~~7		D  JJy))		$))++TQ7#i..HIIItW	))u * $ 	 	 	D	S^^O%%&!'s   A#B< &B< <CCFc                    |r|                      |           t          | |d          }||                                 S |                                 }|||z
  z  }|                      ||z              t          | |d          }|                                 }|r|r|t	          |          z  }|r|r|t	          |          z  }|}||z
  }|                      |           |                     |          }	|	S )a  Read a block of bytes from a file

    Parameters
    ----------
    f: File
        Open file
    offset: int
        Byte offset to start read
    length: int
        Number of bytes to read, read through end of file if None
    delimiter: bytes (optional)
        Ensure reading starts and stops at delimiter bytestring
    split_before: bool (optional)
        Start/stop read *before* delimiter bytestring.


    If using the ``delimiter=`` keyword argument 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, regardless of delimiter.  The bytestring returned WILL
    include the terminating delimiter string.

    Examples
    --------

    >>> from io import BytesIO  # doctest: +SKIP
    >>> f = BytesIO(b'Alice, 100\nBob, 200\nCharlie, 300')  # doctest: +SKIP
    >>> read_block(f, 0, 13)  # doctest: +SKIP
    b'Alice, 100\nBo'

    >>> read_block(f, 0, 13, delimiter=b'\n')  # doctest: +SKIP
    b'Alice, 100\nBob, 200\n'

    >>> read_block(f, 10, 10, delimiter=b'\n')  # doctest: +SKIP
    b'Bob, 200\nCharlie, 300'
    i   )rS   r\   rQ   rP   rT   )
foffsetlengthrW   split_beforefound_start_delimstartfound_end_delimendbs
             r,   
read_blockrg      s    J  	v*1i??>6688O%&. 	uv~(Iu==ffhh  	$ 	$S^^#E 	"| 	"3y>>!CuFF6NNN	vAHr.   c                  8   |r| |fz  } 	 t          t          |                                                                                     S # t          $ rE t          t          |                                           d                                          cY S w xY w)zDeterministic token

    (modified from dask.base)

    >>> tokenize([1, 2, '3'])
    '9d71491b50023b06fc76928e6eddb952'

    >>> tokenize('Hello') == tokenize('Hello')
    True
    F)usedforsecurity)r   rD   encode	hexdigestrV   )argskwargss     r,   tokenizern     s      	J3t99##%%&&00222 J J J3t99##%%u===GGIIIIIJs   ?A
 
ABBc                     t          | t                    r| S t          | d          r|                                 S t          | t          j                  rt          |           S t          | d          r| j        S | S )a6  Attempt to convert a path-like object to a string.

    Parameters
    ----------
    filepath: object to be converted

    Returns
    -------
    filepath_str: maybe a string version of the object

    Notes
    -----
    Objects supporting the fspath protocol are coerced according to its
    __fspath__ method.

    For backwards compatibility with older Python version, pathlib.Path
    objects are specially coerced.

    Any other object is passed through unchanged, which includes bytes,
    strings, buffers, or anything else that's not even path-like.
    
__fspath__r   )
isinstancerD   hasattrrp   pathlibPathr   )filepaths    r,   stringify_pathrv   #  s~    , (C   		<	(	( ""$$$	Hgl	+	+ 8}}	6	"	" }r.   c                 >     | |i |}|                                  |S rC   )_determine_worker)clsrl   rm   insts       r,   make_instancer{   E  s-    3DKr.   c                    d | D             t          d D                       }d}t          |          D ]"t          fdD                       }|s n#|z  d                    d         d                   S )z;For a list of paths, find the shortest prefix common to allc                 8    g | ]}|                     d           S )/)split.0ps     r,   
<listcomp>z!common_prefix.<locals>.<listcomp>M  s"    )))aQWWS\\)))r.   c              3   4   K   | ]}t          |          V  d S rC   )rT   r   s     r,   	<genexpr>z common_prefix.<locals>.<genexpr>N  s(      %%!s1vv%%%%%%r.   r   c              3   H   K   | ]}|         d                   k    V  dS )r   N )r   r   rF   partss     r,   r   z common_prefix.<locals>.<genexpr>Q  s4      55!!A$%(1+%555555r.   r~   N)minrangeallr!   )pathslmaxre   rF   r   s      @@r,   common_prefixr   K  s    ))5)))E%%u%%%%%D
C4[[  55555u55555 	E	HA88E!HRaRL!!!r.   c                 J   t          t                    ri|p                    d          }                    d          t	          |           |r                    dd          d         fd| D             n"t          |           t                    k    sJ S )a  In bulk file operations, construct a new file tree from a list of files

    Parameters
    ----------
    paths: list of str
        The input file tree
    path2: str or list of str
        Root to construct the new list in. If this is already a list of str, we just
        assert it has the right number of elements.
    is_dir: bool (optional)
        For the special case where the input in one element, whether to regard the value
        as the target path, or as a directory to put a file path within. If None, a
        directory is inferred if the path ends in '/'
    exists: bool (optional)
        For a str destination, it is already exists (and is a dir), files should
        end up inside.

    Returns
    -------
    list of str
    r~   r   r   c                 >    g | ]}|                     d           S )r   )replace)r   r   cppath2s     r,   r   zother_paths.<locals>.<listcomp>t  s)    888Q2ua((888r.   )rq   rD   endswithrstripr   r$   rT   )r   r   is_direxistsr   s    `  @r,   other_pathsr   X  s    , % (.5>>#..S!!5!! 	&3""1%B88888%8885zzSZZ''''Lr.   c                 ,    t          | t                    S rC   )rq   BaseExceptionobjs    r,   is_exceptionr   z  s    c=)))r.   c                 6    dD ]}t          | |          s dS dS )N)rQ   closerP   FT)rr   )r^   attrs     r,   
isfileliker   ~  s4    )  q$ 	55	4r.   c                 h    t          j        d| d          }t          |          dk    r|d         S dS )Nz(\:\:|\://)r   r   r	   )r   r   rT   )urlr   s     r,   get_protocolr     s2    H^S!,,E
5zzA~~Qx6r.   c                     ddl m} 	 t           |t          |                     dd          S # t          t
          f$ r Y dS w xY w)z*Can the given URL be used with open_local?r   )get_filesystem_class
local_fileF)fsspecr   getattrr   rV   ImportError)r   r   s     r,   can_be_localr     sf    ++++++++L,>,>??uUUU$   uus   &/ AAc                    | t           j        v r)t           j        |          }t          |d          r|j        S 	 t	          |           S #  Y nxY w	 ddl}|                    |           }|j        S # t          t          f$ r Y dS w xY w)a  For given package name, try to find the version without importing it

    Import and package.__version__ is still the backup here, so an import
    *might* happen.

    Returns either the version string, or None if the package
    or the version was not readily  found.
    __version__r   N)	sysmodulesrr   r   r   	importlibimport_moduler   AttributeError)namemodr   s      r,   "get_package_version_without_importr     s     s{k$3&& 	#?"t}}%%d++(   tts   A AA0 0BBDEBUGTc                 Z   | |t          d          | pt          j        |          } t          j                    }t          j        d          }|                    |           |r| j                                         |                     |           | 	                    |           | S )Nz+Provide either logger object or logger namezD%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s)
rV   logging	getLoggerStreamHandler	FormattersetFormatterhandlersclear
addHandlersetLevel)loggerlogger_namelevelr   handle	formatters         r,   setup_loggingr     s    ~+-FGGG5w(55F"$$F!N I 	"""  
f
OOEMr.   c                 ,    |                     |           S rC   )unstrip_protocol)r   fss     r,   _unstrip_protocolr     s    t$$$r.   c                 "      fdfd}|S )zqMirror attributes and methods from the given
    origin_name attribute of the instance to the
    decorated classc                 D    t          |          }t          ||           S rC   )r   )methodselforiginorigin_names      r,   origin_getterz"mirror_from.<locals>.origin_getter  s"    {++vv&&&r.   c                 n    D ]0}t          |          }t          | |t          |                     1| S rC   )r   setattrproperty)ry   r   wrapped_methodmethodsr   s      r,   wrapperzmirror_from.<locals>.wrapper  sC     	; 	;F$]F;;NC.!9!9::::
r.   r   )r   r   r   r   s   `` @r,   mirror_fromr     sC    
' ' ' ' '      Nr.   c              #      K   | V  d S rC   r   r   s    r,   nullcontextr     s      
IIIIIr.   c           
      &   t          | t                    st          t          |t                    s|gt          |           z  }t          |t                    s|gt          |           z  }t          |          t          |           k    s t          |          t          |           k    rt          t          |          dk    r| ||fS d |D             }|r3d t          t          t          | ||                     D             \  } }}| r| dd         }|dd         }|dd         }t          dt          |                     D ]}	| |	         | |	dz
           k    r	|d          | |	         | |	dz
           k    s,||	         |d         z
  |k    s|g||	         |d         z
  |k    rR|                    | |	                    |                    ||	                    |                    ||	                    ||	         |d<   |||fS | ||fS )a}  Merge adjacent byte-offset ranges when the inter-range
    gap is <= `max_gap`, and when the merged byte range does not
    exceed `max_block` (if specified). By default, this function
    will re-order the input paths and byte ranges to ensure sorted
    order. If the user can guarantee that the inputs are already
    sorted, passing `sort=False` will skip the re-ordering.
    r   c                     g | ]}|pd S )r   r   )r   ss     r,   r   z'merge_offset_ranges.<locals>.<listcomp>  s    %%%af1%%%r.   c                 ,    g | ]}t          |          S r   )list)r   vs     r,   r   z'merge_offset_ranges.<locals>.<listcomp>  s.     
 
 
 GG
 
 
r.   Nr   )	rq   r   	TypeErrorrT   rV   zipsortedr   append)
r   startsendsmax_gap	max_blocksort	new_paths
new_startsnew_endsrF   s
             r,   merge_offset_rangesr     sP    eT"" fd## 'CJJ&dD!! %x#e**$
6{{c%jj  CIIU$;$; 6{{afd""%%f%%%F 

 
vt,, 
 
 
vt  / "1"I	BQBZ
8q#e**%% 	' 	'AQx5Q<''HRL,@aE!a%L((AY"-88*Q*R.0HI/U/U   q***!!&),,,Q((((  $Aw*h.. &$r.   c                     |                                  }	 |                     dd          |                     |           S # |                     |           w xY w)z+Find length of any open read-mode file-liker      )rP   rS   )filelikeposs     r,   	file_sizer     sR    
--//C}}Q""ccs   A ArC   )NF)NNr   T)r   NT)(r   rJ   r9   rs   r   r   
contextlibr   	functoolsr   hashlibr   importlib.metadatar   urllib.parser   DEFAULT_BLOCK_SIZEr-   r&   r=   r@   rN   r\   rg   rn   rv   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r.   r,   <module>r      s-     				  				 



 % % % % % %             & & & & & & ! ! ! ! ! ! O O O Od    	' 	' 	'  :.' .' .'b> > > >BJ J J(  D  
" 
" 
"   D* * *        4    % % %  $   < < < <~    r.   