o
    3g>                     @  s`  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dlm
Z
 d dlmZmZ d dlmZ d dlmZmZ d dlmZmZ d dlmZ d d	lmZmZmZ d d
lmZmZ d dlmZ d dl m!Z! d dl"m#Z#m$Z$ d dl%m&Z& G dd deZ'erd dl(m)Z)m*Z* e+dZ,G dd deZ-G dd deZ.G dd deZ/e/ Z0dS )    )annotationsN)contextmanager)PIPEPopen)mkdtemp)CommandNotFoundConcreteCommand)posix_daemonizewin32_daemonize
iter_lines)IS_WIN32ProcInfoStaticProperty)BaseMachinePopenAddons)BaseEnv)ShellSession)	LocalPathLocalWorkdir)
RemotePathc                   @  s8   e Zd ZeZdd Zdd Zdd Zdd Zd	d
 ZdS )PlumbumLocalPopenc                 O  s   t |i || _d S N)r   _procselfargskwargs r   N/home/garg/my-data/venv/lib/python3.10/site-packages/plumbum/machines/local.py__init__   s   zPlumbumLocalPopen.__init__c                 C     |   S r   r   r   r   r   r   __iter__    s   zPlumbumLocalPopen.__iter__c                 C  s
   | j  S r   )r   	__enter__r"   r   r   r   r$   #      
zPlumbumLocalPopen.__enter__c                 O  s   | j j|i |S r   )r   __exit__r   r   r   r   r&   &   s   zPlumbumLocalPopen.__exit__c                 C  s   t | j|S r   )getattrr   )r   namer   r   r   __getattr__)   s   zPlumbumLocalPopen.__getattr__N)	__name__
__module____qualname__r   r    r#   r$   r&   r)   r   r   r   r   r      s    r   )IMAGE_SUBSYSTEM_WINDOWS_CUIget_pe_subsystemzplumbum.localc                      s:   e Zd ZdZdZe Z fddZdd Zdd Z	  Z
S )	LocalEnvz>The local machine's environment; exposes a dict-like interfacer   c                   sL   t  jttjjtj d tr d| vr"| j	d ur$| j	| d< d S d S d S d S )N)_currHOME)
superr    r   ospathpathsepenvironcopyr   homer"   	__class__r   r   r    <   s   zLocalEnv.__init__c                 C  s:   t j}|  t _zt jt j|}W |t _|S |t _w )aE  Expands any environment variables and home shortcuts found in ``expr``
        (like ``os.path.expanduser`` combined with ``os.path.expandvars``)

        :param expr: An expression containing environment variables (as ``$FOO``) or
                     home shortcuts (as ``~/.bashrc``)

        :returns: The expanded string)r3   r6   getdictr4   
expanduser
expandvarsr   exprprevoutputr   r   r   expandB   s   
zLocalEnv.expandc                 C  s2   t j}|  t _zt j|}W |t _|S |t _w )zExpand home shortcuts (e.g., ``~/foo/bar`` or ``~john/foo/bar``)

        :param expr: An expression containing home shortcuts

        :returns: The expanded string)r3   r6   r;   r4   r<   r>   r   r   r   r<   R   s   
zLocalEnv.expanduser)r*   r+   r,   __doc__	__slots__r   CASE_SENSITIVEr    rB   r<   __classcell__r   r   r9   r   r/   6   s    r/   c                   @  s4   e Zd ZdZdZdddZedd Zdd	d
ZdS )LocalCommandr      autoc                 C  s&   t | ||dkrtj d S | d S )NrI   )r   r    localcustom_encoding)r   
executableencodingr   r   r   r    h   s
   zLocalCommand.__init__c                 C  s   t S r   )rJ   r"   r   r   r   machinem   s   zLocalCommand.machineNc                 K  sR   t |tr|f}| jj| j| d|f|d u r| jn||d u r"| jn|d|S )Nr   )cwdenv)
isinstancestrrN   _popenrL   	formulaterO   rP   )r   r   rO   rP   r   r   r   r   popenq   s   

zLocalCommand.popen)rI   )r   NN)	r*   r+   r,   rD   QUOTE_LEVELr    propertyrN   rU   r   r   r   r   rG   d   s    

rG   c                   @  s   e Zd ZU dZeeZe Ze	
 Ze d Zi Zded< dd Zer;dgedd	 ejjZed
d Znedd Zedd Zdd Zdd Zdd ZeeedddfddZd*ddZ erjdd Z!ndd Z!d d! Z"d+d"d#Z#e$d$d% Z%e$d,d&d'Z&d(d) Z'e(e	j)eZ*dS )-LocalMachinea  The *local machine* (a singleton object). It serves as an entry point to everything
    related to the local machine, such as working directory and environment manipulation,
    command creation, etc.

    Attributes:

    * ``cwd`` - the local working directory
    * ``env`` - the local environment
    * ``custom_encoding`` - the local machine's default encoding (``sys.getfilesystemencoding()``)
    r   z dict[tuple[str, str], LocalPath]_program_cachec                 C  s
   g | _ d S r   )_as_user_stackr"   r   r   r   r       r%   zLocalMachine.__init__ PATHEXTz
:.exe:.batc                 C  sP   |  }| jjD ]}| jD ]}|||  }|dr$| s$|    S qqd S Nx)lowerrP   r4   _EXTENSIONSaccessis_dir)clsprognamepextfnr   r   r   _which   s   
zLocalMachine._whichc                 C  s4   | j jD ]}|| }|dr| s|  S qd S r]   )rP   r4   ra   rb   )rc   rd   re   rg   r   r   r   rh      s   c                 C  s   || j ddf}tt | j| W  d   S 1 sw   Y  |g}d|v r8||dd|ddg7 }|D ]}| |}|rL|| j|< |  S q:t|t	| j j
)a4  Looks up a program in the ``PATH``. If the program is not found, raises
        :class:`CommandNotFound <plumbum.commands.CommandNotFound>`

        :param progname: The program's name. Note that if underscores (``_``) are present
                         in the name, and the exact name is not found, they will be replaced
                         in turn by hyphens (``-``) then periods (``.``), and the name will
                         be looked up again for each alternative

        :returns: A :class:`LocalPath <plumbum.machines.local.LocalPath>`
        PATHr[   N_-.)rP   get
contextlibsuppressKeyErrorrY   replacerh   r   listr4   )rc   rd   keyalternativespnr4   r   r   r   which   s    

zLocalMachine.whichc                 G  sT   t | jg}|D ]}t|trtd||| jt | qtt	j
j| S )zA factory for :class:`LocalPaths <plumbum.path.local.LocalPath>`.
        Usage: ``p = local.path("/usr", "lib", "python2.7")``
        z Cannot construct LocalPath from )rR   rO   rQ   r   	TypeErrorappendrP   r<   r   r3   r4   join)r   partsparts2re   r   r   r   r4      s   
zLocalMachine.pathc                 C  s$   z| |  W dS  t y   Y dS w )NFT)r   r   cmdr   r   r   __contains__   s   
zLocalMachine.__contains__c                 C  s`   t |tr	t|S t |ts)t|}d|v sd|v r"tt|S t| |S t	d|)ao  Returns a `Command` object representing the given program. ``cmd`` can be a string or
        a :class:`LocalPath <plumbum.path.local.LocalPath>`; if it is a path, a command
        representing this path will be returned; otherwise, the program name will be looked up
        in the system's ``PATH`` (using ``which``). Usage::

            ls = local["ls"]
        /\zcmd must not be a RemotePath: )
rQ   r   rG   r   r3   fspathrJ   r4   rv   rw   r|   r   r   r   __getitem__   s   
	

zLocalMachine.__getitem__NFc	              	   K  s8  |rd|	d< t rEd|	vrE|tjd fvrEtt|}
|
tkrEt }||	d< ttdr9| j	tj
jO  _	tj
j|_n| j	tjO  _	tj|_|d u rL| j}| j|g}i }|D ]}|sZqUt|trc| }|| qU| jru| jd |\}}td| t|ft||||t||d|	}t |_| j|_||_|S )NTstart_new_sessionstartupinfo_subprocessz
Running %r)rL   stdinstdoutstderrrO   rP   )r   sysr   r.   rR   r-   
subprocessSTARTUPINFOhasattrdwFlagsr   STARTF_USESHOWWINDOWSW_HIDEwShowWindowrO   rP   rQ   r   r;   updaterZ   loggerdebugr   time_start_timerK   argv)r   rL   r   r   r   r   rO   rP   new_sessionr   	subsystemsuienvs_envprocr   r   r   rS      sX   




zLocalMachine._popenr   Tc                 C  s$   t r
t|||||S t|||||S )a  
        On POSIX systems:

        Run ``command`` as a UNIX daemon: fork a child process to setpid, redirect std handles to /dev/null,
        umask, close all fds, chdir to ``cwd``, then fork and exec ``command``. Returns a ``Popen`` process that
        can be used to poll/wait for the executed command (but keep in mind that you cannot access std handles)

        On Windows:

        Run ``command`` as a "Windows daemon": detach from controlling console and create a new process group.
        This means that the command will not receive console events and would survive its parent's termination.
        Returns a ``Popen`` object.

        .. note:: this does not run ``command`` as a system service, only detaches it from its parent.

        .. versionadded:: 1.3
        )r   r
   r	   )r   commandrO   r   r   rx   r   r   r   daemonic_popen9  s   zLocalMachine.daemonic_popenc                 c  s    ddl }td }|ddd}| }||}zt|}W n ty*   tddw |d}|d	}|d
}	|d}
|D ]}tt	|| ||
 ||	 || V  qAdS )z
            Returns information about all running processes (on Windows: using ``tasklist``)

            .. versionadded:: 1.3
            r   Ntasklistz/Vz/FOCSVz"tasklist must at least have headerz
Image NamePIDStatusz	User Name)
csvrJ   
splitlinesreadernextStopIterationRuntimeErrorindexr   int)r   r   r   rA   linesrowsheaderimgidxpididxstatidxuseridxrowr   r   r   list_processesR  s(   





zLocalMachine.list_processesc              
   c  sp    | d }|ddd  }|d |D ]!}|  }tt|d t|d |d d|d	d
 V  qd
S )z
            Returns information about all running processes (on POSIX systems: using ``ps``)

            .. versionadded:: 1.3
            psz-ez-ozpid,uid,stat,argsr      rH       N)r   popstripsplitr   r   ry   )r   r   r   linerz   r   r   r   r   m  s   
*c                 c  s0    t |}|  D ]}||jr|V  q
dS )z|
        Process grep: return information about all processes whose command-line args match the given regex pattern
        N)recompiler   searchr   )r   patternpatprocinfor   r   r   pgrep|  s   
zLocalMachine.pgrepc                 C  s   t | d j|dS )zCreates a new :class:`ShellSession <plumbum.session.ShellSession>` object; this
        invokes ``/bin/sh`` and executes commands on it over stdin/stdout/stderrsh)r   )r   rU   )r   r   r   r   r   session  s   zLocalMachine.sessionc                 c  s.    |  t }z
|V  W |  dS |  w )zeA context manager that creates a temporary directory, which is removed when the context
        exitsN)r4   r   delete)r   new_dirr   r   r   tempdir  s
   zLocalMachine.tempdirc              	   #  s    t rdu r	d j fdd ndu r$ j fdd n j fdd zdV  W  jd dS  jd w )aN  Run nested commands as the given user. For example::

            head = local["head"]
            head("-n1", "/dev/sda1")    # this will fail...
            with local.as_user():
                head("-n1", "/dev/sda1")

        :param username: The user to run commands as. If not given, root (or Administrator) is assumed
        NAdministratorc                   s4   ddd dd dd | D  d g dfS )Nrunasz	/savecredz/user:"r   c                 s  s    | ]}t |V  qd S r   )rR   ).0ar   r   r   	<genexpr>  s    z9LocalMachine.as_user.<locals>.<lambda>.<locals>.<genexpr>)ry   rv   r   r   usernamer   r   <lambda>  s   z&LocalMachine.as_user.<locals>.<lambda>c                   s   dgt |  dfS )Nsudorr   rv   r   r"   r   r   r     s    c                   s   ddgt |  dfS )Nr   z-ur   r   r   r   r   r     s   r   )r   rZ   rx   r   r   r   r   r   as_user  s"   
zLocalMachine.as_userc                 C  r!   )zUA shorthand for :func:`as_user("root") <plumbum.machines.local.LocalMachine.as_user>`)r   r"   r   r   r   as_root  s   zLocalMachine.as_root)r   NNT)Fr   )+r*   r+   r,   rC   r   r   rO   r/   rP   r   getfilesystemencodingrK   platformunamerY   __annotations__r    r   rm   r_   r   r3   r4   r5   r`   classmethodrh   rv   r~   r   r   rS   r   r   r   r   r   r   r   r   rG   rL   pythonr   r   r   r   rX      sT   
 



B

	
	)rX   )1
__future__r   rn   loggingr3   r   r   r   r   r   r   r   r   tempfiler   plumbum.commandsr   r   plumbum.commands.daemonsr	   r
   plumbum.commands.processesr   plumbum.libr   r   r   plumbum.machines.baser   r   plumbum.machines.envr   plumbum.machines.sessionr   plumbum.path.localr   r   plumbum.path.remoter   r   plumbum.machines._windowsr-   r.   	getLoggerr   r/   rG   rX   rJ   r   r   r   r   <module>   s@    
.  F