Context.py 21 KB

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