o
    tf%                     @  s
  d Z 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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 zddlZW n eyY   dZY nw e	jdkrcejZndddZddddZG dd dZG dd deZeej dS )z!JupyterLab Server process handler    )annotationsN)Logger)which)Any)genwin32cmd_list	list[str]returnstrc                 C  s   ddl }dt|j| S )zShim for list2cmdline on posix.r   N )shlexjoinmapquote)r   r    r   b/var/www/html/software/conda/envs/catlas/lib/python3.10/site-packages/jupyterlab_server/process.pylist2cmdline    s   r   commandenvdict[str, str] | Nonec                 C  sv   |pt j}|dpt j}t| |d}| dkr!|s!d} td|d}|s5| dv r-d}t|tdd|   t j|S )	zGet the full path to a command.

    Parameters
    ----------
    command: str
        The command name or path.
    env: dict, optional
        The environment variables, defaults to `os.environ`.
    PATH)pathnodenodejs)r   r   ZnpmzPlease install Node.js and npm before continuing installation. You may be able to install Node.js from your package manager, from conda, or directly from the Node.js website (https://nodejs.org).z%The command was not found or was not zexecutable: %s.)osenvirongetdefpath_which
ValueErrorr   abspath)r   r   r   Zcommand_with_pathmsgr   r   r   r   '   s   

r   c                   @  s   e Zd ZU dZe Zded< dZ					d)d*ddZ	d+ddZ
d+ddZejd,ddZd-d d!Zed.d$d%Zd/d'd(ZdS )0ProcesszA wrapper for a child process.zweakref.WeakSet_procsNFcmdr	   loggerLogger | Nonecwd
str | None
kill_eventthreading.Event | Noner   r   quietboolr
   Nonec           	      C  s   t |ttfsd}t||r| rd}t||p|  | _d| _|s.| jdt	| || _
i }|r:tj|d< | jd||d|| _|pKt | _tj|  dS )	a)  Start a subprocess that can be run asynchronously.

        Parameters
        ----------
        cmd: list
            The command to run.
        logger: :class:`~logger.Logger`, optional
            The logger instance.
        cwd: string, optional
            The cwd of the process.
        env: dict, optional
            The environment for the process.
        kill_event: :class:`~threading.Event`, optional
            An event used to kill the process operation.
        quiet: bool, optional
            Whether to suppress output.
        zCommand must be given as a listzProcess aborted z> %sstdout)r(   r   Nr   )
isinstancelisttupler    is_setget_logr&   Z
_last_lineinfor   r%   
subprocessDEVNULL_create_processproc	threadingEvent_kill_eventr#   r$   add)	selfr%   r&   r(   r*   r   r,   r"   kwargsr   r   r   __init__H   s"   
zProcess.__init__intc              	   C  s   | j }| du rt|jtj z<z|jdd W n# tj	y=   tj
dkr+tj}ntj}| du r;t|j| Y nw W | tjv rJtj|  | S | tjv rZtj|  w w )z/Terminate the process and return the exit code.Ng       @)timeoutnt)r:   pollr   killpidsignalSIGTERMwaitr7   TimeoutExpirednameZSIGBREAKSIGKILLr#   r$   remove)r?   r:   sigr   r   r   	terminatey   s(   



zProcess.terminatec                 C  sR   | j }| j}| du r%| r|   d}t|td | du s|  S )zhWait for the process to finish.

        Returns
        -------
        The process exit code.
        NProcess was aborted      ?)r:   r=   rE   r4   rP   r    timesleepr?   r:   r*   r"   r   r   r   rJ      s   
zProcess.waitr   c                 c  s\    | j }| j}| du r'| r|   d}t|tdV  | du st|  )z.Asynchronously wait for the process to finish.NrQ   rR   )	r:   r=   rE   r4   rP   r    r   rT   ReturnrU   r   r   r   
wait_async   s   zProcess.wait_asyncr@   subprocess.Popen[str]c                 K  sT   t | j}|dtj t|d |d|d< tjdkr!d|d< tj	|fi |S )zCreate the process.stderrr   r   rD   Tshell)
r2   r%   
setdefaultr7   STDOUTr   r   r   rL   Popen)r?   r@   r%   r   r   r   r9      s   

zProcess._create_processclstype[Process]c                 C  s   t | jD ]}|  qdS )z*Clean up the started subprocesses at exit.N)r2   r$   rP   )r^   r:   r   r   r   _cleanup   s   
zProcess._cleanupr   c                 C  s:   t | dr| jdur| jS td| _| jtj | jS )zGet our logger.r&   NZ
jupyterlab)hasattrr&   logging	getLoggersetLevelINFO)r?   r   r   r   r5      s
   zProcess.get_log)NNNNF)r%   r	   r&   r'   r(   r)   r*   r+   r   r   r,   r-   r
   r.   r
   rB   )r
   r   r@   r   r
   rX   )r^   r_   r
   r.   )r
   r   )__name__
__module____qualname____doc__weakrefWeakSetr$   __annotations___poolrA   rP   rJ   r   	coroutinerW   r9   classmethodr`   r5   r   r   r   r   r#   B   s$   
 
1

r#   c                      sN   e Zd ZdZ				dd fddZdddZd ddZd! fddZ  ZS )"WatchHelperz%A process helper for a watch process.Nr%   r	   startup_regexr   r&   r'   r(   r)   r*   r+   r   r   r
   r.   c           	        s   t  j|||||d tdu r| jj| _	 | j d}|s%d}t|t	|
  t||r2nqtj| jdd| _| j  dS )a  Initialize the process helper.

        Parameters
        ----------
        cmd: list
            The command to run.
        startup_regex: string
            The regex to wait for at startup.
        logger: :class:`~logger.Logger`, optional
            The logger instance.
        cwd: string, optional
            The cwd of the process.
        env: dict, optional
            The environment for the process.
        kill_event: callable, optional
            A function to call to check if we should abort.
        )r&   r(   r*   r   N   utf-8zProcess ended improperlyT)targetdaemon)superrA   ptyr:   r0   _stdoutreadlinedecodeRuntimeErrorprintrstriprematchr;   Thread_read_incomingZ_read_threadstart)	r?   r%   rs   r&   r(   r*   r   liner"   	__class__r   r   rA      s   
	zWatchHelper.__init__rB   c              	   C  s   | j }| du r"tjdkrtt|jtj nt	|jtj z|
  W | tjv r3tj|  |jS | tjv rBtj|  w w )zTerminate the process.NrD   )r:   rE   r   rL   killpggetpgidrG   rH   rI   rF   rJ   r#   r$   rN   
returncode)r?   r:   r   r   r   rP      s   



zWatchHelper.terminatec              
   C  sn   | j  }	 zt|d}W n ty( } z| jd| W Y d}~dS d}~ww |s-dS t|ddd q)z(Run in a thread to read stdout and printrt   i   zRead incoming error %sNru   r/   )end)	rz   filenor   readOSErrorr&   debugr~   r|   )r?   r   bufer   r   r   r     s   
zWatchHelper._read_incomingr@   r   rX   c                   s   d|d< t dur"t  \}}| |d< |d< d|d< t|d| _n#tj|d< tjd	krEt }| j	tj
O  _	||d
< tj|d< d|d< t jdi |S )z"Create the watcher helper process.r   bufsizeNrY   r0   Tstart_new_sessionrbrD   startupinfocreationflagsrZ   r   )ry   openptyr   fdopenrz   r7   PIPErL   ZSTARTUPINFOZdwFlagsZSTARTF_USESHOWWINDOWZCREATE_NEW_PROCESS_GROUPrx   r9   )r?   r@   ZmasterZslaver   r   r   r   r9     s   


zWatchHelper._create_process)NNNN)r%   r	   rs   r   r&   r'   r(   r)   r*   r+   r   r   r
   r.   rf   )r
   r.   rg   )	rh   ri   rj   rk   rA   rP   r   r9   __classcell__r   r   r   r   rr      s    
+
rr   )r   r	   r
   r   )N)r   r   r   r   r
   r   )rk   
__future__r   atexitrb   r   r   rH   r7   sysr;   rS   rl   r   shutilr   r   typingr   tornador   ry   ImportErrorplatformr   r#   rr   registerr`   r   r   r   r   <module>   s:    

 h