PageRenderTime 27ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/couchjs/scons/scons-local-2.0.1/SCons/SConf.py

http://github.com/cloudant/bigcouch
Python | 1030 lines | 984 code | 13 blank | 33 comment | 7 complexity | f4e1f7be334386e50015d4485d4b435e MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.SConf
  2. Autoconf-like configuration support.
  3. """
  4. #
  5. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files (the
  9. # "Software"), to deal in the Software without restriction, including
  10. # without limitation the rights to use, copy, modify, merge, publish,
  11. # distribute, sublicense, and/or sell copies of the Software, and to
  12. # permit persons to whom the Software is furnished to do so, subject to
  13. # the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included
  16. # in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  19. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  20. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. #
  26. __revision__ = "src/engine/SCons/SConf.py 5134 2010/08/16 23:02:40 bdeegan"
  27. import SCons.compat
  28. import io
  29. import os
  30. import re
  31. import sys
  32. import traceback
  33. import SCons.Action
  34. import SCons.Builder
  35. import SCons.Errors
  36. import SCons.Job
  37. import SCons.Node.FS
  38. import SCons.Taskmaster
  39. import SCons.Util
  40. import SCons.Warnings
  41. import SCons.Conftest
  42. from SCons.Debug import Trace
  43. # Turn off the Conftest error logging
  44. SCons.Conftest.LogInputFiles = 0
  45. SCons.Conftest.LogErrorMessages = 0
  46. # Set
  47. build_type = None
  48. build_types = ['clean', 'help']
  49. def SetBuildType(type):
  50. global build_type
  51. build_type = type
  52. # to be set, if we are in dry-run mode
  53. dryrun = 0
  54. AUTO=0 # use SCons dependency scanning for up-to-date checks
  55. FORCE=1 # force all tests to be rebuilt
  56. CACHE=2 # force all tests to be taken from cache (raise an error, if necessary)
  57. cache_mode = AUTO
  58. def SetCacheMode(mode):
  59. """Set the Configure cache mode. mode must be one of "auto", "force",
  60. or "cache"."""
  61. global cache_mode
  62. if mode == "auto":
  63. cache_mode = AUTO
  64. elif mode == "force":
  65. cache_mode = FORCE
  66. elif mode == "cache":
  67. cache_mode = CACHE
  68. else:
  69. raise ValueError("SCons.SConf.SetCacheMode: Unknown mode " + mode)
  70. progress_display = SCons.Util.display # will be overwritten by SCons.Script
  71. def SetProgressDisplay(display):
  72. """Set the progress display to use (called from SCons.Script)"""
  73. global progress_display
  74. progress_display = display
  75. SConfFS = None
  76. _ac_build_counter = 0 # incremented, whenever TryBuild is called
  77. _ac_config_logs = {} # all config.log files created in this build
  78. _ac_config_hs = {} # all config.h files created in this build
  79. sconf_global = None # current sconf object
  80. def _createConfigH(target, source, env):
  81. t = open(str(target[0]), "w")
  82. defname = re.sub('[^A-Za-z0-9_]', '_', str(target[0]).upper())
  83. t.write("""#ifndef %(DEFNAME)s_SEEN
  84. #define %(DEFNAME)s_SEEN
  85. """ % {'DEFNAME' : defname})
  86. t.write(source[0].get_contents())
  87. t.write("""
  88. #endif /* %(DEFNAME)s_SEEN */
  89. """ % {'DEFNAME' : defname})
  90. t.close()
  91. def _stringConfigH(target, source, env):
  92. return "scons: Configure: creating " + str(target[0])
  93. def CreateConfigHBuilder(env):
  94. """Called just before the building targets phase begins."""
  95. if len(_ac_config_hs) == 0:
  96. return
  97. action = SCons.Action.Action(_createConfigH,
  98. _stringConfigH)
  99. sconfigHBld = SCons.Builder.Builder(action=action)
  100. env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} )
  101. for k in _ac_config_hs.keys():
  102. env.SConfigHBuilder(k, env.Value(_ac_config_hs[k]))
  103. class SConfWarning(SCons.Warnings.Warning):
  104. pass
  105. SCons.Warnings.enableWarningClass(SConfWarning)
  106. # some error definitions
  107. class SConfError(SCons.Errors.UserError):
  108. def __init__(self,msg):
  109. SCons.Errors.UserError.__init__(self,msg)
  110. class ConfigureDryRunError(SConfError):
  111. """Raised when a file or directory needs to be updated during a Configure
  112. process, but the user requested a dry-run"""
  113. def __init__(self,target):
  114. if not isinstance(target, SCons.Node.FS.File):
  115. msg = 'Cannot create configure directory "%s" within a dry-run.' % str(target)
  116. else:
  117. msg = 'Cannot update configure test "%s" within a dry-run.' % str(target)
  118. SConfError.__init__(self,msg)
  119. class ConfigureCacheError(SConfError):
  120. """Raised when a use explicitely requested the cache feature, but the test
  121. is run the first time."""
  122. def __init__(self,target):
  123. SConfError.__init__(self, '"%s" is not yet built and cache is forced.' % str(target))
  124. # define actions for building text files
  125. def _createSource( target, source, env ):
  126. fd = open(str(target[0]), "w")
  127. fd.write(source[0].get_contents())
  128. fd.close()
  129. def _stringSource( target, source, env ):
  130. return (str(target[0]) + ' <-\n |' +
  131. source[0].get_contents().replace( '\n', "\n |" ) )
  132. class SConfBuildInfo(SCons.Node.FS.FileBuildInfo):
  133. """
  134. Special build info for targets of configure tests. Additional members
  135. are result (did the builder succeed last time?) and string, which
  136. contains messages of the original build phase.
  137. """
  138. result = None # -> 0/None -> no error, != 0 error
  139. string = None # the stdout / stderr output when building the target
  140. def set_build_result(self, result, string):
  141. self.result = result
  142. self.string = string
  143. class Streamer(object):
  144. """
  145. 'Sniffer' for a file-like writable object. Similar to the unix tool tee.
  146. """
  147. def __init__(self, orig):
  148. self.orig = orig
  149. self.s = io.StringIO()
  150. def write(self, str):
  151. if self.orig:
  152. self.orig.write(str)
  153. self.s.write(str)
  154. def writelines(self, lines):
  155. for l in lines:
  156. self.write(l + '\n')
  157. def getvalue(self):
  158. """
  159. Return everything written to orig since the Streamer was created.
  160. """
  161. return self.s.getvalue()
  162. def flush(self):
  163. if self.orig:
  164. self.orig.flush()
  165. self.s.flush()
  166. class SConfBuildTask(SCons.Taskmaster.AlwaysTask):
  167. """
  168. This is almost the same as SCons.Script.BuildTask. Handles SConfErrors
  169. correctly and knows about the current cache_mode.
  170. """
  171. def display(self, message):
  172. if sconf_global.logstream:
  173. sconf_global.logstream.write("scons: Configure: " + message + "\n")
  174. def display_cached_string(self, bi):
  175. """
  176. Logs the original builder messages, given the SConfBuildInfo instance
  177. bi.
  178. """
  179. if not isinstance(bi, SConfBuildInfo):
  180. SCons.Warnings.warn(SConfWarning,
  181. "The stored build information has an unexpected class: %s" % bi.__class__)
  182. else:
  183. self.display("The original builder output was:\n" +
  184. (" |" + str(bi.string)).replace("\n", "\n |"))
  185. def failed(self):
  186. # check, if the reason was a ConfigureDryRunError or a
  187. # ConfigureCacheError and if yes, reraise the exception
  188. exc_type = self.exc_info()[0]
  189. if issubclass(exc_type, SConfError):
  190. raise
  191. elif issubclass(exc_type, SCons.Errors.BuildError):
  192. # we ignore Build Errors (occurs, when a test doesn't pass)
  193. # Clear the exception to prevent the contained traceback
  194. # to build a reference cycle.
  195. self.exc_clear()
  196. else:
  197. self.display('Caught exception while building "%s":\n' %
  198. self.targets[0])
  199. try:
  200. excepthook = sys.excepthook
  201. except AttributeError:
  202. # Earlier versions of Python don't have sys.excepthook...
  203. def excepthook(type, value, tb):
  204. traceback.print_tb(tb)
  205. print type, value
  206. excepthook(*self.exc_info())
  207. return SCons.Taskmaster.Task.failed(self)
  208. def collect_node_states(self):
  209. # returns (is_up_to_date, cached_error, cachable)
  210. # where is_up_to_date is 1, if the node(s) are up_to_date
  211. # cached_error is 1, if the node(s) are up_to_date, but the
  212. # build will fail
  213. # cachable is 0, if some nodes are not in our cache
  214. T = 0
  215. changed = False
  216. cached_error = False
  217. cachable = True
  218. for t in self.targets:
  219. if T: Trace('%s' % (t))
  220. bi = t.get_stored_info().binfo
  221. if isinstance(bi, SConfBuildInfo):
  222. if T: Trace(': SConfBuildInfo')
  223. if cache_mode == CACHE:
  224. t.set_state(SCons.Node.up_to_date)
  225. if T: Trace(': set_state(up_to-date)')
  226. else:
  227. if T: Trace(': get_state() %s' % t.get_state())
  228. if T: Trace(': changed() %s' % t.changed())
  229. if (t.get_state() != SCons.Node.up_to_date and t.changed()):
  230. changed = True
  231. if T: Trace(': changed %s' % changed)
  232. cached_error = cached_error or bi.result
  233. else:
  234. if T: Trace(': else')
  235. # the node hasn't been built in a SConf context or doesn't
  236. # exist
  237. cachable = False
  238. changed = ( t.get_state() != SCons.Node.up_to_date )
  239. if T: Trace(': changed %s' % changed)
  240. if T: Trace('\n')
  241. return (not changed, cached_error, cachable)
  242. def execute(self):
  243. if not self.targets[0].has_builder():
  244. return
  245. sconf = sconf_global
  246. is_up_to_date, cached_error, cachable = self.collect_node_states()
  247. if cache_mode == CACHE and not cachable:
  248. raise ConfigureCacheError(self.targets[0])
  249. elif cache_mode == FORCE:
  250. is_up_to_date = 0
  251. if cached_error and is_up_to_date:
  252. self.display("Building \"%s\" failed in a previous run and all "
  253. "its sources are up to date." % str(self.targets[0]))
  254. binfo = self.targets[0].get_stored_info().binfo
  255. self.display_cached_string(binfo)
  256. raise SCons.Errors.BuildError # will be 'caught' in self.failed
  257. elif is_up_to_date:
  258. self.display("\"%s\" is up to date." % str(self.targets[0]))
  259. binfo = self.targets[0].get_stored_info().binfo
  260. self.display_cached_string(binfo)
  261. elif dryrun:
  262. raise ConfigureDryRunError(self.targets[0])
  263. else:
  264. # note stdout and stderr are the same here
  265. s = sys.stdout = sys.stderr = Streamer(sys.stdout)
  266. try:
  267. env = self.targets[0].get_build_env()
  268. if cache_mode == FORCE:
  269. # Set up the Decider() to force rebuilds by saying
  270. # that every source has changed. Note that we still
  271. # call the environment's underlying source decider so
  272. # that the correct .sconsign info will get calculated
  273. # and keep the build state consistent.
  274. def force_build(dependency, target, prev_ni,
  275. env_decider=env.decide_source):
  276. env_decider(dependency, target, prev_ni)
  277. return True
  278. if env.decide_source.func_code is not force_build.func_code:
  279. env.Decider(force_build)
  280. env['PSTDOUT'] = env['PSTDERR'] = s
  281. try:
  282. sconf.cached = 0
  283. self.targets[0].build()
  284. finally:
  285. sys.stdout = sys.stderr = env['PSTDOUT'] = \
  286. env['PSTDERR'] = sconf.logstream
  287. except KeyboardInterrupt:
  288. raise
  289. except SystemExit:
  290. exc_value = sys.exc_info()[1]
  291. raise SCons.Errors.ExplicitExit(self.targets[0],exc_value.code)
  292. except Exception, e:
  293. for t in self.targets:
  294. binfo = t.get_binfo()
  295. binfo.__class__ = SConfBuildInfo
  296. binfo.set_build_result(1, s.getvalue())
  297. sconsign_entry = SCons.SConsign.SConsignEntry()
  298. sconsign_entry.binfo = binfo
  299. #sconsign_entry.ninfo = self.get_ninfo()
  300. # We'd like to do this as follows:
  301. # t.store_info(binfo)
  302. # However, we need to store it as an SConfBuildInfo
  303. # object, and store_info() will turn it into a
  304. # regular FileNodeInfo if the target is itself a
  305. # regular File.
  306. sconsign = t.dir.sconsign()
  307. sconsign.set_entry(t.name, sconsign_entry)
  308. sconsign.merge()
  309. raise e
  310. else:
  311. for t in self.targets:
  312. binfo = t.get_binfo()
  313. binfo.__class__ = SConfBuildInfo
  314. binfo.set_build_result(0, s.getvalue())
  315. sconsign_entry = SCons.SConsign.SConsignEntry()
  316. sconsign_entry.binfo = binfo
  317. #sconsign_entry.ninfo = self.get_ninfo()
  318. # We'd like to do this as follows:
  319. # t.store_info(binfo)
  320. # However, we need to store it as an SConfBuildInfo
  321. # object, and store_info() will turn it into a
  322. # regular FileNodeInfo if the target is itself a
  323. # regular File.
  324. sconsign = t.dir.sconsign()
  325. sconsign.set_entry(t.name, sconsign_entry)
  326. sconsign.merge()
  327. class SConfBase(object):
  328. """This is simply a class to represent a configure context. After
  329. creating a SConf object, you can call any tests. After finished with your
  330. tests, be sure to call the Finish() method, which returns the modified
  331. environment.
  332. Some words about caching: In most cases, it is not necessary to cache
  333. Test results explicitely. Instead, we use the scons dependency checking
  334. mechanism. For example, if one wants to compile a test program
  335. (SConf.TryLink), the compiler is only called, if the program dependencies
  336. have changed. However, if the program could not be compiled in a former
  337. SConf run, we need to explicitely cache this error.
  338. """
  339. def __init__(self, env, custom_tests = {}, conf_dir='$CONFIGUREDIR',
  340. log_file='$CONFIGURELOG', config_h = None, _depth = 0):
  341. """Constructor. Pass additional tests in the custom_tests-dictinary,
  342. e.g. custom_tests={'CheckPrivate':MyPrivateTest}, where MyPrivateTest
  343. defines a custom test.
  344. Note also the conf_dir and log_file arguments (you may want to
  345. build tests in the VariantDir, not in the SourceDir)
  346. """
  347. global SConfFS
  348. if not SConfFS:
  349. SConfFS = SCons.Node.FS.default_fs or \
  350. SCons.Node.FS.FS(env.fs.pathTop)
  351. if sconf_global is not None:
  352. raise SCons.Errors.UserError
  353. self.env = env
  354. if log_file is not None:
  355. log_file = SConfFS.File(env.subst(log_file))
  356. self.logfile = log_file
  357. self.logstream = None
  358. self.lastTarget = None
  359. self.depth = _depth
  360. self.cached = 0 # will be set, if all test results are cached
  361. # add default tests
  362. default_tests = {
  363. 'CheckCC' : CheckCC,
  364. 'CheckCXX' : CheckCXX,
  365. 'CheckSHCC' : CheckSHCC,
  366. 'CheckSHCXX' : CheckSHCXX,
  367. 'CheckFunc' : CheckFunc,
  368. 'CheckType' : CheckType,
  369. 'CheckTypeSize' : CheckTypeSize,
  370. 'CheckDeclaration' : CheckDeclaration,
  371. 'CheckHeader' : CheckHeader,
  372. 'CheckCHeader' : CheckCHeader,
  373. 'CheckCXXHeader' : CheckCXXHeader,
  374. 'CheckLib' : CheckLib,
  375. 'CheckLibWithHeader' : CheckLibWithHeader,
  376. }
  377. self.AddTests(default_tests)
  378. self.AddTests(custom_tests)
  379. self.confdir = SConfFS.Dir(env.subst(conf_dir))
  380. if config_h is not None:
  381. config_h = SConfFS.File(config_h)
  382. self.config_h = config_h
  383. self._startup()
  384. def Finish(self):
  385. """Call this method after finished with your tests:
  386. env = sconf.Finish()
  387. """
  388. self._shutdown()
  389. return self.env
  390. def Define(self, name, value = None, comment = None):
  391. """
  392. Define a pre processor symbol name, with the optional given value in the
  393. current config header.
  394. If value is None (default), then #define name is written. If value is not
  395. none, then #define name value is written.
  396. comment is a string which will be put as a C comment in the
  397. header, to explain the meaning of the value (appropriate C comments /* and
  398. */ will be put automatically."""
  399. lines = []
  400. if comment:
  401. comment_str = "/* %s */" % comment
  402. lines.append(comment_str)
  403. if value is not None:
  404. define_str = "#define %s %s" % (name, value)
  405. else:
  406. define_str = "#define %s" % name
  407. lines.append(define_str)
  408. lines.append('')
  409. self.config_h_text = self.config_h_text + '\n'.join(lines)
  410. def BuildNodes(self, nodes):
  411. """
  412. Tries to build the given nodes immediately. Returns 1 on success,
  413. 0 on error.
  414. """
  415. if self.logstream is not None:
  416. # override stdout / stderr to write in log file
  417. oldStdout = sys.stdout
  418. sys.stdout = self.logstream
  419. oldStderr = sys.stderr
  420. sys.stderr = self.logstream
  421. # the engine assumes the current path is the SConstruct directory ...
  422. old_fs_dir = SConfFS.getcwd()
  423. old_os_dir = os.getcwd()
  424. SConfFS.chdir(SConfFS.Top, change_os_dir=1)
  425. # Because we take responsibility here for writing out our
  426. # own .sconsign info (see SConfBuildTask.execute(), above),
  427. # we override the store_info() method with a null place-holder
  428. # so we really control how it gets written.
  429. for n in nodes:
  430. n.store_info = n.do_not_store_info
  431. ret = 1
  432. try:
  433. # ToDo: use user options for calc
  434. save_max_drift = SConfFS.get_max_drift()
  435. SConfFS.set_max_drift(0)
  436. tm = SCons.Taskmaster.Taskmaster(nodes, SConfBuildTask)
  437. # we don't want to build tests in parallel
  438. jobs = SCons.Job.Jobs(1, tm )
  439. jobs.run()
  440. for n in nodes:
  441. state = n.get_state()
  442. if (state != SCons.Node.executed and
  443. state != SCons.Node.up_to_date):
  444. # the node could not be built. we return 0 in this case
  445. ret = 0
  446. finally:
  447. SConfFS.set_max_drift(save_max_drift)
  448. os.chdir(old_os_dir)
  449. SConfFS.chdir(old_fs_dir, change_os_dir=0)
  450. if self.logstream is not None:
  451. # restore stdout / stderr
  452. sys.stdout = oldStdout
  453. sys.stderr = oldStderr
  454. return ret
  455. def pspawn_wrapper(self, sh, escape, cmd, args, env):
  456. """Wrapper function for handling piped spawns.
  457. This looks to the calling interface (in Action.py) like a "normal"
  458. spawn, but associates the call with the PSPAWN variable from
  459. the construction environment and with the streams to which we
  460. want the output logged. This gets slid into the construction
  461. environment as the SPAWN variable so Action.py doesn't have to
  462. know or care whether it's spawning a piped command or not.
  463. """
  464. return self.pspawn(sh, escape, cmd, args, env, self.logstream, self.logstream)
  465. def TryBuild(self, builder, text = None, extension = ""):
  466. """Low level TryBuild implementation. Normally you don't need to
  467. call that - you can use TryCompile / TryLink / TryRun instead
  468. """
  469. global _ac_build_counter
  470. # Make sure we have a PSPAWN value, and save the current
  471. # SPAWN value.
  472. try:
  473. self.pspawn = self.env['PSPAWN']
  474. except KeyError:
  475. raise SCons.Errors.UserError('Missing PSPAWN construction variable.')
  476. try:
  477. save_spawn = self.env['SPAWN']
  478. except KeyError:
  479. raise SCons.Errors.UserError('Missing SPAWN construction variable.')
  480. nodesToBeBuilt = []
  481. f = "conftest_" + str(_ac_build_counter)
  482. pref = self.env.subst( builder.builder.prefix )
  483. suff = self.env.subst( builder.builder.suffix )
  484. target = self.confdir.File(pref + f + suff)
  485. try:
  486. # Slide our wrapper into the construction environment as
  487. # the SPAWN function.
  488. self.env['SPAWN'] = self.pspawn_wrapper
  489. sourcetext = self.env.Value(text)
  490. if text is not None:
  491. textFile = self.confdir.File(f + extension)
  492. textFileNode = self.env.SConfSourceBuilder(target=textFile,
  493. source=sourcetext)
  494. nodesToBeBuilt.extend(textFileNode)
  495. source = textFileNode
  496. else:
  497. source = None
  498. nodes = builder(target = target, source = source)
  499. if not SCons.Util.is_List(nodes):
  500. nodes = [nodes]
  501. nodesToBeBuilt.extend(nodes)
  502. result = self.BuildNodes(nodesToBeBuilt)
  503. finally:
  504. self.env['SPAWN'] = save_spawn
  505. _ac_build_counter = _ac_build_counter + 1
  506. if result:
  507. self.lastTarget = nodes[0]
  508. else:
  509. self.lastTarget = None
  510. return result
  511. def TryAction(self, action, text = None, extension = ""):
  512. """Tries to execute the given action with optional source file
  513. contents <text> and optional source file extension <extension>,
  514. Returns the status (0 : failed, 1 : ok) and the contents of the
  515. output file.
  516. """
  517. builder = SCons.Builder.Builder(action=action)
  518. self.env.Append( BUILDERS = {'SConfActionBuilder' : builder} )
  519. ok = self.TryBuild(self.env.SConfActionBuilder, text, extension)
  520. del self.env['BUILDERS']['SConfActionBuilder']
  521. if ok:
  522. outputStr = self.lastTarget.get_contents()
  523. return (1, outputStr)
  524. return (0, "")
  525. def TryCompile( self, text, extension):
  526. """Compiles the program given in text to an env.Object, using extension
  527. as file extension (e.g. '.c'). Returns 1, if compilation was
  528. successful, 0 otherwise. The target is saved in self.lastTarget (for
  529. further processing).
  530. """
  531. return self.TryBuild(self.env.Object, text, extension)
  532. def TryLink( self, text, extension ):
  533. """Compiles the program given in text to an executable env.Program,
  534. using extension as file extension (e.g. '.c'). Returns 1, if
  535. compilation was successful, 0 otherwise. The target is saved in
  536. self.lastTarget (for further processing).
  537. """
  538. return self.TryBuild(self.env.Program, text, extension )
  539. def TryRun(self, text, extension ):
  540. """Compiles and runs the program given in text, using extension
  541. as file extension (e.g. '.c'). Returns (1, outputStr) on success,
  542. (0, '') otherwise. The target (a file containing the program's stdout)
  543. is saved in self.lastTarget (for further processing).
  544. """
  545. ok = self.TryLink(text, extension)
  546. if( ok ):
  547. prog = self.lastTarget
  548. pname = prog.path
  549. output = self.confdir.File(os.path.basename(pname)+'.out')
  550. node = self.env.Command(output, prog, [ [ pname, ">", "${TARGET}"] ])
  551. ok = self.BuildNodes(node)
  552. if ok:
  553. outputStr = output.get_contents()
  554. return( 1, outputStr)
  555. return (0, "")
  556. class TestWrapper(object):
  557. """A wrapper around Tests (to ensure sanity)"""
  558. def __init__(self, test, sconf):
  559. self.test = test
  560. self.sconf = sconf
  561. def __call__(self, *args, **kw):
  562. if not self.sconf.active:
  563. raise SCons.Errors.UserError
  564. context = CheckContext(self.sconf)
  565. ret = self.test(context, *args, **kw)
  566. if self.sconf.config_h is not None:
  567. self.sconf.config_h_text = self.sconf.config_h_text + context.config_h
  568. context.Result("error: no result")
  569. return ret
  570. def AddTest(self, test_name, test_instance):
  571. """Adds test_class to this SConf instance. It can be called with
  572. self.test_name(...)"""
  573. setattr(self, test_name, SConfBase.TestWrapper(test_instance, self))
  574. def AddTests(self, tests):
  575. """Adds all the tests given in the tests dictionary to this SConf
  576. instance
  577. """
  578. for name in tests.keys():
  579. self.AddTest(name, tests[name])
  580. def _createDir( self, node ):
  581. dirName = str(node)
  582. if dryrun:
  583. if not os.path.isdir( dirName ):
  584. raise ConfigureDryRunError(dirName)
  585. else:
  586. if not os.path.isdir( dirName ):
  587. os.makedirs( dirName )
  588. node._exists = 1
  589. def _startup(self):
  590. """Private method. Set up logstream, and set the environment
  591. variables necessary for a piped build
  592. """
  593. global _ac_config_logs
  594. global sconf_global
  595. global SConfFS
  596. self.lastEnvFs = self.env.fs
  597. self.env.fs = SConfFS
  598. self._createDir(self.confdir)
  599. self.confdir.up().add_ignore( [self.confdir] )
  600. if self.logfile is not None and not dryrun:
  601. # truncate logfile, if SConf.Configure is called for the first time
  602. # in a build
  603. if self.logfile in _ac_config_logs:
  604. log_mode = "a"
  605. else:
  606. _ac_config_logs[self.logfile] = None
  607. log_mode = "w"
  608. fp = open(str(self.logfile), log_mode)
  609. self.logstream = SCons.Util.Unbuffered(fp)
  610. # logfile may stay in a build directory, so we tell
  611. # the build system not to override it with a eventually
  612. # existing file with the same name in the source directory
  613. self.logfile.dir.add_ignore( [self.logfile] )
  614. tb = traceback.extract_stack()[-3-self.depth]
  615. old_fs_dir = SConfFS.getcwd()
  616. SConfFS.chdir(SConfFS.Top, change_os_dir=0)
  617. self.logstream.write('file %s,line %d:\n\tConfigure(confdir = %s)\n' %
  618. (tb[0], tb[1], str(self.confdir)) )
  619. SConfFS.chdir(old_fs_dir)
  620. else:
  621. self.logstream = None
  622. # we use a special builder to create source files from TEXT
  623. action = SCons.Action.Action(_createSource,
  624. _stringSource)
  625. sconfSrcBld = SCons.Builder.Builder(action=action)
  626. self.env.Append( BUILDERS={'SConfSourceBuilder':sconfSrcBld} )
  627. self.config_h_text = _ac_config_hs.get(self.config_h, "")
  628. self.active = 1
  629. # only one SConf instance should be active at a time ...
  630. sconf_global = self
  631. def _shutdown(self):
  632. """Private method. Reset to non-piped spawn"""
  633. global sconf_global, _ac_config_hs
  634. if not self.active:
  635. raise SCons.Errors.UserError("Finish may be called only once!")
  636. if self.logstream is not None and not dryrun:
  637. self.logstream.write("\n")
  638. self.logstream.close()
  639. self.logstream = None
  640. # remove the SConfSourceBuilder from the environment
  641. blds = self.env['BUILDERS']
  642. del blds['SConfSourceBuilder']
  643. self.env.Replace( BUILDERS=blds )
  644. self.active = 0
  645. sconf_global = None
  646. if not self.config_h is None:
  647. _ac_config_hs[self.config_h] = self.config_h_text
  648. self.env.fs = self.lastEnvFs
  649. class CheckContext(object):
  650. """Provides a context for configure tests. Defines how a test writes to the
  651. screen and log file.
  652. A typical test is just a callable with an instance of CheckContext as
  653. first argument:
  654. def CheckCustom(context, ...)
  655. context.Message('Checking my weird test ... ')
  656. ret = myWeirdTestFunction(...)
  657. context.Result(ret)
  658. Often, myWeirdTestFunction will be one of
  659. context.TryCompile/context.TryLink/context.TryRun. The results of
  660. those are cached, for they are only rebuild, if the dependencies have
  661. changed.
  662. """
  663. def __init__(self, sconf):
  664. """Constructor. Pass the corresponding SConf instance."""
  665. self.sconf = sconf
  666. self.did_show_result = 0
  667. # for Conftest.py:
  668. self.vardict = {}
  669. self.havedict = {}
  670. self.headerfilename = None
  671. self.config_h = "" # config_h text will be stored here
  672. # we don't regenerate the config.h file after each test. That means,
  673. # that tests won't be able to include the config.h file, and so
  674. # they can't do an #ifdef HAVE_XXX_H. This shouldn't be a major
  675. # issue, though. If it turns out, that we need to include config.h
  676. # in tests, we must ensure, that the dependencies are worked out
  677. # correctly. Note that we can't use Conftest.py's support for config.h,
  678. # cause we will need to specify a builder for the config.h file ...
  679. def Message(self, text):
  680. """Inform about what we are doing right now, e.g.
  681. 'Checking for SOMETHING ... '
  682. """
  683. self.Display(text)
  684. self.sconf.cached = 1
  685. self.did_show_result = 0
  686. def Result(self, res):
  687. """Inform about the result of the test. res may be an integer or a
  688. string. In case of an integer, the written text will be 'yes' or 'no'.
  689. The result is only displayed when self.did_show_result is not set.
  690. """
  691. if isinstance(res, (int, bool)):
  692. if res:
  693. text = "yes"
  694. else:
  695. text = "no"
  696. elif isinstance(res, str):
  697. text = res
  698. else:
  699. raise TypeError("Expected string, int or bool, got " + str(type(res)))
  700. if self.did_show_result == 0:
  701. # Didn't show result yet, do it now.
  702. self.Display(text + "\n")
  703. self.did_show_result = 1
  704. def TryBuild(self, *args, **kw):
  705. return self.sconf.TryBuild(*args, **kw)
  706. def TryAction(self, *args, **kw):
  707. return self.sconf.TryAction(*args, **kw)
  708. def TryCompile(self, *args, **kw):
  709. return self.sconf.TryCompile(*args, **kw)
  710. def TryLink(self, *args, **kw):
  711. return self.sconf.TryLink(*args, **kw)
  712. def TryRun(self, *args, **kw):
  713. return self.sconf.TryRun(*args, **kw)
  714. def __getattr__( self, attr ):
  715. if( attr == 'env' ):
  716. return self.sconf.env
  717. elif( attr == 'lastTarget' ):
  718. return self.sconf.lastTarget
  719. else:
  720. raise AttributeError("CheckContext instance has no attribute '%s'" % attr)
  721. #### Stuff used by Conftest.py (look there for explanations).
  722. def BuildProg(self, text, ext):
  723. self.sconf.cached = 1
  724. # TODO: should use self.vardict for $CC, $CPPFLAGS, etc.
  725. return not self.TryBuild(self.env.Program, text, ext)
  726. def CompileProg(self, text, ext):
  727. self.sconf.cached = 1
  728. # TODO: should use self.vardict for $CC, $CPPFLAGS, etc.
  729. return not self.TryBuild(self.env.Object, text, ext)
  730. def CompileSharedObject(self, text, ext):
  731. self.sconf.cached = 1
  732. # TODO: should use self.vardict for $SHCC, $CPPFLAGS, etc.
  733. return not self.TryBuild(self.env.SharedObject, text, ext)
  734. def RunProg(self, text, ext):
  735. self.sconf.cached = 1
  736. # TODO: should use self.vardict for $CC, $CPPFLAGS, etc.
  737. st, out = self.TryRun(text, ext)
  738. return not st, out
  739. def AppendLIBS(self, lib_name_list):
  740. oldLIBS = self.env.get( 'LIBS', [] )
  741. self.env.Append(LIBS = lib_name_list)
  742. return oldLIBS
  743. def PrependLIBS(self, lib_name_list):
  744. oldLIBS = self.env.get( 'LIBS', [] )
  745. self.env.Prepend(LIBS = lib_name_list)
  746. return oldLIBS
  747. def SetLIBS(self, val):
  748. oldLIBS = self.env.get( 'LIBS', [] )
  749. self.env.Replace(LIBS = val)
  750. return oldLIBS
  751. def Display(self, msg):
  752. if self.sconf.cached:
  753. # We assume that Display is called twice for each test here
  754. # once for the Checking for ... message and once for the result.
  755. # The self.sconf.cached flag can only be set between those calls
  756. msg = "(cached) " + msg
  757. self.sconf.cached = 0
  758. progress_display(msg, append_newline=0)
  759. self.Log("scons: Configure: " + msg + "\n")
  760. def Log(self, msg):
  761. if self.sconf.logstream is not None:
  762. self.sconf.logstream.write(msg)
  763. #### End of stuff used by Conftest.py.
  764. def SConf(*args, **kw):
  765. if kw.get(build_type, True):
  766. kw['_depth'] = kw.get('_depth', 0) + 1
  767. for bt in build_types:
  768. try:
  769. del kw[bt]
  770. except KeyError:
  771. pass
  772. return SConfBase(*args, **kw)
  773. else:
  774. return SCons.Util.Null()
  775. def CheckFunc(context, function_name, header = None, language = None):
  776. res = SCons.Conftest.CheckFunc(context, function_name, header = header, language = language)
  777. context.did_show_result = 1
  778. return not res
  779. def CheckType(context, type_name, includes = "", language = None):
  780. res = SCons.Conftest.CheckType(context, type_name,
  781. header = includes, language = language)
  782. context.did_show_result = 1
  783. return not res
  784. def CheckTypeSize(context, type_name, includes = "", language = None, expect = None):
  785. res = SCons.Conftest.CheckTypeSize(context, type_name,
  786. header = includes, language = language,
  787. expect = expect)
  788. context.did_show_result = 1
  789. return res
  790. def CheckDeclaration(context, declaration, includes = "", language = None):
  791. res = SCons.Conftest.CheckDeclaration(context, declaration,
  792. includes = includes,
  793. language = language)
  794. context.did_show_result = 1
  795. return not res
  796. def createIncludesFromHeaders(headers, leaveLast, include_quotes = '""'):
  797. # used by CheckHeader and CheckLibWithHeader to produce C - #include
  798. # statements from the specified header (list)
  799. if not SCons.Util.is_List(headers):
  800. headers = [headers]
  801. l = []
  802. if leaveLast:
  803. lastHeader = headers[-1]
  804. headers = headers[:-1]
  805. else:
  806. lastHeader = None
  807. for s in headers:
  808. l.append("#include %s%s%s\n"
  809. % (include_quotes[0], s, include_quotes[1]))
  810. return ''.join(l), lastHeader
  811. def CheckHeader(context, header, include_quotes = '<>', language = None):
  812. """
  813. A test for a C or C++ header file.
  814. """
  815. prog_prefix, hdr_to_check = \
  816. createIncludesFromHeaders(header, 1, include_quotes)
  817. res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix,
  818. language = language,
  819. include_quotes = include_quotes)
  820. context.did_show_result = 1
  821. return not res
  822. def CheckCC(context):
  823. res = SCons.Conftest.CheckCC(context)
  824. context.did_show_result = 1
  825. return not res
  826. def CheckCXX(context):
  827. res = SCons.Conftest.CheckCXX(context)
  828. context.did_show_result = 1
  829. return not res
  830. def CheckSHCC(context):
  831. res = SCons.Conftest.CheckSHCC(context)
  832. context.did_show_result = 1
  833. return not res
  834. def CheckSHCXX(context):
  835. res = SCons.Conftest.CheckSHCXX(context)
  836. context.did_show_result = 1
  837. return not res
  838. # Bram: Make this function obsolete? CheckHeader() is more generic.
  839. def CheckCHeader(context, header, include_quotes = '""'):
  840. """
  841. A test for a C header file.
  842. """
  843. return CheckHeader(context, header, include_quotes, language = "C")
  844. # Bram: Make this function obsolete? CheckHeader() is more generic.
  845. def CheckCXXHeader(context, header, include_quotes = '""'):
  846. """
  847. A test for a C++ header file.
  848. """
  849. return CheckHeader(context, header, include_quotes, language = "C++")
  850. def CheckLib(context, library = None, symbol = "main",
  851. header = None, language = None, autoadd = 1):
  852. """
  853. A test for a library. See also CheckLibWithHeader.
  854. Note that library may also be None to test whether the given symbol
  855. compiles without flags.
  856. """
  857. if library == []:
  858. library = [None]
  859. if not SCons.Util.is_List(library):
  860. library = [library]
  861. # ToDo: accept path for the library
  862. res = SCons.Conftest.CheckLib(context, library, symbol, header = header,
  863. language = language, autoadd = autoadd)
  864. context.did_show_result = 1
  865. return not res
  866. # XXX
  867. # Bram: Can only include one header and can't use #ifdef HAVE_HEADER_H.
  868. def CheckLibWithHeader(context, libs, header, language,
  869. call = None, autoadd = 1):
  870. # ToDo: accept path for library. Support system header files.
  871. """
  872. Another (more sophisticated) test for a library.
  873. Checks, if library and header is available for language (may be 'C'
  874. or 'CXX'). Call maybe be a valid expression _with_ a trailing ';'.
  875. As in CheckLib, we support library=None, to test if the call compiles
  876. without extra link flags.
  877. """
  878. prog_prefix, dummy = \
  879. createIncludesFromHeaders(header, 0)
  880. if libs == []:
  881. libs = [None]
  882. if not SCons.Util.is_List(libs):
  883. libs = [libs]
  884. res = SCons.Conftest.CheckLib(context, libs, None, prog_prefix,
  885. call = call, language = language, autoadd = autoadd)
  886. context.did_show_result = 1
  887. return not res
  888. # Local Variables:
  889. # tab-width:4
  890. # indent-tabs-mode:nil
  891. # End:
  892. # vim: set expandtab tabstop=4 shiftwidth=4: