o
    3g:                     @  sd  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mZ	 d dlm
Z
 d dlmZ d dlmZ dd Zd	d
 Zd(ddZd(ddZerHeneZG dd deZG dd deZG dd deZG dd deZG dd dZe
 Zdadd ZeeddZde_ e!  dd  Z"d!d" Z#e$e# d(d#d$Z%e& Z'e& Z(e'Z)ej*Z+d dd%dddefd&d'Z,dS ))    )annotationsN)Empty)Queue)Thread)IS_WIN32c                 C  s   |  |||| | j||fS N)verify
returncodeprocretcodetimeoutstdoutstderr r   R/home/garg/my-data/venv/lib/python3.10/site-packages/plumbum/commands/processes.py_check_process   s   r   c                   s@   g   fdd}| r|d| j  |d| j t| dd} | s
 S )a  Get a list of all valid standard streams for proc that were opened with PIPE option.

    If proc was started from a Pipeline command, this function assumes it will have a
    "srcproc" member pointing to the previous command in the pipeline. That link will
    be used to traverse all started processes started from the pipeline, the list will
    include stdout/stderr streams opened as PIPE for all commands in the pipeline.
    If that was not the case, some processes could write to pipes no one reads from
    which would result in process stalling after the pipe's buffer is filled.

    Streams that were closed (because they were redirected to the input of a subsequent command)
    are not included in the result
    c                   s$   |d u s|j r	d S  | |f d S r   )closedappend)type_streamstreamsr   r   
add_stream&   s   z&_get_piped_streams.<locals>.add_stream   r   srcprocN)r   r   getattr)r   r   r   r   r   _get_piped_streams   s   r   c           	      #  s~    ddl mm  t fdd}| D ]}|V   d ur) nqD ]\}}|D ]	}||fV  q2q,d S )Nr   )
EVENT_READDefaultSelectorc                  3  s|      } D ]\}}|  || q	 | }|s*r*tdtdd tdd |D ]\}}|j|jfV  q,q)NTpopen line timeout expiredargvmachine)registerselectProcessLineTimedOutr   datafileobjreadline)selstream_typer   readykey_maskr   r   decodeline_timeoutlinesizer   r   r   r   selector9   s   


z#_iter_lines_posix.<locals>.selector)	selectorsr   r   r   poll)	r   r/   r1   r0   r2   retr*   r   liner   r.   r   _iter_lines_posix3   s   
r7   c           	      #  s   G  fdddt }|d u rtd}t |d| j|d| jg}t }d}	 z V  t }d}W n tyC   d}Y nw t | |krZtdt	| d	d t	| d
d | 
 d uran|rhtd q+|D ]}|  qk	 z V  W n
 ty   Y d S w qs)Nc                      s6   e Zd Z fddZfddZfddZ  ZS )z _iter_lines_win32.<locals>.Piperc                   s<   t  jd| dd || _|| _d| _d| _t    d S )NPlumbumPiperr   )nameFT)super__init__pipefdemptydaemonstart)selfr=   r<   	__class__r   r   r;   S   s   z)_iter_lines_win32.<locals>.Piper.__init__c                   s   | j  S r   )r<   r(   rA   )r1   r   r   read_from_pipe[   s   z/_iter_lines_win32.<locals>.Piper.read_from_pipec                   s*   t | jdD ]}| j |f qd S )N    )iterrE   putr=   )rA   r6   )r/   queuer   r   run^   s   z$_iter_lines_win32.<locals>.Piper.run)__name__
__module____qualname__r;   rE   rJ   __classcell__r   r/   r1   rI   rB   r   PiperR   s    rP   infr   r   TFr    r!   r"   皙?)r   floatr   r   r   time
get_nowait
QueueEmptyr%   r   r4   sleepjoin)	r   r/   r1   r0   rP   piperslast_line_tsr>   piperr   rO   r   _iter_lines_win32Q   sH   




r\   c                   @  s(   e Zd ZdZdddddZdd ZdS )	ProcessExecutionErroraJ  Represents the failure of a process. When the exit code of a terminated process does not
    match the expected result, this exception is raised by :func:`run_proc
    <plumbum.commands.run_proc>`. It contains the process' return code, stdout, and stderr, as
    well as the command line used to create the process (``argv``)
    N)hostc                C  s^   t | |||| || _|| _|| _|| _t|trt|}t|tr't|}|| _	|| _
d S r   )	Exceptionr;   messager^   r!   r   
isinstancebytesasciir   r   )rA   r!   r   r   r   r`   r^   r   r   r   r;      s   


zProcessExecutionError.__init__c                 C  s   ddl m} dt| j }dt| j }d|| j}g }| jr1| jdt| j	g}ndt| j	g}d| }|d|g7 }| j
rO|d| j
g7 }|rW|d	|g7 }|r_|d
|g7 }d|S )Nr   )shquote_listz
              |  z
Return code:  | zUnexpected exit code: z
Command line: | z
Host:         | z
Stdout:       | z
Stderr:       |  )plumbum.commands.baserd   rX   strr   
splitlinesr   r!   r`   r   r^   )rA   rd   r   r   cmdlinesr   r   r   __str__   s"   
zProcessExecutionError.__str__r   )rK   rL   rM   __doc__r;   rl   r   r   r   r   r]      s    r]   c                   @     e Zd ZdZdd ZdS )ProcessTimedOutzRaises by :func:`run_proc <plumbum.commands.run_proc>` when a ``timeout`` has been
    specified and it has elapsed before the process terminatedc                 C  s   t | || || _d S r   )r_   r;   r!   )rA   msgr!   r   r   r   r;      s   
zProcessTimedOut.__init__NrK   rL   rM   rm   r;   r   r   r   r   ro          ro   c                   @  rn   )r%   zRaises by :func:`iter_lines <plumbum.commands.iter_lines>` when a ``line_timeout`` has been
    specified and it has elapsed before the process yielded another linec                 C  s    t | ||| || _|| _d S r   )r_   r;   r!   r"   )rA   rp   r!   r"   r   r   r   r;         
zProcessLineTimedOut.__init__Nrq   r   r   r   r   r%      rr   r%   c                      s    e Zd ZdZ fddZ  ZS )CommandNotFoundzRaised by :func:`local.which <plumbum.machines.local.LocalMachine.which>` and
    :func:`RemoteMachine.which <plumbum.machines.remote.RemoteMachine.which>` when a
    command was not found in the system's ``PATH``c                   s    t  | || || _|| _d S r   )r:   r;   programpath)rA   ru   rv   rB   r   r   r;      rs   zCommandNotFound.__init__)rK   rL   rM   rm   r;   rN   r   r   rB   r   rt      s    rt   c                   @  s6   e Zd ZdddZdd Zdd Zdd	 Zd
d ZdS )MinHeapr   c                 C  s   t || _t| j d S r   )list_itemsheapqheapify)rA   itemsr   r   r   r;      s   
zMinHeap.__init__c                 C  s
   t | jS r   )lenry   rD   r   r   r   __len__      
zMinHeap.__len__c                 C  s   t | j| d S r   )rz   heappushry   )rA   itemr   r   r   push   s   zMinHeap.pushc                 C  s   t | j d S r   )rz   heappopry   rD   r   r   r   pop   s   zMinHeap.popc                 C  s
   | j d S )Nr   )ry   rD   r   r   r   peek   r   zMinHeap.peekN)r   )rK   rL   rM   r;   r~   r   r   r   r   r   r   r   rw      s    
rw   Fc                  C  s4  t  } zts| r|  \}}td|t  }nd }tt% tj	|d\}}|t
u r6	 W d    W d S | ||f W d    n1 sGw   Y  t }| r|  \}}||kr]n(|   tt | d u rt|  d|_W d    n1 s~w   Y  | sRtrW d S W d S  ty   trY d S  w )Nr   )r   T)rw   _shutting_downr   maxrT   
contextlibsuppressrV   _timeout_queueget
SystemExitr   r   OSErrorr4   kill
_timed_outr_   )waitingttk_r   r   time_to_killnowr   r   r   _timeout_thread_func   sB   r   PlumbumTimeoutThread)targetr9   Tc                 C  s&   |d urt | t | f d S d S r   )r   rH   rT   )r   r   r   r   r   _register_proc_timeout  s   r   c                   C  s(   da trttdf td d S d S )NTr   rR   )r   r   rH   r   bgthdrX   r   r   r   r   _shutdown_bg_threads  s
   r   c                 C  sh   t | | |  \}}t | _|sd}|sd}t| ddr,|| jd}|| jd}t| ||||S )a  Waits for the given process to terminate, with the expected exit code

    :param proc: a running Popen-like object, with all the expected methods.

    :param retcode: the expected return (exit) code of the process. It defaults to 0 (the
                    convention for success). If ``None``, the return code is ignored.
                    It may also be a tuple (or any object that supports ``__contains__``)
                    of expected return codes.

    :param timeout: the number of seconds (a ``float``) to allow the process to run, before
                    forcefully terminating it. If ``None``, not timeout is imposed; otherwise
                    the process is expected to terminate within that timeout value, or it will
                    be killed and :class:`ProcessTimedOut <plumbum.cli.ProcessTimedOut>`
                    will be raised

    :returns: A tuple of (return code, stdout, stderr)
    rF   custom_encodingNignore)r   communicaterT   	_end_timer   r/   r   r   r
   r   r   r   run_proc-  s   

r   c                 #  s   |du rt }|du rt}|ttfv sJ t| ddpd  fdd}t| | g g g}	|| |||D ]B\}
}| j|dddd |	|
 }|dkrX|| |tj	k rX|d| = |tu rjddg}|||
< t
|V  q3|tu ru|
d |fV  q3t| ||gd	d
 |	D R   dS )a  Runs the given process (equivalent to run_proc()) and yields a tuples of (out, err) line pairs.
    If the exit code of the process does not match the expected one, :class:`ProcessExecutionError
    <plumbum.commands.ProcessExecutionError>` is raised.

    :param retcode: The expected return code of this process (defaults to 0).
                    In order to disable exit-code validation, pass ``None``. It may also
                    be a tuple (or any iterable) of expected exit codes.

    :param timeout: The maximal amount of time (in seconds) to allow the process to run.
                    ``None`` means no timeout is imposed; otherwise, if the process hasn't
                    terminated after that many seconds, the process will be forcefully
                    terminated an exception will be raised

    :param linesize: Maximum number of characters to read from stdout/stderr at each iteration.
                    ``-1`` (default) reads until a b'\n' is encountered.

    :param line_timeout: The maximal amount of time (in seconds) to allow between consecutive lines in either stream.
                    Raise an :class:`ProcessLineTimedOut <plumbum.commands.ProcessLineTimedOut>` if the timeout has
                    been reached. ``None`` means no timeout is imposed.

    :param buffer_size: Maximum number of lines to keep in the stdout/stderr buffers, in case of a ProcessExecutionError.
                    Default is ``None``, which defaults to DEFAULT_BUFFER_SIZE (which is infinite by default).
                    ``0`` will disable buffering completely.

    :param mode: Controls what the generator yields. Defaults to DEFAULT_ITER_LINES_MODE (which is BY_POSITION by default)
                - BY_POSITION (default): yields ``(out, err)`` line tuples, where either item may be ``None``
                - BY_TYPE: yields ``(fd, line)`` tuples, where ``fd`` is 1 (stdout) or 2 (stderr)

    :returns: An iterator of (out, err) line tuples.
    Nr   zutf-8c                   s   | j  dd S )Nreplace)errors)r/   rstrip)sencodingr   r   <lambda>  s    ziter_lines.<locals>.<lambda>)r   r   r   r   r   r   c                 s  s    | ]
}d  |d  V  qdS )
N)rX   ).0r   r   r   r   	<genexpr>  s    ziter_lines.<locals>.<genexpr>)DEFAULT_ITER_LINES_MODEDEFAULT_BUFFER_SIZEBY_POSITIONBY_TYPEr   r   r   r   mathrQ   tupler   )r   r   r   r1   r0   buffer_sizemode_iter_linesr/   bufferstr6   bufferr5   r   r   r   
iter_linesW  s2   (


"r   r   )-
__future__r   atexitr   rz   r   rT   rI   r   rV   r   	threadingr   plumbum.libr   r   r   r7   r\   r   r   r]   r_   ro   r%   AttributeErrorrt   rw   r   r   r   r   r?   r@   r   r   r#   r   objectr   r   r   rQ   r   r   r   r   r   r   <module>   sT    

4/	
!

$