o
    3gM                     @  sp  d dl m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 d dlmZ d dlZd dlmZmZ dZG d	d
 d
eZdZdZdd Z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 eZ!G d!d" d"eZ"G d#d$ d$e#Z$e$ej%Z&G d%d& d&eZ'G d'd( d(eZ(dS ))    )annotationsN)PIPEPopen)TemporaryFile)
MethodType)ClassVar)
iter_linesrun_proc)r   r	   shquoteshquote_listRedirectionErrorBaseCommandPipelineBaseRedirectionBoundCommandBoundEnvCommandConcreteCommandERROUTStdinRedirectionStdoutRedirectionStderrRedirectionAppendingStdoutRedirectionStdinDataRedirectionc                   @  s   e Zd ZdZdS )r   zwRaised when an attempt is made to redirect an process' standard handle,
    which was already redirected to/from a fileN)__name__
__module____qualname____doc__ r   r   M/home/garg/my-data/venv/lib/python3.10/site-packages/plumbum/commands/base.pyr   $   s    r   zIabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@%_-+=:,./z"`$\c                 C  s   t | } t| S )zOQuotes the given text with shell escaping (assumes as syntax similar to ``sh``))strshlexquote)textr   r   r   r
   1   s   
r
   c                 C  s   dd | D S )Nc                 S  s   g | ]}t |qS r   )r
   ).0itemr   r   r   
<listcomp>8   s    z shquote_list.<locals>.<listcomp>r   )seqr   r   r   r   7      r   c                   @  s   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd ZeZedd Zd=d!d"Zd>d#d$Zd?d)d*Zejd>d+d,Zd>d-d.Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Z d9d: Z!d;d< Z"d'S )@r   zBase of all command objects)cwdenvcustom_encoding__weakref__c                 C  s   d |  S )N )join	formulateselfr   r   r   __str__C   r'   zBaseCommand.__str__c                 C  
   t | |S )z%Creates a pipe with the other command)r   )r0   otherr   r   r   __or__F      
zBaseCommand.__or__c                 C  r2   )z/Redirects the process' stdout to the given file)r   r0   filer   r   r   __gt__J   r5   zBaseCommand.__gt__c                 C  r2   )z;Redirects the process' stdout to the given file (appending))r   r6   r   r   r   
__rshift__N   r5   zBaseCommand.__rshift__c                 C  r2   )z/Redirects the process' stderr to the given file)r   r6   r   r   r   __ge__R   r5   zBaseCommand.__ge__c                 C  r2   )z0Redirects the given file into the process' stdin)r   r6   r   r   r   __lt__V   r5   zBaseCommand.__lt__c                 C  r2   )z0Redirects the given data into the process' stdin)r   )r0   datar   r   r   
__lshift__Z   r5   zBaseCommand.__lshift__c                 C  s   t |ttfs
|g}| j| S )zUCreates a bound-command with the given arguments. Shortcut for
        bound_command.)
isinstancetuplelistbound_commandr0   argsr   r   r   __getitem__^   s   
zBaseCommand.__getitem__c                 G  s2   |s| S t | trt| j| jt| S t| |S )z0Creates a bound-command with the given arguments)r>   r   cmdrC   r@   rB   r   r   r   rA   g   s
   

zBaseCommand.bound_commandc                 O  s   | j |fi |d S )z>A shortcut for `run(args)`, returning only the process' stdout   )runr0   rC   kwargsr   r   r   __call__q   s   zBaseCommand.__call__c                 C     t  NNotImplementedErrorr/   r   r   r   _get_encodingu      zBaseCommand._get_encodingc                 K     |s| S t | |dS )z>Returns a BoundEnvCommand with the given environment variables)r)   r   )r0   r)   r   r   r   with_envx   s   zBaseCommand.with_envc                 C  rQ   )z
        Returns a BoundEnvCommand with the specified working directory.
        This overrides a cwd specified in a wrapping `machine.cwd()` context manager.
        )r(   rR   )r0   pathr   r   r   with_cwd~   s   zBaseCommand.with_cwdc                 C  rK   rL   rM   r/   r   r   r   machine      zBaseCommand.machiner   r   c                 C  rK   )a  Formulates the command into a command-line, i.e., a list of shell-quoted strings
        that can be executed by ``Popen`` or shells.

        :param level: The nesting level of the formulation; it dictates how much shell-quoting
                      (if any) should be performed

        :param args: The arguments passed to this command (a tuple)

        :returns: A list of strings
        rM   r0   levelrC   r   r   r   r.      s   zBaseCommand.formulatec                 K  rK   )a  Spawns the given command, returning a ``Popen``-like object.

        .. 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>`_

        :param args: Any arguments to be passed to the process (a tuple)

        :param kwargs: Any keyword-arguments to be passed to the ``Popen`` constructor

        :returns: A ``Popen``-like object
        rM   rH   r   r   r   popen   s   zBaseCommand.popen.	nohup.outNTc                 C  s   | j | ||||S )zRuns a command detached.)rV   daemonic_popen)r0   r(   stdoutstderrappendr   r   r   nohup   s   zBaseCommand.nohupc                 +  sZ    | dd| dd| j|fi | dg fdd}| _ V  |  dS )aY  Runs the given command as a context manager, allowing you to create a
        `pipeline <http://en.wikipedia.org/wiki/Pipeline_(computing)>`_ (not in the UNIX sense)
        of programs, parallelizing their work. In other words, instead of running programs
        one after the other, you can start all of them at the same time and wait for them to
        finish. For a more thorough review, see
        `Lightweight Asynchronism <http://tomerfiliba.com/blog/Toying-with-Context-Managers/>`_.

        Example::

            from plumbum.cmd import mkfs

            with mkfs["-t", "ext3", "/dev/sda1"] as p1:
                with mkfs["-t", "ext3", "/dev/sdb1"] as p2:
                    pass

        .. 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>`_

        For the arguments, see :func:`run <BaseCommand.run>`.

        :returns: A Popen object, augmented with a ``.run()`` method, which returns a tuple of
                  (return code, stdout, stderr)
        retcoder   timeoutNFc                    s   d rd S dd< z-t  W  ` j j jfD ]} tt |   W d    n1 s1w   Y  qS  ` j j jfD ]} tt |   W d    n1 sXw   Y  qBw )Nr   T)	r	   rG   stdinr^   r_   
contextlibsuppress	Exceptionclose)fprb   rc   was_runr   r   runner   s&   

z!BaseCommand.bgrun.<locals>.runner)poprZ   rG   )r0   rC   rI   rm   r   rj   r   bgrun   s   
zBaseCommand.bgrunc                 K  s>   | j |fi |}| W  d   S 1 sw   Y  dS )a  Runs the given command (equivalent to popen() followed by
        :func:`run_proc <plumbum.commands.run_proc>`). If the exit code of the process does
        not match the expected one, :class:`ProcessExecutionError
        <plumbum.commands.ProcessExecutionError>` is raised.

        :param args: Any arguments to be passed to the process (a tuple)

        :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.

                        .. note:: this argument must be passed as a keyword argument.

        :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

                        .. note:: this argument must be passed as a keyword argument.

        :param kwargs: Any keyword-arguments to be passed to the ``Popen`` constructor

        :returns: A tuple of (return code, stdout, stderr)
        N)ro   rG   )r0   rC   rI   rk   r   r   r   rG      s   $zBaseCommand.runc                 C  s   |di |}| |@ S )z
        Applies a modifier to the current object (e.g. FG, NOHUP)
        :param modifier: The modifier class to apply (e.g. FG)
        :param args: A dictionary of arguments to pass to this modifier
        :return:
        Nr   r   )r0   modifierrC   modifier_instancer   r   r   _use_modifier   s   zBaseCommand._use_modifierc                 K     |  tjjj|S )z
        Run this command in the background. Uses all arguments from the BG construct
        :py:class: `plumbum.commands.modifiers.BG`
        )rr   plumbumcommands	modifiersBGr0   rI   r   r   r   run_bg
     zBaseCommand.run_bgc                 K  rs   )z
        Run this command in the foreground. Uses all arguments from the FG construct
        :py:class: `plumbum.commands.modifiers.FG`
        )rr   rt   ru   rv   FGrx   r   r   r   run_fg  rz   zBaseCommand.run_fgc                 K  rs   )z
        Run this command using the TEE construct. Inherits all arguments from TEE
        :py:class: `plumbum.commands.modifiers.TEE`
        )rr   rt   ru   rv   TEErx   r   r   r   run_tee  rz   zBaseCommand.run_teec                 K  rs   )z
        Run this command using the TF construct. Inherits all arguments from TF
        :py:class: `plumbum.commands.modifiers.TF`
        )rr   rt   ru   rv   TFrx   r   r   r   run_tf  rz   zBaseCommand.run_tfc                 K  rs   )z
        Run this command using the RETCODE construct. Inherits all arguments from RETCODE
        :py:class: `plumbum.commands.modifiers.RETCODE`
        )rr   rt   ru   rv   RETCODErx   r   r   r   run_retcode&  rz   zBaseCommand.run_retcodec                 K  rs   )z
        Run this command using the NOHUP construct. Inherits all arguments from NOHUP
        :py:class: `plumbum.commands.modifiers.NOHUP`
        )rr   rt   ru   rv   NOHUPrx   r   r   r   	run_nohup-  rz   zBaseCommand.run_nohupr   r   r   )r[   r\   NT)#r   r   r   r   	__slots__r1   r4   r8   r9   r:   r;   r=   rD   rA   rJ   rO   rS   rU   setenvpropertyrV   r.   rZ   ra   re   contextmanagerro   rG   rr   ry   r|   r~   r   r   r   r   r   r   r   r   >   s@    	
	




2
r   c                   @  H   e Zd ZdZdd Zdd Zdd Zdd
dZedd Z	dddZ
dS )r   rE   rC   c                 C  s   || _ t|| _d S rL   )rE   r@   rC   )r0   rE   rC   r   r   r   __init__8  s   zBoundCommand.__init__c                 C     d| j d| jdS )NzBoundCommand(, )r   r/   r   r   r   __repr__<     zBoundCommand.__repr__c                 C  
   | j  S rL   rE   rO   r/   r   r   r   rO   ?     
zBoundCommand._get_encodingr   r   c                 C  s   | j |d | jt| S )NrF   )rE   r.   rC   r@   rX   r   r   r   r.   B  s   zBoundCommand.formulatec                 C     | j jS rL   rE   rV   r/   r   r   r   rV   E     zBoundCommand.machinec                 K  s.   t |tr|g}| jj| jt| fi |S rL   )r>   r   rE   rZ   rC   r@   rH   r   r   r   rZ   I  s   
zBoundCommand.popenNr   r   r   r   r   r   r   r   rO   r.   r   rV   rZ   r   r   r   r   r   5  s    

r   c                   @  sJ   e Zd ZdZdddZdd Zdd ZdddZedd Z	dddZ
dS )r   )rE   Nc                 C  s   || _ |pi | _|| _d S rL   )rE   r)   r(   )r0   rE   r)   r(   r   r   r   r   T  s   

zBoundEnvCommand.__init__c                 C  r   )NzBoundEnvCommand(r   r   )rE   r)   r/   r   r   r   r   Y  r   zBoundEnvCommand.__repr__c                 C  r   rL   r   r/   r   r   r   rO   \  r   zBoundEnvCommand._get_encodingr   r   c                 C  s   | j ||S rL   )rE   r.   rX   r   r   r   r.   _  r'   zBoundEnvCommand.formulatec                 C  r   rL   r   r/   r   r   r   rV   b  r   zBoundEnvCommand.machinec                 K  s>   |pi }| j j|f|d u r| jn|t| jfi |d|S )N)r(   r)   )rE   rZ   r(   dictr)   )r0   rC   r(   r)   rI   r   r   r   rZ   f  s   zBoundEnvCommand.popen)NNr   )r   NNr   r   r   r   r   r   Q  s    


r   c                   @  r   )r   srccmddstcmdc                 C     || _ || _d S rL   r   )r0   r   r   r   r   r   r   s     
zPipeline.__init__c                 C  r   )Nz	Pipeline(r   r   r   r/   r   r   r   r   w  r   zPipeline.__repr__c                 C  s   | j  p	| j S rL   )r   rO   r   r/   r   r   r   rO   z  s   zPipeline._get_encodingr   r   c                 C  s*   g | j |d d| j|d |S )NrF   |)r   r.   r   rX   r   r   r   r.   }  s   zPipeline.formulatec                 C  r   rL   )r   rV   r/   r   r   r   rV     r   zPipeline.machinec                   s   |  }t|d< d|v r|d |d< | jj|fi |j|d< | jjdi | j  jr>|dtkr>j   _	 j
ttj
 fdd}| j_
 jfdd}t|  _j _ S )Nr^   rd   c                    s.   | i |}j | i |}|p| _ jS rL   )wait
returncode)rC   rI   rc_dstrc_src)dstprocdstproc_waitsrcprocr   r   wait2  s   
zPipeline.popen.<locals>.wait2c                   s^   z	dgt |}W n ty   |d u rd nd|g}Y nw | j||||  |||| d S )Nr   )r@   	TypeErrorr   verify)procrb   rc   r^   r_   
or_retcode)dstproc_verifyr   r   r     s   zPipeline.popen.<locals>.verifyr   )copyr   r   rZ   r^   r   rh   rd   getr   r   	functoolswrapsr   _procr   r   )r0   rC   rI   
src_kwargsr   r   r   )r   r   r   r   r   rZ     s(   



zPipeline.popenNr   r   r   r   r   r   r   r   p  s    

r   c                   @  sb   e Zd ZU dZded< ded< ded< dd Zdd	 Zd
d ZdddZe	dd Z
dddZdS )r   rE   r7   zClassVar[str]SYMKWARGMODEc                 C  r   rL   r   )r0   rE   r7   r   r   r   r     r   zBaseRedirection.__init__c                 C  r   rL   r   r/   r   r   r   rO     r   zBaseRedirection._get_encodingc                 C  s   | j j d| jd| jdS )N(r   r   )	__class__r   rE   r7   r/   r   r   r   r     s   zBaseRedirection.__repr__r   r   c                 C  s0   g | j |d || jtt| jd| jS )NrF   name)rE   r.   r   r
   getattrr7   rX   r   r   r   r.     s   zBaseRedirection.formulatec                 C  r   rL   r   r/   r   r   r   rV     r   zBaseRedirection.machinec                 K  s   ddl m} ddlm} | j|v r"|| j td fvr"t| j dt| j|r,t	dt| jt
|frEtt
| j| jdd }|| j< n| j|| j< d }z| jj|fi |W |r_|  S S |rg|  w w )Nr   )	LocalPath)
RemotePathz is already redirectedz$Cannot redirect to/from remote pathszutf-8)encoding)plumbum.machines.localr   plumbum.machines.remoter   r   r   r   r>   r7   r   r   openr   rE   rZ   rh   )r0   rC   rI   r   r   ri   r   r   r   rZ     s"   "

zBaseRedirection.popenNr   r   )r   r   r   r   __annotations__r   rO   r   r.   r   rV   rZ   r   r   r   r   r     s   
 

r   c                   @     e Zd ZdZdZdZdZdS )r   r   <rd   rNr   r   r   r   r   r   r   r   r   r   r   r     
    r   c                   @  r   )r   r   >r^   wNr   r   r   r   r   r     r   r   c                   @  r   )r   r   z>>r^   aNr   r   r   r   r   r     r   r   c                   @  r   )r   r   z2>r_   r   Nr   r   r   r   r   r     r   r   c                   @  s   e Zd Zdd Zdd ZdS )_ERROUTc                 C     dS )Nr   r   r/   r   r   r   r        z_ERROUT.__repr__c                 C  r   )Nz&1r   r/   r   r   r   r1     r   z_ERROUT.__str__N)r   r   r   r   r1   r   r   r   r   r     s    r   c                   @  sD   e Zd ZdZdZdd Zdd Zdd	d
Zedd Z	dddZ
dS )r   rE   r<   i>  c                 C  r   rL   r   )r0   rE   r<   r   r   r   r     r   zStdinDataRedirection.__init__c                 C  r   rL   r   r/   r   r   r   rO     r   z"StdinDataRedirection._get_encodingr   r   c                 C  s&   dt | j dg| j|d |S )Nzecho r   rF   )r
   r<   rE   r.   rX   r   r   r   r.     s
   zStdinDataRedirection.formulatec                 C  r   rL   r   r/   r   r   r   rV      r   zStdinDataRedirection.machinec                 K  s   | dtd fvrtd| j}t|tr"|  d ur"||  }t }|r<|d | j	 }|
| || j	d  }|s'|d ||d< | jj|fi |S )Nrd   zstdin is already redirectedr   )r   r   r   r<   r>   r   rO   encoder   
CHUNK_SIZEwriteseekrE   rZ   )r0   rC   rI   r<   ri   chunkr   r   r   rZ   $  s   

zStdinDataRedirection.popenNr   r   )r   r   r   r   r   r   rO   r.   r   rV   rZ   r   r   r   r   r     s    

r   c                   @  sZ   e Zd ZU dZded< dd Zdd Zdd	 Zd
d ZdddZ	e
dd ZdddZdS )r   )
executablezClassVar[int]QUOTE_LEVELc                 C  s   || _ || _d | _d | _d S rL   )r   r*   r(   r)   )r0   r   r   r   r   r   r   =  s   
zConcreteCommand.__init__c                 C  s
   t | jS rL   )r   r   r/   r   r   r   r1   C  r   zConcreteCommand.__str__c                 C  s   t | j d| j dS )Nr   r   )typer   r   r/   r   r   r   r   F  s   zConcreteCommand.__repr__c                 C  s   | j S rL   )r*   r/   r   r   r   rO   I  rP   zConcreteCommand._get_encodingr   r   c                   s   t jg}|D ]N}|d u rqt|tr1 jkr&|t| d  q|| d  qt|tt	frF| fdd|D  q|
 jkrQt|nt | q|S )NrF   c                 3  s*    | ]} j krt|nt|V  qd S rL   )r   r
   r   )r#   brY   r0   r   r   	<genexpr>W  s    
z,ConcreteCommand.formulate.<locals>.<genexpr>)r   r   r>   r   r   extendr   r.   r@   r?   r`   r
   )r0   rY   rC   argvr   r   r   r   r.   L  s   


"zConcreteCommand.formulatec                 C  rK   rL   rM   r/   r   r   r   rV   `  rW   zConcreteCommand.machinec                 K  rK   rL   rM   rH   r   r   r   rZ   d  rP   zConcreteCommand.popenNr   r   )r   r   r   r   r   r   r1   r   rO   r.   r   rV   rZ   r   r   r   r   r   7  s   
 

r   ))
__future__r   re   r   r    
subprocessr   r   tempfiler   typesr   typingr   plumbum.commands.modifiersrt   plumbum.commands.processesr   r	   __all__rg   r   
_safechars_funnycharsr
   r   r   r   r   r   r   r   r   r   r   intr   STDOUTr   r   r   r   r   r   r   <module>   s>    	 xF1
)