
    s
ePQ                        U d 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m	Z	 e	rddl
Z
ej        dk    rdndZej        e         ed<   dZej        e         ed	<    G d
 dej                  Z G d dej                  ZdedefdZdedefdZ	 	 d0dedej        eej        f         dej        dedef
dZ G d d          ZefdedededefdZefdedededdfdZddefdeded ed!ej        e         dedej         eeef         fd"Z!defdededed#ed ededefd$Z"d%ddej#        $                    d&          efdededed'ej%        ej                 d edej        ej        eef                  d(ededej         ej        eej        f         df         fd)Z&d%ddej#        $                    d&          efdededed'ej%        ej                 d edej        ej        eef                  d(ededej         ej        eej        f         df         fd*Z'd%ej#        $                    d&          ddd+dfdededed'ej%        ej                 d,ed edej        ej        eef                  d-ed.edej        e         fd/Z(dS )1zLaunch applications utilities.    N)LAUNCH_SCRIPTS_PATHWINwin32nulz	/dev/nullDEVNULLz{package}-{level}-{index}.txtLOG_FILEc                   F    e Zd ZU dZeed<   eed<   eed<   eed<   eed<   dS )CommandDetailsz5Dictionary with extra details about executed command.argsidcmdstdoutstderrN)__name__
__module____qualname____doc__str__annotations__int     >lib/python3.11/site-packages/navigator_updater/utils/launch.pyr
   r
      sC         ??
IIIGGG	HHHKKKKKKKKr   r
   c                      e Zd ZdZdddej                            d          efdededed	e	j
        e	j                 d
ede	j        e	j        eef                  dedede	j        e	j        ee	j        f         ef         fdZdS )
GetCommandz3Common interface for all `get_command_*` functions.r   appN~root_prefixprefixcommandextra_argumentspackage_nameenvironmentcwddefault_scripts_pathreturnc	                     dS )a  
        Generate script to launch application and return path to it.

        :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
        :param prefix: Conda prefix, which should be active.
        :param command: Actual command to launch application.
        :param extra_arguments: Additional arguments to attach to command.
        :param cwd: Custom working directory to launch application in.
        :param package_name: Name of the conda package, or alias of the external application.
        :param environment: Custom environment to launch application in.
        :param default_scripts_path: Root directory to store launch scripts in.
        :return: Path to generated launch script file.
        Nr   )	selfr   r   r    r!   r"   r#   r$   r%   s	            r   __call__zGetCommand.__call__*   s      r   )r   r   r   r   ospath
expanduserr   r   typingIterableAnyOptionalMappingTupler
   r)   r   r   r   r   r   '   s        == <> %EIw))#..(;   	
 $_VZ8   S)AB  #& 
fnS&*_5~E	F     r   r   valuer&   c                     h d}h d|z  }t          |           |z  r$|D ]}|                     |d|           } d|  d} | S )z;Prepare argument which is safe to use in unix command line.>   "$\`>    &;<>|r7   r5   setreplace)r3   
to_replace	to_escape	characters       r   	safe_unixrE   D   sp    0E0E0EJ/M/M/MPZ/ZI
5zzI # 	? 	?IMM)-=)-=-=>>EEELr   c                     h d}t          |           |z  r0|                     dd                              dd          } d|  d} | S )z>Prepare argument which is safe to use in windows command line.>   r9   r5   %r:   r;   r<   r=   r>   r5   z""rG   z"^%"r?   )r3   rC   s     r   safe_windowsrH   S   sU    /W/W/WI
5zzI c4((00f==ELr   Fr    r#   default	recursivec                 H   d}	 |                      d|          }|dk     rn|                      d|          }| |dz   |         }|dz  }|                    ||          }||}at          |          }| d|         |z   | |d         z   } |}|s|t          |          z  }| S )a  
    Update command with environment variables.

    :param command: Original command to update with environment variable values.
    :param environment: Environment variables to inject into command.

                        :code:`None` values won't be expanded.
    :param default: Value to insert for all unknown variables in `command`.
    :param recursive: Allow recursive expand of the values.
    :return: String with expanded environment.
    r   Tz${}      N)findgetr   len)	r    r#   rI   rJ   cursorstartstopenvironment_keyenvironment_values	            r   expand_environmentrW   ^   s    " F-\\$//199LLe,,&uqy~6	(3(Q(Q$F 122&5&/$55F 	-c+,,,F%-( Nr   c                      e Zd ZdZdZ	 	 ddedej        dej	        e         dej	        e         ddf
d	Z
edej        fd
            Zedefd            Zedefd            Zedej	        e         fd            Zedej	        e         fd            Zedej	        e         fd            Zedej	        e         dej	        e         fd            ZddZdS )RunningProcessa  
    Minimal description of a process launched from the Navigator.

    Common example of such process - anything started from the Home page tiles.

    :param package: Name of the Conda package, or alias of a launched application.
    :param process: :class:`~subprocess.Popen` instance, which is used to launch the application.
    :param stdout: Path to a file with captured `stdout`.
    :param stderr: Path to a file with captured `stderr`.
    )__birth	__package	__process__return_code__stderr__stdoutNpackageprocessr   r   r&   c                     |t           k    rd}|t           k    rd}|| _        || _        d| _        || _        || _        t          j                                        | _        dS )z1Initialize new :class:`~RunningProcess` instance.N)	r   _RunningProcess__package_RunningProcess__process_RunningProcess__return_code_RunningProcess__stdout_RunningProcess__stderrdatetimeutcnow_RunningProcess__birth)r(   r`   ra   r   r   s        r   __init__zRunningProcess.__init__   sb     WFWF,39@37<B<B8@8I8P8P8R8Rr   c                 N    t           j                                         | j        z
  S )zCurrent age of the application.)rh   ri   rj   r(   s    r   agezRunningProcess.age   s       ''))DL88r   c                     | j         S )z>Name of the Conda package, or alias of a launched application.)rc   rm   s    r   r`   zRunningProcess.package   s     ~r   c                     | j         j        S )zPID of the process.)rd   pidrm   s    r   rq   zRunningProcess.pid   s     ~!!r   c                 Z    | j         | j                                        | _         | j         S )z"Current status of the application.)re   rd   pollrm   s    r   return_codezRunningProcess.return_code   s,     %!%!4!4!6!6D!!r   c                 6    |                      | j                  S zContent of the `stdout` log.)_RunningProcess__readrg   rm   s    r   r   zRunningProcess.stderr        {{4=)))r   c                 6    |                      | j                  S rv   )rw   rf   rm   s    r   r   zRunningProcess.stdout   rx   r   r+   c                     | dS 	 t          | d          5 }|                                cddd           S # 1 swxY w Y   dS # t          $ r Y dS w xY w)zRead content of the file.Nrt)openreadOSError)r+   streams     r   __readzRunningProcess.__read   s     <4	dD!! %V{{}}% % % % % % % % % % % % % % % % % % 	 	 	44	s,   A 7A ;A ;A 
AAc                     t          j        t           j        t                   t	          t
          | j        | j        g                    D ]'}	 t          j	        |           # t          $ r Y $w xY wdS )zRemove all temporary content.N)r-   castr.   r   filterboolrf   rg   r*   remover~   )r(   r+   s     r   cleanupzRunningProcess.cleanup   sy     K 4fTDMSWS`Ca6b6bcc 	 	D	$   	 	s   A""
A/.A/)NN)r&   N)r   r   r   r   	__slots__r   
subprocessPopenr-   r0   rk   propertyrh   	timedeltarn   r`   r   rq   rt   r   r   staticmethodrw   r   r   r   r   rY   rY      s       	 	 _I ,0+/S SS  %S OC(	S
 OC(S 
S S S S( 9X' 9 9 9 X9     X "S " " " X" "V_S1 " " " X" *, * * * X* *, * * * X* 	V_S) 	foc.B 	 	 	 \	     r   rY   r   r   r%   c                 r   t           j                            |          }t           j                            |           } t           j                            |          }|| k    r=t           j                            |t           j                            |                    }t          j        |d           |S )a  
    Return path to directory, where all launch scripts should be placed.

    This directory can also be used for the application logs.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param default_scripts_path: Root directory to store launch scripts in.
    :return: Path to directory, where launch script should be placed.
    T)exist_ok)r*   r+   abspathjoinbasenamemakedirs)r   r   r%   results       r   get_scripts_pathr      s     '//"677F'//+..KW__V$$Ffbg&6&6v&>&>??K&&&&Mr   c                 
   t          | ||          }t          j        |          D ][}|                    d          s	 t          j        t          j                            ||                     L# t          $ r Y Xw xY wdS )a   
    Try to remove output, error logs for launched applications.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param default_scripts_path: Root directory to store launch scripts in.
    r   r   r%   z.txtN)r   r*   listdirendswithr   r+   r   r~   )r   r   r%   	logs_root	file_paths        r   remove_package_logsr      s     &1  I Z	**  	!!&)) 		Ibgll9i889999 	 	 	D	 s    2A33
B ?B r   r"   id_c                 *   t          | ||          }t                              |d|          }t                              |d|          }|}t          t	          j        |                    }t          j        d          D ]F}t                              |d|          }t                              |d|          }||vr||vr nG|rB| r@t          j        	                    ||          }t          j        	                    ||          }|||fS )a  
    Return the package log names for launched applications.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param package_name: Name of the conda package, or alias of the external application.
    :param id_: Application session identifier.

                Used to create different names for different application launch sessions.
    :param default_scripts_path: Root directory to store launch scripts in.
    r   out)r`   levelindexerrNrN   )rS   )
r   r   formatr@   r*   r   	itertoolscountr+   r   )	r   r   r"   r   r%   r   stdout_log_pathstderr_log_pathuseds	            r   get_package_logsr     s   $ &1  I $??<uTW?XXO#??<uTW?XXO
{ #BJy$9$9 : :?+++ 	 	C&ool%WZo[[O&ool%WZo[[Ot++/2M2M C+ C',,y/BB',,y/BBOS00r   	extensionc                 x   t          | ||          }d}t          r&dt          j        j                                         }t          j                            || |           }t          |d|          5 }	|	
                    |           ddd           n# 1 swxY w Y   t          j        |d           |S )a  
    Create new application launching script file.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param command: Content of the script file.
    :param extension: Extension for the script file (`.bat`, `.sh`)
    :param package_name: Name of the conda package, or alias of the external application.
    :param default_scripts_path: Root directory to store launch scripts in.
    :return: Path to generated launch script file.
    r   zutf-8cpwt)encodingNi  )r   r   ctypescdllkernel32GetACPr*   r+   r   r|   writechmod)
r   r   r    r   r"   r%   scripts_rootr   r   r   s
             r   create_app_run_scriptr   ?  s   & )1  L H
 87,335577 W\\,<0L0L0LMMI	i	1	1	1 VW               HYs   8BB!Br   r   r!   r$   c                    t          | |||          \  }}	}
t          dt          d          t          d          ff                              ||          }t	          |||| d          }t
          j                            | dd          }|D ]$}|d	t          t          |                     z  }%d
                    ddt          j
        j                                         dt          |           d	t          |           | dt          |           dt          |	           dg          }t          | ||d||          }t          j        t          j        z  ||d||
|||	dfS )a  
    Generate script to launch application and return path to it.

    This function is optimized to run on Windows.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param command: Actual command to launch application.
    :param extra_arguments: Additional arguments to attach to command.
    :param cwd: Custom working directory to launch application in.
    :param package_name: Name of the conda package, or alias of the external application.
    :param environment: Custom environment to launch application in.
    :param default_scripts_path: Root directory to store launch scripts in.
    :return: Path to generated launch script file.
    r   r   r"   r%   )zPstart cmd.exe /K "${CONDA_ROOT_PREFIX}\\Scripts\\activate.bat" "${CONDA_PREFIX}"zNstart cmd.exe \K "${CONDA_ROOT_PREFIX}\Scripts\activate.bat" "${CONDA_PREFIX}"zstart powershell.exe -ExecutionPolicy ByPass -NoExit -Command  "& '{CONDA_ROOT_PREFIX}\\shell\\condabin\\conda-hook.ps1' ; conda activate '{CONDA_PREFIX}'"zstart powershell.exe -ExecutionPolicy ByPass -NoExit -Command "& '${CONDA_ROOT_PREFIX}\shell\condabin\conda-hook.ps1' ; conda activate '${CONDA_PREFIX}'"PREFIXCONDA_PREFIXCONDA_ROOT_PREFIXr    r#   Scriptsactivater9   
z	@echo offzchcp zcall  > 2> z.batr   r   r    r   r"   r%   )creationflagsr$   envr   r   r   r   r   )r   dictr   rP   rW   r*   r+   r   rH   r   r   r   r   r   r   CREATE_NO_WINDOWCREATE_NEW_PROCESS_GROUPr   r   r    r!   r"   r#   r$   r%   r   r   r   r   extra_argumentscriptr   s                  r   get_command_on_winr   f  s   8 -=!1	- - -)O_c 	

 y  u 		
   s7G " !"!,
 
  G GLLiDDH * ; ;:|C$7$788:::))/$++--// 	@X&&??f)=)=??WWl?33WW_8U8UWW
  F +!1  I $4z7ZZ 
 !! 	
 
r   c                    t          | |||          \  }}	}
t          |||| d          }t          j                            | dd          }|D ]$}|dt          t          |                     z  }%d                    dd	t          |           dt          |           | d
t          |           dt          |	           dg          }t          | ||d||          }||d||
|||	dfS )a  
    Generate script to launch application and return path to it.

    This function is optimized to run on Linux/OS X.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param command: Actual command to launch application.
    :param extra_arguments: Additional arguments to attach to command.
    :param cwd: Custom working directory to launch application in.
    :param package_name: Name of the conda package, or alias of the external application.
    :param environment: Custom environment to launch application in.
    :param default_scripts_path: Root directory to store launch scripts in.
    :return: Path to generated launch script file.
    r   r   r   binr   r9   r   z#!/usr/bin/env bashz. r   r   r   z.shr   )r$   r   r   )r   rW   r*   r+   r   rE   r   r   r   s                  r   get_command_on_unixr     so   8 -=!1	- - -)O_c !"!,
 
  G GLLeZ@@H * 8 87y^!4!455777))6Yx  669V#4#466QQi00QQY5O5OQQ
	  F +!1  I   !! 	 	r   Tworking_directoryleave_path_alone	non_condac	           	      &   t          |t                    r|f}t          }	t          rt          }	 |	| ||||||          \  }
}|d         }t          rdt          |           }t          |t          j        |fi |
|d         |d                   S )aJ  
    Handle launching commands from projects.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param command: Actual command to launch application.
    :param extra_arguments: Additional arguments to attach to command.
    :param working_directory: Custom working directory to launch application in.

                              If not provided - home directory will be used.
    :param package_name: Name of the conda package, or alias of the external application.
    :param environment: Custom environment to launch application in.
    :param as_admin: Launch application with admin rights.

                     This breaks function result (changes it to :code:`True`/:code:`None`).
    :return: Description of the launched process.
    )r   r   r    r!   r"   r#   r$   r   zcmd.exe /C r   r   )r`   ra   r   r   )	
isinstancer   r   r   r   rH   rY   r   r   )r   r   r    r!   r   r"   r#   r   r   get_command
popen_dict
extra_argsr   s                r   launchr     s    8 /3'' -*, 3K
 )( )['!  J
 6"D
 21\$//11 4444(#(#	   r   )NF))r   rh   r   r*   r   sysr-   navigator_updater.configr   r   r   platformr   Finalr   r   r   	TypedDictr
   Protocolr   rE   rH   r1   r/   r   rW   rY   r   r   r0   r   r2   r   r   r+   r,   r.   r   r   r   r   r   r   <module>r      s   % $ $      				     



  = = = = = = = =  MMM (+|w'>'>UU[c	 P P P=&,s
 = = =    V%          :S S          #	& &&^CO4& & 	&
 	& & & &RU U U U U U U Uv %8  " 		   : %8  " 
	   >  $ 3'1 '1'1'1 '1 
		'1
 '1 \#sC- '1 '1 '1 '1^  3$ $$$ $ 	$
 $ $ 	$ $ $ $V 8:!AE7%%c**$7b bbb b  4	b
 b _V^CH%=>b b "b \&.fj13CCDb b b bR 8:!AE7%%c**$7I III I  4	I
 I _V^CH%=>I I "I \&.fj13CCDI I I I` 8:!#!3!3C!8!8!AE!%8 888 8  4	8
 8 8 _V^CH%=>8 8 8 _^$8 8 8 8 8 8r   