o
    jk                     @  s  U 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kroejd Zded< n	ejd Zded< ee e! e!ef Z"ded< 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win32syszt.TypeAliasCaptureMode)r   fdExceptionInfoc                   @  s   e Zd ZU ded< ded< ded< 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
t.BinaryIO_input_outputbool_pausedinputoutputreturnNonec                 C  s   || _ || _d| _d S )NF)r   r   r   )selfr   r    r   K/home/djax/ivt_ai_plugin/venv/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.   3      zEchoingStdin.readc                 C  r-   r#   )r)   r   read1r/   r   r   r   r1   6   r0   zEchoingStdin.read1c                 C  r-   r#   )r)   r   readliner/   r   r   r   r2   9   r0   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>=   s    z*EchoingStdin.readlines.<locals>.<listcomp>)r   	readlinesr7   r   r7   r   r9   <      zEchoingStdin.readlinescabc.Iterator[bytes]c                   s   t  fdd jD S )Nc                 3  s    | ]}  |V  qd S r#   r4   r5   r7   r   r   	<genexpr>@   s    z(EchoingStdin.__iter__.<locals>.<genexpr>)iterr   r7   r   r7   r   __iter__?   r:   zEchoingStdin.__iter__c                 C  s
   t | jS r#   )reprr   r7   r   r   r   __repr__B   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   r3   )r   r;   r   r!   )__name__
__module____qualname____annotations__r   r%   r)   r.   r1   r2   r9   r>   r@   r   r   r   r   r       s   
 




r   streamEchoingStdin | Noner   cabc.Generator[None]c                 c  s*    | d u r
d V  d S d| _ d V  d| _ d S )NTF)r   )rF   r   r   r   _pause_echoF   s   

rI   c                   @  sH   e Zd ZU dZded< ded< ded< 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
    r,   	_targetfdsaved_fdzt.BinaryIO | None_tmpfiletargetfdr   r   c                 C  s   || _ d| _d | _d S Nr*   )rK   rL   rM   )r   rN   r   r   r   r   _   r   z_FDCapture.__init__c                 C  s4   t | j| _tjdd| _t | j | j d S )Nr   )	buffering)	osduprK   rL   tempfileTemporaryFilerM   dup2filenor7   r   r   r   startd   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   )rM   rQ   rU   rL   rK   closeseekr.   )r   datar   r   r   stopi   s   

z_FDCapture.stopN)rN   r,   r   r   r   r   )r   r'   )rB   rC   rD   __doc__rE   r   rW   r[   r   r   r   r   rJ   P   s   
 


rJ   c                      sH   e Zd ZU dZded< 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
    
io.BytesIOcopy_tor   r   c                   s   t    || _d S r#   )superr   r`   )r   r`   	__class__r   r   r   }   s   

zBytesIOCopy.__init__c                   s   t    | j  d S r#   )ra   flushr`   r7   rb   r   r   rd      s   
zBytesIOCopy.flushbr
   r,   c                   s   | j | t |S r#   )r`   r(   ra   )r   re   rb   r   r   r(      s   zBytesIOCopy.write)r`   r_   r   r   r\   )re   r
   r   r,   )	rB   rC   rD   r]   rE   r   rd   r(   __classcell__r   r   rb   r   r^   u   s   
 r^   c                   @  s4   e Zd ZU dZded< ded< ded< dd	d
ZdS )StreamMixerzMixes `<stdout>` and `<stderr>` streams.

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

    .. versionadded:: 8.2
    r_   r   r^   stdoutstderrr   r   c                 C  s*   t  | _t| jd| _t| jd| _d S )N)r`   )ioBytesIOr   r^   rh   ri   r7   r   r   r   r      s   
zStreamMixer.__init__Nr\   )rB   rC   rD   r]   rE   r   r   r   r   r   rg      s   
 rg   c                      sp   e Zd ZU dZded< ded< ded< 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.
    r!   _name_moder,   _original_fdbufferr   namemodekwargsr"   r   r   c                   s*   t  j|fi | || _|| _d| _d S rO   )ra   r   rm   rn   ro   )r   rp   rq   rr   rs   rb   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   r7   r   r   r   rX      s    z_NamedTextIOWrapper.closec                   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   )ro   ra   rV   r7   rb   r   r   rV      s   

z_NamedTextIOWrapper.filenoc                 C     | j S r#   )rm   r7   r   r   r   rq         z_NamedTextIOWrapper.namec                 C  rt   r#   )rn   r7   r   r   r   rr      ru   z_NamedTextIOWrapper.mode)
rp   r   rq   r!   rr   r!   rs   r"   r   r   r\   )r   r,   rA   )rB   rC   rD   r]   rE   r   rX   rV   propertyrq   rr   rf   r   r   rb   r   rl      s   
 

rl   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!   encoderj   rk   )r   rx   r&   r   r   r   make_input_stream   s   



r   c                   @  s   e Zd ZU dZded< ded< ded< ded< ded	< d
ed< ded< ded< 	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``.
    	CliRunnerrunnerr'   stdout_bytesstderr_bytesoutput_bytesr"   return_valuer,   	exit_codeBaseException | None	exceptionExceptionInfo | Noneexc_infoNr   r   c	           	      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!   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   rx   r   r7   r   r   r   r     s   zResult.outputc                 C  r   )z&The standard output as unicode string.r   r   r   )r   r   r   rx   r   r7   r   r   r   rh   &  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   rx   r   r7   r   r   r   ri   -  s   zResult.stderrc                 C  s,   | j rt| j nd}dt| j d| dS )Nokay< >)r   r?   typerB   )r   exc_strr   r   r   r@   8  s   zResult.__repr__r#   )r   r   r   r'   r   r'   r   r'   r   r"   r   r,   r   r   r   r   r   r   rA   )rB   rC   rD   r]   rE   r   rv   r   rh   ri   r@   r   r   r   r   r      s&   
 
r   c                   @  s   e Zd ZU dZded< ded< ded< ded< d	ed
< 					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.
    r!   rx   cabc.Mapping[str, str | None]envr   
echo_stdincatch_exceptionsr   captureutf-8NFTr   $cabc.Mapping[str, str | None] | Noner   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   r   z( is not supported on Windows. Use 'sys'.)
ValueErrorr   platformrx   r   r   r   r   )r   rx   r   r   r   r   r   r   r   r   h  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)rq   )r   r   r   r   r   get_default_prog_name~  s   
zCliRunner.get_default_prog_name	overridesc                 C  s   t | j}|r|| |S )z8Returns the environment overrides for invoking a script.)dictr   update)r   r   r&   r   r   r   make_env  s   

zCliRunner.make_envr   rw   color9cabc.Generator[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)encodingrq   rr   r   z<stdout>wz<stderr>backslashreplace)r   rq   rr   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   rh   r(   nextrstripStopIterationEOFErrorrd   )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   rh   r(   rd   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.   rh   r(   rd   )r   charr   r   r   _getchar  s
   
z%CliRunner.isolation.<locals>._getcharrF   t.IO[t.Any] | Noner   bool | Nonec                   s   |d u r  S | S r#   r   )rF   r   )default_colorr   r   should_strip_ansi  s   z.CliRunner.isolation.<locals>.should_strip_ansitabr   pdb.Pdbcompletekeyr   t.IO[str] | Nonerh   rs   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   rh   )r   	__stdin__
__stdout__)r   r   r   rh   rs   )old_pdb_initr   r   _patched_pdb_init  s   
z.CliRunner.isolation.<locals>._patched_pdb_initr#   )r   r   r   r!   )r   r   r   r!   )NN)rF   r   r   r   r   r   )r   NN)r   r   r   r!   r   r   rh   r   rs   r"   r   r   )"r   rx   r   r   rh   ri   r   FORCED_WIDTHr   rg   r   r{   r|   BinaryIOr   rl   _CHUNK_SIZErI   r   visible_prompt_funchidden_prompt_funcr   r   r   r   pdbPdbr   itemsrQ   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   	isolation  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   rJ   rW   OSErrorr   rL   r   rh   ro   ri   r~   r!   shlexsplitpopKeyErrorr   main
SystemExitr   r{   r|   coder,   r(   r   rd   r[   getvaluer   )r   r   r   r   r   r   r   r   r   cap_outcap_err
outstreamsr   r   r   r   r   e_codefd_outfd_errrh   ri   r   r   r   r   invokeT  s   5









@zCliRunner.invoketemp_dirstr | os.PathLike[str] | Nonecabc.Generator[str]c                 c  s    ddl }|jdtdd t }tj|d}t| z&|V  W t| |du rAddl}z|	| W dS  t
y@   Y dS w dS t| |du raddl}z|	| W w  t
y`   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.

        .. warning::
            This helper predates Python 3 and modern pytest, and is not
            thread-safe: it relies on :func:`os.chdir`, which mutates
            process-global state, and :meth:`invoke` swaps the
            process-global standard streams too. Parallelize tests with
            processes (``pytest-xdist``), not threads. Locking the
            runner (:pr:`3511`, :pr:`3520`, :pr:`3530`) and a
            ``set_filesystem()`` API (:issue:`3123`) were declined:
            neither removes the global-state mutation. See :issue:`3700`
            and :issue:`3501`.

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

        .. deprecated:: 8.5.0
            Will be removed in Click 9.0. Use
            :class:`tempfile.TemporaryDirectory` or pytest's
            ``tmp_path`` fixture with absolute paths instead.

        .. versionchanged:: 8.0
            Added the ``temp_dir`` parameter.
        r   Nz'isolated_filesystem' is deprecated and will be removed in Click 9.0. Use 'tempfile.TemporaryDirectory' or pytest's 'tmp_path' fixture with absolute paths instead.   )
stacklevel)dir)warningswarnDeprecationWarningrQ   getcwdrS   mkdtempchdirshutilrmtreer   )r   r   r  cwddtr
  r   r   r   isolated_filesystem  s<    


zCliRunner.isolated_filesystem)r   NFTr   )rx   r!   r   r   r   r   r   r   r   r   r   r   )r   r   r   r!   r#   )r   r   r   r   )NNF)r   rw   r   r   r   r   r   r   )NNNNF)r   r   r   r   r   rw   r   r   r   r   r   r   r   r"   r   r   )r   r   r   r   )rB   rC   rD   r]   rE   r   r   r   
contextlibcontextmanagerr   r   r  r   r   r   r   r   =  s@   
 $
	 I r   )rF   rG   r   rH   )r   rw   rx   r!   r   r   )/
__future__r   collections.abcabccabcr  rj   rQ   r   r   r   rS   typingr{   typesr   r   r   r   r   r   r	   TYPE_CHECKING	_typeshedr
   corer   r   Literalr   rE   tupler   BaseExceptionr   r   r  rI   rJ   rk   r^   rg   TextIOWrapperrl   r   r   r   r   r   r   r   <module>   sB    
&	%
7V