jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

748 lines
21KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2010-2018 (ita)
  4. """
  5. Classes and functions enabling the command system
  6. """
  7. import os, re, sys
  8. from waflib import Utils, Errors, Logs
  9. import waflib.Node
  10. if sys.hexversion > 0x3040000:
  11. import types
  12. class imp(object):
  13. new_module = lambda x: types.ModuleType(x)
  14. else:
  15. import imp
  16. # the following 3 constants are updated on each new release (do not touch)
  17. HEXVERSION=0x2001a00
  18. """Constant updated on new releases"""
  19. WAFVERSION="2.0.26"
  20. """Constant updated on new releases"""
  21. WAFREVISION="0fb985ce1932c6f3e7533f435e4ee209d673776e"
  22. """Git revision when the waf version is updated"""
  23. WAFNAME="waf"
  24. """Application name displayed on --help"""
  25. ABI = 20
  26. """Version of the build data cache file format (used in :py:const:`waflib.Context.DBFILE`)"""
  27. DBFILE = '.wafpickle-%s-%d-%d' % (sys.platform, sys.hexversion, ABI)
  28. """Name of the pickle file for storing the build data"""
  29. APPNAME = 'APPNAME'
  30. """Default application name (used by ``waf dist``)"""
  31. VERSION = 'VERSION'
  32. """Default application version (used by ``waf dist``)"""
  33. TOP = 'top'
  34. """The variable name for the top-level directory in wscript files"""
  35. OUT = 'out'
  36. """The variable name for the output directory in wscript files"""
  37. WSCRIPT_FILE = 'wscript'
  38. """Name of the waf script files"""
  39. launch_dir = ''
  40. """Directory from which waf has been called"""
  41. run_dir = ''
  42. """Location of the wscript file to use as the entry point"""
  43. top_dir = ''
  44. """Location of the project directory (top), if the project was configured"""
  45. out_dir = ''
  46. """Location of the build directory (out), if the project was configured"""
  47. waf_dir = ''
  48. """Directory containing the waf modules"""
  49. default_encoding = Utils.console_encoding()
  50. """Encoding to use when reading outputs from other processes"""
  51. g_module = None
  52. """
  53. Module representing the top-level wscript file (see :py:const:`waflib.Context.run_dir`)
  54. """
  55. STDOUT = 1
  56. STDERR = -1
  57. BOTH = 0
  58. classes = []
  59. """
  60. List of :py:class:`waflib.Context.Context` subclasses that can be used as waf commands. The classes
  61. are added automatically by a metaclass.
  62. """
  63. def create_context(cmd_name, *k, **kw):
  64. """
  65. Returns a new :py:class:`waflib.Context.Context` instance corresponding to the given command.
  66. Used in particular by :py:func:`waflib.Scripting.run_command`
  67. :param cmd_name: command name
  68. :type cmd_name: string
  69. :param k: arguments to give to the context class initializer
  70. :type k: list
  71. :param k: keyword arguments to give to the context class initializer
  72. :type k: dict
  73. :return: Context object
  74. :rtype: :py:class:`waflib.Context.Context`
  75. """
  76. for x in classes:
  77. if x.cmd == cmd_name:
  78. return x(*k, **kw)
  79. ctx = Context(*k, **kw)
  80. ctx.fun = cmd_name
  81. return ctx
  82. class store_context(type):
  83. """
  84. Metaclass that registers command classes into the list :py:const:`waflib.Context.classes`
  85. Context classes must provide an attribute 'cmd' representing the command name, and a function
  86. attribute 'fun' representing the function name that the command uses.
  87. """
  88. def __init__(cls, name, bases, dct):
  89. super(store_context, cls).__init__(name, bases, dct)
  90. name = cls.__name__
  91. if name in ('ctx', 'Context'):
  92. return
  93. try:
  94. cls.cmd
  95. except AttributeError:
  96. raise Errors.WafError('Missing command for the context class %r (cmd)' % name)
  97. if not getattr(cls, 'fun', None):
  98. cls.fun = cls.cmd
  99. classes.insert(0, cls)
  100. ctx = store_context('ctx', (object,), {})
  101. """Base class for all :py:class:`waflib.Context.Context` classes"""
  102. class Context(ctx):
  103. """
  104. Default context for waf commands, and base class for new command contexts.
  105. Context objects are passed to top-level functions::
  106. def foo(ctx):
  107. print(ctx.__class__.__name__) # waflib.Context.Context
  108. Subclasses must define the class attributes 'cmd' and 'fun':
  109. :param cmd: command to execute as in ``waf cmd``
  110. :type cmd: string
  111. :param fun: function name to execute when the command is called
  112. :type fun: string
  113. .. 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
  114. :top-classes: waflib.Context.Context
  115. """
  116. errors = Errors
  117. """
  118. Shortcut to :py:mod:`waflib.Errors` provided for convenience
  119. """
  120. tools = {}
  121. """
  122. A module cache for wscript files; see :py:meth:`Context.Context.load`
  123. """
  124. def __init__(self, **kw):
  125. try:
  126. rd = kw['run_dir']
  127. except KeyError:
  128. rd = run_dir
  129. # binds the context to the nodes in use to avoid a context singleton
  130. self.node_class = type('Nod3', (waflib.Node.Node,), {})
  131. self.node_class.__module__ = 'waflib.Node'
  132. self.node_class.ctx = self
  133. self.root = self.node_class('', None)
  134. self.cur_script = None
  135. self.path = self.root.find_dir(rd)
  136. self.stack_path = []
  137. self.exec_dict = {'ctx':self, 'conf':self, 'bld':self, 'opt':self}
  138. self.logger = None
  139. def finalize(self):
  140. """
  141. Called to free resources such as logger files
  142. """
  143. try:
  144. logger = self.logger
  145. except AttributeError:
  146. pass
  147. else:
  148. Logs.free_logger(logger)
  149. delattr(self, 'logger')
  150. def load(self, tool_list, *k, **kw):
  151. """
  152. Loads a Waf tool as a module, and try calling the function named :py:const:`waflib.Context.Context.fun`
  153. from it. A ``tooldir`` argument may be provided as a list of module paths.
  154. :param tool_list: list of Waf tool names to load
  155. :type tool_list: list of string or space-separated string
  156. """
  157. tools = Utils.to_list(tool_list)
  158. path = Utils.to_list(kw.get('tooldir', ''))
  159. with_sys_path = kw.get('with_sys_path', True)
  160. for t in tools:
  161. module = load_tool(t, path, with_sys_path=with_sys_path)
  162. fun = getattr(module, kw.get('name', self.fun), None)
  163. if fun:
  164. fun(self)
  165. def execute(self):
  166. """
  167. Here, it calls the function name in the top-level wscript file. Most subclasses
  168. redefine this method to provide additional functionality.
  169. """
  170. self.recurse([os.path.dirname(g_module.root_path)])
  171. def pre_recurse(self, node):
  172. """
  173. Method executed immediately before a folder is read by :py:meth:`waflib.Context.Context.recurse`.
  174. The current script is bound as a Node object on ``self.cur_script``, and the current path
  175. is bound to ``self.path``
  176. :param node: script
  177. :type node: :py:class:`waflib.Node.Node`
  178. """
  179. self.stack_path.append(self.cur_script)
  180. self.cur_script = node
  181. self.path = node.parent
  182. def post_recurse(self, node):
  183. """
  184. Restores ``self.cur_script`` and ``self.path`` right after :py:meth:`waflib.Context.Context.recurse` terminates.
  185. :param node: script
  186. :type node: :py:class:`waflib.Node.Node`
  187. """
  188. self.cur_script = self.stack_path.pop()
  189. if self.cur_script:
  190. self.path = self.cur_script.parent
  191. def recurse(self, dirs, name=None, mandatory=True, once=True, encoding=None):
  192. """
  193. Runs user-provided functions from the supplied list of directories.
  194. The directories can be either absolute, or relative to the directory
  195. of the wscript file
  196. The methods :py:meth:`waflib.Context.Context.pre_recurse` and
  197. :py:meth:`waflib.Context.Context.post_recurse` are called immediately before
  198. and after a script has been executed.
  199. :param dirs: List of directories to visit
  200. :type dirs: list of string or space-separated string
  201. :param name: Name of function to invoke from the wscript
  202. :type name: string
  203. :param mandatory: whether sub wscript files are required to exist
  204. :type mandatory: bool
  205. :param once: read the script file once for a particular context
  206. :type once: bool
  207. """
  208. try:
  209. cache = self.recurse_cache
  210. except AttributeError:
  211. cache = self.recurse_cache = {}
  212. for d in Utils.to_list(dirs):
  213. if not os.path.isabs(d):
  214. # absolute paths only
  215. d = os.path.join(self.path.abspath(), d)
  216. WSCRIPT = os.path.join(d, WSCRIPT_FILE)
  217. WSCRIPT_FUN = WSCRIPT + '_' + (name or self.fun)
  218. node = self.root.find_node(WSCRIPT_FUN)
  219. if node and (not once or node not in cache):
  220. cache[node] = True
  221. self.pre_recurse(node)
  222. try:
  223. function_code = node.read('r', encoding)
  224. exec(compile(function_code, node.abspath(), 'exec'), self.exec_dict)
  225. finally:
  226. self.post_recurse(node)
  227. elif not node:
  228. node = self.root.find_node(WSCRIPT)
  229. tup = (node, name or self.fun)
  230. if node and (not once or tup not in cache):
  231. cache[tup] = True
  232. self.pre_recurse(node)
  233. try:
  234. wscript_module = load_module(node.abspath(), encoding=encoding)
  235. user_function = getattr(wscript_module, (name or self.fun), None)
  236. if not user_function:
  237. if not mandatory:
  238. continue
  239. raise Errors.WafError('No function %r defined in %s' % (name or self.fun, node.abspath()))
  240. user_function(self)
  241. finally:
  242. self.post_recurse(node)
  243. elif not node:
  244. if not mandatory:
  245. continue
  246. try:
  247. os.listdir(d)
  248. except OSError:
  249. raise Errors.WafError('Cannot read the folder %r' % d)
  250. raise Errors.WafError('No wscript file in directory %s' % d)
  251. def log_command(self, cmd, kw):
  252. if Logs.verbose:
  253. fmt = os.environ.get('WAF_CMD_FORMAT')
  254. if fmt == 'string':
  255. if not isinstance(cmd, str):
  256. cmd = Utils.shell_escape(cmd)
  257. Logs.debug('runner: %r', cmd)
  258. Logs.debug('runner_env: kw=%s', kw)
  259. def exec_command(self, cmd, **kw):
  260. """
  261. Runs an external process and returns the exit status::
  262. def run(tsk):
  263. ret = tsk.generator.bld.exec_command('touch foo.txt')
  264. return ret
  265. If the context has the attribute 'log', then captures and logs the process stderr/stdout.
  266. Unlike :py:meth:`waflib.Context.Context.cmd_and_log`, this method does not return the
  267. stdout/stderr values captured.
  268. :param cmd: command argument for subprocess.Popen
  269. :type cmd: string or list
  270. :param kw: keyword arguments for subprocess.Popen. The parameters input/timeout will be passed to wait/communicate.
  271. :type kw: dict
  272. :returns: process exit status
  273. :rtype: integer
  274. :raises: :py:class:`waflib.Errors.WafError` if an invalid executable is specified for a non-shell process
  275. :raises: :py:class:`waflib.Errors.WafError` in case of execution failure
  276. """
  277. subprocess = Utils.subprocess
  278. kw['shell'] = isinstance(cmd, str)
  279. self.log_command(cmd, kw)
  280. if self.logger:
  281. self.logger.info(cmd)
  282. if 'stdout' not in kw:
  283. kw['stdout'] = subprocess.PIPE
  284. if 'stderr' not in kw:
  285. kw['stderr'] = subprocess.PIPE
  286. if Logs.verbose and not kw['shell'] and not Utils.check_exe(cmd[0]):
  287. raise Errors.WafError('Program %s not found!' % cmd[0])
  288. cargs = {}
  289. if 'timeout' in kw:
  290. if sys.hexversion >= 0x3030000:
  291. cargs['timeout'] = kw['timeout']
  292. if not 'start_new_session' in kw:
  293. kw['start_new_session'] = True
  294. del kw['timeout']
  295. if 'input' in kw:
  296. if kw['input']:
  297. cargs['input'] = kw['input']
  298. kw['stdin'] = subprocess.PIPE
  299. del kw['input']
  300. if 'cwd' in kw:
  301. if not isinstance(kw['cwd'], str):
  302. kw['cwd'] = kw['cwd'].abspath()
  303. encoding = kw.pop('decode_as', default_encoding)
  304. try:
  305. ret, out, err = Utils.run_process(cmd, kw, cargs)
  306. except Exception as e:
  307. raise Errors.WafError('Execution failure: %s' % str(e), ex=e)
  308. if out:
  309. if not isinstance(out, str):
  310. out = out.decode(encoding, errors='replace')
  311. if self.logger:
  312. self.logger.debug('out: %s', out)
  313. else:
  314. Logs.info(out, extra={'stream':sys.stdout, 'c1': ''})
  315. if err:
  316. if not isinstance(err, str):
  317. err = err.decode(encoding, errors='replace')
  318. if self.logger:
  319. self.logger.error('err: %s' % err)
  320. else:
  321. Logs.info(err, extra={'stream':sys.stderr, 'c1': ''})
  322. return ret
  323. def cmd_and_log(self, cmd, **kw):
  324. """
  325. Executes a process and returns stdout/stderr if the execution is successful.
  326. An exception is thrown when the exit status is non-0. In that case, both stderr and stdout
  327. will be bound to the WafError object (configuration tests)::
  328. def configure(conf):
  329. out = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.STDOUT, quiet=waflib.Context.BOTH)
  330. (out, err) = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.BOTH)
  331. (out, err) = conf.cmd_and_log(cmd, input='\\n'.encode(), output=waflib.Context.STDOUT)
  332. try:
  333. conf.cmd_and_log(['which', 'someapp'], output=waflib.Context.BOTH)
  334. except Errors.WafError as e:
  335. print(e.stdout, e.stderr)
  336. :param cmd: args for subprocess.Popen
  337. :type cmd: list or string
  338. :param kw: keyword arguments for subprocess.Popen. The parameters input/timeout will be passed to wait/communicate.
  339. :type kw: dict
  340. :returns: a tuple containing the contents of stdout and stderr
  341. :rtype: string
  342. :raises: :py:class:`waflib.Errors.WafError` if an invalid executable is specified for a non-shell process
  343. :raises: :py:class:`waflib.Errors.WafError` in case of execution failure; stdout/stderr/returncode are bound to the exception object
  344. """
  345. subprocess = Utils.subprocess
  346. kw['shell'] = isinstance(cmd, str)
  347. self.log_command(cmd, kw)
  348. quiet = kw.pop('quiet', None)
  349. to_ret = kw.pop('output', STDOUT)
  350. if Logs.verbose and not kw['shell'] and not Utils.check_exe(cmd[0]):
  351. raise Errors.WafError('Program %r not found!' % cmd[0])
  352. kw['stdout'] = kw['stderr'] = subprocess.PIPE
  353. if quiet is None:
  354. self.to_log(cmd)
  355. cargs = {}
  356. if 'timeout' in kw:
  357. if sys.hexversion >= 0x3030000:
  358. cargs['timeout'] = kw['timeout']
  359. if not 'start_new_session' in kw:
  360. kw['start_new_session'] = True
  361. del kw['timeout']
  362. if 'input' in kw:
  363. if kw['input']:
  364. cargs['input'] = kw['input']
  365. kw['stdin'] = subprocess.PIPE
  366. del kw['input']
  367. if 'cwd' in kw:
  368. if not isinstance(kw['cwd'], str):
  369. kw['cwd'] = kw['cwd'].abspath()
  370. encoding = kw.pop('decode_as', default_encoding)
  371. try:
  372. ret, out, err = Utils.run_process(cmd, kw, cargs)
  373. except Exception as e:
  374. raise Errors.WafError('Execution failure: %s' % str(e), ex=e)
  375. if not isinstance(out, str):
  376. out = out.decode(encoding, errors='replace')
  377. if not isinstance(err, str):
  378. err = err.decode(encoding, errors='replace')
  379. if out and quiet != STDOUT and quiet != BOTH:
  380. self.to_log('out: %s' % out)
  381. if err and quiet != STDERR and quiet != BOTH:
  382. self.to_log('err: %s' % err)
  383. if ret:
  384. e = Errors.WafError('Command %r returned %r' % (cmd, ret))
  385. e.returncode = ret
  386. e.stderr = err
  387. e.stdout = out
  388. raise e
  389. if to_ret == BOTH:
  390. return (out, err)
  391. elif to_ret == STDERR:
  392. return err
  393. return out
  394. def fatal(self, msg, ex=None):
  395. """
  396. Prints an error message in red and stops command execution; this is
  397. usually used in the configuration section::
  398. def configure(conf):
  399. conf.fatal('a requirement is missing')
  400. :param msg: message to display
  401. :type msg: string
  402. :param ex: optional exception object
  403. :type ex: exception
  404. :raises: :py:class:`waflib.Errors.ConfigurationError`
  405. """
  406. if self.logger:
  407. self.logger.info('from %s: %s' % (self.path.abspath(), msg))
  408. try:
  409. logfile = self.logger.handlers[0].baseFilename
  410. except AttributeError:
  411. pass
  412. else:
  413. if os.environ.get('WAF_PRINT_FAILURE_LOG'):
  414. # see #1930
  415. msg = 'Log from (%s):\n%s\n' % (logfile, Utils.readf(logfile))
  416. else:
  417. msg = '%s\n(complete log in %s)' % (msg, logfile)
  418. raise self.errors.ConfigurationError(msg, ex=ex)
  419. def to_log(self, msg):
  420. """
  421. Logs information to the logger (if present), or to stderr.
  422. Empty messages are not printed::
  423. def build(bld):
  424. bld.to_log('starting the build')
  425. Provide a logger on the context class or override this method if necessary.
  426. :param msg: message
  427. :type msg: string
  428. """
  429. if not msg:
  430. return
  431. if self.logger:
  432. self.logger.info(msg)
  433. else:
  434. sys.stderr.write(str(msg))
  435. sys.stderr.flush()
  436. def msg(self, *k, **kw):
  437. """
  438. Prints a configuration message of the form ``msg: result``.
  439. The second part of the message will be in colors. The output
  440. can be disabled easily by setting ``in_msg`` to a positive value::
  441. def configure(conf):
  442. self.in_msg = 1
  443. conf.msg('Checking for library foo', 'ok')
  444. # no output
  445. :param msg: message to display to the user
  446. :type msg: string
  447. :param result: result to display
  448. :type result: string or boolean
  449. :param color: color to use, see :py:const:`waflib.Logs.colors_lst`
  450. :type color: string
  451. """
  452. try:
  453. msg = kw['msg']
  454. except KeyError:
  455. msg = k[0]
  456. self.start_msg(msg, **kw)
  457. try:
  458. result = kw['result']
  459. except KeyError:
  460. result = k[1]
  461. color = kw.get('color')
  462. if not isinstance(color, str):
  463. color = result and 'GREEN' or 'YELLOW'
  464. self.end_msg(result, color, **kw)
  465. def start_msg(self, *k, **kw):
  466. """
  467. Prints the beginning of a 'Checking for xxx' message. See :py:meth:`waflib.Context.Context.msg`
  468. """
  469. if kw.get('quiet'):
  470. return
  471. msg = kw.get('msg') or k[0]
  472. try:
  473. if self.in_msg:
  474. self.in_msg += 1
  475. return
  476. except AttributeError:
  477. self.in_msg = 0
  478. self.in_msg += 1
  479. try:
  480. self.line_just = max(self.line_just, len(msg))
  481. except AttributeError:
  482. self.line_just = max(40, len(msg))
  483. for x in (self.line_just * '-', msg):
  484. self.to_log(x)
  485. Logs.pprint('NORMAL', "%s :" % msg.ljust(self.line_just), sep='')
  486. def end_msg(self, *k, **kw):
  487. """Prints the end of a 'Checking for' message. See :py:meth:`waflib.Context.Context.msg`"""
  488. if kw.get('quiet'):
  489. return
  490. self.in_msg -= 1
  491. if self.in_msg:
  492. return
  493. result = kw.get('result') or k[0]
  494. defcolor = 'GREEN'
  495. if result is True:
  496. msg = 'ok'
  497. elif not result:
  498. msg = 'not found'
  499. defcolor = 'YELLOW'
  500. else:
  501. msg = str(result)
  502. self.to_log(msg)
  503. try:
  504. color = kw['color']
  505. except KeyError:
  506. if len(k) > 1 and k[1] in Logs.colors_lst:
  507. # compatibility waf 1.7
  508. color = k[1]
  509. else:
  510. color = defcolor
  511. Logs.pprint(color, msg)
  512. def load_special_tools(self, var, ban=[]):
  513. """
  514. Loads third-party extensions modules for certain programming languages
  515. by trying to list certain files in the extras/ directory. This method
  516. is typically called once for a programming language group, see for
  517. example :py:mod:`waflib.Tools.compiler_c`
  518. :param var: glob expression, for example 'cxx\\_\\*.py'
  519. :type var: string
  520. :param ban: list of exact file names to exclude
  521. :type ban: list of string
  522. """
  523. if os.path.isdir(waf_dir):
  524. lst = self.root.find_node(waf_dir).find_node('waflib/extras').ant_glob(var)
  525. for x in lst:
  526. if not x.name in ban:
  527. load_tool(x.name.replace('.py', ''))
  528. else:
  529. from zipfile import PyZipFile
  530. waflibs = PyZipFile(waf_dir)
  531. lst = waflibs.namelist()
  532. for x in lst:
  533. if not re.match('waflib/extras/%s' % var.replace('*', '.*'), var):
  534. continue
  535. f = os.path.basename(x)
  536. doban = False
  537. for b in ban:
  538. r = b.replace('*', '.*')
  539. if re.match(r, f):
  540. doban = True
  541. if not doban:
  542. f = f.replace('.py', '')
  543. load_tool(f)
  544. cache_modules = {}
  545. """
  546. Dictionary holding already loaded modules (wscript), indexed by their absolute path.
  547. The modules are added automatically by :py:func:`waflib.Context.load_module`
  548. """
  549. def load_module(path, encoding=None):
  550. """
  551. Loads a wscript file as a python module. This method caches results in :py:attr:`waflib.Context.cache_modules`
  552. :param path: file path
  553. :type path: string
  554. :return: Loaded Python module
  555. :rtype: module
  556. """
  557. try:
  558. return cache_modules[path]
  559. except KeyError:
  560. pass
  561. module = imp.new_module(WSCRIPT_FILE)
  562. try:
  563. code = Utils.readf(path, m='r', encoding=encoding)
  564. except EnvironmentError:
  565. raise Errors.WafError('Could not read the file %r' % path)
  566. module_dir = os.path.dirname(path)
  567. sys.path.insert(0, module_dir)
  568. try:
  569. exec(compile(code, path, 'exec'), module.__dict__)
  570. finally:
  571. sys.path.remove(module_dir)
  572. cache_modules[path] = module
  573. return module
  574. def load_tool(tool, tooldir=None, ctx=None, with_sys_path=True):
  575. """
  576. Imports a Waf tool as a python module, and stores it in the dict :py:const:`waflib.Context.Context.tools`
  577. :type tool: string
  578. :param tool: Name of the tool
  579. :type tooldir: list
  580. :param tooldir: List of directories to search for the tool module
  581. :type with_sys_path: boolean
  582. :param with_sys_path: whether or not to search the regular sys.path, besides waf_dir and potentially given tooldirs
  583. """
  584. if tool == 'java':
  585. tool = 'javaw' # jython
  586. else:
  587. tool = tool.replace('++', 'xx')
  588. if not with_sys_path:
  589. back_path = sys.path
  590. sys.path = []
  591. try:
  592. if tooldir:
  593. assert isinstance(tooldir, list)
  594. sys.path = tooldir + sys.path
  595. try:
  596. __import__(tool)
  597. except ImportError as e:
  598. e.waf_sys_path = list(sys.path)
  599. raise
  600. finally:
  601. for d in tooldir:
  602. sys.path.remove(d)
  603. ret = sys.modules[tool]
  604. Context.tools[tool] = ret
  605. return ret
  606. else:
  607. if not with_sys_path:
  608. sys.path.insert(0, waf_dir)
  609. try:
  610. for x in ('waflib.Tools.%s', 'waflib.extras.%s', 'waflib.%s', '%s'):
  611. try:
  612. __import__(x % tool)
  613. break
  614. except ImportError:
  615. x = None
  616. else: # raise an exception
  617. __import__(tool)
  618. except ImportError as e:
  619. e.waf_sys_path = list(sys.path)
  620. raise
  621. finally:
  622. if not with_sys_path:
  623. sys.path.remove(waf_dir)
  624. ret = sys.modules[x % tool]
  625. Context.tools[tool] = ret
  626. return ret
  627. finally:
  628. if not with_sys_path:
  629. sys.path += back_path