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.

672 lines
18KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2010 (ita)
  4. """
  5. Configuration system
  6. A :py:class:`waflib.Configure.ConfigurationContext` instance is created when ``waf configure`` is called, it is used to:
  7. * create data dictionaries (ConfigSet instances)
  8. * store the list of modules to import
  9. * hold configuration routines such as ``find_program``, etc
  10. """
  11. import os, shlex, sys, time, re, shutil
  12. from waflib import ConfigSet, Utils, Options, Logs, Context, Build, Errors
  13. BREAK = 'break'
  14. """In case of a configuration error, break"""
  15. CONTINUE = 'continue'
  16. """In case of a configuration error, continue"""
  17. WAF_CONFIG_LOG = 'config.log'
  18. """Name of the configuration log file"""
  19. autoconfig = False
  20. """Execute the configuration automatically"""
  21. conf_template = '''# project %(app)s configured on %(now)s by
  22. # waf %(wafver)s (abi %(abi)s, python %(pyver)x on %(systype)s)
  23. # using %(args)s
  24. #'''
  25. class ConfigurationContext(Context.Context):
  26. '''configures the project'''
  27. cmd = 'configure'
  28. error_handlers = []
  29. """
  30. Additional functions to handle configuration errors
  31. """
  32. def __init__(self, **kw):
  33. super(ConfigurationContext, self).__init__(**kw)
  34. self.environ = dict(os.environ)
  35. self.all_envs = {}
  36. self.top_dir = None
  37. self.out_dir = None
  38. self.tools = [] # tools loaded in the configuration, and that will be loaded when building
  39. self.hash = 0
  40. self.files = []
  41. self.tool_cache = []
  42. self.setenv('')
  43. def setenv(self, name, env=None):
  44. """
  45. Set a new config set for conf.env. If a config set of that name already exists,
  46. recall it without modification.
  47. The name is the filename prefix to save to ``c4che/NAME_cache.py``, and it
  48. is also used as *variants* by the build commands.
  49. Though related to variants, whatever kind of data may be stored in the config set::
  50. def configure(cfg):
  51. cfg.env.ONE = 1
  52. cfg.setenv('foo')
  53. cfg.env.ONE = 2
  54. def build(bld):
  55. 2 == bld.env_of_name('foo').ONE
  56. :param name: name of the configuration set
  57. :type name: string
  58. :param env: ConfigSet to copy, or an empty ConfigSet is created
  59. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  60. """
  61. if name not in self.all_envs or env:
  62. if not env:
  63. env = ConfigSet.ConfigSet()
  64. self.prepare_env(env)
  65. else:
  66. env = env.derive()
  67. self.all_envs[name] = env
  68. self.variant = name
  69. def get_env(self):
  70. """Getter for the env property"""
  71. return self.all_envs[self.variant]
  72. def set_env(self, val):
  73. """Setter for the env property"""
  74. self.all_envs[self.variant] = val
  75. env = property(get_env, set_env)
  76. def init_dirs(self):
  77. """
  78. Initialize the project directory and the build directory
  79. """
  80. top = self.top_dir
  81. if not top:
  82. top = Options.options.top
  83. if not top:
  84. top = getattr(Context.g_module, Context.TOP, None)
  85. if not top:
  86. top = self.path.abspath()
  87. top = os.path.abspath(top)
  88. self.srcnode = (os.path.isabs(top) and self.root or self.path).find_dir(top)
  89. assert(self.srcnode)
  90. out = self.out_dir
  91. if not out:
  92. out = Options.options.out
  93. if not out:
  94. out = getattr(Context.g_module, Context.OUT, None)
  95. if not out:
  96. out = Options.lockfile.replace('.lock-waf_%s_' % sys.platform, '').replace('.lock-waf', '')
  97. # someone can be messing with symlinks
  98. out = os.path.realpath(out)
  99. self.bldnode = (os.path.isabs(out) and self.root or self.path).make_node(out)
  100. self.bldnode.mkdir()
  101. if not os.path.isdir(self.bldnode.abspath()):
  102. conf.fatal('Could not create the build directory %s' % self.bldnode.abspath())
  103. def execute(self):
  104. """
  105. See :py:func:`waflib.Context.Context.execute`
  106. """
  107. self.init_dirs()
  108. self.cachedir = self.bldnode.make_node(Build.CACHE_DIR)
  109. self.cachedir.mkdir()
  110. path = os.path.join(self.bldnode.abspath(), WAF_CONFIG_LOG)
  111. self.logger = Logs.make_logger(path, 'cfg')
  112. app = getattr(Context.g_module, 'APPNAME', '')
  113. if app:
  114. ver = getattr(Context.g_module, 'VERSION', '')
  115. if ver:
  116. app = "%s (%s)" % (app, ver)
  117. now = time.ctime()
  118. pyver = sys.hexversion
  119. systype = sys.platform
  120. args = " ".join(sys.argv)
  121. wafver = Context.WAFVERSION
  122. abi = Context.ABI
  123. self.to_log(conf_template % vars())
  124. self.msg('Setting top to', self.srcnode.abspath())
  125. self.msg('Setting out to', self.bldnode.abspath())
  126. if id(self.srcnode) == id(self.bldnode):
  127. Logs.warn('Setting top == out (remember to use "update_outputs")')
  128. elif id(self.path) != id(self.srcnode):
  129. if self.srcnode.is_child_of(self.path):
  130. Logs.warn('Are you certain that you do not want to set top="." ?')
  131. super(ConfigurationContext, self).execute()
  132. self.store()
  133. Context.top_dir = self.srcnode.abspath()
  134. Context.out_dir = self.bldnode.abspath()
  135. # this will write a configure lock so that subsequent builds will
  136. # consider the current path as the root directory (see prepare_impl).
  137. # to remove: use 'waf distclean'
  138. env = ConfigSet.ConfigSet()
  139. env['argv'] = sys.argv
  140. env['options'] = Options.options.__dict__
  141. env.run_dir = Context.run_dir
  142. env.top_dir = Context.top_dir
  143. env.out_dir = Context.out_dir
  144. # conf.hash & conf.files hold wscript files paths and hash
  145. # (used only by Configure.autoconfig)
  146. env['hash'] = self.hash
  147. env['files'] = self.files
  148. env['environ'] = dict(self.environ)
  149. if not self.env.NO_LOCK_IN_RUN and not getattr(Options.options, 'no_lock_in_run'):
  150. env.store(os.path.join(Context.run_dir, Options.lockfile))
  151. if not self.env.NO_LOCK_IN_TOP and not getattr(Options.options, 'no_lock_in_top'):
  152. env.store(os.path.join(Context.top_dir, Options.lockfile))
  153. if not self.env.NO_LOCK_IN_OUT and not getattr(Options.options, 'no_lock_in_out'):
  154. env.store(os.path.join(Context.out_dir, Options.lockfile))
  155. def prepare_env(self, env):
  156. """
  157. Insert *PREFIX*, *BINDIR* and *LIBDIR* values into ``env``
  158. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  159. :param env: a ConfigSet, usually ``conf.env``
  160. """
  161. if not env.PREFIX:
  162. if Options.options.prefix or Utils.is_win32:
  163. env.PREFIX = os.path.abspath(os.path.expanduser(Options.options.prefix))
  164. else:
  165. env.PREFIX = ''
  166. if not env.BINDIR:
  167. if Options.options.bindir:
  168. env.BINDIR = os.path.abspath(os.path.expanduser(Options.options.bindir))
  169. else:
  170. env.BINDIR = Utils.subst_vars('${PREFIX}/bin', env)
  171. if not env.LIBDIR:
  172. if Options.options.libdir:
  173. env.LIBDIR = os.path.abspath(os.path.expanduser(Options.options.libdir))
  174. else:
  175. env.LIBDIR = Utils.subst_vars('${PREFIX}/lib%s' % Utils.lib64(), env)
  176. def store(self):
  177. """Save the config results into the cache file"""
  178. n = self.cachedir.make_node('build.config.py')
  179. n.write('version = 0x%x\ntools = %r\n' % (Context.HEXVERSION, self.tools))
  180. if not self.all_envs:
  181. self.fatal('nothing to store in the configuration context!')
  182. for key in self.all_envs:
  183. tmpenv = self.all_envs[key]
  184. tmpenv.store(os.path.join(self.cachedir.abspath(), key + Build.CACHE_SUFFIX))
  185. def load(self, input, tooldir=None, funs=None, with_sys_path=True):
  186. """
  187. Load Waf tools, which will be imported whenever a build is started.
  188. :param input: waf tools to import
  189. :type input: list of string
  190. :param tooldir: paths for the imports
  191. :type tooldir: list of string
  192. :param funs: functions to execute from the waf tools
  193. :type funs: list of string
  194. """
  195. tools = Utils.to_list(input)
  196. if tooldir: tooldir = Utils.to_list(tooldir)
  197. for tool in tools:
  198. # avoid loading the same tool more than once with the same functions
  199. # used by composite projects
  200. mag = (tool, id(self.env), tooldir, funs)
  201. if mag in self.tool_cache:
  202. self.to_log('(tool %s is already loaded, skipping)' % tool)
  203. continue
  204. self.tool_cache.append(mag)
  205. module = None
  206. try:
  207. module = Context.load_tool(tool, tooldir, ctx=self, with_sys_path=with_sys_path)
  208. except ImportError as e:
  209. self.fatal('Could not load the Waf tool %r from %r\n%s' % (tool, sys.path, e))
  210. except Exception as e:
  211. self.to_log('imp %r (%r & %r)' % (tool, tooldir, funs))
  212. self.to_log(Utils.ex_stack())
  213. raise
  214. if funs is not None:
  215. self.eval_rules(funs)
  216. else:
  217. func = getattr(module, 'configure', None)
  218. if func:
  219. if type(func) is type(Utils.readf): func(self)
  220. else: self.eval_rules(func)
  221. self.tools.append({'tool':tool, 'tooldir':tooldir, 'funs':funs})
  222. def post_recurse(self, node):
  223. """
  224. Records the path and a hash of the scripts visited, see :py:meth:`waflib.Context.Context.post_recurse`
  225. :param node: script
  226. :type node: :py:class:`waflib.Node.Node`
  227. """
  228. super(ConfigurationContext, self).post_recurse(node)
  229. self.hash = Utils.h_list((self.hash, node.read('rb')))
  230. self.files.append(node.abspath())
  231. def eval_rules(self, rules):
  232. """
  233. Execute the configuration tests. The method :py:meth:`waflib.Configure.ConfigurationContext.err_handler`
  234. is used to process the eventual exceptions
  235. :param rules: list of configuration method names
  236. :type rules: list of string
  237. """
  238. self.rules = Utils.to_list(rules)
  239. for x in self.rules:
  240. f = getattr(self, x)
  241. if not f: self.fatal("No such method '%s'." % x)
  242. try:
  243. f()
  244. except Exception as e:
  245. ret = self.err_handler(x, e)
  246. if ret == BREAK:
  247. break
  248. elif ret == CONTINUE:
  249. continue
  250. else:
  251. raise
  252. def err_handler(self, fun, error):
  253. """
  254. Error handler for the configuration tests, the default is to let the exception raise
  255. :param fun: configuration test
  256. :type fun: method
  257. :param error: exception
  258. :type error: exception
  259. """
  260. pass
  261. def conf(f):
  262. """
  263. Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
  264. :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
  265. named 'mandatory' to disable the configuration errors::
  266. def configure(conf):
  267. conf.find_program('abc', mandatory=False)
  268. :param f: method to bind
  269. :type f: function
  270. """
  271. def fun(*k, **kw):
  272. mandatory = True
  273. if 'mandatory' in kw:
  274. mandatory = kw['mandatory']
  275. del kw['mandatory']
  276. try:
  277. return f(*k, **kw)
  278. except Errors.ConfigurationError:
  279. if mandatory:
  280. raise
  281. setattr(ConfigurationContext, f.__name__, fun)
  282. setattr(Build.BuildContext, f.__name__, fun)
  283. return f
  284. @conf
  285. def add_os_flags(self, var, dest=None, dup=True):
  286. """
  287. Import operating system environment values into ``conf.env`` dict::
  288. def configure(conf):
  289. conf.add_os_flags('CFLAGS')
  290. :param var: variable to use
  291. :type var: string
  292. :param dest: destination variable, by default the same as var
  293. :type dest: string
  294. :param dup: add the same set of flags again
  295. :type dup: bool
  296. """
  297. try:
  298. flags = shlex.split(self.environ[var])
  299. except KeyError:
  300. return
  301. # TODO: in waf 1.9, make dup=False the default
  302. if dup or ''.join(flags) not in ''.join(Utils.to_list(self.env[dest or var])):
  303. self.env.append_value(dest or var, flags)
  304. @conf
  305. def cmd_to_list(self, cmd):
  306. """
  307. Detect if a command is written in pseudo shell like ``ccache g++`` and return a list.
  308. :param cmd: command
  309. :type cmd: a string or a list of string
  310. """
  311. if isinstance(cmd, str) and cmd.find(' '):
  312. try:
  313. os.stat(cmd)
  314. except OSError:
  315. return shlex.split(cmd)
  316. else:
  317. return [cmd]
  318. return cmd
  319. @conf
  320. def check_waf_version(self, mini='1.7.99', maxi='1.9.0', **kw):
  321. """
  322. Raise a Configuration error if the Waf version does not strictly match the given bounds::
  323. conf.check_waf_version(mini='1.8.0', maxi='1.9.0')
  324. :type mini: number, tuple or string
  325. :param mini: Minimum required version
  326. :type maxi: number, tuple or string
  327. :param maxi: Maximum allowed version
  328. """
  329. self.start_msg('Checking for waf version in %s-%s' % (str(mini), str(maxi)), **kw)
  330. ver = Context.HEXVERSION
  331. if Utils.num2ver(mini) > ver:
  332. self.fatal('waf version should be at least %r (%r found)' % (Utils.num2ver(mini), ver))
  333. if Utils.num2ver(maxi) < ver:
  334. self.fatal('waf version should be at most %r (%r found)' % (Utils.num2ver(maxi), ver))
  335. self.end_msg('ok', **kw)
  336. @conf
  337. def find_file(self, filename, path_list=[]):
  338. """
  339. Find a file in a list of paths
  340. :param filename: name of the file to search for
  341. :param path_list: list of directories to search
  342. :return: the first occurrence filename or '' if filename could not be found
  343. """
  344. for n in Utils.to_list(filename):
  345. for d in Utils.to_list(path_list):
  346. p = os.path.join(d, n)
  347. if os.path.exists(p):
  348. return p
  349. self.fatal('Could not find %r' % filename)
  350. @conf
  351. def find_program(self, filename, **kw):
  352. """
  353. Search for a program on the operating system
  354. When var is used, you may set os.environ[var] to help find a specific program version, for example::
  355. $ CC='ccache gcc' waf configure
  356. :param path_list: paths to use for searching
  357. :type param_list: list of string
  358. :param var: store the result to conf.env[var], by default use filename.upper()
  359. :type var: string
  360. :param ext: list of extensions for the binary (do not add an extension for portability)
  361. :type ext: list of string
  362. :param msg: name to display in the log, by default filename is used
  363. :type msg: string
  364. :param interpreter: interpreter for the program
  365. :type interpreter: ConfigSet variable key
  366. """
  367. exts = kw.get('exts', Utils.is_win32 and '.exe,.com,.bat,.cmd' or ',.sh,.pl,.py')
  368. environ = kw.get('environ', getattr(self, 'environ', os.environ))
  369. ret = ''
  370. filename = Utils.to_list(filename)
  371. msg = kw.get('msg', ', '.join(filename))
  372. var = kw.get('var', '')
  373. if not var:
  374. var = re.sub(r'[-.]', '_', filename[0].upper())
  375. path_list = kw.get('path_list', '')
  376. if path_list:
  377. path_list = Utils.to_list(path_list)
  378. else:
  379. path_list = environ.get('PATH', '').split(os.pathsep)
  380. if var in environ:
  381. filename = environ[var]
  382. if os.path.isfile(filename):
  383. # typical CC=/usr/bin/gcc waf configure build
  384. ret = [filename]
  385. else:
  386. # case CC='ccache gcc' waf configure build
  387. ret = self.cmd_to_list(filename)
  388. elif self.env[var]:
  389. # set by the user in the wscript file
  390. ret = self.env[var]
  391. ret = self.cmd_to_list(ret)
  392. else:
  393. if not ret:
  394. ret = self.find_binary(filename, exts.split(','), path_list)
  395. if not ret and Utils.winreg:
  396. ret = Utils.get_registry_app_path(Utils.winreg.HKEY_CURRENT_USER, filename)
  397. if not ret and Utils.winreg:
  398. ret = Utils.get_registry_app_path(Utils.winreg.HKEY_LOCAL_MACHINE, filename)
  399. ret = self.cmd_to_list(ret)
  400. if ret:
  401. if len(ret) == 1:
  402. retmsg = ret[0]
  403. else:
  404. retmsg = ret
  405. else:
  406. retmsg = False
  407. self.msg("Checking for program '%s'" % msg, retmsg, **kw)
  408. if not kw.get('quiet', None):
  409. self.to_log('find program=%r paths=%r var=%r -> %r' % (filename, path_list, var, ret))
  410. if not ret:
  411. self.fatal(kw.get('errmsg', '') or 'Could not find the program %r' % filename)
  412. interpreter = kw.get('interpreter', None)
  413. if interpreter is None:
  414. if not Utils.check_exe(ret[0], env=environ):
  415. self.fatal('Program %r is not executable' % ret)
  416. self.env[var] = ret
  417. else:
  418. self.env[var] = self.env[interpreter] + ret
  419. return ret
  420. @conf
  421. def find_binary(self, filenames, exts, paths):
  422. for f in filenames:
  423. for ext in exts:
  424. exe_name = f + ext
  425. if os.path.isabs(exe_name):
  426. if os.path.isfile(exe_name):
  427. return exe_name
  428. else:
  429. for path in paths:
  430. x = os.path.expanduser(os.path.join(path, exe_name))
  431. if os.path.isfile(x):
  432. return x
  433. return None
  434. @conf
  435. def run_build(self, *k, **kw):
  436. """
  437. Create a temporary build context to execute a build. A reference to that build
  438. context is kept on self.test_bld for debugging purposes, and you should not rely
  439. on it too much (read the note on the cache below).
  440. The parameters given in the arguments to this function are passed as arguments for
  441. a single task generator created in the build. Only three parameters are obligatory:
  442. :param features: features to pass to a task generator created in the build
  443. :type features: list of string
  444. :param compile_filename: file to create for the compilation (default: *test.c*)
  445. :type compile_filename: string
  446. :param code: code to write in the filename to compile
  447. :type code: string
  448. Though this function returns *0* by default, the build may set an attribute named *retval* on the
  449. build context object to return a particular value. See :py:func:`waflib.Tools.c_config.test_exec_fun` for example.
  450. This function also provides a limited cache. To use it, provide the following option::
  451. def options(opt):
  452. opt.add_option('--confcache', dest='confcache', default=0,
  453. action='count', help='Use a configuration cache')
  454. And execute the configuration with the following command-line::
  455. $ waf configure --confcache
  456. """
  457. lst = [str(v) for (p, v) in kw.items() if p != 'env']
  458. h = Utils.h_list(lst)
  459. dir = self.bldnode.abspath() + os.sep + (not Utils.is_win32 and '.' or '') + 'conf_check_' + Utils.to_hex(h)
  460. try:
  461. os.makedirs(dir)
  462. except OSError:
  463. pass
  464. try:
  465. os.stat(dir)
  466. except OSError:
  467. self.fatal('cannot use the configuration test folder %r' % dir)
  468. cachemode = getattr(Options.options, 'confcache', None)
  469. if cachemode == 1:
  470. try:
  471. proj = ConfigSet.ConfigSet(os.path.join(dir, 'cache_run_build'))
  472. except OSError:
  473. pass
  474. except IOError:
  475. pass
  476. else:
  477. ret = proj['cache_run_build']
  478. if isinstance(ret, str) and ret.startswith('Test does not build'):
  479. self.fatal(ret)
  480. return ret
  481. bdir = os.path.join(dir, 'testbuild')
  482. if not os.path.exists(bdir):
  483. os.makedirs(bdir)
  484. self.test_bld = bld = Build.BuildContext(top_dir=dir, out_dir=bdir)
  485. bld.init_dirs()
  486. bld.progress_bar = 0
  487. bld.targets = '*'
  488. bld.logger = self.logger
  489. bld.all_envs.update(self.all_envs) # not really necessary
  490. bld.env = kw['env']
  491. # OMG huge hack
  492. bld.kw = kw
  493. bld.conf = self
  494. kw['build_fun'](bld)
  495. ret = -1
  496. try:
  497. try:
  498. bld.compile()
  499. except Errors.WafError:
  500. ret = 'Test does not build: %s' % Utils.ex_stack()
  501. self.fatal(ret)
  502. else:
  503. ret = getattr(bld, 'retval', 0)
  504. finally:
  505. if cachemode == 1:
  506. # cache the results each time
  507. proj = ConfigSet.ConfigSet()
  508. proj['cache_run_build'] = ret
  509. proj.store(os.path.join(dir, 'cache_run_build'))
  510. else:
  511. shutil.rmtree(dir)
  512. return ret
  513. @conf
  514. def ret_msg(self, msg, args):
  515. if isinstance(msg, str):
  516. return msg
  517. return msg(args)
  518. @conf
  519. def test(self, *k, **kw):
  520. if not 'env' in kw:
  521. kw['env'] = self.env.derive()
  522. # validate_c for example
  523. if kw.get('validate', None):
  524. kw['validate'](kw)
  525. self.start_msg(kw['msg'], **kw)
  526. ret = None
  527. try:
  528. ret = self.run_build(*k, **kw)
  529. except self.errors.ConfigurationError:
  530. self.end_msg(kw['errmsg'], 'YELLOW', **kw)
  531. if Logs.verbose > 1:
  532. raise
  533. else:
  534. self.fatal('The configuration failed')
  535. else:
  536. kw['success'] = ret
  537. if kw.get('post_check', None):
  538. ret = kw['post_check'](kw)
  539. if ret:
  540. self.end_msg(kw['errmsg'], 'YELLOW', **kw)
  541. self.fatal('The configuration failed %r' % ret)
  542. else:
  543. self.end_msg(self.ret_msg(kw['okmsg'], kw), **kw)
  544. return ret