Package SCons :: Module SConf
[hide private]
[frames] | no frames]

Source Code for Module SCons.SConf

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