o
    Th                     @   s  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
 d dlmZ d dlmZmZmZmZmZmZmZmZmZmZ zd dlZW n eyW   dZY nw zd dlZW n eyi   dZY nw zd dlZW n ey{   dZY nw ddlmZmZmZm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+m,Z, erdd	l-m.Z. dd
l/m0Z0 G dd dZ1G dd de1Z2G dd dZ3G dd de3Z4		ddedee5 dee5 dee5df fddZ6de5fddZ7dS )    N)PopenPIPE)TracebackType)
TYPE_CHECKINGAnyCallableDict	GeneratorIOListOptionalTupleType   )UnexpectedExitFailureThreadExceptionWatcherErrorSubprocessPipeErrorCommandTimedOut)WINDOWSpty_sizecharacter_bufferedready_for_readingbytes_to_read)
has_filenoisattyExceptionHandlingThread)Context)StreamWatcherc                
   @   sn  e Zd ZU dZeeef ed< eed< dZ	dZ
dsd
dZdededed fddZdedd	fddZdededd	fddZdededed fddZdtddZduddZdedd	fddZdee ddfdd Zd!edee fd"d#Zdeeeef ee ee f fd$d%Zdeddfd&d'Zd(edeed	d	f fd)d*Zd+e d,edd	fd-d.Z!d/ee d0ed1e d(edd	f
d2d3Z"d/ee d0ed1e dd	fd4d5Z#d/ee d0ed1e dd	fd6d7Z$d8e dee fd9d:Z%	;dvd8e d1e d<edd	fd=d>Z&d8e d1e defd?d@Z'd/ee dd	fdAdBZ(dCeeef dDedeeef fdEdFZ)dGedHedefdIdJZ*e+defdKdLZ,dwdMdNZ-dOedd	fdPdQZ.dOe/defdRdSZ0e+defdTdUZ1dedVedCeeef dd	fdWdXZ2dYedd	fdZd[Z3d\edee/ fd]d^Z4d\edee/ fd_d`Z5dOe/dd	fdadbZ6dwdcddZ7defdedfZ8dxdidjZ9dee fdkdlZ:dwdmdnZ;dwdodpZ<e+defdqdrZ=d	S )yRunnera-  
    Partially-abstract core command-running API.

    This class is not usable by itself and must be subclassed, implementing a
    number of methods such as `start`, `wait` and `returncode`. For a subclass
    implementation example, see the source code for `.Local`.

    .. versionadded:: 1.0
    opts	using_ptyi  g{Gz?contextr   returnNc                 C   sF   || _ t | _| jj| _| jj| _d| _g | _d| _	d| _
d| _dS )a"  
        Create a new runner with a handle on some `.Context`.

        :param context:
            a `.Context` instance, used to transmit default options and provide
            access to other contextualized information (e.g. a remote-oriented
            `.Runner` might want a `.Context` subclass holding info about
            hostnames and ports.)

            .. note::
                The `.Context` given to `.Runner` instances **must** contain
                default config values for the `.Runner` class in question. At a
                minimum, this means values for each of the default
                `.Runner.run` keyword arguments such as ``echo`` and ``warn``.

        :raises exceptions.ValueError:
            if not all expected default values are found in ``context``.
        FN)r#   	threadingEventprogram_finished	__class__read_chunk_sizeinput_sleepwarned_about_pty_fallbackwatchers_timer_asynchronous	_disownedselfr#    r2   A/var/www/html/venv/lib/python3.10/site-packages/invoke/runners.py__init__M   s   



zRunner.__init__commandkwargsResultc                 K   sH   z| j |fi |W | js| js|   S S S | js"| js#|   w w w )a0  
        Execute ``command``, returning an instance of `Result` once complete.

        By default, this method is synchronous (it only returns once the
        subprocess has completed), and allows interactive keyboard
        communication with the subprocess.

        It can instead behave asynchronously (returning early & requiring
        interaction with the resulting object to manage subprocess lifecycle)
        if you specify ``asynchronous=True``. Furthermore, you can completely
        disassociate the subprocess from Invoke's control (allowing it to
        persist on its own after Python exits) by saying ``disown=True``. See
        the per-kwarg docs below for details on both of these.

        .. note::
            All kwargs will default to the values found in this instance's
            `~.Runner.context` attribute, specifically in its configuration's
            ``run`` subtree (e.g. ``run.echo`` provides the default value for
            the ``echo`` keyword, etc). The base default values are described
            in the parameter list below.

        :param str command: The shell command to execute.

        :param bool asynchronous:
            When set to ``True`` (default ``False``), enables asynchronous
            behavior, as follows:

            - Connections to the controlling terminal are disabled, meaning you
              will not see the subprocess output and it will not respond to
              your keyboard input - similar to ``hide=True`` and
              ``in_stream=False`` (though explicitly given
              ``(out|err|in)_stream`` file-like objects will still be honored
              as normal).
            - `.run` returns immediately after starting the subprocess, and its
              return value becomes an instance of `Promise` instead of
              `Result`.
            - `Promise` objects are primarily useful for their `~Promise.join`
              method, which blocks until the subprocess exits (similar to
              threading APIs) and either returns a final `~Result` or raises an
              exception, just as a synchronous ``run`` would.

                - As with threading and similar APIs, users of
                  ``asynchronous=True`` should make sure to ``join`` their
                  `Promise` objects to prevent issues with interpreter
                  shutdown.
                - One easy way to handle such cleanup is to use the `Promise`
                  as a context manager - it will automatically ``join`` at the
                  exit of the context block.

            .. versionadded:: 1.4

        :param bool disown:
            When set to ``True`` (default ``False``), returns immediately like
            ``asynchronous=True``, but does not perform any background work
            related to that subprocess (it is completely ignored). This allows
            subprocesses using shell backgrounding or similar techniques (e.g.
            trailing ``&``, ``nohup``) to persist beyond the lifetime of the
            Python process running Invoke.

            .. note::
                If you're unsure whether you want this or ``asynchronous``, you
                probably want ``asynchronous``!

            Specifically, ``disown=True`` has the following behaviors:

            - The return value is ``None`` instead of a `Result` or subclass.
            - No I/O worker threads are spun up, so you will have no access to
              the subprocess' stdout/stderr, your stdin will not be forwarded,
              ``(out|err|in)_stream`` will be ignored, and features like
              ``watchers`` will not function.
            - No exit code is checked for, so you will not receive any errors
              if the subprocess fails to exit cleanly.
            - ``pty=True`` may not function correctly (subprocesses may not run
              at all; this seems to be a potential bug in Python's
              ``pty.fork``) unless your command line includes tools such as
              ``nohup`` or (the shell builtin) ``disown``.

            .. versionadded:: 1.4

        :param bool dry:
            Whether to dry-run instead of truly invoking the given command. See
            :option:`--dry` (which flips this on globally) for details on this
            behavior.

            .. versionadded:: 1.3

        :param bool echo:
            Controls whether `.run` prints the command string to local stdout
            prior to executing it. Default: ``False``.

            .. note::
                ``hide=True`` will override ``echo=True`` if both are given.

        :param echo_format:
            A string, which when passed to Python's inbuilt ``.format`` method,
            will change the format of the output when ``run.echo`` is set to
            true.

            Currently, only ``{command}`` is supported as a parameter.

            Defaults to printing the full command string in ANSI-escaped bold.

        :param bool echo_stdin:
            Whether to write data from ``in_stream`` back to ``out_stream``.

            In other words, in normal interactive usage, this parameter
            controls whether Invoke mirrors what you type back to your
            terminal.

            By default (when ``None``), this behavior is triggered by the
            following:

                * Not using a pty to run the subcommand (i.e. ``pty=False``),
                  as ptys natively echo stdin to stdout on their own;
                * And when the controlling terminal of Invoke itself (as per
                  ``in_stream``) appears to be a valid terminal device or TTY.
                  (Specifically, when `~invoke.util.isatty` yields a ``True``
                  result when given ``in_stream``.)

                  .. note::
                      This property tends to be ``False`` when piping another
                      program's output into an Invoke session, or when running
                      Invoke within another program (e.g. running Invoke from
                      itself).

            If both of those properties are true, echoing will occur; if either
            is false, no echoing will be performed.

            When not ``None``, this parameter will override that auto-detection
            and force, or disable, echoing.

        :param str encoding:
            Override auto-detection of which encoding the subprocess is using
            for its stdout/stderr streams (which defaults to the return value
            of `default_encoding`).

        :param err_stream:
            Same as ``out_stream``, except for standard error, and defaulting
            to ``sys.stderr``.

        :param dict env:
            By default, subprocesses receive a copy of Invoke's own environment
            (i.e. ``os.environ``). Supply a dict here to update that child
            environment.

            For example, ``run('command', env={'PYTHONPATH':
            '/some/virtual/env/maybe'})`` would modify the ``PYTHONPATH`` env
            var, with the rest of the child's env looking identical to the
            parent.

            .. seealso:: ``replace_env`` for changing 'update' to 'replace'.

        :param bool fallback:
            Controls auto-fallback behavior re: problems offering a pty when
            ``pty=True``. Whether this has any effect depends on the specific
            `Runner` subclass being invoked. Default: ``True``.

        :param hide:
            Allows the caller to disable ``run``'s default behavior of copying
            the subprocess' stdout and stderr to the controlling terminal.
            Specify ``hide='out'`` (or ``'stdout'``) to hide only the stdout
            stream, ``hide='err'`` (or ``'stderr'``) to hide only stderr, or
            ``hide='both'`` (or ``True``) to hide both streams.

            The default value is ``None``, meaning to print everything;
            ``False`` will also disable hiding.

            .. note::
                Stdout and stderr are always captured and stored in the
                ``Result`` object, regardless of ``hide``'s value.

            .. note::
                ``hide=True`` will also override ``echo=True`` if both are
                given (either as kwargs or via config/CLI).

        :param in_stream:
            A file-like stream object to used as the subprocess' standard
            input. If ``None`` (the default), ``sys.stdin`` will be used.

            If ``False``, will disable stdin mirroring entirely (though other
            functionality which writes to the subprocess' stdin, such as
            autoresponding, will still function.) Disabling stdin mirroring can
            help when ``sys.stdin`` is a misbehaving non-stream object, such as
            under test harnesses or headless command runners.

        :param out_stream:
            A file-like stream object to which the subprocess' standard output
            should be written. If ``None`` (the default), ``sys.stdout`` will
            be used.

        :param bool pty:
            By default, ``run`` connects directly to the invoked process and
            reads its stdout/stderr streams. Some programs will buffer (or even
            behave) differently in this situation compared to using an actual
            terminal or pseudoterminal (pty). To use a pty instead of the
            default behavior, specify ``pty=True``.

            .. warning::
                Due to their nature, ptys have a single output stream, so the
                ability to tell stdout apart from stderr is **not possible**
                when ``pty=True``. As such, all output will appear on
                ``out_stream`` (see below) and be captured into the ``stdout``
                result attribute. ``err_stream`` and ``stderr`` will always be
                empty when ``pty=True``.

        :param bool replace_env:
            When ``True``, causes the subprocess to receive the dictionary
            given to ``env`` as its entire shell environment, instead of
            updating a copy of ``os.environ`` (which is the default behavior).
            Default: ``False``.

        :param str shell:
            Which shell binary to use. Default: ``/bin/bash`` (on Unix;
            ``COMSPEC`` or ``cmd.exe`` on Windows.)

        :param timeout:
            Cause the runner to submit an interrupt to the subprocess and raise
            `.CommandTimedOut`, if the command takes longer than ``timeout``
            seconds to execute. Defaults to ``None``, meaning no timeout.

            .. versionadded:: 1.3

        :param bool warn:
            Whether to warn and continue, instead of raising
            `.UnexpectedExit`, when the executed command exits with a
            nonzero status. Default: ``False``.

            .. note::
                This setting has no effect on exceptions, which will still be
                raised, typically bundled in `.ThreadException` objects if they
                were raised by the IO worker threads.

                Similarly, `.WatcherError` exceptions raised by
                `.StreamWatcher` instances will also ignore this setting, and
                will usually be bundled inside `.Failure` objects (in order to
                preserve the execution context).

                Ditto `.CommandTimedOut` - basically, anything that prevents a
                command from actually getting to "exited with an exit code"
                ignores this flag.

        :param watchers:
            A list of `.StreamWatcher` instances which will be used to scan the
            program's ``stdout`` or ``stderr`` and may write into its ``stdin``
            (typically ``bytes`` objects) in response to patterns or other
            heuristics.

            See :doc:`/concepts/watchers` for details on this functionality.

            Default: ``[]``.

        :returns:
            `Result`, or a subclass thereof.

        :raises:
            `.UnexpectedExit`, if the command exited nonzero and
            ``warn`` was ``False``.

        :raises:
            `.Failure`, if the command didn't even exit cleanly, e.g. if a
            `.StreamWatcher` raised `.WatcherError`.

        :raises:
            `.ThreadException` (if the background I/O threads encountered
            exceptions other than `.WatcherError`).

        .. versionadded:: 1.0
        )	_run_bodyr.   r/   stopr1   r5   r6   r2   r2   r3   run}   s     

z
Runner.runc                 C   s   t | jd j|d d S )Necho_format)r5   )printr!   format)r1   r5   r2   r2   r3   echo  s   zRunner.echoc                 C   sx   |  | | | jd | jd | _| jd p|  | _| jd r&| | t|| jd | j| j| jd | jd| _	dS )	zK
        Prepare data on ``self`` so we're ready to start running.
        envreplace_envencodingr?   shellhide)r5   rC   r@   ptyrD   rB   N)
_unify_kwargs_with_configgenerate_envr!   r@   default_encodingrB   r?   dictr"   result_kwargsr:   r2   r2   r3   _setup  s   


zRunner._setupc              	   K   s   |  || | jd r| jdi t| jddddS | || jd | j | jr*d S | | jd  | 	 \| _
| _| _| j
 D ]}|  qA| jrO|  S |  S )Ndry r   stdoutstderrexitedrC   timeoutr2   )rK   r!   generate_resultrI   rJ   startr@   r/   start_timercreate_io_threadsthreadsrO   rP   valuesr.   make_promise_finish)r1   r5   r6   threadr2   r2   r3   r8     s   

zRunner._run_bodyPromisec                 C   s   t | S )zt
        Return a `Promise` allowing async control of the rest of lifecycle.

        .. versionadded:: 1.4
        )r\   r1   r2   r2   r3   rY     s   zRunner.make_promisec           
      C   s  zX	 z|    W n ty } z| | W Y d }~nd }~ww qW | j  g }g }| j D ]'\}}|| | |	 }|d urW|j
}t|trR|| q0|| q0n7| j  g }g }| j D ]'\}}|| | |	 }|d ur|j
}t|tr|| qg|| qgw |rt|| |}|rt||d d| jd }	|	d ur| jrt||	d|s| jd st||S )NTr   )reasonrR   )rR   warn)waitKeyboardInterruptsend_interruptr'   setrW   itemsjoin_thread_join_timeout	exceptionvalue
isinstancer   appendr   _collate_resultr   r!   	timed_outr   r   )
r1   ewatcher_errorsthread_exceptionstargetr[   rg   realresultrR   r2   r2   r3   rZ     s`   







zRunner._finishc                 C   s~  i }| j jj D ]\}}||d}|du r|n|||< q	| j jjj}|d||d< |r=d}t|t	|
 d |d | _|d | _| jrS| jrSd}t||d d	u r]d
|d< |d d	u rgd	|d< | jrnd	|d< |d |d }}	t|d ||	|d< |du rtj}|	du rtj}	|d }
|
du r| jrd
ntj}
| |d |d | _|d r|d | _|| _||	|
d| _dS )z
        Unify `run` kwargs with config options to arrive at local options.

        Sets:

        - ``self.opts`` - opts dict
        - ``self.streams`` - map of stream names to stream target values
        NrR   z-run() got an unexpected keyword argument '{}'r   asynchronousdisownz>Cannot give both 'asynchronous' and 'disown' at the same time!rD   TFr?   rL   
out_stream
err_stream	in_streamrE   fallbackr,   )outerrin)r#   configr;   rd   poptimeoutsr5   	TypeErrorr>   listkeysr.   r/   
ValueErrornormalize_hidesysrO   rP   stdinshould_use_ptyr"   r,   r!   streams)r1   r6   r!   keyrh   runtimeconfig_timeoutrz   ru   rv   rw   r2   r2   r3   rF   	  sD   	


z Runner._unify_kwargs_with_configrn   c              	   C   sv   d | j}d | j}tr"|dddd}|dddd}|r&d n|  }| jdi t| j|||d}|S )NrM   z

rN   r2   )	re   rO   rP   r   replace
returncoderS   rI   rJ   )r1   rn   rO   rP   rQ   rr   r2   r2   r3   rk   E  s   
zRunner._collate_resultrp   c                 C   sB   || j krd S | j}|| jkr| j}|| jv r| j| jrdS d S )Nr   )handle_stdinhandle_stderrhandle_stdoutrW   is_dead)r1   rp   oppositer2   r2   r3   rf   a  s   

zRunner._thread_join_timeoutc                 C   s   g }g }| j |d| jd v | jd di}| jd r,| jd | jd | jd d|| j< | js@|d| jd v | jd	 d|| j< i }| D ]\}}t||d
}|||< qF|||fS )z
        Create and return a dictionary of IO thread worker objects.

        Caller is expected to handle persisting and/or starting the wrapped
        threads.
        rO   rD   ry   )buffer_rD   outputr{   
echo_stdin)input_r   r?   rP   rz   )rp   r6   )r   r!   r   r   r"   r   rd   r   )r1   rO   rP   thread_argsrW   rp   r6   tr2   r2   r3   rV   q  s.   	


zRunner.create_io_threadsc                 K   s   t di |S )a4  
        Create & return a suitable `Result` instance from the given ``kwargs``.

        Subclasses may wish to override this in order to manipulate things or
        generate a `Result` subclass (e.g. ones containing additional metadata
        besides the default).

        .. versionadded:: 1.0
        Nr2   )r7   )r1   r6   r2   r2   r3   rS     s   
zRunner.generate_resultreaderc                 c   s$    	 || j }|sdS | |V  q)a  
        Iteratively read & decode bytes from a subprocess' out/err stream.

        :param reader:
            A literal reader function/partial, wrapping the actual stream
            object in question, which takes a number of bytes to read, and
            returns that many bytes (or ``None``).

            ``reader`` should be a reference to either `read_proc_stdout` or
            `read_proc_stderr`, which perform the actual, platform/library
            specific read calls.

        :returns:
            A generator yielding strings.

            Specifically, each resulting string is the result of decoding
            `read_chunk_size` bytes read from the subprocess' out/err stream.

        .. versionadded:: 1.0
        TN)r)   decode)r1   r   datar2   r2   r3   read_proc_output  s   
zRunner.read_proc_outputstreamstringc                 C   s   | | |  dS )a  
        Write ``string`` to ``stream``.

        Also calls ``.flush()`` on ``stream`` to ensure that real terminal
        streams don't buffer.

        :param stream:
            A file-like stream object, mapping to the ``out_stream`` or
            ``err_stream`` parameters of `run`.

        :param string: A Unicode string object.

        :returns: ``None``.

        .. versionadded:: 1.0
        N)writeflush)r1   r   r   r2   r2   r3   write_our_output  s   
zRunner.write_our_outputr   rD   r   c                 C   s:   |  |D ]}|s| j||d || | | qd S )Nr   r   )r   r   rj   respond)r1   r   rD   r   r   r   r2   r2   r3   _handle_output  s   
zRunner._handle_outputc                 C      | j |||| jd dS )a  
        Read process' stdout, storing into a buffer & printing/parsing.

        Intended for use as a thread target. Only terminates when all stdout
        from the subprocess has been read.

        :param buffer_: The capture buffer shared with the main thread.
        :param bool hide: Whether or not to replay data into ``output``.
        :param output:
            Output stream (file-like object) to write data into when not
            hiding.

        :returns: ``None``.

        .. versionadded:: 1.0
        r   N)r   read_proc_stdoutr1   r   rD   r   r2   r2   r3   r     s   

zRunner.handle_stdoutc                 C   r   )z
        Read process' stderr, storing into a buffer & printing/parsing.

        Identical to `handle_stdout` except for the stream read from; see its
        docstring for API details.

        .. versionadded:: 1.0
        r   N)r   read_proc_stderrr   r2   r2   r3   r     s   

zRunner.handle_stderrr   c              
   C   sn   d}t |r5z	|t|}W n ty( } z|jtjkr W Y d}~nd}~ww |r5t|tr5| |}|S )a
  
        Read & decode bytes from a local stdin stream.

        :param input_:
            Actual stream object to read from. Maps to ``in_stream`` in `run`,
            so will often be ``sys.stdin``, but might be any stream-like
            object.

        :returns:
            A Unicode string, the result of decoding the read bytes (this might
            be the empty string if the pipe has closed/reached EOF); or
            ``None`` if stdin wasn't ready for reading yet.

        .. versionadded:: 1.0
        N)	r   readr   OSErrorerrnoEBADFri   bytesr   )r1   r   bytes_rm   r2   r2   r3   read_our_stdin  s   
zRunner.read_our_stdinFr?   c                 C   s   d}t |H 	 | |}|r(| | |du r| ||}|r'| j||d n|dur7| js7|s7|   d}| j r?|s?nt	
| j qW d   dS 1 sQw   Y  dS )a  
        Read local stdin, copying into process' stdin as necessary.

        Intended for use as a thread target.

        .. note::
            Because real terminal stdin streams have no well-defined "end", if
            such a stream is detected (based on existence of a callable
            ``.fileno()``) this method will wait until `program_finished` is
            set, before terminating.

            When the stream doesn't appear to be from a terminal, the same
            semantics as `handle_stdout` are used - the stream is simply
            ``read()`` from until it returns an empty value.

        :param input_: Stream (file-like object) from which to read.
        :param output: Stream (file-like object) to which echoing may occur.
        :param bool echo: User override option for stdin-stdout echoing.

        :returns: ``None``.

        .. versionadded:: 1.0
        FTNr   )r   r   write_proc_stdinshould_echo_stdinr   r"   close_proc_stdinr'   is_settimesleepr*   )r1   r   r   r?   closed_stdinr   r2   r2   r3   r   B  s*   "



"zRunner.handle_stdinc                 C   s   | j  ot|S )aW  
        Determine whether data read from ``input_`` should echo to ``output``.

        Used by `handle_stdin`; tests attributes of ``input_`` and ``output``.

        :param input_: Input stream (file-like object).
        :param output: Output stream (file-like object).
        :returns: A ``bool``.

        .. versionadded:: 1.0
        )r"   r   )r1   r   r   r2   r2   r3   r     s   zRunner.should_echo_stdinc                 C   s4   d |}| jD ]}||D ]}| | qqdS )a  
        Write to the program's stdin in response to patterns in ``buffer_``.

        The patterns and responses are driven by the `.StreamWatcher` instances
        from the ``watchers`` kwarg of `run` - see :doc:`/concepts/watchers`
        for a conceptual overview.

        :param buffer:
            The capture buffer for this thread's particular IO stream.

        :returns: ``None``.

        .. versionadded:: 1.0
        rM   N)re   r,   submitr   )r1   r   r   watcherresponser2   r2   r3   r     s   

zRunner.respondr@   rA   c                 C   s   |r|S t tjfi |S )a~  
        Return a suitable environment dict based on user input & behavior.

        :param dict env: Dict supplying overrides or full env, depending.
        :param bool replace_env:
            Whether ``env`` updates, or is used in place of, the value of
            `os.environ`.

        :returns: A dictionary of shell environment vars.

        .. versionadded:: 1.0
        )rI   osenviron)r1   r@   rA   r2   r2   r3   rG     s   zRunner.generate_envrE   rx   c                 C   s   |S )al  
        Should execution attempt to use a pseudo-terminal?

        :param bool pty:
            Whether the user explicitly asked for a pty.
        :param bool fallback:
            Whether falling back to non-pty execution should be allowed, in
            situations where ``pty=True`` but a pty could not be allocated.

        .. versionadded:: 1.0
        r2   )r1   rE   rx   r2   r2   r3   r        zRunner.should_use_ptyc                 C   s   t dd | j D S )a  
        Detect whether any IO threads appear to have terminated unexpectedly.

        Used during process-completion waiting (in `wait`) to ensure we don't
        deadlock our child process if our IO processing threads have
        errored/died.

        :returns:
            ``True`` if any threads appear to have terminated with an
            exception, ``False`` otherwise.

        .. versionadded:: 1.0
        c                 s   s    | ]}|j V  qd S N)r   ).0xr2   r2   r3   	<genexpr>  s    z*Runner.has_dead_threads.<locals>.<genexpr>)anyrW   rX   r]   r2   r2   r3   has_dead_threads  s   zRunner.has_dead_threadsc                 C   s(   	 | j }| j}|s|rdS t| j q)z
        Block until the running command appears to have exited.

        :returns: ``None``.

        .. versionadded:: 1.0
        TN)process_is_finishedr   r   r   r*   )r1   proc_finisheddead_threadsr2   r2   r3   r`     s   zRunner.waitr   c                 C   s   |  || j dS )z
        Write encoded ``data`` to the running process' stdin.

        :param data: A Unicode string.

        :returns: ``None``.

        .. versionadded:: 1.0
        N)_write_proc_stdinencoderB   r1   r   r2   r2   r3   r     s   zRunner.write_proc_stdinc                 C   s   | | jdS )z_
        Decode some ``data`` bytes, returning Unicode.

        .. versionadded:: 1.0
        r   )r   rB   r   r2   r2   r3   r     s   zRunner.decodec                 C      t )a^  
        Determine whether our subprocess has terminated.

        .. note::
            The implementation of this method should be nonblocking, as it is
            used within a query/poll loop.

        :returns:
            ``True`` if the subprocess has finished running, ``False``
            otherwise.

        .. versionadded:: 1.0
        NotImplementedErrorr]   r2   r2   r3   r     s   zRunner.process_is_finishedrC   c                 C   r   )ai  
        Initiate execution of ``command`` (via ``shell``, with ``env``).

        Typically this means use of a forked subprocess or requesting start of
        execution on a remote system.

        In most cases, this method will also set subclass-specific member
        variables used in other methods such as `wait` and/or `returncode`.

        :param str command:
            Command string to execute.

        :param str shell:
            Shell to use when executing ``command``.

        :param dict env:
            Environment dict used to prep shell environment.

        .. versionadded:: 1.0
        r   )r1   r5   rC   r@   r2   r2   r3   rT     s   zRunner.startrR   c                 C   s*   |durt || j| _| j  dS dS )zS
        Start a timer to `kill` our subprocess after ``timeout`` seconds.
        N)r%   Timerkillr-   rT   )r1   rR   r2   r2   r3   rU   -  s   zRunner.start_timer	num_bytesc                 C   r   )z
        Read ``num_bytes`` from the running process' stdout stream.

        :param int num_bytes: Number of bytes to read at maximum.

        :returns: A string/bytes object.

        .. versionadded:: 1.0
        r   r1   r   r2   r2   r3   r   5     
zRunner.read_proc_stdoutc                 C   r   )z
        Read ``num_bytes`` from the running process' stderr stream.

        :param int num_bytes: Number of bytes to read at maximum.

        :returns: A string/bytes object.

        .. versionadded:: 1.0
        r   r   r2   r2   r3   r   A  r   zRunner.read_proc_stderrc                 C   r   )aF  
        Write ``data`` to running process' stdin.

        This should never be called directly; it's for subclasses to implement.
        See `write_proc_stdin` for the public API call.

        :param data: Already-encoded byte data suitable for writing.

        :returns: ``None``.

        .. versionadded:: 1.0
        r   r   r2   r2   r3   r   M  r   zRunner._write_proc_stdinc                 C   r   )zk
        Close running process' stdin.

        :returns: ``None``.

        .. versionadded:: 1.3
        r   r]   r2   r2   r3   r   \  s   zRunner.close_proc_stdinc                 C   s   t  S )z
        Return a string naming the expected encoding of subprocess streams.

        This return value should be suitable for use by encode/decode methods.

        .. versionadded:: 1.0
        )rH   r]   r2   r2   r3   rH   f  s   
zRunner.default_encoding	interruptra   c                 C   s   |  d dS )a  
        Submit an interrupt signal to the running subprocess.

        In almost all implementations, the default behavior is what will be
        desired: submit ```` to the subprocess' stdin pipe. However, we
        leave this as a public method in case this default needs to be
        augmented or replaced.

        :param interrupt:
            The locally-sourced ``KeyboardInterrupt`` causing the method call.

        :returns: ``None``.

        .. versionadded:: 1.0
        N)r   )r1   r   r2   r2   r3   rb   r  s   zRunner.send_interruptc                 C   r   )a  
        Return the numeric return/exit code resulting from command execution.

        :returns:
            `int`, if any reasonable return code could be determined, or
            ``None`` in corner cases where that was not possible.

        .. versionadded:: 1.0
        r   r]   r2   r2   r3   r     r   zRunner.returncodec                 C   s   | j r
| j   dS dS )aM  
        Perform final cleanup, if necessary.

        This method is called within a ``finally`` clause inside the main `run`
        method. Depending on the subclass, it may be a no-op, or it may do
        things such as close network connections or open files.

        :returns: ``None``

        .. versionadded:: 1.0
        N)r-   cancelr]   r2   r2   r3   r9     s   zRunner.stopc                 C   r   )aS  
        Forcibly terminate the subprocess.

        Typically only used by the timeout functionality.

        This is often a "best-effort" attempt, e.g. remote subprocesses often
        must settle for simply shutting down the local side of the network
        connection and hoping the remote end eventually gets the message.
        r   r]   r2   r2   r3   r     r   zRunner.killc                 C   s   t | jo	| j  S )zq
        Returns ``True`` if the subprocess stopped because it timed out.

        .. versionadded:: 1.3
        )boolr-   is_aliver]   r2   r2   r3   rl     s   	zRunner.timed_outr#   r   r$   Nr$   r\   )r$   r7   )Fr$   N)r   ra   r$   N)>__name__
__module____qualname____doc__r   strr   __annotations__r   r)   r*   r4   r   r;   r?   rK   r8   rY   rZ   rF   r   r   rk   r   intrf   r   r   rV   rS   r	   r   r
   r   r   r   r   r   r   r   r   rG   r   propertyr   r`   r   r   r   r   rT   rU   r   r   r   r   rH   rb   r   r9   r   rl   r2   r2   r2   r3   r    =   s   
 

0  

<<
*!


,
B




"




r    c                       s   e Zd ZdZd% fddZd&d
ededefddZdedee	 fddZ
dedee	 fddZde	ddfddZd'ddZdededeeef ddfddZd'ddZedefdd Zdee fd!d"Zd' fd#d$Z  ZS )(LocalaF  
    Execute a command on the local system in a subprocess.

    .. note::
        When Invoke itself is executed without a controlling terminal (e.g.
        when ``sys.stdin`` lacks a useful ``fileno``), it's not possible to
        present a handle on our PTY to local subprocesses. In such situations,
        `Local` will fallback to behaving as if ``pty=False`` (on the theory
        that degraded execution is better than none at all) as well as printing
        a warning to stderr.

        To disable this behavior, say ``fallback=False``.

    .. versionadded:: 1.0
    r#   r   r$   Nc                    s   t  | d| _d S Nr   )superr4   statusr0   r(   r2   r3   r4     s   
zLocal.__init__FTrE   rx   c                 C   s>   d}|rd}t tjs|r| jsd}tj| d| _d}|S )NFTzAWARNING: stdin has no fileno; falling back to non-pty execution!
)r   r   r   r+   rP   r   )r1   rE   rx   use_ptyrz   r2   r2   r3   r     s   zLocal.should_use_ptyr   c              
      s   | j r5z
t| j|}W |S  ty4 } zt| d}t fdd|D s' d }W Y d }~|S d }~ww | jrH| jjrHt| jj	 |}|S d }|S )N)zInput/output errorz	I/O errorc                 3   s    | ]}| v V  qd S r   r2   )r   errorstringifiedr2   r3   r     s    z)Local.read_proc_stdout.<locals>.<genexpr>)
r"   r   r   	parent_fdr   r   r   processrO   fileno)r1   r   r   rm   	io_errorsr2   r   r3   r     s$   zLocal.read_proc_stdoutc                 C   s&   | j r| j jrt| j j |S d S r   )r   rP   r   r   r   r   r2   r2   r3   r     s   zLocal.read_proc_stderrr   c              
   C   sz   | j r| j}n| jr| jjr| jj }ntdz	t|| W d S  ty< } zdt	|vr1 W Y d }~d S d }~ww )Nz/Unable to write to missing subprocess or stdin!zBroken pipe)
r"   r   r   r   r   r   r   r   r   r   )r1   r   fdrm   r2   r2   r3   r     s   zLocal._write_proc_stdinc                 C   s4   | j rtd| jr| jjr| jj  d S td)Nz Cannot close stdin when pty=Truez,Unable to close missing subprocess or stdin!)r"   r   r   r   closer]   r2   r2   r3   r     s   zLocal.close_proc_stdinr5   rC   r@   c              	   C   s   | j rBtd u rd}t| t \}}t \| _| _| jdkr@t	d||dd}t
tj tj| t||d|g| d S d S t|d||tttd| _d S )NzKYou indicated pty=True, but your platform doesn't support the 'pty' module!r   HHHHz-cT)rC   
executabler@   rO   rP   r   )r"   rE   r   exitr   forkpidr   structpackfcntlioctlrO   r   termios
TIOCSWINSZr   execver   r   r   )r1   r5   rC   r@   rz   colsrowswinsizer2   r2   r3   rT     s(   



zLocal.startc                 C   s>   | j r| jn| jj}z
t|tj W d S  ty   Y d S w r   )r"   r   r   r   r   signalSIGKILLProcessLookupError)r1   r   r2   r2   r3   r   C  s   z
Local.killc                 C   s2   | j rt| jtj\}| _|dkS | j d uS r   )r"   r   waitpidr   WNOHANGr   r   poll)r1   pid_valr2   r2   r3   r   L  s   zLocal.process_is_finishedc                 C   sR   | j r%d }t| jrt| j}|S t| jr#t| j}d| }|S | jjS )N)	r"   r   	WIFEXITEDr   WEXITSTATUSWIFSIGNALEDWTERMSIGr   r   )r1   coder2   r2   r3   r   [  s   zLocal.returncodec                    s<   t    | jrz	t| j W d S  ty   Y d S w d S r   )r   r9   r"   r   r   r   	Exceptionr]   r   r2   r3   r9   p  s   
z
Local.stopr   )FTr   )r   r   r   r   r4   r   r   r   r   r   r   r   r   r   r   r   r   rT   r   r   r   r   r9   __classcell__r2   r2   r   r3   r     s    
"
'	r   c                   @   s   e Zd ZdZdddddddde f	dededee d	ed
edeeeef  de	de
deedf fddZede	fddZde
fddZdefddZdefddZede
fddZede
fddZd$d ed!e	defd"d#ZdS )%r7   a  
    A container for information about the result of a command execution.

    All params are exposed as attributes of the same name and type.

    :param str stdout:
        The subprocess' standard output.

    :param str stderr:
        Same as ``stdout`` but containing standard error (unless the process
        was invoked via a pty, in which case it will be empty; see
        `.Runner.run`.)

    :param str encoding:
        The string encoding used by the local shell environment.

    :param str command:
        The command which was executed.

    :param str shell:
        The shell binary used for execution.

    :param dict env:
        The shell environment used for execution. (Default is the empty dict,
        ``{}``, not ``None`` as displayed in the signature.)

    :param int exited:
        An integer representing the subprocess' exit/return code.

        .. note::
            This may be ``None`` in situations where the subprocess did not run
            to completion, such as when auto-responding failed or a timeout was
            reached.

    :param bool pty:
        A boolean describing whether the subprocess was invoked with a pty or
        not; see `.Runner.run`.

    :param tuple hide:
        A tuple of stream names (none, one or both of ``('stdout', 'stderr')``)
        which were hidden from the user when the generating command executed;
        this is a normalized value derived from the ``hide`` parameter of
        `.Runner.run`.

        For example, ``run('command', hide='stdout')`` will yield a `Result`
        where ``result.hide == ('stdout',)``; ``hide=True`` or ``hide='both'``
        results in ``result.hide == ('stdout', 'stderr')``; and ``hide=False``
        (the default) generates ``result.hide == ()`` (the empty tuple.)

    .. note::
        `Result` objects' truth evaluation is equivalent to their `.ok`
        attribute's value. Therefore, quick-and-dirty expressions like the
        following are possible::

            if run("some shell command"):
                do_something()
            else:
                handle_problem()

        However, remember `Zen of Python #2
        <http://zen-of-python.info/explicit-is-better-than-implicit.html#2>`_.

    .. versionadded:: 1.0
    rM   Nr   FrO   rP   rB   r5   rC   r@   rQ   rE   rD   .c
           
      C   sT   || _ || _|d u rt }|| _|| _|| _|d u ri n|| _|| _|| _|	| _	d S r   )
rO   rP   rH   rB   r5   rC   r@   rQ   rE   rD   )
r1   rO   rP   rB   r5   rC   r@   rQ   rE   rD   r2   r2   r3   r4     s   
zResult.__init__r$   c                 C      | j S )zJ
        An alias for ``.exited``.

        .. versionadded:: 1.0
        )rQ   r]   r2   r2   r3   return_code  s   zResult.return_codec                 C   r  r   okr]   r2   r2   r3   __bool__  s   zResult.__bool__c                 C   sd   | j d urd| j }nd}|g}dD ]}t| |}||r&d|| nd| qd|S )NzCommand exited with status {}.z4Command was not fully executed due to watcher error.)rO   rP   z=== {} ===
{}
z(no {})r   )rQ   r>   getattrrj   rstripre   )r1   descretr   valr2   r2   r3   __str__  s   


	zResult.__str__c                 C   s   d}| | j| jS )Nz<Result cmd={!r} exited={}>)r>   r5   rQ   )r1   templater2   r2   r3   __repr__  s   zResult.__repr__c                 C   s   t | jdkS )zY
        A boolean equivalent to ``exited == 0``.

        .. versionadded:: 1.0
        r   )r   rQ   r]   r2   r2   r3   r    s   z	Result.okc                 C   s   | j  S )z
        The inverse of ``ok``.

        I.e., ``True`` if the program exited with a nonzero return code, and
        ``False`` otherwise.

        .. versionadded:: 1.0
        r  r]   r2   r2   r3   failed  s   
zResult.failed
   r   countc                 C   s"   dd t| | | d  S )a  
        Return the last ``count`` lines of ``stream``, plus leading whitespace.

        :param str stream:
            Name of some captured stream attribute, eg ``"stdout"``.
        :param int count:
            Number of lines to preserve.

        .. versionadded:: 1.3
        z

r   N)re   r  
splitlines)r1   r   r  r2   r2   r3   tail  s   "zResult.tail)r  )r   r   r   r   tupler   r   r   r   r   r   r   r4   r   r  r  r  r  r  r  r!  r2   r2   r2   r3   r7   ~  sP    D	


r7   c                   @   sX   e Zd ZdZdddZdefdd	Zdd
dZdee	e
  de
dee ddfddZdS )r\   a4  
    A promise of some future `Result`, yielded from asynchronous execution.

    This class' primary API member is `join`; instances may also be used as
    context managers, which will automatically call `join` when the block
    exits. In such cases, the context manager yields ``self``.

    `Promise` also exposes copies of many `Result` attributes, specifically
    those that derive from `~Runner.run` kwargs and not the result of command
    execution. For example, ``command`` is replicated here, but ``stdout`` is
    not.

    .. versionadded:: 1.4
    runnerr    r$   Nc                 C   s,   || _ | j j D ]
\}}t| || q	dS )z
        Create a new promise.

        :param runner:
            An in-flight `Runner` instance making this promise.

            Must already have started the subprocess and spun up IO threads.
        N)r#  rJ   rd   setattr)r1   r#  r   rh   r2   r2   r3   r4   5  s   	zPromise.__init__c                 C   s$   z| j  W | j   S | j   w )ak  
        Block until associated subprocess exits, returning/raising the result.

        This acts identically to the end of a synchronously executed ``run``,
        namely that:

        - various background threads (such as IO workers) are themselves
          joined;
        - if the subprocess exited normally, a `Result` is returned;
        - in any other case (unforeseen exceptions, IO sub-thread
          `.ThreadException`, `.Failure`, `.WatcherError`) the relevant
          exception is raised here.

        See `~Runner.run` docs, or those of the relevant classes, for further
        details.
        )r#  rZ   r9   r]   r2   r2   r3   re   D  s   
zPromise.joinc                 C   s   | S r   r2   r]   r2   r2   r3   	__enter__Z  s   zPromise.__enter__exc_type	exc_valueexc_tbc                 C   s   |    d S r   )re   )r1   r&  r'  r(  r2   r2   r3   __exit__]  s   zPromise.__exit__)r#  r    r$   Nr   )r   r   r   r   r4   r7   re   r%  r   r   BaseExceptionr   r)  r2   r2   r2   r3   r\   %  s    


r\   r  ru   rv   r$   .c                 C   s   d}| |vrd}t || || dv rg }n| dv r ddg}n| dkr(dg}n| dkr0dg}n| g}|d ur@d|v r@|d |d urMd|v rM|d t|S )	N)NFry   rO   rz   rP   bothTz$'hide' got {!r} which is not in {!r})NF)r+  TrO   rP   ry   rz   )r   r>   remover"  )r  ru   rv   	hide_valsrz   rD   r2   r2   r3   r   f  s$   


r   c                  C   s   t d} | S )z
    Obtain apparent interpreter-local default text encoding.

    Often used as a baseline in situations where we must use SOME encoding for
    unknown-but-presumably-text bytes, and the user has not specified an
    override.
    F)localegetpreferredencoding)rB   r2   r2   r3   rH     s   
rH   )NN)8r   r.  r   r   r   r%   r   r  
subprocessr   r   typesr   typingr   r   r   r   r	   r
   r   r   r   r   rE   ImportErrorr   r   
exceptionsr   r   r   r   r   r   	terminalsr   r   r   r   r   utilr   r   r   r#   r   r,   r   r    r   r7   r\   r   r   rH   r2   r2   r2   r3   <module>   sv    0           H (C

