U
    HZûaÛR  ã                   @   s   d Z ddlZddlZddlZddlmZmZmZ ddlZej	dkr\ddl
Z
G dd„ deƒZnddlZdZdZd	Zd
ZdZdejej	ef ZdZdZdZdZdZdZdZdZdZdZe ¡ ZdZ dZ!dZ"dZ#g Z$dd„ Z%G dd„ de&ƒZ'e'defi ƒZ(G dd„ de(ƒZ)i Z*d!dd„Z+d"dd „Z,dS )#z3
Classes and functions enabling the command system
é    N)ÚUtilsÚErrorsÚLogsi  c                   @   s   e Zd Zdd„ ZdS )Úimpc                 C   s
   t  | ¡S )N)ÚtypesÚ
ModuleType)Úx© r	   ú)/wcdo/src/waf-tools/waf/waflib/Context.pyÚ<lambda>   ó    zimp.<lambda>N)Ú__name__Ú
__module__Ú__qualname__Ú
new_moduler	   r	   r	   r
   r      s   r   i  z2.0.20Z(668769470956da8c5b60817cb8884cd7d0f87cd4Úwafé   z.wafpickle-%s-%d-%dÚAPPNAMEÚVERSIONÚtopÚoutÚwscriptÚ é   éÿÿÿÿc                 O   s6   t D ]}|j| kr|||Ž  S qt||Ž}| |_|S )a¿  
	Returns a new :py:class:`waflib.Context.Context` instance corresponding to the given command.
	Used in particular by :py:func:`waflib.Scripting.run_command`

	:param cmd_name: command name
	:type cmd_name: string
	:param k: arguments to give to the context class initializer
	:type k: list
	:param k: keyword arguments to give to the context class initializer
	:type k: dict
	:return: Context object
	:rtype: :py:class:`waflib.Context.Context`
	)ÚclassesÚcmdÚContextÚfun)Úcmd_nameÚkÚkwr   Úctxr	   r	   r
   Úcreate_contextS   s    

r#   c                       s    e Zd ZdZ‡ fdd„Z‡  ZS )Ústore_contexta  
	Metaclass that registers command classes into the list :py:const:`waflib.Context.classes`
	Context classes must provide an attribute 'cmd' representing the command name, and a function
	attribute 'fun' representing the function name that the command uses.
	c                    sx   t t| ƒ |||¡ | j}|dkr&d S z
| j W n" tk
rR   t d| ¡‚Y nX t| dd ƒsh| j| _	t
 d| ¡ d S )N)r"   r   z.Missing command for the context class %r (cmd)r   r   )Úsuperr$   Ú__init__r   r   ÚAttributeErrorr   ÚWafErrorÚgetattrr   r   Úinsert)ÚclsÚnameÚbasesÚdct©Ú	__class__r	   r
   r&   n   s    
zstore_context.__init__)r   r   r   Ú__doc__r&   Ú__classcell__r	   r	   r/   r
   r$   h   s   r$   r"   c                   @   s    e Zd ZdZeZi Zdd„ Zdd„ Zdd„ Z	dd	„ Z
d
d„ Zdd„ Zd$dd„Zdd„ Zdd„ Zdd„ Zd%dd„Zdd„ Zdd„ Zdd„ Zd d!„ Zg fd"d#„ZdS )&r   aÒ  
	Default context for waf commands, and base class for new command contexts.

	Context objects are passed to top-level functions::

		def foo(ctx):
			print(ctx.__class__.__name__) # waflib.Context.Context

	Subclasses must define the class attributes 'cmd' and 'fun':

	:param cmd: command to execute as in ``waf cmd``
	:type cmd: string
	:param fun: function name to execute when the command is called
	:type fun: string

	.. inheritance-diagram:: waflib.Context.Context waflib.Build.BuildContext waflib.Build.InstallContext waflib.Build.UninstallContext waflib.Build.StepContext waflib.Build.ListContext waflib.Configure.ConfigurationContext waflib.Scripting.Dist waflib.Scripting.DistCheck waflib.Build.CleanContext

	c                 K   sŒ   z|d }W n t k
r$   t}Y nX tdtjjfi ƒ| _d| j_| | j_|  dd ¡| _d | _	| j 
|¡| _g | _| | | | dœ| _d | _d S )NÚrun_dirZNod3zwaflib.Noder   )r"   ÚconfÚbldÚopt)ÚKeyErrorr3   ÚtypeÚwaflibÚNodeZ
node_classr   r"   ÚrootÚ
cur_scriptÚfind_dirÚpathÚ
stack_pathÚ	exec_dictÚlogger)Úselfr!   Zrdr	   r	   r
   r&       s    
zContext.__init__c                 C   s8   z
| j }W n tk
r   Y nX t |¡ t| dƒ dS )z3
		Called to free resources such as logger files
		rA   N)rA   r'   r   Úfree_loggerÚdelattr)rB   rA   r	   r	   r
   Úfinalize³   s    

zContext.finalizec           
      O   sf   t  |¡}t  | dd¡¡}| dd¡}|D ]4}t|||d�}t|| d| j¡dƒ}	|	r,|	| ƒ q,dS )a+  
		Loads a Waf tool as a module, and try calling the function named :py:const:`waflib.Context.Context.fun`
		from it.  A ``tooldir`` argument may be provided as a list of module paths.

		:param tool_list: list of Waf tool names to load
		:type tool_list: list of string or space-separated string
		Útooldirr   Úwith_sys_pathT)rG   r,   N)r   Úto_listÚgetÚ	load_toolr)   r   )
rB   Ú	tool_listr    r!   Útoolsr>   rG   ÚtÚmoduler   r	   r	   r
   Úload¿   s    
zContext.loadc                 C   s   |   tj tj¡g¡ dS )z‘
		Here, it calls the function name in the top-level wscript file. Most subclasses
		redefine this method to provide additional functionality.
		N)ÚrecurseÚosr>   ÚdirnameÚg_moduleÚ	root_path)rB   r	   r	   r
   ÚexecuteÑ   s    zContext.executec                 C   s    | j  | j¡ || _|j| _dS )a!  
		Method executed immediately before a folder is read by :py:meth:`waflib.Context.Context.recurse`.
		The current script is bound as a Node object on ``self.cur_script``, and the current path
		is bound to ``self.path``

		:param node: script
		:type node: :py:class:`waflib.Node.Node`
		N)r?   Úappendr<   Úparentr>   ©rB   Únoder	   r	   r
   Úpre_recurseØ   s    	zContext.pre_recursec                 C   s    | j  ¡ | _| jr| jj| _dS )z¸
		Restores ``self.cur_script`` and ``self.path`` right after :py:meth:`waflib.Context.Context.recurse` terminates.

		:param node: script
		:type node: :py:class:`waflib.Node.Node`
		N)r?   Úpopr<   rW   r>   rX   r	   r	   r
   Úpost_recurseæ   s    zContext.post_recurseNTc              
   C   sê  z
| j }W n tk
r(   i  }| _ Y nX t |¡D �]®}tj |¡sZtj | j ¡ |¡}tj |t	¡}|d |pv| j
 }	| j |	¡}
|
rà|r–|
|kràd||
< |  |
¡ z(|
 d|¡}tt||
 ¡ dƒ| jƒ W 5 |  |
¡ X q4|
s4| j |¡}
|
|pú| j
f}|
�r–|�r||k�r–d||< |  |
¡ z`t|
 ¡ |d�}t||�pF| j
dƒ}|�s||�s^W ¢,q4t d|�pn| j
|
 ¡ f ¡‚|| ƒ W 5 |  |
¡ X q4|
s4|�s¢q4zt |¡ W n$ tk
�rÔ   t d| ¡‚Y nX t d	| ¡‚q4dS )
aÅ  
		Runs user-provided functions from the supplied list of directories.
		The directories can be either absolute, or relative to the directory
		of the wscript file

		The methods :py:meth:`waflib.Context.Context.pre_recurse` and
		:py:meth:`waflib.Context.Context.post_recurse` are called immediately before
		and after a script has been executed.

		:param dirs: List of directories to visit
		:type dirs: list of string or space-separated string
		:param name: Name of function to invoke from the wscript
		:type  name: string
		:param mandatory: whether sub wscript files are required to exist
		:type  mandatory: bool
		:param once: read the script file once for a particular context
		:type once: bool
		Ú_TÚrÚexec)ÚencodingNzNo function %r defined in %szCannot read the folder %rzNo wscript file in directory %s)Zrecurse_cacher'   r   rH   rQ   r>   ÚisabsÚjoinÚabspathÚWSCRIPT_FILEr   r;   Ú	find_noderZ   r\   Úreadr_   Úcompiler@   Úload_moduler)   r   r(   ÚlistdirÚOSError)rB   Údirsr,   Ú	mandatoryÚoncer`   ÚcacheÚdZWSCRIPTZWSCRIPT_FUNrY   Zfunction_codeÚtupZwscript_moduleÚuser_functionr	   r	   r
   rP   ñ   sP    


zContext.recursec                 C   sJ   t jrFtj d¡}|dkr.t|tƒs.t |¡}t  	d|¡ t  	d|¡ d S )NZWAF_CMD_FORMATÚstringz
runner: %rzrunner_env: kw=%s)
r   ÚverboserQ   ÚenvironrI   Ú
isinstanceÚstrr   Úshell_escapeÚdebug)rB   r   r!   Úfmtr	   r	   r
   Úlog_command4  s    

zContext.log_commandc           
   
   K   s  t j}t|tƒ|d< |  ||¡ | jr2| j |¡ d|krD|j|d< d|krV|j|d< tj	r„|d s„t  
|d ¡s„t d|d  ¡‚i }d|kr¼tjdkr¶|d |d< d|kr¶d	|d< |d= d
|krè|d
 râ|d
 |d
< |j|d< |d
= d|k�rt|d tƒ�s|d  ¡ |d< | dt¡}zt  |||¡\}}}W n: tk
�rp }	 ztjdt|	ƒ |	d�‚W 5 d}	~	X Y nX |�rÀt|tƒ�s’|j|dd�}| j�rª| j d|¡ ntj|tjddœd� |�rt|tƒ�sà|j|dd�}| j�rú| j d| ¡ ntj|tjddœd� |S )a.  
		Runs an external process and returns the exit status::

			def run(tsk):
				ret = tsk.generator.bld.exec_command('touch foo.txt')
				return ret

		If the context has the attribute 'log', then captures and logs the process stderr/stdout.
		Unlike :py:meth:`waflib.Context.Context.cmd_and_log`, this method does not return the
		stdout/stderr values captured.

		:param cmd: command argument for subprocess.Popen
		:type cmd: string or list
		:param kw: keyword arguments for subprocess.Popen. The parameters input/timeout will be passed to wait/communicate.
		:type kw: dict
		:returns: process exit status
		:rtype: integer
		:raises: :py:class:`waflib.Errors.WafError` if an invalid executable is specified for a non-shell process
		:raises: :py:class:`waflib.Errors.WafError` in case of execution failure
		ÚshellÚstdoutÚstderrr   zProgram %s not found!Útimeouté  Ústart_new_sessionTÚinputÚstdinÚcwdÚ	decode_asúExecution failure: %s©ÚexNÚreplace©Úerrorsúout: %sr   )ÚstreamÚc1)Úextraúerr: %s)r   Ú
subprocessru   rv   rz   rA   ÚinfoÚPIPEr   rs   Ú	check_exer   r(   ÚsysÚ
hexversionrc   r[   Údefault_encodingÚrun_processÚ	ExceptionÚdecoderx   r|   Úerrorr}   )
rB   r   r!   r�   Úcargsr`   Úretr   ÚerrÚer	   r	   r
   Úexec_command=  sX    




(zContext.exec_commandc              
   K   sN  t j}t|tƒ|d< |  ||¡ | dd¡}| dt¡}tjrf|d sft  	|d ¡sft
 d|d  ¡‚|j |d< |d< |dkrŠ|  |¡ i }d	|krÂtjd
kr¼|d	 |d	< d|kr¼d|d< |d	= d|krî|d rè|d |d< |j|d< |d= d|k�rt|d tƒ�s|d  ¡ |d< | dt¡}zt  |||¡\}}	}
W n: tk
�rv } zt
jdt|ƒ |d�‚W 5 d}~X Y nX t|	tƒ�s’|	j|dd�}	t|
tƒ�s¬|
j|dd�}
|	�rÔ|tk�rÔ|tk�rÔ|  d|	 ¡ |
�rü|tk�rü|tk�rü|  d|
 ¡ |�r*t
 d||f ¡}||_|
|_|	|_|‚|tk�r<|	|
fS |tk�rJ|
S |	S )a»  
		Executes a process and returns stdout/stderr if the execution is successful.
		An exception is thrown when the exit status is non-0. In that case, both stderr and stdout
		will be bound to the WafError object (configuration tests)::

			def configure(conf):
				out = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.STDOUT, quiet=waflib.Context.BOTH)
				(out, err) = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.BOTH)
				(out, err) = conf.cmd_and_log(cmd, input='\n'.encode(), output=waflib.Context.STDOUT)
				try:
					conf.cmd_and_log(['which', 'someapp'], output=waflib.Context.BOTH)
				except Errors.WafError as e:
					print(e.stdout, e.stderr)

		:param cmd: args for subprocess.Popen
		:type cmd: list or string
		:param kw: keyword arguments for subprocess.Popen. The parameters input/timeout will be passed to wait/communicate.
		:type kw: dict
		:returns: a tuple containing the contents of stdout and stderr
		:rtype: string
		:raises: :py:class:`waflib.Errors.WafError` if an invalid executable is specified for a non-shell process
		:raises: :py:class:`waflib.Errors.WafError` in case of execution failure; stdout/stderr/returncode are bound to the exception object
		r{   ÚquietNÚoutputr   zProgram %r not found!r|   r}   r~   r   r€   Tr�   r‚   rƒ   r„   r…   r†   rˆ   r‰   r‹   r�   zCommand %r returned %r)r   r�   ru   rv   rz   r[   ÚSTDOUTr   rs   r“   r   r(   r’   Úto_logr”   r•   rc   r–   r—   r˜   r™   ÚBOTHÚSTDERRÚ
returncoder}   r|   )rB   r   r!   r�   r    Zto_retr›   r`   rœ   r   r�   rž   r	   r	   r
   Úcmd_and_logŠ  sb    



(

zContext.cmd_and_logc                 C   sˆ   | j r | j  d| j ¡ |f ¡ z| j jd j}W n tk
rF   Y n.X tj 	d¡rhd|t
 |¡f }nd||f }| jj||d�‚dS )af  
		Prints an error message in red and stops command execution; this is
		usually used in the configuration section::

			def configure(conf):
				conf.fatal('a requirement is missing')

		:param msg: message to display
		:type msg: string
		:param ex: optional exception object
		:type ex: exception
		:raises: :py:class:`waflib.Errors.ConfigurationError`
		zfrom %s: %sr   ZWAF_PRINT_FAILURE_LOGzLog from (%s):
%s
z%s
(complete log in %s)r†   N)rA   r‘   r>   rc   ÚhandlersÚbaseFilenamer'   rQ   rt   rI   r   ÚreadfrŠ   ÚConfigurationError)rB   Úmsgr‡   Zlogfiler	   r	   r
   Úfatalß  s    zContext.fatalc                 C   s:   |sdS | j r| j  |¡ ntj t|ƒ¡ tj ¡  dS )a  
		Logs information to the logger (if present), or to stderr.
		Empty messages are not printed::

			def build(bld):
				bld.to_log('starting the build')

		Provide a logger on the context class or override this method if necessary.

		:param msg: message
		:type msg: string
		N)rA   r‘   r”   r}   Úwriterv   Úflush)rB   r¬   r	   r	   r
   r£   û  s    zContext.to_logc                 O   s–   z|d }W n t k
r(   |d }Y nX | j|f|Ž z|d }W n t k
r`   |d }Y nX | d¡}t|tƒs‚|r~dp€d}| j||f|Ž dS )	a  
		Prints a configuration message of the form ``msg: result``.
		The second part of the message will be in colors. The output
		can be disabled easly by setting ``in_msg`` to a positive value::

			def configure(conf):
				self.in_msg = 1
				conf.msg('Checking for library foo', 'ok')
				# no output

		:param msg: message to display to the user
		:type msg: string
		:param result: result to display
		:type result: string or boolean
		:param color: color to use, see :py:const:`waflib.Logs.colors_lst`
		:type color: string
		r¬   r   Úresultr   ÚcolorÚGREENÚYELLOWN)r7   Ú	start_msgrI   ru   rv   Úend_msg)rB   r    r!   r¬   r°   r±   r	   r	   r
   r¬     s    

zContext.msgc                 O   sâ   |  d¡rdS |  d¡p|d }z| jr<|  jd7  _W dS W n tk
rX   d| _Y nX |  jd7  _zt| jt|ƒƒ| _W n$ tk
r¢   tdt|ƒƒ| _Y nX | jd |fD ]}|  |¡ q²tjdd	| 	| j¡ d
d� dS )ze
		Prints the beginning of a 'Checking for xxx' message. See :py:meth:`waflib.Context.Context.msg`
		r    Nr¬   r   r   é(   ú-ÚNORMALz%s :r   )Úsep)
rI   Úin_msgr'   ÚmaxZ	line_justÚlenr£   r   ÚpprintÚljust)rB   r    r!   r¬   r   r	   r	   r
   r´   5  s"    

zContext.start_msgc                 O   sÄ   |  d¡rdS |  jd8  _| jr&dS |  d¡p6|d }d}|dkrJd}n|sXd	}d
}nt|ƒ}|  |¡ z|d }W n< tk
r²   t|ƒdkrª|d tjkrª|d }n|}Y nX t ||¡ dS )zUPrints the end of a 'Checking for' message. See :py:meth:`waflib.Context.Context.msg`r    Nr   r°   r   r²   TÚokz	not foundr³   r±   )	rI   rº   rv   r£   r7   r¼   r   Ú
colors_lstr½   )rB   r    r!   r°   Zdefcolorr¬   r±   r	   r	   r
   rµ   M  s*    



zContext.end_msgc                 C   sÞ   t j t¡rL| j t¡ d¡ |¡}|D ] }|j|kr(t|j 	dd¡ƒ q(nŽddl
m} |tƒ}| ¡ }|D ]l}t d| 	dd¡ |¡sŠqlt j |¡}d	}|D ] }	|	 	dd¡}
t |
|¡ržd
}qž|sl| 	dd¡}t|ƒ qldS )a   
		Loads third-party extensions modules for certain programming languages
		by trying to list certain files in the extras/ directory. This method
		is typically called once for a programming language group, see for
		example :py:mod:`waflib.Tools.compiler_c`

		:param var: glob expression, for example 'cxx\_\*.py'
		:type var: string
		:param ban: list of exact file names to exclude
		:type ban: list of string
		zwaflib/extrasz.pyr   r   )Ú	PyZipFilezwaflib/extras/%sÚ*z.*FTN)rQ   r>   ÚisdirÚwaf_dirr;   re   Úant_globr,   rJ   rˆ   ÚzipfilerÁ   ZnamelistÚreÚmatchÚbasename)rB   ÚvarZbanÚlstr   rÁ   ZwaflibsÚfZdobanÚbr^   r	   r	   r
   Úload_special_toolsk  s(    
zContext.load_special_tools)NTTN)N)r   r   r   r1   r   rŠ   rL   r&   rE   rO   rU   rZ   r\   rP   rz   rŸ   r§   r­   r£   r¬   r´   rµ   rÎ   r	   r	   r	   r
   r   ‚   s&   
C	MU
$r   c              	   C   s°   z
t |  W S  tk
r   Y nX t t¡}ztj| d|d�}W n" tk
r`   t 	d|  ¡‚Y nX t
j | ¡}tj d|¡ ztt|| dƒ|jƒ W 5 tj |¡ X |t | < |S )zÎ
	Loads a wscript file as a python module. This method caches results in :py:attr:`waflib.Context.cache_modules`

	:param path: file path
	:type path: string
	:return: Loaded Python module
	:rtype: module
	r^   )Úmr`   zCould not read the file %rr   r_   )Úcache_modulesr7   r   r   rd   r   rª   ÚEnvironmentErrorr   r(   rQ   r>   rR   r”   r*   Úremover_   rg   Ú__dict__)r>   r`   rN   ÚcodeZ
module_dirr	   r	   r
   rh   “  s     	

rh   Tc           	   
   C   s¬  | dkrd} n|   dd¡} |s*tj}g t_�zd|rÄt|tƒs@t‚|tj t_zBzt| ƒ W n0 tk
rŠ } zttjƒ|_	‚ W 5 d}~X Y nX W 5 |D ]}tj |¡ q”X tj
|  }|tj| < |W ¢ÐS |sÖtj dt¡ z‚zJdD ]8}zt||  ƒ W  �q W qÞ tk
�r   d}Y qÞX qÞt| ƒ W n2 tk
�rT } zttjƒ|_	‚ W 5 d}~X Y nX W 5 |�sltj t¡ X tj
||   }|tj| < |W ¢S W 5 |�s¦t j|7  _X dS )a�  
	Imports a Waf tool as a python module, and stores it in the dict :py:const:`waflib.Context.Context.tools`

	:type  tool: string
	:param tool: Name of the tool
	:type  tooldir: list
	:param tooldir: List of directories to search for the tool module
	:type  with_sys_path: boolean
	:param with_sys_path: whether or not to search the regular sys.path, besides waf_dir and potentially given tooldirs
	ÚjavaZjavawz++ZxxNr   )zwaflib.Tools.%szwaflib.extras.%sz	waflib.%sz%s)rˆ   r”   r>   ru   ÚlistÚAssertionErrorrÒ   Ú
__import__ÚImportErrorÚwaf_sys_pathÚmodulesr   rL   r*   rÄ   )	ÚtoolrF   r"   rG   Z	back_pathro   rž   rœ   r   r	   r	   r
   rJ   ±  sP    


rJ   )N)NNT)-r1   rQ   rÇ   r”   r9   r   r   r   Zwaflib.Noder•   r   Úobjectr   Ú
HEXVERSIONÚ
WAFVERSIONÚWAFREVISIONÚWAFNAMEÚABIÚplatformÚDBFILEr   r   ÚTOPÚOUTrd   Ú
launch_dirr3   Útop_dirÚout_dirrÄ   Úconsole_encodingr–   rS   r¢   r¥   r¤   r   r#   r8   r$   r"   r   rÐ   rh   rJ   r	   r	   r	   r
   Ú<module>   sP   
    
