o
    3gB                     @  s$  d dl mZ d dlZd dlmZmZ d dlmZ d dlmZ d dl	Z
d dlmZmZmZ d dlmZ G dd	 d	ZG d
d d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eZG dd deZG dd dZG dd dZe Ze Ze Ze Ze Ze Z dS )    )annotationsN)DEBUGINFO)select)PIPE)BY_TYPEProcessExecutionErrorrun_proc)read_fd_decode_safelyc                   @  sZ   e Zd ZdZdddZdd Zdd ZeZd	d
 Ze	dd Z
e	dd Ze	dd ZdS )FuturezRepresents a "future result" of a running process. It basically wraps a ``Popen``
    object and the expected exit code, and provides poll(), wait(), returncode, stdout,
    and stderr.
    Nc                 C  s(   || _ || _|| _d | _d | _d | _d S N)proc_expected_retcode_timeout_returncode_stdout_stderr)selfr   expected_retcodetimeout r   R/home/garg/my-data/venv/lib/python3.10/site-packages/plumbum/commands/modifiers.py__init__   s   
zFuture.__init__c                 C  s(   |   r| jnd}d| jjd| dS )Nrunningz<Future z (z)>)readyr   r   argv)r   r   r   r   r   __repr__   s   zFuture.__repr__c                 C  s    | j  dur|   | jduS )zsPolls the underlying process for termination; returns ``False`` if still running,
        or ``True`` if terminatedN)r   pollwaitr   r   r   r   r   r      s   
zFuture.pollc                 C  s0   | j durdS t| j| j| j\| _ | _| _dS )z{Waits for the process to terminate; will raise a
        :class:`plumbum.commands.ProcessExecutionError` in case of failureN)r   r	   r   r   r   r   r   r   r   r   r   r   (   s
   
zFuture.waitc                 C     |    | jS )zPThe process' stdout; accessing this property will wait for the process to finish)r   r   r   r   r   r   stdout1      zFuture.stdoutc                 C  r    )zPThe process' stderr; accessing this property will wait for the process to finish)r   r   r   r   r   r   stderr7   r"   zFuture.stderrc                 C  r    )zTThe process' returncode; accessing this property will wait for the process to finish)r   r   r   r   r   r   
returncode=   r"   zFuture.returncoder   )__name__
__module____qualname____doc__r   r   r   r   r   propertyr!   r#   r$   r   r   r   r   r      s    
	

r   c                   @  s$   e Zd ZdZdd Zedd ZdS )ExecutionModifier)__weakref__c                 C  s   i }| j jD ]"}t|dd}t|tr|f}|D ]}|d dkr't| |||< qqdd | D }d|}| j j d| d	S )
zgAutomatically creates a representation for given subclass with slots.
        Ignore hidden properties.	__slots__r   r   _c                 s  s"    | ]\}}| d | V  qdS )z = Nr   ).0namevaluer   r   r   	<genexpr>W   s     z-ExecutionModifier.__repr__.<locals>.<genexpr>z, ())	__class____mro__getattr
isinstancestritemsjoinr%   )r   slotscls
slots_listpropmystrs
mystrs_strr   r   r   r   L   s   

zExecutionModifier.__repr__c                 O     | |i |S r   r   r<   argskwargsr   r   r   __call__[      zExecutionModifier.__call__N)r%   r&   r'   r,   r   classmethodrE   r   r   r   r   r*   I   s
    r*   c                   @  &   e Zd ZdZdZd	ddZdd ZdS )
_BGa  
    An execution modifier that runs the given command in the background, returning a
    :class:`Future <plumbum.commands.Future>` object. In order to mimic shell syntax, it applies
    when you right-and it with a command. If you wish to expect a different return code
    (other than the normal success indicate by 0), use ``BG(retcode)``. Example::

        future = sleep[5] & BG       # a future expecting an exit code of 0
        future = sleep[5] & BG(7)    # a future expecting an exit code of 7

    .. note::

       When processes run in the **background** (either via ``popen`` or
       :class:`& BG <plumbum.commands.BG>`), their stdout/stderr pipes might fill up,
       causing them to hang. If you know a process produces output, be sure to consume it
       every once in a while, using a monitoring thread/reactor in the background.
       For more info, see `#48 <https://github.com/tomerfiliba/plumbum/issues/48>`_
    retcodekargsr   r   Nc                 K  s   || _ || _|| _d S r   rJ   )r   rK   r   rL   r   r   r   r   u   s   
z_BG.__init__c                 C  s    t |jdi | j| j| jdS )N)r   r   )r   popenrL   rK   r   r   cmdr   r   r   __rand__z   s    z_BG.__rand__r   Nr%   r&   r'   r(   r,   r   rP   r   r   r   r   rI   `   s
    
rI   c                   @  rH   )
_FGaY  
    An execution modifier that runs the given command in the foreground, passing it the
    current process' stdin, stdout and stderr. Useful for interactive programs that require
    a TTY. There is no return value.

    In order to mimic shell syntax, it applies when you right-and it with a command.
    If you wish to expect a different return code (other than the normal success indicate by 0),
    use ``FG(retcode)``. Example::

        vim & FG       # run vim in the foreground, expecting an exit code of 0
        vim & FG(7)    # run vim in the foreground, expecting an exit code of 7
    rK   r   r   Nc                 C  s   || _ || _d S r   rT   )r   rK   r   r   r   r   r      s   
z_FG.__init__c                 C  s   || j d d d | jd d S )NrK   stdinr!   r#   r   rT   rN   r   r   r   rP      s   
z_FG.__rand__rQ   rR   r   r   r   r   rS   ~   s
    
rS   c                   @  s&   e Zd ZdZdZd
ddZdd	 ZdS )_TEEa:  Run a command, dumping its stdout/stderr to the current process's stdout
    and stderr, but ALSO return them.  Useful for interactive programs that
    expect a TTY but also have valuable output.

    Use as:

        ls["-l"] & TEE

    Returns a tuple of (return code, stdout, stderr), just like ``run()``.
    rK   bufferedr   r   TNc                 C     || _ || _|| _dS )z`retcode` is the return code to expect to mean "success".  Set
        `buffered` to False to disable line-buffering the output, which may
        cause stdout and stderr to become more entangled than usual.
        NrX   )r   rK   rY   r   r   r   r   r      s   
z_TEE.__init__c                 C  s:  |j | jd tt| jd}g }g }|j}|j}||||i}|tj|tji}d}	|	sn| d u}	d}
|
rld}
t||fdd\}}}|D ]'}|| }t	|d\}}|sRqBd}
|| 
| | jsd||   || qB|
s3|	r)|  ddd |D }dd	d |D }|j||fW  d    S 1 sw   Y  d S )
NrU   FTr   i    c                 S     g | ]}| d qS zutf-8decoder.   xr   r   r   
<listcomp>       z!_TEE.__rand__.<locals>.<listcomp>c                 S  r\   r]   r^   r`   r   r   r   rb      rc   )bgrunrK   r   r   r!   r#   sysr   r   r
   writerY   flushappendr   r:   r$   )r   rO   poutbuferrbufouterrbufferstee_todoneprogressr   r-   fdbufdatatextr!   r#   r   r   r   rP      sL   %
$z_TEE.__rand__)r   TNrR   r   r   r   r   rW      s
    
	rW   c                   @  s8   e Zd ZdZdZ			dddZedd	 Zd
d ZdS )_TFa  
    An execution modifier that runs the given command, but returns True/False depending on the retcode.
    This returns True if the expected exit code is returned, and false if it is not.
    This is useful for checking true/false bash commands.

    If you wish to expect a different return code (other than the normal success indicate by 0),
    use ``TF(retcode)``. If you want to run the process in the foreground, then use
    ``TF(FG=True)``.

    Example::

        local['touch']['/root/test'] & TF * Returns False, since this cannot be touched
        local['touch']['/root/test'] & TF(1) # Returns True
        local['touch']['/root/test'] & TF(FG=True) * Returns False, will show error message
    rK   FGr   r   FNc                 C  rZ   )zv`retcode` is the return code to expect to mean "success".  Set
        `FG` to True to run in the foreground.
        Nrw   )r   rK   rx   r   r   r   r   r      s   	
z_TF.__init__c                 O  rA   r   r   rB   r   r   r   rE     rF   z_TF.__call__c                 C  sN   z| j r|| jd d d | jd W dS || j| jd W dS  ty&   Y dS w )NrU   rT   TF)rx   rK   r   r   rN   r   r   r   rP     s   	z_TF.__rand__)r   FN	r%   r&   r'   r(   r,   r   rG   rE   rP   r   r   r   r   rv      s    

rv   c                   @  s6   e Zd ZdZdZ		dddZedd Zd	d
 ZdS )_RETCODEa  
    An execution modifier that runs the given command, causing it to run and return the retcode.
    This is useful for working with bash commands that have important retcodes but not very
    useful output.

    If you want to run the process in the foreground, then use ``RETCODE(FG=True)``.

    Example::

        local['touch']['/root/test'] & RETCODE # Returns 1, since this cannot be touched
        local['touch']['/root/test'] & RETCODE(FG=True) * Returns 1, will show error message
    
foregroundr   FNc                 C  s   || _ || _dS )z&`FG` to True to run in the foreground.Nr{   )r   rx   r   r   r   r   r   2  s   
z_RETCODE.__init__c                 O  rA   r   r   rB   r   r   r   rE   ;  rF   z_RETCODE.__call__c                 C  s8   | j r|jd d d d | jd}|d S |jd | jdd S )NrU   r   rT   )r|   runr   )r   rO   resultr   r   r   rP   ?  s   z_RETCODE.__rand__)FNry   r   r   r   r   rz   "  s    
	
rz   c                   @  s&   e Zd ZdZdZdddZd	d
 ZdS )_NOHUPad  
    An execution modifier that runs the given command in the background, disconnected
    from the current process, returning a
    standard popen object. It will keep running even if you close the current process.
    In order to slightly mimic shell syntax, it applies
    when you right-and it with a command. If you wish to use a different working directory
    or different stdout, stderr, you can use named arguments. The default is ``NOHUP(
    cwd=local.cwd, stdout='nohup.out', stderr=None)``. If stderr is None, stderr will be
    sent to stdout. Use ``os.devnull`` for null output. Will respect redirected output.
    Example::

        sleep[5] & NOHUP                       # Outputs to nohup.out
        sleep[5] & NOHUP(stdout=os.devnull)    # No output

    The equivalent bash command would be

    .. code-block:: bash

        nohup sleep 5 &

    cwdr!   r#   rh   .	nohup.outNTc                 C  s   || _ || _|| _|| _dS )zuSet ``cwd``, ``stdout``, or ``stderr``.
        Runs as a forked process. You can set ``append=False``, too.
        Nr   )r   r   r!   r#   rh   r   r   r   r   b  s   
z_NOHUP.__init__c                 C  sd   t |tjjjr|j}d}|j}nt |tjjjr"|j}d}|j}n| j}| j	}|
| j|| j|S )NFT)r7   plumbumcommandsbaseStdoutRedirectionfilerO   AppendingStdoutRedirectionr!   rh   nohupr   r#   )r   rO   r!   rh   r   r   r   rP   k  s   z_NOHUP.__rand__)r   r   NTrR   r   r   r   r   r   I  s
    
	r   c                   @  s   e Zd Zdd Zdd ZdS )LogPipec                 C  s"   || _ || _|| _|| _|| _d S r   )line_timeoutkwlevelsprefixlog)r   r   r   r   r   r   r   r   r   r   {  s
   
zLogPipe.__init__c                 C  s   t |dr|n| }|jd| jtd| jD ]$\}}|sq| j| }| D ]}| jr5| j d| }| 	|| q(q|j
S )N
iter_lines)r   modez: r   )hasattrrM   r   r   r   r   r   
splitlinesr   r   r$   )r   rO   rM   typlineslevelliner   r   r   rP     s   
zLogPipe.__rand__N)r%   r&   r'   r   rP   r   r   r   r   r   z  s    r   c                   @  sL   e Zd ZdZdZdZdZeZeZ	dddZ	ddd	Z
dd
dZdd ZdS )PipeToLoggerMixina  
    This mixin allows piping plumbum commands' output into a logger.
    The logger must implement a ``log(level, msg)`` method, as in ``logging.Logger``

    Example::

        class MyLogger(logging.Logger, PipeToLoggerMixin):
            pass

        logger = MyLogger("example.app")

    Here we send the output of an install.sh script into our log::

        local['./install.sh'] & logger

    We can choose the log-level for each stream::

        local['./install.sh'] & logger.pipe(out_level=logging.DEBUG, err_level=logging.DEBUG)

    Or use a convenience method for it::

        local['./install.sh'] & logger.pipe_debug()

    A prefix can be added to each line::

        local['./install.sh'] & logger.pipe(prefix="install.sh: ")

    If the command fails, an exception is raised as usual. This can be modified::

        local['install.sh'] & logger.pipe_debug(retcode=None)

    An exception is also raised if too much time (``DEFAULT_LINE_TIMEOUT``) passed between lines in the stream,
    This can also be modified::

        local['install.sh'] & logger.pipe(line_timeout=10)

    If we happen to use logbook::

        class MyLogger(logbook.Logger, PipeToLoggerMixin):
            from logbook import DEBUG, INFO  # hook up with logbook's levels

    iX  r   r   Nc                 K  sZ   t | | jt | | jd}|du r| j}|dur||d< |dur$||d< t||||| jS )a  
        Pipe a command's stdout and stderr lines into this logger.

        :param out_level: the log level for lines coming from stdout
        :param err_level: the log level for lines coming from stderr

        Optionally use `prefix` for each line.
        )      Nr   r   )r6   DEFAULT_STDOUTDEFAULT_STDERRDEFAULT_LINE_TIMEOUTr   r   )r   	out_level	err_levelr   r   r   r   r   r   r   pipe  s   

zPipeToLoggerMixin.pipec                 K     | j | j| jfd|i|S )z`
        Pipe a command's stdout and stderr lines into this logger (both at level INFO)
        r   )r   r   r   r   r   r   r   r   	pipe_info     zPipeToLoggerMixin.pipe_infoc                 K  r   )za
        Pipe a command's stdout and stderr lines into this logger (both at level DEBUG)
        r   )r   r   r   r   r   r   
pipe_debug  r   zPipeToLoggerMixin.pipe_debugc                 C  s    ||  t| | jt| | j@ S )z
        Pipe a command's stdout and stderr lines into this logger.
        Log levels for each stream are determined by ``DEFAULT_STDOUT`` and ``DEFAULT_STDERR``.
        )r   r6   r   r   rN   r   r   r   rP     s   zPipeToLoggerMixin.__rand__)NNNNr   )r%   r&   r'   r(   r   r   r   r   r   r   r   r   rP   r   r   r   r   r     s    +


r   )!
__future__r   re   loggingr   r   r   
subprocessr   plumbum.commands.baser   plumbum.commands.processesr   r   r	   plumbum.libr
   r   r*   rI   rS   rW   rv   rz   r   r   r   BGrx   NOHUPRETCODETEETFr   r   r   r   <module>   s0    <Q5'1d
