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.

666 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:
  150. env.store(os.path.join(Context.run_dir, Options.lockfile))
  151. if not self.env.NO_LOCK_IN_TOP:
  152. env.store(os.path.join(Context.top_dir, Options.lockfile))
  153. if not self.env.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):
  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), 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)
  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):
  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. """
  295. # do not use 'get' to make certain the variable is not defined
  296. try: self.env.append_value(dest or var, shlex.split(self.environ[var]))
  297. except KeyError: pass
  298. @conf
  299. def cmd_to_list(self, cmd):
  300. """
  301. Detect if a command is written in pseudo shell like ``ccache g++`` and return a list.
  302. :param cmd: command
  303. :type cmd: a string or a list of string
  304. """
  305. if isinstance(cmd, str) and cmd.find(' '):
  306. try:
  307. os.stat(cmd)
  308. except OSError:
  309. return shlex.split(cmd)
  310. else:
  311. return [cmd]
  312. return cmd
  313. @conf
  314. def check_waf_version(self, mini='1.7.99', maxi='1.9.0', **kw):
  315. """
  316. Raise a Configuration error if the Waf version does not strictly match the given bounds::
  317. conf.check_waf_version(mini='1.8.0', maxi='1.9.0')
  318. :type mini: number, tuple or string
  319. :param mini: Minimum required version
  320. :type maxi: number, tuple or string
  321. :param maxi: Maximum allowed version
  322. """
  323. self.start_msg('Checking for waf version in %s-%s' % (str(mini), str(maxi)), **kw)
  324. ver = Context.HEXVERSION
  325. if Utils.num2ver(mini) > ver:
  326. self.fatal('waf version should be at least %r (%r found)' % (Utils.num2ver(mini), ver))
  327. if Utils.num2ver(maxi) < ver:
  328. self.fatal('waf version should be at most %r (%r found)' % (Utils.num2ver(maxi), ver))
  329. self.end_msg('ok', **kw)
  330. @conf
  331. def find_file(self, filename, path_list=[]):
  332. """
  333. Find a file in a list of paths
  334. :param filename: name of the file to search for
  335. :param path_list: list of directories to search
  336. :return: the first occurrence filename or '' if filename could not be found
  337. """
  338. for n in Utils.to_list(filename):
  339. for d in Utils.to_list(path_list):
  340. p = os.path.join(d, n)
  341. if os.path.exists(p):
  342. return p
  343. self.fatal('Could not find %r' % filename)
  344. @conf
  345. def find_program(self, filename, **kw):
  346. """
  347. Search for a program on the operating system
  348. When var is used, you may set os.environ[var] to help find a specific program version, for example::
  349. $ CC='ccache gcc' waf configure
  350. :param path_list: paths to use for searching
  351. :type param_list: list of string
  352. :param var: store the result to conf.env[var], by default use filename.upper()
  353. :type var: string
  354. :param ext: list of extensions for the binary (do not add an extension for portability)
  355. :type ext: list of string
  356. :param msg: name to display in the log, by default filename is used
  357. :type msg: string
  358. :param interpreter: interpreter for the program
  359. :type interpreter: ConfigSet variable key
  360. """
  361. exts = kw.get('exts', Utils.is_win32 and '.exe,.com,.bat,.cmd' or ',.sh,.pl,.py')
  362. environ = kw.get('environ', getattr(self, 'environ', os.environ))
  363. ret = ''
  364. filename = Utils.to_list(filename)
  365. msg = kw.get('msg', ', '.join(filename))
  366. var = kw.get('var', '')
  367. if not var:
  368. var = re.sub(r'[-.]', '_', filename[0].upper())
  369. path_list = kw.get('path_list', '')
  370. if path_list:
  371. path_list = Utils.to_list(path_list)
  372. else:
  373. path_list = environ.get('PATH', '').split(os.pathsep)
  374. if var in environ:
  375. filename = environ[var]
  376. if os.path.isfile(filename):
  377. # typical CC=/usr/bin/gcc waf configure build
  378. ret = [filename]
  379. else:
  380. # case CC='ccache gcc' waf configure build
  381. ret = self.cmd_to_list(filename)
  382. elif self.env[var]:
  383. # set by the user in the wscript file
  384. ret = self.env[var]
  385. ret = self.cmd_to_list(ret)
  386. else:
  387. if not ret:
  388. ret = self.find_binary(filename, exts.split(','), path_list)
  389. if not ret and Utils.winreg:
  390. ret = Utils.get_registry_app_path(Utils.winreg.HKEY_CURRENT_USER, filename)
  391. if not ret and Utils.winreg:
  392. ret = Utils.get_registry_app_path(Utils.winreg.HKEY_LOCAL_MACHINE, filename)
  393. ret = self.cmd_to_list(ret)
  394. if ret:
  395. if len(ret) == 1:
  396. retmsg = ret[0]
  397. else:
  398. retmsg = ret
  399. else:
  400. retmsg = False
  401. self.msg("Checking for program '%s'" % msg, retmsg, **kw)
  402. if not kw.get('quiet', None):
  403. self.to_log('find program=%r paths=%r var=%r -> %r' % (filename, path_list, var, ret))
  404. if not ret:
  405. self.fatal(kw.get('errmsg', '') or 'Could not find the program %r' % filename)
  406. interpreter = kw.get('interpreter', None)
  407. if interpreter is None:
  408. if not Utils.check_exe(ret[0], env=environ):
  409. self.fatal('Program %r is not executable' % ret)
  410. self.env[var] = ret
  411. else:
  412. self.env[var] = self.env[interpreter] + ret
  413. return ret
  414. @conf
  415. def find_binary(self, filenames, exts, paths):
  416. for f in filenames:
  417. for ext in exts:
  418. exe_name = f + ext
  419. if os.path.isabs(exe_name):
  420. if os.path.isfile(exe_name):
  421. return exe_name
  422. else:
  423. for path in paths:
  424. x = os.path.expanduser(os.path.join(path, exe_name))
  425. if os.path.isfile(x):
  426. return x
  427. return None
  428. @conf
  429. def run_build(self, *k, **kw):
  430. """
  431. Create a temporary build context to execute a build. A reference to that build
  432. context is kept on self.test_bld for debugging purposes, and you should not rely
  433. on it too much (read the note on the cache below).
  434. The parameters given in the arguments to this function are passed as arguments for
  435. a single task generator created in the build. Only three parameters are obligatory:
  436. :param features: features to pass to a task generator created in the build
  437. :type features: list of string
  438. :param compile_filename: file to create for the compilation (default: *test.c*)
  439. :type compile_filename: string
  440. :param code: code to write in the filename to compile
  441. :type code: string
  442. Though this function returns *0* by default, the build may set an attribute named *retval* on the
  443. build context object to return a particular value. See :py:func:`waflib.Tools.c_config.test_exec_fun` for example.
  444. This function also provides a limited cache. To use it, provide the following option::
  445. def options(opt):
  446. opt.add_option('--confcache', dest='confcache', default=0,
  447. action='count', help='Use a configuration cache')
  448. And execute the configuration with the following command-line::
  449. $ waf configure --confcache
  450. """
  451. lst = [str(v) for (p, v) in kw.items() if p != 'env']
  452. h = Utils.h_list(lst)
  453. dir = self.bldnode.abspath() + os.sep + (not Utils.is_win32 and '.' or '') + 'conf_check_' + Utils.to_hex(h)
  454. try:
  455. os.makedirs(dir)
  456. except OSError:
  457. pass
  458. try:
  459. os.stat(dir)
  460. except OSError:
  461. self.fatal('cannot use the configuration test folder %r' % dir)
  462. cachemode = getattr(Options.options, 'confcache', None)
  463. if cachemode == 1:
  464. try:
  465. proj = ConfigSet.ConfigSet(os.path.join(dir, 'cache_run_build'))
  466. except OSError:
  467. pass
  468. except IOError:
  469. pass
  470. else:
  471. ret = proj['cache_run_build']
  472. if isinstance(ret, str) and ret.startswith('Test does not build'):
  473. self.fatal(ret)
  474. return ret
  475. bdir = os.path.join(dir, 'testbuild')
  476. if not os.path.exists(bdir):
  477. os.makedirs(bdir)
  478. self.test_bld = bld = Build.BuildContext(top_dir=dir, out_dir=bdir)
  479. bld.init_dirs()
  480. bld.progress_bar = 0
  481. bld.targets = '*'
  482. bld.logger = self.logger
  483. bld.all_envs.update(self.all_envs) # not really necessary
  484. bld.env = kw['env']
  485. # OMG huge hack
  486. bld.kw = kw
  487. bld.conf = self
  488. kw['build_fun'](bld)
  489. ret = -1
  490. try:
  491. try:
  492. bld.compile()
  493. except Errors.WafError:
  494. ret = 'Test does not build: %s' % Utils.ex_stack()
  495. self.fatal(ret)
  496. else:
  497. ret = getattr(bld, 'retval', 0)
  498. finally:
  499. if cachemode == 1:
  500. # cache the results each time
  501. proj = ConfigSet.ConfigSet()
  502. proj['cache_run_build'] = ret
  503. proj.store(os.path.join(dir, 'cache_run_build'))
  504. else:
  505. shutil.rmtree(dir)
  506. return ret
  507. @conf
  508. def ret_msg(self, msg, args):
  509. if isinstance(msg, str):
  510. return msg
  511. return msg(args)
  512. @conf
  513. def test(self, *k, **kw):
  514. if not 'env' in kw:
  515. kw['env'] = self.env.derive()
  516. # validate_c for example
  517. if kw.get('validate', None):
  518. kw['validate'](kw)
  519. self.start_msg(kw['msg'], **kw)
  520. ret = None
  521. try:
  522. ret = self.run_build(*k, **kw)
  523. except self.errors.ConfigurationError:
  524. self.end_msg(kw['errmsg'], 'YELLOW', **kw)
  525. if Logs.verbose > 1:
  526. raise
  527. else:
  528. self.fatal('The configuration failed')
  529. else:
  530. kw['success'] = ret
  531. if kw.get('post_check', None):
  532. ret = kw['post_check'](kw)
  533. if ret:
  534. self.end_msg(kw['errmsg'], 'YELLOW', **kw)
  535. self.fatal('The configuration failed %r' % ret)
  536. else:
  537. self.end_msg(self.ret_msg(kw['okmsg'], kw), **kw)
  538. return ret