
    .Phc                     r   d Z ddlZddlZddlZddlZddlZddlZddlmZm	Z	m
Z
 g dZdZdZdZd Z G d	 d
          Zej        ej        z  ej        z  Z eed          r
eej        z  Z eed          r
eej        z  ZeZ eed          r
eej        z  Z	 ddlZd Zn# e$ r d ZY nw xY wd Zd Zej        dk    r8ddl Z ddl m!Z! ddl"m#Z#m$Z$ e j%        j&        j'        Z(e!e!e!e#e$e$ge(_)        d Z*d%dZ+nd Z*d%dZ+e+Z,de*_          G d d          Z-d&dZ.d'dZ/e/Z0 G d d           Z1d!d"d#e2fd$Z3dS )(zVirtually every Python programmer has used Python for wrangling
disk contents, and ``fileutils`` collects solutions to some of the
most commonly-found gaps in the standard library.
    N)copy2copystatError)mkdir_patomic_saveAtomicSaver	FilePermsiter_find_filescopytreei  i     c                     	 t          j        |            nM# t          $ r@}|j        t          j        k    r%t           j                            |           rY d}~dS  d}~ww xY wdS )a!  Creates a directory and any parent directories that may need to
    be created along the way, without raising errors for any existing
    directories. This function mimics the behavior of the ``mkdir -p``
    command available in Linux/BSD environments, but also works on
    Windows.
    N)osmakedirsOSErrorerrnoEEXISTpathisdir)r   excs     Q/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/boltons/fileutils.pyr   r   7   sr    
D   9$$t)<)<$FFFFF Fs    
A!4AAA!c                       e Zd ZdZ G d d          ZddZed             Zed             Zd Z	 ed	d
          Z
	  edd          Z	  edd          Z	 d ZdS )r	   as  The :class:`FilePerms` type is used to represent standard POSIX
    filesystem permissions:

      * Read
      * Write
      * Execute

    Across three classes of user:

      * Owning (u)ser
      * Owner's (g)roup
      * Any (o)ther user

    This class assists with computing new permissions, as well as
    working with numeric octal ``777``-style and ``rwx``-style
    permissions. Currently it only considers the bottom 9 permission
    bits; it does not support sticky bits or more advanced permission
    systems.

    Args:
        user (str): A string in the 'rwx' format, omitting characters
            for which owning user's permissions are not provided.
        group (str): A string in the 'rwx' format, omitting characters
            for which owning group permissions are not provided.
        other (str): A string in the 'rwx' format, omitting characters
            for which owning other/world permissions are not provided.

    There are many ways to use :class:`FilePerms`:

    >>> FilePerms(user='rwx', group='xrw', other='wxr')  # note character order
    FilePerms(user='rwx', group='rwx', other='rwx')
    >>> int(FilePerms('r', 'r', ''))
    288
    >>> oct(288)[-3:]  # XXX Py3k
    '440'

    See also the :meth:`FilePerms.from_int` and
    :meth:`FilePerms.from_path` classmethods for useful alternative
    ways to construct :class:`FilePerms` objects.
    c                   N    e Zd ZdZ ed          ZddddZd ZddZd	 Z	d
 Z
dS )FilePerms._FilePermPropertyrwx         )rwxc                 "    || _         || _        d S N)	attributeoffset)selfr#   r$   s      r   __init__z$FilePerms._FilePermProperty.__init__v   s    &DN DKKK    Nc                 4    || S t          || j                  S r"   )getattrr#   )r%   fp_objtype_s      r   __get__z#FilePerms._FilePermProperty.__get__z   s    ~64>222r'   c                     t          | j                  }||k    rd S 	 t          t          |                     j        z
  }n # t
          $ r t          d|z            w xY w|rt          d|d|d j                   fd}d                    t          t          |          |d                    }t          | j        |                                ||           d S )	Nzexpected string, not %rzgot invalid chars z in permission specification z*, expected empty string or one or more of c                     j         |          S r"   )	_perm_val)cr%   s    r   sort_keyz5FilePerms._FilePermProperty.__set__.<locals>.sort_key   s    DN1$55r'    T)keyreverse)r)   r#   setstr	_perm_set	TypeError
ValueError_perm_charsjoinsortedsetattr_update_integer)r%   r*   valuecurinvalid_charsr1   	new_values   `      r   __set__z#FilePerms._FilePermProperty.__set__   s)   &$.11Ce||C #CJJ$. @ C C C 9E ABBBC M j %2MM555$:J:J"L M M M
 65555s5zz+3T!C !C !C D DIFDNI666  33333s   $A A"c                     d}d}|D ]*}d|                     |          z  }||| j        dz  z  z  }+|xj        |z  c_        d S )Nr   xwrr      )indexr$   _integer)r%   r*   r?   moder3   symbolbits          r   r>   z+FilePerms._FilePermProperty._update_integer   s\    DC 3 3399V,,,q12OOt#OOOOr'   r"   )__name__
__module____qualname__r:   	frozensetr7   r/   r&   r,   rC   r>    r'   r   _FilePermPropertyr   q   sx        Ie$$	!!,,		! 	! 	!	3 	3 	3 	3
	4 	4 	4(	$ 	$ 	$ 	$ 	$r'   rQ   r2   c                 h    d\  | _         | _        | _        d| _        || _        || _        || _        d S )Nr2   r2   r2   r   )_user_group_otherrH   usergroupother)r%   rW   rX   rY   s       r   r&   zFilePerms.__init__   s4    /9,
DK	



r'   c                     |t           z  }d}g }|r*|                    ||t          z                      |dz  }|*|                                  | | S )zCreate a :class:`FilePerms` object from an integer.

        >>> FilePerms.from_int(0o644)  # note the leading zero-oh for octal
        FilePerms(user='rw', group='r', other='r')
        )r2   r    r   xwr   rxrwr   rF   )
FULL_PERMSappend_SINGLE_FULL_PERMr4   )clsir3   partss       r   from_intzFilePerms.from_int   sj     	
Z: 	LLQ!223444!GA  	 	sE{r'   c                     t          j        |          }|                     t          j        |j                            S )ao  Make a new :class:`FilePerms` object based on the permissions
        assigned to the file or directory at *path*.

        Args:
            path (str): Filesystem path of the target file.

        Here's an example that holds true on most systems:

        >>> import tempfile
        >>> 'r' in FilePerms.from_path(tempfile.gettempdir()).user
        True
        )r   statrd   S_IMODEst_mode)ra   r   stat_ress      r   	from_pathzFilePerms.from_path   s0     74==||DL)9::;;;r'   c                     | j         S r"   )rH   r%   s    r   __int__zFilePerms.__int__   s
    }r'   rT   r   rU   r   rV   r   c                 T    | j         j        }|d| j        d| j        d| j        dS )Nz(user=z, group=z, other=))	__class__rL   rW   rX   rY   )r%   cns     r   __repr__zFilePerms.__repr__   s5    ^$22tyyy$***djjj: 	;r'   NrS   )rL   rM   rN   __doc__rQ   r&   classmethodrd   rj   rm   rW   rX   rY   rr   rP   r'   r   r	   r	   G   s        ' 'R($ ($ ($ ($ ($ ($ ($ ($T      [ < < [<    Wa((D5h**E6h**E6; ; ; ; ;r'   r	   O_NOINHERIT
O_NOFOLLOWO_BINARYc                     	 t          j         | t           j        d          }|t           j        z  }t          j         | t           j        |           n# t          $ r Y nw xY wdS )zDoes a best-effort :func:`fcntl.fcntl` call to set a fd to be
        automatically closed by any future child processes.

        Implementation from the :mod:`tempfile` module.
        r   N)fcntlF_GETFD
FD_CLOEXECF_SETFDr   )fdflagss     r   set_cloexecr      sm    	2KEM155E
 U%%EKEM51111  	 	 	D	 	s    A 
AAc                     dS )z5Dummy set_cloexec for platforms without fcntl supportNrP   )r}   s    r   r   r      s    r'   c                     t          | fi |S )a  A convenient interface to the :class:`AtomicSaver` type. Example:

    >>> try:
    ...     with atomic_save("file.txt", text_mode=True) as fo:
    ...         _ = fo.write('bye')
    ...         1/0  # will error
    ...         fo.write('bye')
    ... except ZeroDivisionError:
    ...     pass  # at least our file.txt didn't get overwritten

    See the :class:`AtomicSaver` documentation for details.
    )r   )	dest_pathkwargss     r   r   r      s     y++F+++r'   c                     t          | t                    r| S t          j                    pt          j                    }|                     |          S r"   )
isinstancer6   sysgetfilesystemencodinggetdefaultencodingdecode)r   encodings     r   path_to_unicoder     sG    $ (**Fc.D.F.FH;;x   r'   nt)	c_wchar_p)DWORDLPVOIDc                 X   	 t          j        | |           d S # t          $ r!}|j        t          j        k    rn Y d }~nd }~ww xY wt          |           } t          |          }t          t          |          t          |           d dd d           }|st          d|d|           d S )Nr   zfailed to replace z with )r   renamer   r   r   r   _ReplaceFiler   )srcdstweress       r   replacer     s    		 Ic3F 	 	 	x5<'' 	 c""c""9S>>9S>>D$0 0 	ECsCCCCCDDDs    
A?AFc                 V    |rt          | |           nt          j        | |           dS z<Rename *src* to *dst*, replacing *dst* if *overwrite is TrueN)r   r   r   r   r   	overwrites      r   atomic_renamer   -  s4     	 CIc3r'   c                 ,    t          j        | |          S r"   )r   r   )r   r   s     r   r   r   6  s    yc"""r'   c                     |rt          j        | |           n)t          j        | |           t          j        |            dS r   )r   r   linkunlinkr   s      r   r   r   :  sC     	Ic3GCIcNNNr'   a   Similar to :func:`os.replace` in Python 3.3+,
this function will atomically create or replace the file at path
*dst* with the file at path *src*.

On Windows, this function uses the ReplaceFile API for maximum
possible atomicity on a range of filesystems.
c                   4    e Zd ZdZeZd Zd Zd Zd Z	d Z
dS )r   a(
  ``AtomicSaver`` is a configurable `context manager`_ that provides
    a writable :class:`file` which will be moved into place as long as
    no exceptions are raised within the context manager's block. These
    "part files" are created in the same directory as the destination
    path to ensure atomic move operations (i.e., no cross-filesystem
    moves occur).

    Args:
        dest_path (str): The path where the completed file will be
            written.
        overwrite (bool): Whether to overwrite the destination file if
            it exists at completion time. Defaults to ``True``.
        file_perms (int): Integer representation of file permissions
            for the newly-created file. Defaults are, when the
            destination path already exists, to copy the permissions
            from the previous file, or if the file did not exist, to
            respect the user's configured `umask`_, usually resulting
            in octal 0644 or 0664.
        text_mode (bool): Whether to open the destination file in text
            mode (i.e., ``'w'`` not ``'wb'``). Defaults to ``False`` (``wb``).
        part_file (str): Name of the temporary *part_file*. Defaults
            to *dest_path* + ``.part``. Note that this argument is
            just the filename, and not the full path of the part
            file. To guarantee atomic saves, part files are always
            created in the same directory as the destination path.
        overwrite_part (bool): Whether to overwrite the *part_file*,
            should it exist at setup time. Defaults to ``False``,
            which results in an :exc:`OSError` being raised on
            pre-existing part files. Be careful of setting this to
            ``True`` in situations when multiple threads or processes
            could be writing to the same part file.
        rm_part_on_exc (bool): Remove *part_file* on exception cases.
            Defaults to ``True``, but ``False`` can be useful for
            recovery in some cases. Note that resumption is not
            automatic and by default an :exc:`OSError` is raised if
            the *part_file* exists.

    Practically, the AtomicSaver serves a few purposes:

      * Avoiding overwriting an existing, valid file with a partially
        written one.
      * Providing a reasonable guarantee that a part file only has one
        writer at a time.
      * Optional recovery of partial data in failure cases.

    .. _context manager: https://docs.python.org/2/reference/compound_stmts.html#with
    .. _umask: https://en.wikipedia.org/wiki/Umask

    c                 b   || _         |                    dd          | _        |                    dd           | _        |                    dd          | _        |                    dd           | _        |                    dd          | _        |                    dd          | _        |                    d	d
          | _        |r$t          d|
                                          t          j                            | j                   | _         t          j                            | j                   | _        | j        s|dz   | _        n/t          j                            | j        | j                  | _        | j        rdnd| _        | j        rt&          nt(          | _        d | _        d S )Nr   T
file_permsoverwrite_partF	part_filerm_part_on_exc	text_mode	bufferingzunexpected kwargs: z.partzw+zw+b)r   popr   r   r   part_filenamer   r   r   r8   keysr   r   abspathdirnamedest_dir	part_pathr;   rI   _TEXT_OPENFLAGS_BIN_OPENFLAGS
open_flagsr   )r%   r   r   s      r   r&   zAtomicSaver.__init__  s\   "K66 **\488$jj)95AA#ZZT::$jj)94@@K77K44 	EC&++--CCDDD8877! 	M&0DNNW\\$-9KLLDN N5DD	-1^O//r'   c                    d}| j         }|M	 t          j        | j                  }t          j        |j                  }n# t          $ r | j        }d}Y nw xY wt          j        | j	        | j
        |          }t          |           t          j        || j        | j                  | _        |rD	 t          j        | j	        |           n(# t          $ r | j                                          w xY wd S )NTF)r   r   rf   r   rg   rh   r   _default_file_permsopenr   r   r   fdopenrI   r   r   chmodclose)r%   do_chmodr   ri   r}   s        r   _open_part_filezAtomicSaver._open_part_file  s   _
!74>22!\(*:;;

 ! ! !!5
 !
 WT^T_jAAB2ty$.AA  	4444   $$&&& 	s   2A   AA0C %C0c                 L   t           j                            | j                  r'| j        s t          t          j        d| j                  | j        r=t           j                            | j	                  rt          j
        | j	                   |                                  dS )aS  Called on context manager entry (the :keyword:`with` statement),
        the ``setup()`` method creates the temporary file in the same
        directory as the destination file.

        ``setup()`` tests for a writable directory with rename permissions
        early, as the part file may not be written to immediately (not
        using :func:`os.access` because of the potential issues of
        effective vs. real privileges).

        If the caller is not using the :class:`AtomicSaver` as a
        context manager, this method should be called explicitly
        before writing.
        z*Overwrite disabled and file already existsN)r   r   lexistsr   r   r   r   r   r   r   r   r   rl   s    r   setupzAtomicSaver.setup  s     7??4>** 	.> .elJ"n. . .  	&27??4>#B#B 	&Idn%%%r'   c                 8    |                                   | j        S r"   )r   r   rl   s    r   	__enter__zAtomicSaver.__enter__  s    

~r'   c                    | j         r]| j                                          t          j        | j                                                    | j                                          |r4| j        r+	 t          j        | j                   n# t          $ r Y nw xY wd S 	 t          | j        | j        | j                   nA# t          $ r4 | j        r+	 t          j        | j                   n# t          $ r Y nw xY w w xY wd S )N)r   )r   flushr   fsyncfilenor   r   r   r   	Exceptionr   r   r   r   r%   exc_typeexc_valexc_tbs       r   __exit__zAtomicSaver.__exit__  s<   > 	#N  """HT^**,,---N  """ 	" Idn----    DF		$.$.$(N4 4 4 4 4 	 	 	" Idn----    D	 	sB   /B	 	
BB!B> >C<C*)C<*
C74C<6C77C<N)rL   rM   rN   rs   RW_PERMSr   r&   r   r   r   r   rP   r'   r   r   r   O  sr        0 0b #  .  6  0      r'   r   c              #     K   t          |t                    r|g}t          j        d                    d |D                                 }|sg }nt          |t                    r|g}t          j        d                    d |D                                 }t          |                     t          j        j	                            }t          j
        |           D ]\  }}	}
|9t          |                    t          j        j	                            |z
  |k    rA|rV|	D ]S}|                    |          r<|r|                    |          r/t          j                            ||          }|V  T|
D ]S}|                    |          r<|r|                    |          r/t          j                            ||          }|V  TdS )a  Returns a generator that yields file paths under a *directory*,
    matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also
    supports *ignored* patterns.

    Args:
        directory (str): Path that serves as the root of the
            search. Yielded paths will include this as a prefix.
        patterns (str or list): A single pattern or list of
            glob-formatted patterns to find under *directory*.
        ignored (str or list): A single pattern or list of
            glob-formatted patterns to ignore.
        include_dirs (bool): Whether to include directories that match
           patterns, as well. Defaults to ``False``.
        max_depth (int): traverse up to this level of subdirectory.
           I.e., 0 for the specified *directory* only, 1 for *directory* 
           and one level of subdirectory.

    For example, finding Python files in the current directory:

    >>> _CUR_DIR = os.path.dirname(os.path.abspath(__file__))
    >>> filenames = sorted(iter_find_files(_CUR_DIR, '*.py'))
    >>> os.path.basename(filenames[-1])
    'urlutils.py'

    Or, Python files while ignoring emacs lockfiles:

    >>> filenames = iter_find_files(_CUR_DIR, '*.py', ignored='.#*')

    .. _glob: https://en.wikipedia.org/wiki/Glob_%28programming%29

    |c                 6    g | ]}t          j        |          S rP   fnmatch	translate.0ps     r   
<listcomp>z#iter_find_files.<locals>.<listcomp>  s#    "J"J"JA7#4Q#7#7"J"J"Jr'   c                 6    g | ]}t          j        |          S rP   r   r   s     r   r   z#iter_find_files.<locals>.<listcomp>  s#    !H!H!H1'"3A"6"6!H!H!Hr'   N)r   r6   recompiler;   lensplitr   r   sepwalkmatch)	directorypatternsignoredinclude_dirs	max_depthpats_reign_restart_depthrootdirsfilesbasenamefilenames                r   r
   r
     s     @ (C   :j"J"J"J"J"JKKLLG 	GS	!	! )Z!H!H!H!H!HIIJJFioobgk2233KWY//  dE c$**RW[*A*A&B&B[&PT]%]%] 	#  # #==** # !6<<#9#9 ! !w||D(;;H"NNN 	 	H}}X&&  v||H55 7<<h77	 Fr'   c           	         t          j        |           }| || |          }nt                      }t          |           g }|D ]E}||v rt           j                            | |          }t           j                            ||          }		 |rIt           j                            |          r*t          j        |          }
t          j        |
|	           nBt           j        	                    |          rt          ||	||           nt          ||	           # t          $ r+}|                    |j        d                    Y d}~d}~wt          $ r0}|                    ||	t#          |          f           Y d}~?d}~ww xY w	 t%          | |           n<# t          $ r/}|                    | |t#          |          f           Y d}~nd}~ww xY w|rt          |          dS )a3  The ``copy_tree`` function is an exact copy of the built-in
    :func:`shutil.copytree`, with one key difference: it will not
    raise an exception if part of the tree already exists. It achieves
    this by using :func:`mkdir_p`.

    As of Python 3.8, you may pass :func:`shutil.copytree` the
    `dirs_exist_ok=True` flag to achieve the same effect.

    Args:
        src (str): Path of the source directory to copy.
        dst (str): Destination path. Existing directories accepted.
        symlinks (bool): If ``True``, copy symlinks rather than their
            contents.
        ignore (callable): A callable that takes a path and directory
            listing, returning the files within the listing to be ignored.

    For more details, check out :func:`shutil.copytree` and
    :func:`shutil.copy2`.

    Nr   )r   listdirr5   r   r   r;   islinkreadlinksymlinkr   r   r   r   extendargsr   r_   r6   r   )r   r   symlinksignorenamesignored_nameserrorsnamesrcnamedstnamelinktoewhys                r   	copy_treer   *  s   * JsOOEsE**CLLLF 8 8=  ',,sD))',,sD))	8 (BGNN733 (W--
67++++w'' ('8V<<<< gw'''  	% 	% 	%MM!&)$$$$$$$$ 	8 	8 	8MM7GSXX677777777	8,c , , ,sCS*++++++++, Fmm s=   BD
F	& EF	%FF	F 
G(%GGc                   v    e Zd ZddZd Zd Zd Zd Zdd	Zdd
Z	ddZ
d Zd Zd Zd Zd Zd Zd Zd ZdS )	DummyFiler   Nc                 v    || _         || _        d| _        d | _        d| _        d | _        d | _        d| _        d S )NFr   )r   rI   closedr   isattyr   newlines	softspace)r%   r   rI   r   s       r   r&   zDummyFile.__init__j  s>    		r'   c                     d| _         d S )NT)r  rl   s    r   r   zDummyFile.closet  s    r'   c                     dS )Nr   rP   rl   s    r   r   zDummyFile.filenow  s    rr'   c                 2    | j         rt          d          d S NI/O operation on a closed filer  r9   rl   s    r   r   zDummyFile.flushz       ; 	?=>>>r'   c                     t                      r"   StopIterationrl   s    r   nextzDummyFile.next      oor'   r   c                 2    | j         rt          d          dS Nr	  r2   r
  r%   sizes     r   readzDummyFile.read       ; 	?=>>>rr'   c                 2    | j         rt          d          dS r  r
  r  s     r   readlinezDummyFile.readline  r  r'   c                 2    | j         rt          d          g S r  r
  r  s     r   	readlineszDummyFile.readlines  s     ; 	?=>>>	r'   c                 2    | j         rt          d          d S r  r
  rl   s    r   seekzDummyFile.seek  r  r'   c                 2    | j         rt          d          dS )Nr	  r   r
  rl   s    r   tellzDummyFile.tell  s     ; 	?=>>>qr'   c                 2    | j         rt          d          d S r  r
  rl   s    r   truncatezDummyFile.truncate  r  r'   c                 2    | j         rt          d          d S r  r
  )r%   strings     r   writezDummyFile.write  r  r'   c                 2    | j         rt          d          d S r  r
  )r%   list_of_stringss     r   
writelineszDummyFile.writelines  r  r'   c                     t                      r"   r  rl   s    r   __next__zDummyFile.__next__  r  r'   c                 2    | j         rt          d          d S r  r
  rl   s    r   r   zDummyFile.__enter__  r  r'   c                     d S r"   rP   r   s       r   r   zDummyFile.__exit__  s    r'   )r   N)r   )rL   rM   rN   r&   r   r   r   r  r  r  r  r  r  r   r#  r&  r(  r   r   rP   r'   r   r   r   g  s                
     
   
   
  
  
  
  
  
    
    r'   r      )keepr,  c          
      &   |dk     rt          d|           t          j                            |           sdS t          j                            |           st          d|  d          t          j                            |           \  }}g }t          d|dz             D ];}|r|                    | d| |            !|                    | d|            <| g|z   }t          t          t          ||dd                                       D ]:\  }}t          j                            |          s%t          j        ||           ;t          j                            |d                   rt          j        |d                    dS )a4  
    If *filename.ext* exists, it will be moved to *filename.1.ext*, 
    with all conflicting filenames being moved up by one, dropping any files beyond *keep*.

    After rotation, *filename* will be available for creation as a new file.

    Fails if *filename* is not a file or if *keep* is not > 0.
    r   zexpected "keep" to be >=1, not Nz	expected z to be a file.r   )r9   r   r   existsisfilesplitextranger_   reversedlistzipr   remove)	r   r,  fn_rootfn_ext
kept_namesrb   fns	orig_name	kept_names	            r   rotate_filer=    s    axxA4AABBB7>>(## 7>>(## ><X<<<===g&&x00OGVJ1dQh 0 0 	06616f667777..1..////*z
!C (c#s122w.?.?)@)@ A A ( (	9w~~i(( 	
	)Y''''	w~~jn%% "
	*R.!!!
Fr'   )F)NFN)FN)4rs   r   r   r   rf   r   r   shutilr   r   r   __all__r^   r   r`   r   r	   O_RDWRO_CREATO_EXCLr   hasattrru   rv   r   rw   ry   r   ImportErrorr   r   r   ctypesr   ctypes.wintypesr   r   windllkernel32ReplaceFiler   argtypesr   r   _atomic_renamer   r
   r   r   r   intr=  rP   r'   r   <module>rM     sD  >  
			 				 



    ) ) ) ) ) ) ) ) ) )* * * 
    J; J; J; J; J; J; J; J;^ )bj(294
72} &r~%O
72| %r}$O 
72z "bk!N           ,, , , ! ! ! 7d??MMM      --------=)5L&	9"FF4L  *    # # #    Z Z Z Z Z Z Z Zz; ; ; ;|6 6 6 6r L L L L L L L L^ *+ ! ! !3 ! ! ! ! ! !s   B# #B.-B.