"""SCons.ScriptThis file implements the main() function used by the scons script.Architecturally, this *is* the scons script, and will likely only becalled from the external "scons" wrapper. Consequently, anything hereshould not be, or be considered, part of the build engine. If it'ssomething that we expect other software to want to use, it should go insome other module. If it's specific to the "scons" script invocation,it goes here."""unsupported_python_version=(2,3,0)deprecated_python_version=(2,4,0)# __COPYRIGHT__## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be included# in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.__revision__="__FILE__ __REVISION__ __DATE__ __DEVELOPER__"importSCons.compatimportosimportsysimporttimeimporttraceback# Strip the script directory from sys.path() so on case-insensitive# (Windows) systems Python doesn't think that the "scons" script is the# "SCons" package. Replace it with our own version directory so, if# if they're there, we pick up the right version of the build engine# modules.#sys.path = [os.path.join(sys.prefix,# 'lib',# 'scons-%d' % SCons.__version__)] + sys.path[1:]importSCons.CacheDirimportSCons.DebugimportSCons.DefaultsimportSCons.EnvironmentimportSCons.ErrorsimportSCons.JobimportSCons.NodeimportSCons.Node.FSimportSCons.PlatformimportSCons.SConfimportSCons.ScriptimportSCons.TaskmasterimportSCons.UtilimportSCons.WarningsimportSCons.Script.Interactivedeffetch_win32_parallel_msg():# A subsidiary function that exists solely to isolate this import# so we don't have to pull it in on all platforms, and so that an# in-line "import" statement in the _main() function below doesn't# cause warnings about local names shadowing use of the 'SCons'# globl in nest scopes and UnboundLocalErrors and the like in some# versions (2.1) of Python.importSCons.Platform.win32returnSCons.Platform.win32.parallel_msg#classSConsPrintHelpException(Exception):passdisplay=SCons.Util.displayprogress_display=SCons.Util.DisplayEngine()first_command_start=Nonelast_command_end=NoneclassProgressor(object):prev=''count=0target_string='$TARGET'def__init__(self,obj,interval=1,file=None,overwrite=False):iffileisNone:file=sys.stdoutself.obj=objself.file=fileself.interval=intervalself.overwrite=overwriteifcallable(obj):self.func=objelifSCons.Util.is_List(obj):self.func=self.spinnerelifobj.find(self.target_string)!=-1:self.func=self.replace_stringelse:self.func=self.stringdefwrite(self,s):self.file.write(s)self.file.flush()self.prev=sdeferase_previous(self):ifself.prev:length=len(self.prev)ifself.prev[-1]in('\n','\r'):length=length-1self.write(' '*length+'\r')self.prev=''defspinner(self,node):self.write(self.obj[self.count%len(self.obj)])defstring(self,node):self.write(self.obj)defreplace_string(self,node):self.write(self.obj.replace(self.target_string,str(node)))def__call__(self,node):self.count=self.count+1if(self.count%self.interval)==0:ifself.overwrite:self.erase_previous()self.func(node)ProgressObject=SCons.Util.Null()defProgress(*args,**kw):globalProgressObjectProgressObject=Progressor(*args,**kw)# Task control.#_BuildFailures=[]defGetBuildFailures():return_BuildFailuresclassBuildTask(SCons.Taskmaster.OutOfDateTask):"""An SCons build task."""progress=ProgressObjectdefdisplay(self,message):display('scons: '+message)defprepare(self):self.progress(self.targets[0])returnSCons.Taskmaster.OutOfDateTask.prepare(self)defneeds_execute(self):ifSCons.Taskmaster.OutOfDateTask.needs_execute(self):returnTrueifself.topandself.targets[0].has_builder():display("scons: `%s' is up to date."%str(self.node))returnFalsedefexecute(self):ifprint_time:start_time=time.time()globalfirst_command_startiffirst_command_startisNone:first_command_start=start_timeSCons.Taskmaster.OutOfDateTask.execute(self)ifprint_time:globalcumulative_command_timegloballast_command_endfinish_time=time.time()last_command_end=finish_timecumulative_command_time=cumulative_command_time+finish_time-start_timesys.stdout.write("Command execution time:%s:%f seconds\n"%(str(self.node),finish_time-start_time))defdo_failed(self,status=2):_BuildFailures.append(self.exception[1])globalexit_statusglobalthis_build_statusifself.options.ignore_errors:SCons.Taskmaster.OutOfDateTask.executed(self)elifself.options.keep_going:SCons.Taskmaster.OutOfDateTask.fail_continue(self)exit_status=statusthis_build_status=statuselse:SCons.Taskmaster.OutOfDateTask.fail_stop(self)exit_status=statusthis_build_status=statusdefexecuted(self):t=self.targets[0]ifself.topandnott.has_builder()andnott.side_effect:ifnott.exists():ift.__class__.__name__in('File','Dir','Entry'):errstr="Do not know how to make %s target `%s' (%s)."%(t.__class__.__name__,t,t.abspath)else:# Alias or Python or ...errstr="Do not know how to make %s target `%s'."%(t.__class__.__name__,t)sys.stderr.write("scons: *** "+errstr)ifnotself.options.keep_going:sys.stderr.write(" Stop.")sys.stderr.write("\n")try:raiseSCons.Errors.BuildError(t,errstr)exceptKeyboardInterrupt:raiseexcept:self.exception_set()self.do_failed()else:print"scons: Nothing to be done for `%s'."%tSCons.Taskmaster.OutOfDateTask.executed(self)else:SCons.Taskmaster.OutOfDateTask.executed(self)deffailed(self):# Handle the failure of a build task. The primary purpose here# is to display the various types of Errors and Exceptions# appropriately.exc_info=self.exc_info()try:t,e,tb=exc_infoexceptValueError:t,e=exc_infotb=NoneiftisNone:# The Taskmaster didn't record an exception for this Task;# see if the sys module has one.try:t,e,tb=sys.exc_info()[:]exceptValueError:t,e=exc_infotb=None# Deprecated string exceptions will have their string stored# in the first entry of the tuple.ifeisNone:e=tbuildError=SCons.Errors.convert_to_BuildError(e)ifnotbuildError.node:buildError.node=self.nodenode=buildError.nodeifnotSCons.Util.is_List(node):node=[node]nodename=', '.join(map(str,node))errfmt="scons: *** [%s] %s\n"sys.stderr.write(errfmt%(nodename,buildError))if(buildError.exc_info[2]andbuildError.exc_info[1]andnotisinstance(buildError.exc_info[1],(EnvironmentError,SCons.Errors.StopError,SCons.Errors.UserError))):type,value,trace=buildError.exc_infotraceback.print_exception(type,value,trace)eliftbandprint_stacktrace:sys.stderr.write("scons: internal stack trace:\n")traceback.print_tb(tb,file=sys.stderr)self.exception=(e,buildError,tb)# type, value, tracebackself.do_failed(buildError.exitstatus)self.exc_clear()defpostprocess(self):ifself.top:t=self.targets[0]fortpinself.options.tree_printers:tp.display(t)ifself.options.debug_includes:tree=t.render_include_tree()iftree:printprinttreeSCons.Taskmaster.OutOfDateTask.postprocess(self)defmake_ready(self):"""Make a task ready for execution"""SCons.Taskmaster.OutOfDateTask.make_ready(self)ifself.out_of_dateandself.options.debug_explain:explanation=self.out_of_date[0].explain()ifexplanation:sys.stdout.write("scons: "+explanation)classCleanTask(SCons.Taskmaster.AlwaysTask):"""An SCons clean task."""deffs_delete(self,path,pathstr,remove=1):try:ifos.path.lexists(path):ifos.path.isfile(path)oros.path.islink(path):ifremove:os.unlink(path)display("Removed "+pathstr)elifos.path.isdir(path)andnotos.path.islink(path):# delete everything in the dirforeinsorted(os.listdir(path)):p=os.path.join(path,e)s=os.path.join(pathstr,e)ifos.path.isfile(p):ifremove:os.unlink(p)display("Removed "+s)else:self.fs_delete(p,s,remove)# then delete dir itselfifremove:os.rmdir(path)display("Removed directory "+pathstr)else:errstr="Path '%s' exists but isn't a file or directory."raiseSCons.Errors.UserError(errstr%(pathstr))exceptSCons.Errors.UserError,e:printeexcept(IOError,OSError),e:print"scons: Could not remove '%s':"%pathstr,e.strerrordefshow(self):target=self.targets[0]if(target.has_builder()ortarget.side_effect)andnottarget.noclean:fortinself.targets:ifnott.isdir():display("Removed "+str(t))iftargetinSCons.Environment.CleanTargets:files=SCons.Environment.CleanTargets[target]forfinfiles:self.fs_delete(f.abspath,str(f),0)defremove(self):target=self.targets[0]if(target.has_builder()ortarget.side_effect)andnottarget.noclean:fortinself.targets:try:removed=t.remove()exceptOSError,e:# An OSError may indicate something like a permissions# issue, an IOError would indicate something like# the file not existing. In either case, print a# message and keep going to try to remove as many# targets aa possible.print"scons: Could not remove '%s':"%str(t),e.strerrorelse:ifremoved:display("Removed "+str(t))iftargetinSCons.Environment.CleanTargets:files=SCons.Environment.CleanTargets[target]forfinfiles:self.fs_delete(f.abspath,str(f))execute=remove# We want the Taskmaster to update the Node states (and therefore# handle reference counts, etc.), but we don't want to call# back to the Node's post-build methods, which would do things# we don't want, like store .sconsign information.executed=SCons.Taskmaster.Task.executed_without_callbacks# Have the taskmaster arrange to "execute" all of the targets, because# we'll figure out ourselves (in remove() or show() above) whether# anything really needs to be done.make_ready=SCons.Taskmaster.Task.make_ready_alldefprepare(self):passclassQuestionTask(SCons.Taskmaster.AlwaysTask):"""An SCons task for the -q (question) option."""defprepare(self):passdefexecute(self):ifself.targets[0].get_state()!=SCons.Node.up_to_dateor \
(self.topandnotself.targets[0].exists()):globalexit_statusglobalthis_build_statusexit_status=1this_build_status=1self.tm.stop()defexecuted(self):passclassTreePrinter(object):def__init__(self,derived=False,prune=False,status=False):self.derived=derivedself.prune=pruneself.status=statusdefget_all_children(self,node):returnnode.all_children()defget_derived_children(self,node):children=node.all_children(None)return[xforxinchildrenifx.has_builder()]defdisplay(self,t):ifself.derived:func=self.get_derived_childrenelse:func=self.get_all_childrens=self.statusand2or0SCons.Util.print_tree(t,func,prune=self.prune,showtags=s)defpython_version_string():returnsys.version.split()[0]defpython_version_unsupported(version=sys.version_info):returnversion<unsupported_python_versiondefpython_version_deprecated(version=sys.version_info):returnversion<deprecated_python_version# Global variablesprint_objects=0print_memoizer=0print_stacktrace=0print_time=0sconscript_time=0cumulative_command_time=0exit_status=0# final exit status, assume success by defaultthis_build_status=0# "exit status" of an individual buildnum_jobs=Nonedelayed_warnings=[]classFakeOptionParser(object):""" A do-nothing option parser, used for the initial OptionsParser variable. During normal SCons operation, the OptionsParser is created right away by the main() function. Certain tests scripts however, can introspect on different Tool modules, the initialization of which can try to add a new, local option to an otherwise uninitialized OptionsParser object. This allows that introspection to happen without blowing up. """classFakeOptionValues(object):def__getattr__(self,attr):returnNonevalues=FakeOptionValues()defadd_local_option(self,*args,**kw):passOptionsParser=FakeOptionParser()defAddOption(*args,**kw):if'default'notinkw:kw['default']=Noneresult=OptionsParser.add_local_option(*args,**kw)returnresultdefGetOption(name):returngetattr(OptionsParser.values,name)defSetOption(name,value):returnOptionsParser.values.set_option(name,value)#classStats(object):def__init__(self):self.stats=[]self.labels=[]self.append=self.do_nothingself.print_stats=self.do_nothingdefenable(self,outfp):self.outfp=outfpself.append=self.do_appendself.print_stats=self.do_printdefdo_nothing(self,*args,**kw):passclassCountStats(Stats):defdo_append(self,label):self.labels.append(label)self.stats.append(SCons.Debug.fetchLoggedInstances())defdo_print(self):stats_table={}forsinself.stats:fornin[t[0]fortins]:stats_table[n]=[0,0,0,0]i=0forsinself.stats:forn,cins:stats_table[n][i]=ci=i+1self.outfp.write("Object counts:\n")pre=[" "]post=[" %s\n"]l=len(self.stats)fmt1=''.join(pre+[' %7s']*l+post)fmt2=''.join(pre+[' %7d']*l+post)labels=self.labels[:l]labels.append(("","Class"))self.outfp.write(fmt1%tuple([x[0]forxinlabels]))self.outfp.write(fmt1%tuple([x[1]forxinlabels]))forkinsorted(stats_table.keys()):r=stats_table[k][:l]+[k]self.outfp.write(fmt2%tuple(r))count_stats=CountStats()classMemStats(Stats):defdo_append(self,label):self.labels.append(label)self.stats.append(SCons.Debug.memory())defdo_print(self):fmt='Memory %-32s%12d\n'forlabel,statsinzip(self.labels,self.stats):self.outfp.write(fmt%(label,stats))memory_stats=MemStats()# utility functionsdef_scons_syntax_error(e):"""Handle syntax errors. Print out a message and show where the error occurred. """etype,value,tb=sys.exc_info()lines=traceback.format_exception_only(etype,value)forlineinlines:sys.stderr.write(line+'\n')sys.exit(2)deffind_deepest_user_frame(tb):""" Find the deepest stack frame that is not part of SCons. Input is a "pre-processed" stack trace in the form returned by traceback.extract_tb() or traceback.extract_stack() """tb.reverse()# find the deepest traceback frame that is not part# of SCons:forframeintb:filename=frame[0]iffilename.find(os.sep+'SCons'+os.sep)==-1:returnframereturntb[0]def_scons_user_error(e):"""Handle user errors. Print out a message and a description of the error, along with the line number and routine where it occured. The file and line number will be the deepest stack frame that is not part of SCons itself. """globalprint_stacktraceetype,value,tb=sys.exc_info()ifprint_stacktrace:traceback.print_exception(etype,value,tb)filename,lineno,routine,dummy=find_deepest_user_frame(traceback.extract_tb(tb))sys.stderr.write("\nscons: *** %s\n"%value)sys.stderr.write('File "%s", line %d, in %s\n'%(filename,lineno,routine))sys.exit(2)def_scons_user_warning(e):"""Handle user warnings. Print out a message and a description of the warning, along with the line number and routine where it occured. The file and line number will be the deepest stack frame that is not part of SCons itself. """etype,value,tb=sys.exc_info()filename,lineno,routine,dummy=find_deepest_user_frame(traceback.extract_tb(tb))sys.stderr.write("\nscons: warning: %s\n"%e)sys.stderr.write('File "%s", line %d, in %s\n'%(filename,lineno,routine))def_scons_internal_warning(e):"""Slightly different from _scons_user_warning in that we use the *current call stack* rather than sys.exc_info() to get our stack trace. This is used by the warnings framework to print warnings."""filename,lineno,routine,dummy=find_deepest_user_frame(traceback.extract_stack())sys.stderr.write("\nscons: warning: %s\n"%e.args[0])sys.stderr.write('File "%s", line %d, in %s\n'%(filename,lineno,routine))def_scons_internal_error():"""Handle all errors but user errors. Print out a message telling the user what to do in this case and print a normal trace. """print'internal error'traceback.print_exc()sys.exit(2)def_SConstruct_exists(dirname='',repositories=[],filelist=None):"""This function checks that an SConstruct file exists in a directory. If so, it returns the path of the file. By default, it checks the current directory. """ifnotfilelist:filelist=['SConstruct','Sconstruct','sconstruct']forfileinfilelist:sfile=os.path.join(dirname,file)ifos.path.isfile(sfile):returnsfileifnotos.path.isabs(sfile):forrepinrepositories:ifos.path.isfile(os.path.join(rep,sfile)):returnsfilereturnNonedef_set_debug_values(options):globalprint_memoizer,print_objects,print_stacktrace,print_timedebug_values=options.debugif"count"indebug_values:# All of the object counts are within "if __debug__:" blocks,# which get stripped when running optimized (with python -O or# from compiled *.pyo files). Provide a warning if __debug__ is# stripped, so it doesn't just look like --debug=count is broken.enable_count=Falseif__debug__:enable_count=Trueifenable_count:count_stats.enable(sys.stdout)else:msg="--debug=count is not supported when running SCons\n"+ \
"\twith the python -O option or optimized (.pyo) modules."SCons.Warnings.warn(SCons.Warnings.NoObjectCountWarning,msg)if"dtree"indebug_values:options.tree_printers.append(TreePrinter(derived=True))options.debug_explain=("explain"indebug_values)if"findlibs"indebug_values:SCons.Scanner.Prog.print_find_libs="findlibs"options.debug_includes=("includes"indebug_values)print_memoizer=("memoizer"indebug_values)if"memory"indebug_values:memory_stats.enable(sys.stdout)print_objects=("objects"indebug_values)if"presub"indebug_values:SCons.Action.print_actions_presub=1if"stacktrace"indebug_values:print_stacktrace=1if"stree"indebug_values:options.tree_printers.append(TreePrinter(status=True))if"time"indebug_values:print_time=1if"tree"indebug_values:options.tree_printers.append(TreePrinter())if"prepare"indebug_values:SCons.Taskmaster.print_prepare=1if"duplicate"indebug_values:SCons.Node.FS.print_duplicate=1def_create_path(plist):path='.'fordinplist:ifos.path.isabs(d):path=delse:path=path+'/'+dreturnpathdef_load_site_scons_dir(topdir,site_dir_name=None):"""Load the site_scons dir under topdir. Prepends site_scons to sys.path, imports site_scons/site_init.py, and prepends site_scons/site_tools to default toolpath."""ifsite_dir_name:err_if_not_found=True# user specified: err if missingelse:site_dir_name="site_scons"err_if_not_found=Falsesite_dir=os.path.join(topdir,site_dir_name)ifnotos.path.exists(site_dir):iferr_if_not_found:raiseSCons.Errors.UserError("site dir %s not found."%site_dir)returnsite_init_filename="site_init.py"site_init_modname="site_init"site_tools_dirname="site_tools"# prepend to sys.pathsys.path=[os.path.abspath(site_dir)]+sys.pathsite_init_file=os.path.join(site_dir,site_init_filename)site_tools_dir=os.path.join(site_dir,site_tools_dirname)ifos.path.exists(site_init_file):importimp,re# TODO(2.4): turn this into try:-except:-finally:try:try:fp,pathname,description=imp.find_module(site_init_modname,[site_dir])# Load the file into SCons.Script namespace. This is# opaque and clever; m is the module object for the# SCons.Script module, and the exec ... in call executes a# file (or string containing code) in the context of the# module's dictionary, so anything that code defines ends# up adding to that module. This is really short, but all# the error checking makes it longer.try:m=sys.modules['SCons.Script']exceptException,e:fmt='cannot import site_init.py: missing SCons.Script module %s'raiseSCons.Errors.InternalError(fmt%repr(e))try:sfx=description[0]modname=os.path.basename(pathname)[:-len(sfx)]site_m={"__file__":pathname,"__name__":modname,"__doc__":None}re_special=re.compile("__[^_]+__")forkinm.__dict__.keys():ifnotre_special.match(k):site_m[k]=m.__dict__[k]# This is the magic.execfpinsite_mexceptKeyboardInterrupt:raiseexceptException,e:fmt='*** Error loading site_init file %s:\n'sys.stderr.write(fmt%repr(site_init_file))raiseelse:forkinsite_m:ifnotre_special.match(k):m.__dict__[k]=site_m[k]exceptKeyboardInterrupt:raiseexceptImportError,e:fmt='*** cannot import site init file %s:\n'sys.stderr.write(fmt%repr(site_init_file))raisefinally:iffp:fp.close()ifos.path.exists(site_tools_dir):# prepend to DefaultToolpathSCons.Tool.DefaultToolpath.insert(0,os.path.abspath(site_tools_dir))def_load_all_site_scons_dirs(topdir,verbose=None):"""Load all of the predefined site_scons dir. Order is significant; we load them in order from most generic (machine-wide) to most specific (topdir). The verbose argument is only for testing. """platform=SCons.Platform.platform_default()defhomedir(d):returnos.path.expanduser('~/'+d)ifplatform=='win32'orplatform=='cygwin':# Note we use $ here instead of %...% because older# pythons (prior to 2.6?) didn't expand %...% on Windows.# This set of dirs should work on XP, Vista, 7 and later.sysdirs=[os.path.expandvars('$ALLUSERSPROFILE\\Application Data\\scons'),os.path.expandvars('$USERPROFILE\\Local Settings\\Application Data\\scons')]appdatadir=os.path.expandvars('$APPDATA\\scons')ifappdatadirnotinsysdirs:sysdirs.append(appdatadir)sysdirs.append(homedir('.scons'))elifplatform=='darwin':# MacOS Xsysdirs=['/Library/Application Support/SCons','/opt/local/share/scons',# (for MacPorts)'/sw/share/scons',# (for Fink)homedir('Library/Application Support/SCons'),homedir('.scons')]elifplatform=='sunos':# Solarissysdirs=['/opt/sfw/scons','/usr/share/scons',homedir('.scons')]else:# Linux, HPUX, etc.# assume posix-like, i.e. platform == 'posix'sysdirs=['/usr/share/scons',homedir('.scons')]dirs=sysdirs+[topdir]fordindirs:ifverbose:# this is used by unit tests.print"Loading site dir ",d_load_site_scons_dir(d)deftest_load_all_site_scons_dirs(d):_load_all_site_scons_dirs(d,True)defversion_string(label,module):version=module.__version__build=module.__build__ifbuild:ifbuild[0]!='.':build='.'+buildversion=version+buildfmt="\t%s: v%s, %s, by %s on %s\n"returnfmt%(label,version,module.__date__,module.__developer__,module.__buildsys__)defpath_string(label,module):path=module.__path__return"\t%s path: %s\n"%(label,path)def_main(parser):globalexit_statusglobalthis_build_statusoptions=parser.values# Here's where everything really happens.# First order of business: set up default warnings and then# handle the user's warning options, so that we can issue (or# suppress) appropriate warnings about anything that might happen,# as configured by the user.default_warnings=[SCons.Warnings.WarningOnByDefault,SCons.Warnings.DeprecatedWarning,]forwarningindefault_warnings:SCons.Warnings.enableWarningClass(warning)SCons.Warnings._warningOut=_scons_internal_warningSCons.Warnings.process_warn_strings(options.warn)# Now that we have the warnings configuration set up, we can actually# issue (or suppress) any warnings about warning-worthy things that# occurred while the command-line options were getting parsed.try:dw=options.delayed_warningsexceptAttributeError:passelse:delayed_warnings.extend(dw)forwarning_type,messageindelayed_warnings:SCons.Warnings.warn(warning_type,message)ifoptions.diskcheck:SCons.Node.FS.set_diskcheck(options.diskcheck)# Next, we want to create the FS object that represents the outside# world's file system, as that's central to a lot of initialization.# To do this, however, we need to be in the directory from which we# want to start everything, which means first handling any relevant# options that might cause us to chdir somewhere (-C, -D, -U, -u).ifoptions.directory:script_dir=os.path.abspath(_create_path(options.directory))else:script_dir=os.getcwd()target_top=Noneifoptions.climb_up:target_top='.'# directory to prepend to targetswhilescript_dirandnot_SConstruct_exists(script_dir,options.repository,options.file):script_dir,last_part=os.path.split(script_dir)iflast_part:target_top=os.path.join(last_part,target_top)else:script_dir=''ifscript_dirandscript_dir!=os.getcwd():ifnotoptions.silent:display("scons: Entering directory `%s'"%script_dir)try:os.chdir(script_dir)exceptOSError:sys.stderr.write("Could not change directory to %s\n"%script_dir)# Now that we're in the top-level SConstruct directory, go ahead# and initialize the FS object that represents the file system,# and make it the build engine default.fs=SCons.Node.FS.get_default_fs()forrepinoptions.repository:fs.Repository(rep)# Now that we have the FS object, the next order of business is to# check for an SConstruct file (or other specified config file).# If there isn't one, we can bail before doing any more work.scripts=[]ifoptions.file:scripts.extend(options.file)ifnotscripts:sfile=_SConstruct_exists(repositories=options.repository,filelist=options.file)ifsfile:scripts.append(sfile)ifnotscripts:ifoptions.help:# There's no SConstruct, but they specified -h.# Give them the options usage now, before we fail# trying to read a non-existent SConstruct file.raiseSConsPrintHelpExceptionraiseSCons.Errors.UserError("No SConstruct file found.")ifscripts[0]=="-":d=fs.getcwd()else:d=fs.File(scripts[0]).dirfs.set_SConstruct_dir(d)_set_debug_values(options)SCons.Node.implicit_cache=options.implicit_cacheSCons.Node.implicit_deps_changed=options.implicit_deps_changedSCons.Node.implicit_deps_unchanged=options.implicit_deps_unchangedifoptions.no_exec:SCons.SConf.dryrun=1SCons.Action.execute_actions=Noneifoptions.question:SCons.SConf.dryrun=1ifoptions.clean:SCons.SConf.SetBuildType('clean')ifoptions.help:SCons.SConf.SetBuildType('help')SCons.SConf.SetCacheMode(options.config)SCons.SConf.SetProgressDisplay(progress_display)ifoptions.no_progressoroptions.silent:progress_display.set_mode(0)ifoptions.site_dir:_load_site_scons_dir(d.path,options.site_dir)elifnotoptions.no_site_dir:_load_all_site_scons_dirs(d.path)ifoptions.include_dir:sys.path=options.include_dir+sys.path# That should cover (most of) the options. Next, set up the variables# that hold command-line arguments, so the SConscript files that we# read and execute have access to them.targets=[]xmit_args=[]forainparser.largs:ifa[:1]=='-':continueif'='ina:xmit_args.append(a)else:targets.append(a)SCons.Script._Add_Targets(targets+parser.rargs)SCons.Script._Add_Arguments(xmit_args)# If stdout is not a tty, replace it with a wrapper object to call flush# after every write.## Tty devices automatically flush after every newline, so the replacement# isn't necessary. Furthermore, if we replace sys.stdout, the readline# module will no longer work. This affects the behavior during# --interactive mode. --interactive should only be used when stdin and# stdout refer to a tty.ifnothasattr(sys.stdout,'isatty')ornotsys.stdout.isatty():sys.stdout=SCons.Util.Unbuffered(sys.stdout)ifnothasattr(sys.stderr,'isatty')ornotsys.stderr.isatty():sys.stderr=SCons.Util.Unbuffered(sys.stderr)memory_stats.append('before reading SConscript files:')count_stats.append(('pre-','read'))# And here's where we (finally) read the SConscript files.progress_display("scons: Reading SConscript files ...")start_time=time.time()try:forscriptinscripts:SCons.Script._SConscript._SConscript(fs,script)exceptSCons.Errors.StopError,e:# We had problems reading an SConscript file, such as it# couldn't be copied in to the VariantDir. Since we're just# reading SConscript files and haven't started building# things yet, stop regardless of whether they used -i or -k# or anything else.sys.stderr.write("scons: *** %s Stop.\n"%e)exit_status=2sys.exit(exit_status)globalsconscript_timesconscript_time=time.time()-start_timeprogress_display("scons: done reading SConscript files.")memory_stats.append('after reading SConscript files:')count_stats.append(('post-','read'))# Re-{enable,disable} warnings in case they disabled some in# the SConscript file.## We delay enabling the PythonVersionWarning class until here so that,# if they explicity disabled it in either in the command line or in# $SCONSFLAGS, or in the SConscript file, then the search through# the list of deprecated warning classes will find that disabling# first and not issue the warning.#SCons.Warnings.enableWarningClass(SCons.Warnings.PythonVersionWarning)SCons.Warnings.process_warn_strings(options.warn)# Now that we've read the SConscript files, we can check for the# warning about deprecated Python versions--delayed until here# in case they disabled the warning in the SConscript files.ifpython_version_deprecated():msg="Support for pre-2.4 Python (%s) is deprecated.\n"+ \
" If this will cause hardship, contact dev@scons.tigris.org."SCons.Warnings.warn(SCons.Warnings.PythonVersionWarning,msg%python_version_string())ifnotoptions.help:SCons.SConf.CreateConfigHBuilder(SCons.Defaults.DefaultEnvironment())# Now re-parse the command-line options (any to the left of a '--'# argument, that is) with any user-defined command-line options that# the SConscript files may have added to the parser object. This will# emit the appropriate error message and exit if any unknown option# was specified on the command line.parser.preserve_unknown_options=Falseparser.parse_args(parser.largs,options)ifoptions.help:help_text=SCons.Script.help_textifhelp_textisNone:# They specified -h, but there was no Help() inside the# SConscript files. Give them the options usage.raiseSConsPrintHelpExceptionelse:printhelp_textprint"Use scons -H for help about command-line options."exit_status=0return# Change directory to the top-level SConstruct directory, then tell# the Node.FS subsystem that we're all done reading the SConscript# files and calling Repository() and VariantDir() and changing# directories and the like, so it can go ahead and start memoizing# the string values of file system nodes.fs.chdir(fs.Top)SCons.Node.FS.save_strings(1)# Now that we've read the SConscripts we can set the options# that are SConscript settable:SCons.Node.implicit_cache=options.implicit_cacheSCons.Node.FS.set_duplicate(options.duplicate)fs.set_max_drift(options.max_drift)SCons.Job.explicit_stack_size=options.stack_sizeifoptions.md5_chunksize:SCons.Node.FS.File.md5_chunksize=options.md5_chunksizeplatform=SCons.Platform.platform_module()ifoptions.interactive:SCons.Script.Interactive.interact(fs,OptionsParser,options,targets,target_top)else:# Build the targetsnodes=_build_targets(fs,options,targets,target_top)ifnotnodes:exit_status=2def_build_targets(fs,options,targets,target_top):globalthis_build_statusthis_build_status=0progress_display.set_mode(not(options.no_progressoroptions.silent))display.set_mode(notoptions.silent)SCons.Action.print_actions=notoptions.silentSCons.Action.execute_actions=notoptions.no_execSCons.Node.FS.do_store_info=notoptions.no_execSCons.SConf.dryrun=options.no_execifoptions.diskcheck:SCons.Node.FS.set_diskcheck(options.diskcheck)SCons.CacheDir.cache_enabled=notoptions.cache_disableSCons.CacheDir.cache_debug=options.cache_debugSCons.CacheDir.cache_force=options.cache_forceSCons.CacheDir.cache_show=options.cache_showifoptions.no_exec:CleanTask.execute=CleanTask.showelse:CleanTask.execute=CleanTask.removelookup_top=NoneiftargetsorSCons.Script.BUILD_TARGETS!=SCons.Script._build_plus_default:# They specified targets on the command line or modified# BUILD_TARGETS in the SConscript file(s), so if they used -u,# -U or -D, we have to look up targets relative to the top,# but we build whatever they specified.iftarget_top:lookup_top=fs.Dir(target_top)target_top=Nonetargets=SCons.Script.BUILD_TARGETSelse:# There are no targets specified on the command line,# so if they used -u, -U or -D, we may have to restrict# what actually gets built.d=Noneiftarget_top:ifoptions.climb_up==1:# -u, local directory and belowtarget_top=fs.Dir(target_top)lookup_top=target_topelifoptions.climb_up==2:# -D, all Default() targetstarget_top=Nonelookup_top=Noneelifoptions.climb_up==3:# -U, local SConscript Default() targetstarget_top=fs.Dir(target_top)defcheck_dir(x,target_top=target_top):ifhasattr(x,'cwd')andnotx.cwdisNone:cwd=x.cwd.srcnode()returncwd==target_topelse:# x doesn't have a cwd, so it's either not a target,# or not a file, so go ahead and keep it as a default# target and let the engine sort it out:return1d=list(filter(check_dir,SCons.Script.DEFAULT_TARGETS))SCons.Script.DEFAULT_TARGETS[:]=dtarget_top=Nonelookup_top=Nonetargets=SCons.Script._Get_Default_Targets(d,fs)ifnottargets:sys.stderr.write("scons: *** No targets specified and no Default() targets found. Stop.\n")returnNonedefEntry(x,ltop=lookup_top,ttop=target_top,fs=fs):ifisinstance(x,SCons.Node.Node):node=xelse:node=None# Why would ltop be None? Unfortunately this happens.ifltopisNone:ltop=''# Curdir becomes important when SCons is called with -u, -C,# or similar option that changes directory, and so the paths# of targets given on the command line need to be adjusted.curdir=os.path.join(os.getcwd(),str(ltop))forlookupinSCons.Node.arg2nodes_lookups:node=lookup(x,curdir=curdir)ifnodeisnotNone:breakifnodeisNone:node=fs.Entry(x,directory=ltop,create=1)ifttopandnotnode.is_under(ttop):ifisinstance(node,SCons.Node.FS.Dir)andttop.is_under(node):node=ttopelse:node=Nonereturnnodenodes=[_ffor_finmap(Entry,targets)if_f]task_class=BuildTask# default action is to build targetsopening_message="Building targets ..."closing_message="done building targets."ifoptions.keep_going:failure_message="done building targets (errors occurred during build)."else:failure_message="building terminated because of errors."ifoptions.question:task_class=QuestionTasktry:ifoptions.clean:task_class=CleanTaskopening_message="Cleaning targets ..."closing_message="done cleaning targets."ifoptions.keep_going:failure_message="done cleaning targets (errors occurred during clean)."else:failure_message="cleaning terminated because of errors."exceptAttributeError:passtask_class.progress=ProgressObjectifoptions.random:deforder(dependencies):"""Randomize the dependencies."""importrandom# This is cribbed from the implementation of# random.shuffle() in Python 2.X.d=dependenciesforiinrange(len(d)-1,0,-1):j=int(random.random()*(i+1))d[i],d[j]=d[j],d[i]returndelse:deforder(dependencies):"""Leave the order of dependencies alone."""returndependenciesifoptions.taskmastertrace_file=='-':tmtrace=sys.stdoutelifoptions.taskmastertrace_file:tmtrace=open(options.taskmastertrace_file,'wb')else:tmtrace=Nonetaskmaster=SCons.Taskmaster.Taskmaster(nodes,task_class,order,tmtrace)# Let the BuildTask objects get at the options to respond to the# various print_* settings, tree_printer list, etc.BuildTask.options=optionsglobalnum_jobsnum_jobs=options.num_jobsjobs=SCons.Job.Jobs(num_jobs,taskmaster)ifnum_jobs>1:msg=Noneifjobs.num_jobs==1:msg="parallel builds are unsupported by this version of Python;\n"+ \
"\tignoring -j or num_jobs option.\n"elifsys.platform=='win32':msg=fetch_win32_parallel_msg()ifmsg:SCons.Warnings.warn(SCons.Warnings.NoParallelSupportWarning,msg)memory_stats.append('before building targets:')count_stats.append(('pre-','build'))defjobs_postfunc(jobs=jobs,options=options,closing_message=closing_message,failure_message=failure_message):ifjobs.were_interrupted():ifnotoptions.no_progressandnotoptions.silent:sys.stderr.write("scons: Build interrupted.\n")globalexit_statusglobalthis_build_statusexit_status=2this_build_status=2ifthis_build_status:progress_display("scons: "+failure_message)else:progress_display("scons: "+closing_message)ifnotoptions.no_exec:ifjobs.were_interrupted():progress_display("scons: writing .sconsign file.")SCons.SConsign.write()progress_display("scons: "+opening_message)jobs.run(postfunc=jobs_postfunc)memory_stats.append('after building targets:')count_stats.append(('post-','build'))returnnodesdef_exec_main(parser,values):sconsflags=os.environ.get('SCONSFLAGS','')all_args=sconsflags.split()+sys.argv[1:]options,args=parser.parse_args(all_args,values)ifisinstance(options.debug,list)and"pdb"inoptions.debug:importpdbpdb.Pdb().runcall(_main,parser)elifoptions.profile_file:# compat layer imports "cProfile" for us if it's available.fromprofileimportProfile# Some versions of Python 2.4 shipped a profiler that had the# wrong 'c_exception' entry in its dispatch table. Make sure# we have the right one. (This may put an unnecessary entry# in the table in earlier versions of Python, but its presence# shouldn't hurt anything).try:dispatch=Profile.dispatchexceptAttributeError:passelse:dispatch['c_exception']=Profile.trace_dispatch_returnprof=Profile()try:prof.runcall(_main,parser)exceptSConsPrintHelpException,e:prof.dump_stats(options.profile_file)raiseeexceptSystemExit:passprof.dump_stats(options.profile_file)else:_main(parser)defmain():globalOptionsParserglobalexit_statusglobalfirst_command_start# Check up front for a Python version we do not support. We# delay the check for deprecated Python versions until later,# after the SConscript files have been read, in case they# disable that warning.ifpython_version_unsupported():msg="scons: *** SCons version %s does not run under Python version %s.\n"sys.stderr.write(msg%(SCons.__version__,python_version_string()))sys.exit(1)parts=["SCons by Steven Knight et al.:\n"]try:import__main__parts.append(version_string("script",__main__))except(ImportError,AttributeError):# On Windows there is no scons.py, so there is no# __main__.__version__, hence there is no script version.passparts.append(version_string("engine",SCons))parts.append(path_string("engine",SCons))parts.append("__COPYRIGHT__")version=''.join(parts)importSConsOptionsparser=SConsOptions.Parser(version)values=SConsOptions.SConsValues(parser.get_default_values())OptionsParser=parsertry:_exec_main(parser,values)exceptSystemExit,s:ifs:exit_status=sexceptKeyboardInterrupt:print("scons: Build interrupted.")sys.exit(2)exceptSyntaxError,e:_scons_syntax_error(e)exceptSCons.Errors.InternalError:_scons_internal_error()exceptSCons.Errors.UserError,e:_scons_user_error(e)exceptSConsPrintHelpException:parser.print_help()exit_status=0exceptSCons.Errors.BuildError,e:exit_status=e.exitstatusexcept:# An exception here is likely a builtin Python exception Python# code in an SConscript file. Show them precisely what the# problem was and where it happened.SCons.Script._SConscript.SConscript_exception()sys.exit(2)memory_stats.print_stats()count_stats.print_stats()ifprint_objects:SCons.Debug.listLoggedInstances('*')#SCons.Debug.dumpLoggedInstances('*')ifprint_memoizer:SCons.Memoize.Dump("Memoizer (memory cache) hits and misses:")# Dump any development debug info that may have been enabled.# These are purely for internal debugging during development, so# there's no need to control them with --debug= options; they're# controlled by changing the source code.SCons.Debug.dump_caller_counts()SCons.Taskmaster.dump_stats()ifprint_time:total_time=time.time()-SCons.Script.start_timeifnum_jobs==1:ct=cumulative_command_timeelse:iflast_command_endisNoneorfirst_command_startisNone:ct=0.0else:ct=last_command_end-first_command_startscons_time=total_time-sconscript_time-ctprint"Total build time: %f seconds"%total_timeprint"Total SConscript file execution time: %f seconds"%sconscript_timeprint"Total SCons execution time: %f seconds"%scons_timeprint"Total command execution time: %f seconds"%ctsys.exit(exit_status)# Local Variables:# tab-width:4# indent-tabs-mode:nil# End:# vim: set expandtab tabstop=4 shiftwidth=4: