o
    
jud                     @  sP  d dl mZ 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m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 ejr_d d
lmZ ddlmZ ejd ZG dd dZejd(ddZG dd dZ G dd dej!Z"G dd dZ#G dd dej$Z%d)d"d#Z&G d$d% d%Z'G d&d' d'Z(dS )*    )annotationsN)TracebackType   )_compat)
formatting)termui)utils)_find_binary_reader)ReadableBuffer)Command)sysfdc                   @  sl   e Zd Zd#ddZd$ddZd%ddZd&d'ddZd&d'ddZd&d'ddZd(ddZ	d)ddZ
d*d d!Zd"S )+EchoingStdininput
t.BinaryIOoutputreturnNonec                 C  s   || _ || _d| _d S )NF)_input_output_paused)selfr   r    r   @/home/kuhnn/.local/lib/python3.10/site-packages/click/testing.py__init__      
zEchoingStdin.__init__xstrt.Anyc                 C  s   t | j|S N)getattrr   )r   r   r   r   r   __getattr__"   s   zEchoingStdin.__getattr__rvbytesc                 C  s   | j s	| j| |S r   )r   r   write)r   r"   r   r   r   _echo%   s   zEchoingStdin._echonintc                 C     |  | j|S r   )r%   r   readr   r'   r   r   r   r*   +      zEchoingStdin.readc                 C  r)   r   )r%   r   read1r+   r   r   r   r-   .   r,   zEchoingStdin.read1c                 C  r)   r   )r%   r   readliner+   r   r   r   r.   1   r,   zEchoingStdin.readlinelist[bytes]c                   s    fdd j  D S )Nc                   s   g | ]}  |qS r   r%   .0r   r   r   r   
<listcomp>5   s    z*EchoingStdin.readlines.<locals>.<listcomp>)r   	readlinesr3   r   r3   r   r5   4      zEchoingStdin.readlinescabc.Iterator[bytes]c                   s   t  fdd jD S )Nc                 3  s    | ]}  |V  qd S r   r0   r1   r3   r   r   	<genexpr>8   s    z(EchoingStdin.__iter__.<locals>.<genexpr>)iterr   r3   r   r3   r   __iter__7   r6   zEchoingStdin.__iter__c                 C  s
   t | jS r   )reprr   r3   r   r   r   __repr__:   s   
zEchoingStdin.__repr__N)r   r   r   r   r   r   )r   r   r   r   )r"   r#   r   r#   )r&   )r'   r(   r   r#   )r   r/   )r   r7   r   r   )__name__
__module____qualname__r   r!   r%   r*   r-   r.   r5   r:   r<   r   r   r   r   r      s    




r   streamEchoingStdin | Noner   cabc.Iterator[None]c                 c  s*    | d u r
d V  d S d| _ d V  d| _ d S )NTF)r   )rA   r   r   r   _pause_echo>   s   

rD   c                   @  s.   e Zd ZdZdddZddd	ZdddZdS )
_FDCaptureaV  Redirect a file descriptor to a temporary file for capture.

    Saves the current target of *targetfd* via :func:`os.dup`, then
    redirects it to a temporary file via :func:`os.dup2`. On
    :meth:`stop`, restores the original ``fd`` and returns the captured
    bytes. Inspired by Pytest's ``FDCapture``.

    .. versionadded:: 8.4.0
    targetfdr(   r   r   c                 C  s   || _ d| _d | _d S Nr&   )	_targetfdsaved_fd_tmpfile)r   rF   r   r   r   r   S   r   z_FDCapture.__init__c                 C  s4   t | j| _tjdd| _t | j | j d S )Nr   )	buffering)	osduprH   rI   tempfileTemporaryFilerJ   dup2filenor3   r   r   r   startX   s   z_FDCapture.startr#   c                 C  s^   | j d us	J dt| j| j t| j d| _| j d | j  }| j   d | _ |S )Nz!_FDCapture.start() was not calledr&   r   )rJ   rL   rP   rI   rH   closeseekr*   )r   datar   r   r   stop]   s   

z_FDCapture.stopN)rF   r(   r   r   r   r   )r   r#   )r>   r?   r@   __doc__r   rR   rV   r   r   r   r   rE   H   s
    


rE   c                      s>   e Zd ZdZd fddZd fdd	Zd fddZ  ZS )BytesIOCopyzdPatch ``io.BytesIO`` to let the written stream be copied to another.

    .. versionadded:: 8.2
    copy_to
io.BytesIOr   r   c                   s   t    || _d S r   )superr   rZ   )r   rZ   	__class__r   r   r   o   s   

zBytesIOCopy.__init__c                   s   t    | j  d S r   )r\   flushrZ   r3   r]   r   r   r_   s   s   
zBytesIOCopy.flushbr
   r(   c                   s   | j | t |S r   )rZ   r$   r\   )r   r`   r]   r   r   r$   w   s   zBytesIOCopy.write)rZ   r[   r   r   rW   )r`   r
   r   r(   )r>   r?   r@   rX   r   r_   r$   __classcell__r   r   r]   r   rY   i   s
    rY   c                   @  s   e Zd ZdZdddZdS )StreamMixerzMixes `<stdout>` and `<stderr>` streams.

    The result is available in the ``output`` attribute.

    .. versionadded:: 8.2
    r   r   c                 C  s*   t  | _t| jd| _t| jd| _d S )N)rZ   )ioBytesIOr   rY   stdoutstderrr3   r   r   r   r      s   
zStreamMixer.__init__NrW   )r>   r?   r@   rX   r   r   r   r   r   rb   |   s    rb   c                      sV   e Zd ZdZd fddZdddZd fddZedddZedddZ	  Z
S )_NamedTextIOWrappera  A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``
    that does not close its underlying buffer.

    When ``CliRunner`` runs in ``fd`` mode, ``_original_fd`` is patched to
    point at the saved (pre-redirection) ``fd``, so C-level consumers that call
    :meth:`fileno` (like ``faulthandler`` or ``subprocess``) keep working. In
    the default ``sys`` mode ``_original_fd`` stays at ``-1`` and
    :meth:`fileno` raises :exc:`io.UnsupportedOperation`, matching the
    pre-``8.3.3`` behavior.
    bufferr   namer   modekwargsr   r   r   c                   s*   t  j|fi | || _|| _d| _d S rG   )r\   r   _name_mode_original_fd)r   rh   ri   rj   rk   r]   r   r   r      s   
z_NamedTextIOWrapper.__init__c                 C  s   dS )zThe buffer this object contains belongs to some other object,
        so prevent the default ``__del__`` implementation from closing
        that buffer.

        .. versionadded:: 8.3.2
        Nr   r3   r   r   r   rS      s    z_NamedTextIOWrapper.closer(   c                   s   | j dkr| j S t  S )zReturn the file descriptor of the saved original stream when
        ``CliRunner`` runs in ``fd`` mode. Otherwise delegate to
        :class:`~io.TextIOWrapper`, which raises
        :exc:`io.UnsupportedOperation` for a ``BytesIO``-backed buffer.
        r   )rn   r\   rQ   r3   r]   r   r   rQ      s   

z_NamedTextIOWrapper.filenoc                 C     | j S r   )rl   r3   r   r   r   ri         z_NamedTextIOWrapper.namec                 C  ro   r   )rm   r3   r   r   r   rj      rp   z_NamedTextIOWrapper.mode)
rh   r   ri   r   rj   r   rk   r   r   r   rW   )r   r(   r=   )r>   r?   r@   rX   r   rS   rQ   propertyri   rj   ra   r   r   r]   r   rg      s    

rg   r    str | bytes | t.IO[t.Any] | Nonecharsetr   r   c                 C  sZ   t | drttd| }|d ur|S td| d u rd} n
t| tr(| |} t	| S )Nr*   zt.IO[t.Any]z.Could not find binary reader for input stream.    )
hasattrr	   tcast	TypeError
isinstancer   encoderc   rd   )r   rs   r"   r   r   r   make_input_stream   s   



r{   c                   @  sR   e Zd ZdZ	ddddZedddZedddZedddZdddZ	dS ) ResultaC  Holds the captured result of an invoked CLI script.

    :param runner: The runner that created the result
    :param stdout_bytes: The standard output as bytes.
    :param stderr_bytes: The standard error as bytes.
    :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the
        user would see  it in its terminal.
    :param return_value: The value returned from the invoked command.
    :param exit_code: The exit code as integer.
    :param exception: The exception that happened if one did.
    :param exc_info: Exception information (exception type, exception instance,
        traceback type).

    .. versionchanged:: 8.2
        ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and
        ``mix_stderr`` has been removed.

    .. versionadded:: 8.0
        Added ``return_value``.
    Nrunner	CliRunnerstdout_bytesr#   stderr_bytesoutput_bytesreturn_valuer   	exit_coder(   	exceptionBaseException | Noneexc_info?tuple[type[BaseException], BaseException, TracebackType] | Nonec	           	      C  s4   || _ || _|| _|| _|| _|| _|| _|| _d S r   r}   r   r   r   r   r   r   r   )	r   r}   r   r   r   r   r   r   r   r   r   r   r      s   
zResult.__init__r   r   c                 C     | j | jjdddS )a  The terminal output as unicode string, as the user would see it.

        .. versionchanged:: 8.2
            No longer a proxy for ``self.stdout``. Now has its own independent stream
            that is mixing `<stdout>` and `<stderr>`, in the order they were written.
        replace

)r   decoder}   rs   r   r3   r   r   r   r      s   zResult.outputc                 C  r   )z&The standard output as unicode string.r   r   r   )r   r   r}   rs   r   r3   r   r   r   re     s   zResult.stdoutc                 C  r   )zThe standard error as unicode string.

        .. versionchanged:: 8.2
            No longer raise an exception, always returns the `<stderr>` string.
        r   r   r   )r   r   r}   rs   r   r3   r   r   r   rf     s   zResult.stderrc                 C  s,   | j rt| j nd}dt| j d| dS )Nokay< >)r   r;   typer>   )r   exc_strr   r   r   r<     s   zResult.__repr__r   )r}   r~   r   r#   r   r#   r   r#   r   r   r   r(   r   r   r   r   r=   )
r>   r?   r@   rX   r   rq   r   re   rf   r<   r   r   r   r   r|      s    
r|   c                   @  s   e Zd ZdZ					d/d0ddZd1ddZ	d2d3ddZej			d4d5d d!Z						d6d7d(d)Z
ej	d2d8d-d.ZdS )9r~   a  The CLI runner provides functionality to invoke a Click command line
    script for unittesting purposes in a isolated environment.  This only
    works in single-threaded systems without any concurrency as it changes the
    global interpreter state.

    :param charset: the character set for the input and output data.
    :param env: a dictionary with environment variables for overriding.
    :param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes
                       to `<stdout>`.  This is useful for showing examples in
                       some circumstances.  Note that regular prompts
                       will automatically echo the input.
    :param catch_exceptions: Whether to catch any exceptions other than
                             ``SystemExit`` when running :meth:`~CliRunner.invoke`.
    :param capture: Selects the output capture strategy. ``sys`` (default)
        captures Python-level writes only and leaves
        :meth:`sys.stdout.fileno` raising :exc:`io.UnsupportedOperation`, so
        user code that calls :func:`os.dup2` on ``sys.stdout.fileno()`` cannot
        clobber the host runner's stdout. ``fd`` redirects file descriptors
        ``1`` and ``2`` via :func:`os.dup2` to a temporary file, also catching
        output from stale stream references, C extensions, and subprocesses.
        ``fd`` is not supported on Windows.

    .. versionchanged:: 8.4.0
        Added the ``capture`` parameter. The default ``sys`` mode no longer
        exposes the original fd through :meth:`fileno`, reverting the change
        introduced in ``8.3.3`` that broke Pytest's ``fd``-level capture
        teardown. Use ``capture="fd"`` to restore that behavior with proper
        isolation. :issue:`3384`

    .. versionchanged:: 8.2
        Added the ``catch_exceptions`` parameter.

    .. versionchanged:: 8.2
        ``mix_stderr`` parameter has been removed.
    utf-8NFTr   rs   r   env$cabc.Mapping[str, str | None] | None
echo_stdinboolcatch_exceptionscaptureCaptureModer   r   c                 C  s`   |dvrt d|d|dkrtjdkrt d|d|| _|p#i | _|| _|| _|| _d S )N>   r   r   zcapture=z) is not valid. Choose from 'sys' or 'fd'.r   win32z( is not supported on Windows. Use 'sys'.)
ValueErrorr   platformrs   r   r   r   r   )r   rs   r   r   r   r   r   r   r   r   D  s   



zCliRunner.__init__clir   c                 C  s
   |j pdS )zGiven a command object it will return the default program name
        for it.  The default is the `name` attribute or ``"root"`` if not
        set.
        root)ri   )r   r   r   r   r   get_default_prog_nameZ  s   
zCliRunner.get_default_prog_name	overridescabc.Mapping[str, str | None]c                 C  s   t | j}|r|| |S )z8Returns the environment overrides for invoking a script.)dictr   update)r   r   r"   r   r   r   make_enva  s   

zCliRunner.make_envr   rr   color8cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]c                 #  s   t || j}d}tj}tj}tj}tj}	dt_| |}t	 }
| j
r0ttjt||
j }}t|| jddd t_| j
rBd_t|
j| jdddt_t|
j| jd	dd
dt_t|d*d+fdd}t|d*d+fdd}t|d,dd}| 	d-d. fdd}tj}tj}tj}tj}tj}tjj|t_|t_|t_|t_|t_			d/d0fd(d)}|tj_i }zy| D ]%\}}tj|||< |du rztj|= W q t y   Y qw |tj|< q|
j|
j|
j!fV  W | D ]\}}|du rztj|= W q t y
   Y qw |tj|< q|t_|t_|t_|t_|t_|t_|t_|t_|	t_tj_dS | D ]"\}}|du rRztj|= W q6 t yQ   Y q6w |tj|< q6|t_|t_|t_|t_|t_|t_|t_|t_|	t_tj_w )1a\  A context manager that sets up the isolation for invoking of a
        command line tool.  This sets up `<stdin>` with the given input data
        and `os.environ` with the overrides from the given dictionary.
        This also rebinds some internals in Click to be mocked (like the
        prompt functionality).

        This is automatically done in the :meth:`invoke` method.

        :param input: the input stream to put into `sys.stdin`.
        :param env: the environment overrides as dictionary.
        :param color: whether the output should contain color codes. The
                      application can still override this explicitly.

        .. versionadded:: 8.2
            An additional output stream is returned, which is a mix of
            `<stdout>` and `<stderr>` streams.

        .. versionchanged:: 8.2
            Always returns the `<stderr>` stream.

        .. versionchanged:: 8.0
            `<stderr>` is opened with ``errors="backslashreplace"``
            instead of the default ``"strict"``.

        .. versionchanged:: 4.0
            Added the ``color`` parameter.
        NP   z<stdin>r)encodingri   rj   r   z<stdout>wz<stderr>backslashreplace)r   ri   rj   errorsprompt
str | Noner   r   c              
     sd   t j| pd z	t d}W n ty! } zt |d }~ww t j| d t j  |S )N r   r   )r   re   r$   nextrstripStopIterationEOFErrorr_   )r   vale
text_inputr   r   visible_input  s   
z*CliRunner.isolation.<locals>.visible_inputc              
     sR   t j| pd d t j  zt dW S  ty( } zt |d }~ww )Nr   r   r   )r   re   r$   r_   r   r   r   r   )r   r   r   r   r   hidden_input  s   
z)CliRunner.isolation.<locals>.hidden_inputechor   c                 S  s*   t jd}| rt j| t j  |S )Nr   )r   stdinr*   re   r$   r_   )r   charr   r   r   _getchar  s
   
z%CliRunner.isolation.<locals>._getcharrA   t.IO[t.Any] | Noner   bool | Nonec                   s   |d u r  S | S r   r   )rA   r   )default_colorr   r   should_strip_ansi  s   z.CliRunner.isolation.<locals>.should_strip_ansitabr   pdb.Pdbcompletekeyr   t.IO[str] | Nonere   rk   r   r   c                   s8   |du rt j}|du rt j} | f|||d| dS )ab  Default ``pdb.Pdb`` to real terminal streams during
            ``CliRunner`` isolation.

            Without this patch, ``pdb.Pdb.__init__`` inherits from
            ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout``
            when no explicit streams are provided. During isolation
            those are ``BytesIO``-backed wrappers, so the debugger
            reads from an empty buffer and writes to captured output,
            making interactive debugging impossible.

            By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the
            original terminal streams Python preserves regardless of
            redirection), debuggers can interact with the user while
            ``click.echo`` output is still captured normally.

            This covers ``pdb.set_trace()``, ``breakpoint()``,
            ``pdb.post_mortem()``, and debuggers that subclass
            ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout``
            arguments are honored and not overridden. Debuggers that
            do not subclass ``pdb.Pdb`` (pudb, debugpy) are not
            covered.
            N)r   r   re   )r   	__stdin__
__stdout__)r   r   r   re   rk   )old_pdb_initr   r   _patched_pdb_init  s   
z.CliRunner.isolation.<locals>._patched_pdb_initr   )r   r   r   r   )r   r   r   r   )NN)rA   r   r   r   r   r   )r   NN)r   r   r   r   r   r   re   r   rk   r   r   r   )"r{   rs   r   r   re   rf   r   FORCED_WIDTHr   rb   r   rv   rw   BinaryIOr   rg   _CHUNK_SIZErD   r   visible_prompt_funchidden_prompt_funcr   r   r   r   pdbPdbr   itemsrL   environget	Exceptionr   )r   r   r   r   bytes_input
echo_input	old_stdin
old_stdout
old_stderrold_forced_widthstream_mixerr   r   r   r   old_visible_prompt_funcold_hidden_prompt_funcold__getchar_funcold_should_strip_ansiold__compat_should_strip_ansir   old_envkeyvaluer   )r   r   r   r   	isolationj  s   "


	%


zCliRunner.isolationargsstr | cabc.Sequence[str] | Noner   extrar   r|   c                 K  s  d}|du r	| j }d}	d}
| jdkr2td}	td}
z
|	  |
  W n ty1   d }	}
Y nw | j|||d4}|	durN|
durN|	jtj_	|
jtj
_	d}d}d}t|tr^t|}z|d}W n tys   | |}Y nw zz|jd|p|d|d	|}W n\ ty } z4t }td
|j}|du rd}|dkr|}t|tstjt| tjd d}|}W Y d}~n!d}~w ty } z|s΂ |}d}t }W Y d}~nd}~ww W tj  tj
  |	dur|
dur|	 }|
 }|r|d | |r|d | |d  }|d  }|d  }nCtj  tj
  |	durU|
durU|	 }|
 }|rK|d | |rU|d | |d  }|d  }|d  }w W d   n	1 ssw   Y  t| |||||||dS )a{  Invokes a command in an isolated environment.  The arguments are
        forwarded directly to the command line script, the `extra` keyword
        arguments are passed to the :meth:`~clickpkg.Command.main` function of
        the command.

        This returns a :class:`Result` object.

        :param cli: the command to invoke
        :param args: the arguments to invoke. It may be given as an iterable
                     or a string. When given as string it will be interpreted
                     as a Unix shell command. More details at
                     :func:`shlex.split`.
        :param input: the input data for `sys.stdin`.
        :param env: the environment overrides.
        :param catch_exceptions: Whether to catch any other exceptions than
                                 ``SystemExit``. If :data:`None`, the value
                                 from :class:`CliRunner` is used.
        :param extra: the keyword arguments to pass to :meth:`main`.
        :param color: whether the output should contain color codes. The
                      application can still override this explicitly.

        .. versionadded:: 8.2
            The result object has the ``output_bytes`` attribute with
            the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would
            see it in its terminal.

        .. versionchanged:: 8.2
            The result object always returns the ``stderr_bytes`` stream.

        .. versionchanged:: 8.0
            The result object has the ``return_value`` attribute with
            the value returned from the invoked command.

        .. versionchanged:: 4.0
            Added the ``color`` parameter.

        .. versionchanged:: 3.0
            Added the ``catch_exceptions`` parameter.

        .. versionchanged:: 3.0
            The result object has the ``exc_info`` attribute with the
            traceback if available.
        Nr   r      )r   r   r   r   	prog_namer   )r   r   zint | t.Any | Noner   r   )r   r   rE   rR   OSErrorr   rI   r   re   rn   rf   ry   r   shlexsplitpopKeyErrorr   main
SystemExitr   rv   rw   coder(   r$   r   r_   rV   getvaluer|   )r   r   r   r   r   r   r   r   r   cap_outcap_err
outstreamsr   r   r   r   r   e_codefd_outfd_errre   rf   r   r   r   r   invoke0  s   5









@zCliRunner.invoketemp_dirstr | os.PathLike[str] | Nonecabc.Iterator[str]c                 c  s    t  }tj|d}t | z&|V  W t | |du r5ddl}z|| W dS  ty4   Y dS w dS t | |du rUddl}z|| W w  tyT   Y w w w )a  A context manager that creates a temporary directory and
        changes the current working directory to it. This isolates tests
        that affect the contents of the CWD to prevent them from
        interfering with each other.

        :param temp_dir: Create the temporary directory under this
            directory. If given, the created directory is not removed
            when exiting.

        .. versionchanged:: 8.0
            Added the ``temp_dir`` parameter.
        )dirNr   )rL   getcwdrN   mkdtempchdirshutilrmtreer   )r   r   cwddtr  r   r   r   isolated_filesystem  s0   


zCliRunner.isolated_filesystem)r   NFTr   )rs   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   )r   r   r   r   )NNF)r   rr   r   r   r   r   r   r   )NNNNF)r   r   r   r   r   rr   r   r   r   r   r   r   r   r   r   r|   )r   r   r   r   )r>   r?   r@   rX   r   r   r   
contextlibcontextmanagerr   r   r  r   r   r   r   r~     s6    &
	 I r~   )rA   rB   r   rC   )r   rr   rs   r   r   r   ))
__future__r   collections.abcabccabcr  rc   rL   r   r   r   rN   typingrv   typesr   r   r   r   r   r   r	   TYPE_CHECKING	_typeshedr
   corer   Literalr   r   r	  rD   rE   rd   rY   rb   TextIOWrapperrg   r{   r|   r~   r   r   r   r   <module>   s<    
"	!
3N