
    <[j0                    |   U 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	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 d dlmZ d dlmZmZmZmZ esej        dk    rd dlZnd dlmZ er2d dlmZ d d	lm Z m!Z!m"Z" d d
l#m$Z$m%Z%m&Z&  ede           Z' e$d          Z(e)e*e+         dz  e+dz  edz  f         Z,de-d<    ed          Z. edd          Z/ edd          Z0ej1        dCd            Z2ej1        dDdEd            Z3d Z4dFd$Z5 e4ej6        e5          Z7dGd(Z8 e8e2e3          Z9	 dHd.Z:dId0Z;ej1        e	j<        fdJd4            Z= ej>        e= e;            5          Z?ej1        dde?fdKd<            Z@ G d= d>          ZA G d? d@ejB        ejC                  ZB G dA dBejC                  ZDdS )L    )annotationsN)Callable	GeneratorIterator)TracebackType)TYPE_CHECKINGLiteralTypeVarcast)      )tarfile)	TypeAlias)FileDescriptorOrPath
OptExcInfoStrPath)	ParamSpecSelfUnpack_FileDescriptorOrPathT)bound_Pr   _UnpackableOptExcInfo_R_T1_coT)	covariant_T2_codirr   returnIterator[StrPath]c              #     K   t          j                    }t          j        |            	 | V  t          j        |           dS # t          j        |           w xY w)z
    >>> tmp_path = getfixture('tmp_path')
    >>> with pushd(tmp_path):
    ...     assert os.getcwd() == os.fspath(tmp_path)
    >>> assert os.getcwd() != os.fspath(tmp_path)
    N)osgetcwdchdir)r   origs     _/home/thesage/.hermes/hermes-agent/venv/lib/python3.11/site-packages/jaraco/context/__init__.pypushdr'   4   sQ       9;;DHSMMM			
s   A Aurlstr
target_dirStrPath | Nonec              #    K   |Gt           j                            |                               dd                              dd          }t          j        |           	 t
          j                            |           }t          j	        |d          5 }|
                    |t                     ddd           n# 1 swxY w Y   |V  t          j        |           dS # t          j        |           w xY w)au  
    Get a URL to a tarball, download, extract, yield, then clean up.

    Assumes everything in the tarball is prefixed with a common
    directory. That common path is stripped and the contents
    are extracted to ``target_dir``, similar to passing
    ``-C {target} --strip-components 1`` to the ``tar`` command.

    Uses the streaming protocol to extract the contents from a
    stream in a single pass without loading the whole file into
    memory.

    >>> import urllib.request
    >>> url = getfixture('tarfile_served')
    >>> target = getfixture('tmp_path') / 'out'
    >>> tb = tarball(url, target_dir=target)
    >>> import pathlib
    >>> with tb as extracted:
    ...     contents = pathlib.Path(extracted, 'contents.txt').read_text(encoding='utf-8')
    >>> assert not os.path.exists(extracted)

    If the target is not specified, contents are extracted to a
    directory relative to the current working directory named after
    the name of the file as extracted from the URL.

    >>> target = getfixture('tmp_path')
    >>> with pushd(target), tarball(url):
    ...     target.joinpath('served').is_dir()
    True
    Nz.tar.gz z.tgzzr|*)fileobjmode)pathfilter)r"   r0   basenamereplacemkdirurllibrequesturlopenr   open
extractall_default_filtershutilrmtree)r(   r*   reqtfs       r&   tarballr?   E   s4     @ W%%c**229bAAII&RTUU
HZ"n$$S))\#E222 	CbMMz/MBBB	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	Cj!!!!!j!!!!s0   !5C$ B?3C$ ?CC$ CC$ $C:c                 6    d }t          j        || d           S )Nc                      fdS )Nc                0      | |          |          S N )memberr0   f1f2s     r&   <lambda>z?_compose_tarfile_filters.<locals>.compose_two.<locals>.<lambda>s   s    BBrr&$'7'7$>$>     rD   )rF   rG   s   ``r&   compose_twoz-_compose_tarfile_filters.<locals>.compose_twor   s    >>>>>>rI   c                    | S rC   rD   )rE   r0   s     r&   rH   z*_compose_tarfile_filters.<locals>.<lambda>u   s    v rI   )	functoolsreduce)filtersrJ   s     r&   _compose_tarfile_filtersrO   q   s,    ? ? ? K2M2MNNNrI   rE   tarfile.TarInfor0   objectc                L    | j                             dd          \  }| _         | S )N/   )namesplit)rE   r0   _s      r&   strip_first_componentrX   x   s&     [&&sA..NAv{MrI   cmgrsUnpack[tuple[Callable[[_T1_co], contextlib.AbstractContextManager[_T2_co]], Callable[_P, contextlib.AbstractContextManager[_T1_co]]]]9Callable[_P, contextlib._GeneratorContextManager[_T2_co]]c                 N    dd}t          j        |t          |                     S )	a  
    Compose any number of dependent context managers into a single one.

    The last, innermost context manager may take arbitrary arguments, but
    each successive context manager should accept the result from the
    previous as a single parameter.

    Like :func:`jaraco.functools.compose`, behavior works from right to
    left, so the context manager should be indicated from outermost to
    innermost.

    Example, to create a context manager to change to a temporary
    directory:

    >>> temp_dir_as_cwd = _compose(pushd, temp_dir)
    >>> with temp_dir_as_cwd() as dir:
    ...     assert os.path.samefile(os.getcwd(), dir)
    inner7Callable[_P, contextlib.AbstractContextManager[_T1_co]]outer=Callable[[_T1_co], contextlib.AbstractContextManager[_T2_co]]r   r[   c                <     d fd}t          j        |          S )	Nargs_P.argskwargs	_P.kwargsr   Generator[_T2_co]c               ?     K    | i |5 } |          5 }|V  d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S rC   rD   )rb   rd   savedresr]   r_   s       r&   composedz/_compose.<locals>.compose_two.<locals>.composed   s      ''' 5%%,, #			                                s,   A)A-	A-	AAA)rb   rc   rd   re   r   rf   )
contextlibcontextmanager)r]   r_   rj   s   `` r&   rJ   z_compose.<locals>.compose_two   s:    	 	 	 	 	 	 	 (222rI   )r]   r^   r_   r`   r   r[   )rL   rM   reversed)rY   rJ   s     r&   _composern      s1    83 3 3 3 K%999rI   func*Callable[[_FileDescriptorOrPathT], object]exc_infotuple[object, OSError, object]Nonec                   |\  }}}| t           j        t           j        t           j        fv r[|j        t          j        k    rFt          j        |t          j        t          j	        z  t          j
        z              | |           dS  )z>
    Add support for removing read-only files on Windows.
    N)r"   rmdirremoveunlinkerrnoEACCESchmodstatS_IRWXUS_IRWXGS_IRWXO)ro   r0   rq   rW   excs        r&   remove_readonlyr      sk     IAsA")RY///CI4M4M
t|dl2T\ABBBT




rI   Callable[..., None]c                     t          j                    dk    r3t          j        t	          dt
          j                  t                    nt
          j        S )NWindowsr   )onerror)platformsystemrL   partialr   r;   r<   r   rD   rI   r&   robust_removerr      sR     ?	)) 	&66#	
 	
 	
 	
 ]rI   removerCallable[[str], object]Generator[str]c              #  p   K   t          j                    }	 |V   | |           dS #  | |           w xY w)z
    Create a temporary directory context. Pass a custom remover
    to override the removal behavior.

    >>> import pathlib
    >>> with temp_dir() as the_dir:
    ...     assert os.path.isdir(the_dir)
    >>> assert not os.path.exists(the_dir)
    N)tempfilemkdtemp)r   temp_dirs     r&   r   r      sP       !!Hs   ( 5)r   branch
str | Nonequietbooldest_ctx4Callable[[], contextlib.AbstractContextManager[str]]c              #    K   d| v rdnd} |            5 }|d| |g}|                     d|gt          |          z             |rt          j        nd}t          j        |||           |V  ddd           dS # 1 swxY w Y   dS )a  
    Check out the repo indicated by url.

    If dest_ctx is supplied, it should be a context manager
    to yield the target directory for the check out.

    >>> getfixture('ensure_git')
    >>> getfixture('needs_internet')
    >>> repo = repo_context('https://github.com/jaraco/jaraco.context')
    >>> with repo as dest:
    ...     listing = os.listdir(dest)
    >>> 'README.rst' in listing
    True
    githgclonez--branchN)stdoutstderr)extendr   
subprocessDEVNULL
check_call)r(   r   r   r   exerepo_dircmdstreams           r&   repo_contextr      s      * C<<%%TC	 xGS(+

J'$v,,6777',6##$c&@@@@                 s   AA;;A?A?c                      e Zd ZU dZdZded<   effddZd d
Ze	d!d            Z
e	d"d            Ze	d#d            Zd$dZd%dZedd&dZd'dZdS )(ExceptionTrapa  
    A context manager that will catch certain exceptions and provide an
    indication they occurred.

    >>> with ExceptionTrap() as trap:
    ...     raise Exception()
    >>> bool(trap)
    True

    >>> with ExceptionTrap() as trap:
    ...     pass
    >>> bool(trap)
    False

    >>> with ExceptionTrap(ValueError) as trap:
    ...     raise ValueError("1 + 1 is not 3")
    >>> bool(trap)
    True
    >>> trap.value
    ValueError('1 + 1 is not 3')
    >>> trap.tb
    <traceback object at ...>

    >>> with ExceptionTrap(ValueError) as trap:
    ...     raise Exception()
    Traceback (most recent call last):
    ...
    Exception

    >>> bool(trap)
    False
    )NNNr   rq   
exceptionstuple[type[BaseException], ...]c                    || _         d S rC   )r   )selfr   s     r&   __init__zExceptionTrap.__init__+  s    $rI   r   r   c                    | S rC   rD   r   s    r&   	__enter__zExceptionTrap.__enter__.      rI   type[BaseException] | Nonec                    | j         d         S Nr   rq   r   s    r&   typezExceptionTrap.type1      }QrI   BaseException | Nonec                    | j         d         S )NrT   r   r   s    r&   valuezExceptionTrap.value5  r   rI   TracebackType | Nonec                    | j         d         S )N   r   r   s    r&   tbzExceptionTrap.tb9  r   rI   Unpack[_UnpackableOptExcInfo]*builtins.type[BaseException] | None | boolc                V    |d         }|ot          || j                  }|r|| _        |S r   )
issubclassr   rq   )r   rq   exc_typematchess       r&   __exit__zExceptionTrap.__exit__=  s7     A;Dz(DODD 	%$DMrI   r   c                *    t          | j                  S rC   )r   r   r   s    r&   __bool__zExceptionTrap.__bool__G  s    DIrI   _testro   Callable[_P, _R]r   Callable[[ExceptionTrap], bool]$functools._Wrapped[_P, _R, _P, bool]c               P     t          j                  d fd            }|S )	a>  
        Wrap func and replace the result with the truth
        value of the trap (True if an exception occurred).

        Decorate a function that always fails.

        >>> @ExceptionTrap(ValueError).raises
        ... def fail():
        ...     raise ValueError('failed')
        >>> fail()
        True
        rb   rc   rd   re   r   r   c                     t          j                  5 } | i | d d d            n# 1 swxY w Y    |          S rC   )r   r   )rb   rd   trapr   ro   r   s      r&   wrapperz%ExceptionTrap.raises.<locals>.wrapperZ  s    t// &4d%f%%%& & & & & & & & & & & & & & &5;;s   	+//)rb   rc   rd   re   r   r   )rL   wraps)r   ro   r   r   s   ``` r&   raiseszExceptionTrap.raisesJ  sK      
			 	 	 	 	 	 	 
		
 rI   c                D    |                      |t          j                  S )a7  
        Wrap func and replace the result with the truth
        value of the trap (True if no exception).

        Decorate a function that always fails.

        >>> @ExceptionTrap(ValueError).passes
        ... def fail():
        ...     raise ValueError('failed')

        >>> fail()
        False
        r   )r   operatornot_)r   ro   s     r&   passeszExceptionTrap.passesb  s     {{4x}{555rI   N)r   r   r   r   )r   r   )r   r   )r   r   )rq   r   r   r   )r   r   )ro   r   r   r   r   r   )ro   r   r   r   )__name__
__module____qualname____doc__rq   __annotations__	Exceptionr   r   propertyr   r   r   r   r   r   r   r   rD   rI   r&   r   r     s'         B ,H++++FO\ % % % % %          X        X        X        SW     06 6 6 6 6 6rI   r   c                      e Zd ZdZdS )suppressz
    A version of contextlib.suppress with decorator support.

    >>> @suppress(KeyError)
    ... def key_error():
    ...     {}['']
    >>> key_error()
    N)r   r   r   r   rD   rI   r&   r   r   s  s           rI   r   c                  .    e Zd ZdZ	 dddZddZddZdS )on_interruptaF  
    Replace a KeyboardInterrupt with SystemExit(1).

    Useful in conjunction with console entry point functions.

    >>> def do_interrupt():
    ...     raise KeyboardInterrupt()
    >>> on_interrupt('error')(do_interrupt)()
    Traceback (most recent call last):
    ...
    SystemExit: 1
    >>> on_interrupt('error', code=255)(do_interrupt)()
    Traceback (most recent call last):
    ...
    SystemExit: 255
    >>> on_interrupt('suppress')(do_interrupt)()
    >>> with __import__('pytest').raises(KeyboardInterrupt):
    ...     on_interrupt('ignore')(do_interrupt)()
    errorrT   codeintaction&Literal['ignore', 'suppress', 'error']c               "    || _         || _        d S rC   )r   r   )r   r   r   s      r&   r   zon_interrupt.__init__  s     			rI   r   r   c                    | S rC   rD   r   s    r&   r   zon_interrupt.__enter__  r   rI   exctyper   excinstr   exctbr   None | boolc                    |t           us| j        dk    rd S | j        dk    rt          | j                  || j        dk    S )Nignorer   r   )KeyboardInterruptr   
SystemExitr   )r   r   r   r   s       r&   r   zon_interrupt.__exit__  sM     +++t{h/F/F4[G##TY''W4{j((rI   N)r   rT   )r   r   r   r   r   )r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   rD   rI   r&   r   r   ~  sf         * XY       
) 
) 
) 
) 
) 
)rI   r   )r   r   r   r    rC   )r(   r)   r*   r+   r   r    )rE   rP   r0   rQ   r   rP   )rY   rZ   r   r[   )ro   rp   r0   r   rq   rr   r   rs   )r   r   )r   r   r   r   )
r(   r)   r   r   r   r   r   r   r   r   )E
__future__r   builtinsrk   rx   rL   r   r"   r   r;   r{   r   sysr   urllib.requestr5   collections.abcr   r   r   typesr   typingr   r	   r
   r   version_infor   	backportsr   	_typeshedr   r   r   typing_extensionsr   r   r   r   r   tupler   BaseExceptionr   r   r   r   r   rl   r'   r?   rO   rX   data_filterr:   rn   tarball_cwdr   r   r<   r   r   robust_temp_dirr   r   r   ContextDecoratorr   rD   rI   r&   <module>r     s3   " " " " " " "            				        



      9 9 9 9 9 9 9 9 9 9                   "C$//NNNN!!!!!! 	      CCCCCCCCCC9999999999$W (<   
4B#($DD$     
 WT]]	T	*	*	*	T	*	*	*      (" (" (" (" ("VO O O    +*7+>@UVV*: *: *: *:Z hug&&
   $	 	 	 	 06     " $)#Hnn6F6FGGG  ET	    :i6 i6 i6 i6 i6 i6 i6 i6X    z"J$?   () () () () ():. () () () () ()rI   