Context.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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=0x2010400
  18. """Constant updated on new releases"""
  19. WAFVERSION="2.1.4"
  20. """Constant updated on new releases"""
  21. WAFREVISION="627780cbb74b86b31016c822dcf2b0bfcbb337cb"
  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, **kw):
  151. """
  152. Loads a Waf tool as a module, and try calling the function named :py:const:`waflib.Context.Context.fun` from it.
  153. :param tool_list: list of Waf tool names to load
  154. :type tool_list: list of string or space-separated string
  155. :param tooldir: paths for the imports
  156. :type tooldir: list of string
  157. """
  158. tools = Utils.to_list(tool_list)
  159. path = Utils.to_list(kw.get('tooldir', ''))
  160. with_sys_path = kw.get('with_sys_path', True)
  161. for t in tools:
  162. module = load_tool(t, path, with_sys_path=with_sys_path)
  163. fun = getattr(module, kw.get('name', self.fun), None)
  164. if fun:
  165. fun(self)
  166. def execute(self):
  167. """
  168. Here, it calls the function name in the top-level wscript file. Most subclasses
  169. redefine this method to provide additional functionality.
  170. """
  171. self.recurse([os.path.dirname(g_module.root_path)])
  172. def pre_recurse(self, node):
  173. """
  174. Method executed immediately before a folder is read by :py:meth:`waflib.Context.Context.recurse`.
  175. The current script is bound as a Node object on ``self.cur_script``, and the current path
  176. is bound to ``self.path``
  177. :param node: script
  178. :type node: :py:class:`waflib.Node.Node`
  179. """
  180. self.stack_path.append(self.cur_script)
  181. self.cur_script = node
  182. self.path = node.parent
  183. def post_recurse(self, node):
  184. """
  185. Restores ``self.cur_script`` and ``self.path`` right after :py:meth:`waflib.Context.Context.recurse` terminates.
  186. :param node: script
  187. :type node: :py:class:`waflib.Node.Node`
  188. """
  189. self.cur_script = self.stack_path.pop()
  190. if self.cur_script:
  191. self.path = self.cur_script.parent
  192. def recurse(self, dirs, name=None, mandatory=True, once=True, encoding=None):
  193. """
  194. Runs user-provided functions from the supplied list of directories.
  195. The directories can be either absolute, or relative to the directory
  196. of the wscript file
  197. The methods :py:meth:`waflib.Context.Context.pre_recurse` and
  198. :py:meth:`waflib.Context.Context.post_recurse` are called immediately before
  199. and after a script has been executed.
  200. :param dirs: List of directories to visit
  201. :type dirs: list of string or space-separated string
  202. :param name: Name of function to invoke from the wscript
  203. :type name: string
  204. :param mandatory: whether sub wscript files are required to exist
  205. :type mandatory: bool
  206. :param once: read the script file once for a particular context
  207. :type once: bool
  208. """
  209. try:
  210. cache = self.recurse_cache
  211. except AttributeError:
  212. cache = self.recurse_cache = {}
  213. for d in Utils.to_list(dirs):
  214. if not os.path.isabs(d):
  215. # absolute paths only
  216. d = os.path.join(self.path.abspath(), d)
  217. WSCRIPT = os.path.join(d, WSCRIPT_FILE)
  218. WSCRIPT_FUN = WSCRIPT + '_' + (name or self.fun)
  219. node = self.root.find_node(WSCRIPT_FUN)
  220. if node and (not once or node not in cache):
  221. cache[node] = True
  222. self.pre_recurse(node)
  223. try:
  224. function_code = node.read('r', encoding)
  225. exec(compile(function_code, node.abspath(), 'exec'), self.exec_dict)
  226. finally:
  227. self.post_recurse(node)
  228. elif not node:
  229. node = self.root.find_node(WSCRIPT)
  230. tup = (node, name or self.fun)
  231. if node and (not once or tup not in cache):
  232. cache[tup] = True
  233. self.pre_recurse(node)
  234. try:
  235. wscript_module = load_module(node.abspath(), encoding=encoding)
  236. user_function = getattr(wscript_module, (name or self.fun), None)
  237. if not user_function:
  238. if not mandatory:
  239. continue
  240. raise Errors.WafError('No function %r defined in %s' % (name or self.fun, node.abspath()))
  241. user_function(self)
  242. finally:
  243. self.post_recurse(node)
  244. elif not node:
  245. if not mandatory:
  246. continue
  247. try:
  248. os.listdir(d)
  249. except OSError:
  250. raise Errors.WafError('Cannot read the folder %r' % d)
  251. raise Errors.WafError('No wscript file in directory %s' % d)
  252. def log_command(self, cmd, kw):
  253. if Logs.verbose:
  254. fmt = os.environ.get('WAF_CMD_FORMAT')
  255. if fmt == 'string':
  256. if not isinstance(cmd, str):
  257. cmd = Utils.shell_escape(cmd)
  258. Logs.debug('runner: %r', cmd)
  259. Logs.debug('runner_env: kw=%s', kw)
  260. def exec_command(self, cmd, **kw):
  261. """
  262. Runs an external process and returns the exit status::
  263. def run(tsk):
  264. ret = tsk.generator.bld.exec_command('touch foo.txt')
  265. return ret
  266. If the context has the attribute 'log', then captures and logs the process stderr/stdout.
  267. Unlike :py:meth:`waflib.Context.Context.cmd_and_log`, this method does not return the
  268. stdout/stderr values captured.
  269. :param cmd: command argument for subprocess.Popen
  270. :type cmd: string or list
  271. :param kw: keyword arguments for subprocess.Popen. The parameters input/timeout will be passed to wait/communicate.
  272. :type kw: dict
  273. :returns: process exit status
  274. :rtype: integer
  275. :raises: :py:class:`waflib.Errors.WafError` if an invalid executable is specified for a non-shell process
  276. :raises: :py:class:`waflib.Errors.WafError` in case of execution failure
  277. """
  278. subprocess = Utils.subprocess
  279. kw['shell'] = isinstance(cmd, str)
  280. self.log_command(cmd, kw)
  281. if self.logger:
  282. self.logger.info(cmd)
  283. if 'stdout' not in kw:
  284. kw['stdout'] = subprocess.PIPE
  285. if 'stderr' not in kw:
  286. kw['stderr'] = subprocess.PIPE
  287. if Logs.verbose and not kw['shell'] and not Utils.check_exe(cmd[0], env=kw.get('env', os.environ)):
  288. # This call isn't a shell command, and if the specified exe doesn't exist, check for a relative path being set
  289. # with cwd and if so assume the caller knows what they're doing and don't pre-emptively fail
  290. if not (cmd[0][0] == '.' and 'cwd' in kw):
  291. raise Errors.WafError('Program %s not found!' % cmd[0])
  292. cargs = {}
  293. if 'timeout' in kw:
  294. if sys.hexversion >= 0x3030000:
  295. cargs['timeout'] = kw['timeout']
  296. if not 'start_new_session' in kw:
  297. kw['start_new_session'] = True
  298. del kw['timeout']
  299. if 'input' in kw:
  300. if kw['input']:
  301. cargs['input'] = kw['input']
  302. kw['stdin'] = subprocess.PIPE
  303. del kw['input']
  304. if 'cwd' in kw:
  305. if not isinstance(kw['cwd'], str):
  306. kw['cwd'] = kw['cwd'].abspath()
  307. encoding = kw.pop('decode_as', default_encoding)
  308. try:
  309. ret, out, err = Utils.run_process(cmd, kw, cargs)
  310. except Exception as e:
  311. raise Errors.WafError('Execution failure: %s' % str(e), ex=e)
  312. if out:
  313. if not isinstance(out, str):
  314. out = out.decode(encoding, errors='replace')
  315. if self.logger:
  316. self.logger.debug('out: %s', out)
  317. else:
  318. Logs.info(out, extra={'stream':sys.stdout, 'c1': ''})
  319. if err:
  320. if not isinstance(err, str):
  321. err = err.decode(encoding, errors='replace')
  322. if self.logger:
  323. self.logger.error('err: %s' % err)
  324. else:
  325. Logs.info(err, extra={'stream':sys.stderr, 'c1': ''})
  326. return ret
  327. def cmd_and_log(self, cmd, **kw):
  328. """
  329. Executes a process and returns stdout/stderr if the execution is successful.
  330. An exception is thrown when the exit status is non-0. In that case, both stderr and stdout
  331. will be bound to the WafError object (configuration tests)::
  332. def configure(conf):
  333. out = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.STDOUT, quiet=waflib.Context.BOTH)
  334. (out, err) = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.BOTH)
  335. (out, err) = conf.cmd_and_log(cmd, input='\\n'.encode(), output=waflib.Context.STDOUT)
  336. try:
  337. conf.cmd_and_log(['which', 'someapp'], output=waflib.Context.BOTH)
  338. except Errors.WafError as e:
  339. print(e.stdout, e.stderr)
  340. :param cmd: args for subprocess.Popen
  341. :type cmd: list or string
  342. :param kw: keyword arguments for subprocess.Popen. The parameters input/timeout will be passed to wait/communicate.
  343. :type kw: dict
  344. :returns: a tuple containing the contents of stdout and stderr
  345. :rtype: string
  346. :raises: :py:class:`waflib.Errors.WafError` if an invalid executable is specified for a non-shell process
  347. :raises: :py:class:`waflib.Errors.WafError` in case of execution failure; stdout/stderr/returncode are bound to the exception object
  348. """
  349. subprocess = Utils.subprocess
  350. kw['shell'] = isinstance(cmd, str)
  351. self.log_command(cmd, kw)
  352. quiet = kw.pop('quiet', None)
  353. to_ret = kw.pop('output', STDOUT)
  354. if Logs.verbose and not kw['shell'] and not Utils.check_exe(cmd[0], env=kw.get('env', os.environ)):
  355. # This call isn't a shell command, and if the specified exe doesn't exist, check for a relative path being set
  356. # with cwd and if so assume the caller knows what they're doing and don't pre-emptively fail
  357. if not (cmd[0][0] == '.' and 'cwd' in kw):
  358. raise Errors.WafError('Program %s not found!' % cmd[0])
  359. kw['stdout'] = kw['stderr'] = subprocess.PIPE
  360. if quiet is None:
  361. self.to_log(cmd)
  362. cargs = {}
  363. if 'timeout' in kw:
  364. if sys.hexversion >= 0x3030000:
  365. cargs['timeout'] = kw['timeout']
  366. if not 'start_new_session' in kw:
  367. kw['start_new_session'] = True
  368. del kw['timeout']
  369. if 'input' in kw:
  370. if kw['input']:
  371. cargs['input'] = kw['input']
  372. kw['stdin'] = subprocess.PIPE
  373. del kw['input']
  374. if 'cwd' in kw:
  375. if not isinstance(kw['cwd'], str):
  376. kw['cwd'] = kw['cwd'].abspath()
  377. encoding = kw.pop('decode_as', default_encoding)
  378. try:
  379. ret, out, err = Utils.run_process(cmd, kw, cargs)
  380. except Exception as e:
  381. raise Errors.WafError('Execution failure: %s' % str(e), ex=e)
  382. if not isinstance(out, str):
  383. out = out.decode(encoding, errors='replace')
  384. if not isinstance(err, str):
  385. err = err.decode(encoding, errors='replace')
  386. if out and quiet != STDOUT and quiet != BOTH:
  387. self.to_log('out: %s' % out)
  388. if err and quiet != STDERR and quiet != BOTH:
  389. self.to_log('err: %s' % err)
  390. if ret:
  391. e = Errors.WafError('Command %r returned %r' % (cmd, ret))
  392. e.returncode = ret
  393. e.stderr = err
  394. e.stdout = out
  395. raise e
  396. if to_ret == BOTH:
  397. return (out, err)
  398. elif to_ret == STDERR:
  399. return err
  400. return out
  401. def fatal(self, msg, ex=None):
  402. """
  403. Prints an error message in red and stops command execution; this is
  404. usually used in the configuration section::
  405. def configure(conf):
  406. conf.fatal('a requirement is missing')
  407. :param msg: message to display
  408. :type msg: string
  409. :param ex: optional exception object
  410. :type ex: exception
  411. :raises: :py:class:`waflib.Errors.ConfigurationError`
  412. """
  413. if self.logger:
  414. self.logger.info('from %s: %s' % (self.path.abspath(), msg))
  415. try:
  416. logfile = self.logger.handlers[0].baseFilename
  417. except AttributeError:
  418. pass
  419. else:
  420. if os.environ.get('WAF_PRINT_FAILURE_LOG'):
  421. # see #1930
  422. msg = 'Log from (%s):\n%s\n' % (logfile, Utils.readf(logfile))
  423. else:
  424. msg = '%s\n(complete log in %s)' % (msg, logfile)
  425. raise self.errors.ConfigurationError(msg, ex=ex)
  426. def to_log(self, msg):
  427. """
  428. Logs information to the logger (if present), or to stderr.
  429. Empty messages are not printed::
  430. def build(bld):
  431. bld.to_log('starting the build')
  432. Provide a logger on the context class or override this method if necessary.
  433. :param msg: message
  434. :type msg: string
  435. """
  436. if not msg:
  437. return
  438. if self.logger:
  439. self.logger.info(msg)
  440. else:
  441. sys.stderr.write(str(msg))
  442. sys.stderr.flush()
  443. def msg(self, *k, **kw):
  444. """
  445. Prints a configuration message of the form ``msg: result``.
  446. The second part of the message will be in colors. The output
  447. can be disabled easily by setting ``in_msg`` to a positive value::
  448. def configure(conf):
  449. self.in_msg = 1
  450. conf.msg('Checking for library foo', 'ok')
  451. # no output
  452. :param msg: message to display to the user
  453. :type msg: string
  454. :param result: result to display
  455. :type result: string or boolean
  456. :param color: color to use, see :py:const:`waflib.Logs.colors_lst`
  457. :type color: string
  458. """
  459. try:
  460. msg = kw['msg']
  461. except KeyError:
  462. msg = k[0]
  463. self.start_msg(msg, **kw)
  464. try:
  465. result = kw['result']
  466. except KeyError:
  467. result = k[1]
  468. color = kw.get('color')
  469. if not isinstance(color, str):
  470. color = result and 'GREEN' or 'YELLOW'
  471. self.end_msg(result, color, **kw)
  472. def start_msg(self, *k, **kw):
  473. """
  474. Prints the beginning of a 'Checking for xxx' message. See :py:meth:`waflib.Context.Context.msg`
  475. """
  476. if kw.get('quiet'):
  477. return
  478. msg = kw.get('msg') or k[0]
  479. try:
  480. if self.in_msg:
  481. self.in_msg += 1
  482. return
  483. except AttributeError:
  484. self.in_msg = 0
  485. self.in_msg += 1
  486. try:
  487. self.line_just = max(self.line_just, len(msg))
  488. except AttributeError:
  489. self.line_just = max(40, len(msg))
  490. for x in (self.line_just * '-', msg):
  491. self.to_log(x)
  492. Logs.pprint('NORMAL', "%s :" % msg.ljust(self.line_just), sep='')
  493. def end_msg(self, *k, **kw):
  494. """Prints the end of a 'Checking for' message. See :py:meth:`waflib.Context.Context.msg`"""
  495. if kw.get('quiet'):
  496. return
  497. self.in_msg -= 1
  498. if self.in_msg:
  499. return
  500. result = kw.get('result') or k[0]
  501. defcolor = 'GREEN'
  502. if result is True:
  503. msg = 'ok'
  504. elif not result:
  505. msg = 'not found'
  506. defcolor = 'YELLOW'
  507. else:
  508. msg = str(result)
  509. self.to_log(msg)
  510. try:
  511. color = kw['color']
  512. except KeyError:
  513. if len(k) > 1 and k[1] in Logs.colors_lst:
  514. # compatibility waf 1.7
  515. color = k[1]
  516. else:
  517. color = defcolor
  518. Logs.pprint(color, msg)
  519. def load_special_tools(self, var, ban=[]):
  520. """
  521. Loads third-party extensions modules for certain programming languages
  522. by trying to list certain files in the extras/ directory. This method
  523. is typically called once for a programming language group, see for
  524. example :py:mod:`waflib.Tools.compiler_c`
  525. :param var: glob expression, for example 'cxx\\_\\*.py'
  526. :type var: string
  527. :param ban: list of exact file names to exclude
  528. :type ban: list of string
  529. """
  530. if os.path.isdir(waf_dir):
  531. lst = self.root.find_node(waf_dir).find_node('waflib/extras').ant_glob(var)
  532. for x in lst:
  533. if not x.name in ban:
  534. load_tool(x.name.replace('.py', ''))
  535. else:
  536. from zipfile import PyZipFile
  537. waflibs = PyZipFile(waf_dir)
  538. lst = waflibs.namelist()
  539. for x in lst:
  540. if not re.match('waflib/extras/%s' % var.replace('*', '.*'), var):
  541. continue
  542. f = os.path.basename(x)
  543. doban = False
  544. for b in ban:
  545. r = b.replace('*', '.*')
  546. if re.match(r, f):
  547. doban = True
  548. if not doban:
  549. f = f.replace('.py', '')
  550. load_tool(f)
  551. cache_modules = {}
  552. """
  553. Dictionary holding already loaded modules (wscript), indexed by their absolute path.
  554. The modules are added automatically by :py:func:`waflib.Context.load_module`
  555. """
  556. def load_module(path, encoding=None):
  557. """
  558. Loads a wscript file as a python module. This method caches results in :py:attr:`waflib.Context.cache_modules`
  559. :param path: file path
  560. :type path: string
  561. :return: Loaded Python module
  562. :rtype: module
  563. """
  564. try:
  565. return cache_modules[path]
  566. except KeyError:
  567. pass
  568. module = imp.new_module(WSCRIPT_FILE)
  569. try:
  570. code = Utils.readf(path, m='r', encoding=encoding)
  571. except EnvironmentError:
  572. raise Errors.WafError('Could not read the file %r' % path)
  573. module_dir = os.path.dirname(path)
  574. sys.path.insert(0, module_dir)
  575. try:
  576. exec(compile(code, path, 'exec'), module.__dict__)
  577. finally:
  578. sys.path.remove(module_dir)
  579. cache_modules[path] = module
  580. return module
  581. def load_tool(tool, tooldir=None, ctx=None, with_sys_path=True):
  582. """
  583. Imports a Waf tool as a python module, and stores it in the dict :py:const:`waflib.Context.Context.tools`
  584. :type tool: string
  585. :param tool: Name of the tool
  586. :type tooldir: list
  587. :param tooldir: List of directories to search for the tool module
  588. :type with_sys_path: boolean
  589. :param with_sys_path: whether or not to search the regular sys.path, besides waf_dir and potentially given tooldirs
  590. """
  591. if tool == 'java':
  592. tool = 'javaw' # jython
  593. else:
  594. tool = tool.replace('++', 'xx')
  595. if not with_sys_path:
  596. back_path = sys.path
  597. sys.path = []
  598. try:
  599. if tooldir:
  600. assert isinstance(tooldir, list)
  601. sys.path = tooldir + sys.path
  602. try:
  603. __import__(tool)
  604. except ImportError as e:
  605. e.waf_sys_path = list(sys.path)
  606. raise
  607. finally:
  608. for d in tooldir:
  609. sys.path.remove(d)
  610. ret = sys.modules[tool]
  611. Context.tools[tool] = ret
  612. return ret
  613. else:
  614. if not with_sys_path:
  615. sys.path.insert(0, waf_dir)
  616. try:
  617. for x in ('waflib.Tools.%s', 'waflib.extras.%s', 'waflib.%s', '%s'):
  618. try:
  619. __import__(x % tool)
  620. break
  621. except ImportError:
  622. x = None
  623. else: # raise an exception
  624. __import__(tool)
  625. except ImportError as e:
  626. e.waf_sys_path = list(sys.path)
  627. raise
  628. finally:
  629. if not with_sys_path:
  630. sys.path.remove(waf_dir)
  631. ret = sys.modules[x % tool]
  632. Context.tools[tool] = ret
  633. return ret
  634. finally:
  635. if not with_sys_path:
  636. sys.path += back_path