"""SCons.EnvironmentBase class for construction Environments. These arethe primary objects used to communicate dependency andconstruction information to the build engine.Keyword arguments supplied when the construction Environmentis created are construction variables used to initialize theEnvironment"""## __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__"importcopyimportosimportsysimportreimportshlexfromcollectionsimportUserDictimportSCons.ActionimportSCons.BuilderfromSCons.DebugimportlogInstanceCreationimportSCons.DefaultsimportSCons.ErrorsimportSCons.MemoizeimportSCons.NodeimportSCons.Node.AliasimportSCons.Node.FSimportSCons.Node.PythonimportSCons.PlatformimportSCons.SConfimportSCons.SConsignimportSCons.SubstimportSCons.ToolimportSCons.UtilimportSCons.Warningsclass_Null(object):pass_null=_Null_warn_copy_deprecated=True_warn_source_signatures_deprecated=True_warn_target_signatures_deprecated=TrueCleanTargets={}CalculatorArgs={}semi_deepcopy=SCons.Util.semi_deepcopysemi_deepcopy_dict=SCons.Util.semi_deepcopy_dict# Pull UserError into the global name space for the benefit of# Environment().SourceSignatures(), which has some import statements# which seem to mess up its ability to reference SCons directly.UserError=SCons.Errors.UserErrordefalias_builder(env,target,source):passAliasBuilder=SCons.Builder.Builder(action=alias_builder,target_factory=SCons.Node.Alias.default_ans.Alias,source_factory=SCons.Node.FS.Entry,multi=1,is_explicit=None,name='AliasBuilder')defapply_tools(env,tools,toolpath):# Store the toolpath in the Environment.iftoolpathisnotNone:env['toolpath']=toolpathifnottools:return# Filter out null tools from the list.fortoolin[_ffor_fintoolsif_f]:ifSCons.Util.is_List(tool)orisinstance(tool,tuple):toolname=tool[0]toolargs=tool[1]# should be a dict of kw argstool=env.Tool(toolname,**toolargs)else:env.Tool(tool)# These names are (or will be) controlled by SCons; users should never# set or override them. This warning can optionally be turned off,# but scons will still ignore the illegal variable names even if it's off.reserved_construction_var_names=['CHANGED_SOURCES','CHANGED_TARGETS','SOURCE','SOURCES','TARGET','TARGETS','UNCHANGED_SOURCES','UNCHANGED_TARGETS',]future_reserved_construction_var_names=[#'HOST_OS',#'HOST_ARCH',#'HOST_CPU',]defcopy_non_reserved_keywords(dict):result=semi_deepcopy(dict)forkinresult.keys():ifkinreserved_construction_var_names:msg="Ignoring attempt to set reserved variable `$%s'"SCons.Warnings.warn(SCons.Warnings.ReservedVariableWarning,msg%k)delresult[k]returnresultdef_set_reserved(env,key,value):msg="Ignoring attempt to set reserved variable `$%s'"SCons.Warnings.warn(SCons.Warnings.ReservedVariableWarning,msg%key)def_set_future_reserved(env,key,value):env._dict[key]=valuemsg="`$%s' will be reserved in a future release and setting it will become ignored"SCons.Warnings.warn(SCons.Warnings.FutureReservedVariableWarning,msg%key)def_set_BUILDERS(env,key,value):try:bd=env._dict[key]forkinbd.keys():delbd[k]exceptKeyError:bd=BuilderDict(kwbd,env)env._dict[key]=bdfork,vinvalue.items():ifnotSCons.Builder.is_a_Builder(v):raiseSCons.Errors.UserError('%s is not a Builder.'%repr(v))bd.update(value)def_del_SCANNERS(env,key):delenv._dict[key]env.scanner_map_delete()def_set_SCANNERS(env,key,value):env._dict[key]=valueenv.scanner_map_delete()def_delete_duplicates(l,keep_last):"""Delete duplicates from a sequence, keeping the first or last."""seen={}result=[]ifkeep_last:# reverse in & out, then keep firstl.reverse()foriinl:try:ifinotinseen:result.append(i)seen[i]=1exceptTypeError:# probably unhashable. Just keep it.result.append(i)ifkeep_last:result.reverse()returnresult# The following is partly based on code in a comment added by Peter# Shannon at the following page (there called the "transplant" class):## ASPN : Python Cookbook : Dynamically added methods to a class# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732## We had independently been using the idiom as BuilderWrapper, but# factoring out the common parts into this base class, and making# BuilderWrapper a subclass that overrides __call__() to enforce specific# Builder calling conventions, simplified some of our higher-layer code.classMethodWrapper(object):""" A generic Wrapper class that associates a method (which can actually be any callable) with an object. As part of creating this MethodWrapper object an attribute with the specified (by default, the name of the supplied method) is added to the underlying object. When that new "method" is called, our __call__() method adds the object as the first argument, simulating the Python behavior of supplying "self" on method calls. We hang on to the name by which the method was added to the underlying base class so that we can provide a method to "clone" ourselves onto a new underlying object being copied (without which we wouldn't need to save that info). """def__init__(self,object,method,name=None):ifnameisNone:name=method.__name__self.object=objectself.method=methodself.name=namesetattr(self.object,name,self)def__call__(self,*args,**kwargs):nargs=(self.object,)+argsreturnself.method(*nargs,**kwargs)defclone(self,new_object):""" Returns an object that re-binds the underlying "method" to the specified new object. """returnself.__class__(new_object,self.method,self.name)classBuilderWrapper(MethodWrapper):""" A MethodWrapper subclass that that associates an environment with a Builder. This mainly exists to wrap the __call__() function so that all calls to Builders can have their argument lists massaged in the same way (treat a lone argument as the source, treat two arguments as target then source, make sure both target and source are lists) without having to have cut-and-paste code to do it. As a bit of obsessive backwards compatibility, we also intercept attempts to get or set the "env" or "builder" attributes, which were the names we used before we put the common functionality into the MethodWrapper base class. We'll keep this around for a while in case people shipped Tool modules that reached into the wrapper (like the Tool/qt.py module does, or did). There shouldn't be a lot attribute fetching or setting on these, so a little extra work shouldn't hurt. """def__call__(self,target=None,source=_null,*args,**kw):ifsourceis_null:source=targettarget=NoneiftargetisnotNoneandnotSCons.Util.is_List(target):target=[target]ifsourceisnotNoneandnotSCons.Util.is_List(source):source=[source]returnMethodWrapper.__call__(self,target,source,*args,**kw)def__repr__(self):return'<BuilderWrapper %s>'%repr(self.name)def__str__(self):returnself.__repr__()def__getattr__(self,name):ifname=='env':returnself.objectelifname=='builder':returnself.methodelse:raiseAttributeError(name)def__setattr__(self,name,value):ifname=='env':self.object=valueelifname=='builder':self.method=valueelse:self.__dict__[name]=value# This allows a Builder to be executed directly# through the Environment to which it's attached.# In practice, we shouldn't need this, because# builders actually get executed through a Node.# But we do have a unit test for this, and can't# yet rule out that it would be useful in the# future, so leave it for now.#def execute(self, **kw):# kw['env'] = self.env# self.builder.execute(**kw)classBuilderDict(UserDict):"""This is a dictionary-like class used by an Environment to hold the Builders. We need to do this because every time someone changes the Builders in the Environment's BUILDERS dictionary, we must update the Environment's attributes."""def__init__(self,dict,env):# Set self.env before calling the superclass initialization,# because it will end up calling our other methods, which will# need to point the values in this dictionary to self.env.self.env=envUserDict.__init__(self,dict)def__semi_deepcopy__(self):# These cannot be copied since they would both modify the same builder object, and indeed# just copying would modify the original builderraiseTypeError('cannot semi_deepcopy a BuilderDict')def__setitem__(self,item,val):try:method=getattr(self.env,item).methodexceptAttributeError:passelse:self.env.RemoveMethod(method)UserDict.__setitem__(self,item,val)BuilderWrapper(self.env,val,item)def__delitem__(self,item):UserDict.__delitem__(self,item)delattr(self.env,item)defupdate(self,dict):fori,vindict.items():self.__setitem__(i,v)_is_valid_var=re.compile(r'[_a-zA-Z]\w*$')defis_valid_construction_var(varstr):"""Return if the specified string is a legitimate construction variable. """return_is_valid_var.match(varstr)classSubstitutionEnvironment(object):"""Base class for different flavors of construction environments. This class contains a minimal set of methods that handle contruction variable expansion and conversion of strings to Nodes, which may or may not be actually useful as a stand-alone class. Which methods ended up in this class is pretty arbitrary right now. They're basically the ones which we've empirically determined are common to the different construction environment subclasses, and most of the others that use or touch the underlying dictionary of construction variables. Eventually, this class should contain all the methods that we determine are necessary for a "minimal" interface to the build engine. A full "native Python" SCons environment has gotten pretty heavyweight with all of the methods and Tools and construction variables we've jammed in there, so it would be nice to have a lighter weight alternative for interfaces that don't need all of the bells and whistles. (At some point, we'll also probably rename this class "Base," since that more reflects what we want this class to become, but because we've released comments that tell people to subclass Environment.Base to create their own flavors of construction environment, we'll save that for a future refactoring when this class actually becomes useful.) """ifSCons.Memoize.use_memoizer:__metaclass__=SCons.Memoize.Memoized_Metaclassdef__init__(self,**kw):"""Initialization of an underlying SubstitutionEnvironment class. """if__debug__:logInstanceCreation(self,'Environment.SubstitutionEnvironment')self.fs=SCons.Node.FS.get_default_fs()self.ans=SCons.Node.Alias.default_ansself.lookup_list=SCons.Node.arg2nodes_lookupsself._dict=kw.copy()self._init_special()self.added_methods=[]#self._memo = {}def_init_special(self):"""Initial the dispatch tables for special handling of special construction variables."""self._special_del={}self._special_del['SCANNERS']=_del_SCANNERSself._special_set={}forkeyinreserved_construction_var_names:self._special_set[key]=_set_reservedforkeyinfuture_reserved_construction_var_names:self._special_set[key]=_set_future_reservedself._special_set['BUILDERS']=_set_BUILDERSself._special_set['SCANNERS']=_set_SCANNERS# Freeze the keys of self._special_set in a list for use by# methods that need to check. (Empirically, list scanning has# gotten better than dict.has_key() in Python 2.5.)self._special_set_keys=list(self._special_set.keys())def__cmp__(self,other):returncmp(self._dict,other._dict)def__delitem__(self,key):special=self._special_del.get(key)ifspecial:special(self,key)else:delself._dict[key]def__getitem__(self,key):returnself._dict[key]def__setitem__(self,key,value):# This is heavily used. This implementation is the best we have# according to the timings in bench/env.__setitem__.py.## The "key in self._special_set_keys" test here seems to perform# pretty well for the number of keys we have. A hard-coded# list works a little better in Python 2.5, but that has the# disadvantage of maybe getting out of sync if we ever add more# variable names. Using self._special_set.has_key() works a# little better in Python 2.4, but is worse than this test.# So right now it seems like a good trade-off, but feel free to# revisit this with bench/env.__setitem__.py as needed (and# as newer versions of Python come out).ifkeyinself._special_set_keys:self._special_set[key](self,key,value)else:# If we already have the entry, then it's obviously a valid# key and we don't need to check. If we do check, using a# global, pre-compiled regular expression directly is more# efficient than calling another function or a method.ifkeynotinself._dict \
andnot_is_valid_var.match(key):raiseSCons.Errors.UserError("Illegal construction variable `%s'"%key)self._dict[key]=valuedefget(self,key,default=None):"""Emulates the get() method of dictionaries."""returnself._dict.get(key,default)defhas_key(self,key):returnkeyinself._dictdef__contains__(self,key):returnself._dict.__contains__(key)defitems(self):returnlist(self._dict.items())defarg2nodes(self,args,node_factory=_null,lookup_list=_null,**kw):ifnode_factoryis_null:node_factory=self.fs.Fileiflookup_listis_null:lookup_list=self.lookup_listifnotargs:return[]args=SCons.Util.flatten(args)nodes=[]forvinargs:ifSCons.Util.is_String(v):n=Noneforlinlookup_list:n=l(v)ifnisnotNone:breakifnisnotNone:ifSCons.Util.is_String(n):# n = self.subst(n, raw=1, **kw)kw['raw']=1n=self.subst(n,**kw)ifnode_factory:n=node_factory(n)ifSCons.Util.is_List(n):nodes.extend(n)else:nodes.append(n)elifnode_factory:# v = node_factory(self.subst(v, raw=1, **kw))kw['raw']=1v=node_factory(self.subst(v,**kw))ifSCons.Util.is_List(v):nodes.extend(v)else:nodes.append(v)else:nodes.append(v)returnnodesdefgvars(self):returnself._dictdeflvars(self):return{}defsubst(self,string,raw=0,target=None,source=None,conv=None,executor=None):"""Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters. """gvars=self.gvars()lvars=self.lvars()lvars['__env__']=selfifexecutor:lvars.update(executor.get_lvars())returnSCons.Subst.scons_subst(string,self,raw,target,source,gvars,lvars,conv)defsubst_kw(self,kw,raw=0,target=None,source=None):nkw={}fork,vinkw.items():k=self.subst(k,raw,target,source)ifSCons.Util.is_String(v):v=self.subst(v,raw,target,source)nkw[k]=vreturnnkwdefsubst_list(self,string,raw=0,target=None,source=None,conv=None,executor=None):"""Calls through to SCons.Subst.scons_subst_list(). See the documentation for that function."""gvars=self.gvars()lvars=self.lvars()lvars['__env__']=selfifexecutor:lvars.update(executor.get_lvars())returnSCons.Subst.scons_subst_list(string,self,raw,target,source,gvars,lvars,conv)defsubst_path(self,path,target=None,source=None):"""Substitute a path list, turning EntryProxies into Nodes and leaving Nodes (and other objects) as-is."""ifnotSCons.Util.is_List(path):path=[path]defs(obj):"""This is the "string conversion" routine that we have our substitutions use to return Nodes, not strings. This relies on the fact that an EntryProxy object has a get() method that returns the underlying Node that it wraps, which is a bit of architectural dependence that we might need to break or modify in the future in response to additional requirements."""try:get=obj.getexceptAttributeError:obj=SCons.Util.to_String_for_subst(obj)else:obj=get()returnobjr=[]forpinpath:ifSCons.Util.is_String(p):p=self.subst(p,target=target,source=source,conv=s)ifSCons.Util.is_List(p):iflen(p)==1:p=p[0]else:# We have an object plus a string, or multiple# objects that we need to smush together. No choice# but to make them into a string.p=''.join(map(SCons.Util.to_String_for_subst,p))else:p=s(p)r.append(p)returnrsubst_target_source=substdefbacktick(self,command):importsubprocess# common argumentskw={'stdin':'devnull','stdout':subprocess.PIPE,'stderr':subprocess.PIPE,'universal_newlines':True,}# if the command is a list, assume it's been quoted# othewise force a shellifnotSCons.Util.is_List(command):kw['shell']=True# run constructed commandp=SCons.Action._subproc(self,command,**kw)out,err=p.communicate()status=p.wait()iferr:sys.stderr.write(unicode(err))ifstatus:raiseOSError("'%s' exited %d"%(command,status))returnoutdefAddMethod(self,function,name=None):""" Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself. """method=MethodWrapper(self,function,name)self.added_methods.append(method)defRemoveMethod(self,function):""" Removes the specified function's MethodWrapper from the added_methods list, so we don't re-bind it when making a clone. """self.added_methods=[dmfordminself.added_methodsifnotdm.methodisfunction]defOverride(self,overrides):""" Produce a modified environment whose variables are overriden by the overrides dictionaries. "overrides" is a dictionary that will override the variables of this environment. This function is much more efficient than Clone() or creating a new Environment because it doesn't copy the construction environment dictionary, it just wraps the underlying construction environment, and doesn't even create a wrapper object if there are no overrides. """ifnotoverrides:returnselfo=copy_non_reserved_keywords(overrides)ifnoto:returnselfoverrides={}merges=Noneforkey,valueino.items():ifkey=='parse_flags':merges=valueelse:overrides[key]=SCons.Subst.scons_subst_once(value,self,key)env=OverrideEnvironment(self,overrides)ifmerges:env.MergeFlags(merges)returnenvdefParseFlags(self,*flags):""" Parse the set of flags and return a dict with the flags placed in the appropriate entry. The flags are treated as a typical set of command-line flags for a GNU-like toolchain and used to populate the entries in the dict immediately below. If one of the flag strings begins with a bang (exclamation mark), it is assumed to be a command and the rest of the string is executed; the result of that evaluation is then added to the dict. """dict={'ASFLAGS':SCons.Util.CLVar(''),'CFLAGS':SCons.Util.CLVar(''),'CCFLAGS':SCons.Util.CLVar(''),'CXXFLAGS':SCons.Util.CLVar(''),'CPPDEFINES':[],'CPPFLAGS':SCons.Util.CLVar(''),'CPPPATH':[],'FRAMEWORKPATH':SCons.Util.CLVar(''),'FRAMEWORKS':SCons.Util.CLVar(''),'LIBPATH':[],'LIBS':[],'LINKFLAGS':SCons.Util.CLVar(''),'RPATH':[],}defdo_parse(arg):# if arg is a sequence, recurse with each elementifnotarg:returnifnotSCons.Util.is_String(arg):fortinarg:do_parse(t)return# if arg is a command, execute itifarg[0]=='!':arg=self.backtick(arg[1:])# utility function to deal with -D optiondefappend_define(name,dict=dict):t=name.split('=')iflen(t)==1:dict['CPPDEFINES'].append(name)else:dict['CPPDEFINES'].append([t[0],'='.join(t[1:])])# Loop through the flags and add them to the appropriate option.# This tries to strike a balance between checking for all possible# flags and keeping the logic to a finite size, so it doesn't# check for some that don't occur often. It particular, if the# flag is not known to occur in a config script and there's a way# of passing the flag to the right place (by wrapping it in a -W# flag, for example) we don't check for it. Note that most# preprocessor options are not handled, since unhandled options# are placed in CCFLAGS, so unless the preprocessor is invoked# separately, these flags will still get to the preprocessor.# Other options not currently handled:# -iqoutedir (preprocessor search path)# -u symbol (linker undefined symbol)# -s (linker strip files)# -static* (linker static binding)# -shared* (linker dynamic binding)# -symbolic (linker global binding)# -R dir (deprecated linker rpath)# IBM compilers may also accept -qframeworkdir=fooparams=shlex.split(arg)append_next_arg_to=None# for multi-word argsforarginparams:ifappend_next_arg_to:ifappend_next_arg_to=='CPPDEFINES':append_define(arg)elifappend_next_arg_to=='-include':t=('-include',self.fs.File(arg))dict['CCFLAGS'].append(t)elifappend_next_arg_to=='-isysroot':t=('-isysroot',arg)dict['CCFLAGS'].append(t)dict['LINKFLAGS'].append(t)elifappend_next_arg_to=='-arch':t=('-arch',arg)dict['CCFLAGS'].append(t)dict['LINKFLAGS'].append(t)else:dict[append_next_arg_to].append(arg)append_next_arg_to=Noneelifnotarg[0]in['-','+']:dict['LIBS'].append(self.fs.File(arg))elifarg=='-dylib_file':dict['LINKFLAGS'].append(arg)append_next_arg_to='LINKFLAGS'elifarg[:2]=='-L':ifarg[2:]:dict['LIBPATH'].append(arg[2:])else:append_next_arg_to='LIBPATH'elifarg[:2]=='-l':ifarg[2:]:dict['LIBS'].append(arg[2:])else:append_next_arg_to='LIBS'elifarg[:2]=='-I':ifarg[2:]:dict['CPPPATH'].append(arg[2:])else:append_next_arg_to='CPPPATH'elifarg[:4]=='-Wa,':dict['ASFLAGS'].append(arg[4:])dict['CCFLAGS'].append(arg)elifarg[:4]=='-Wl,':ifarg[:11]=='-Wl,-rpath=':dict['RPATH'].append(arg[11:])elifarg[:7]=='-Wl,-R,':dict['RPATH'].append(arg[7:])elifarg[:6]=='-Wl,-R':dict['RPATH'].append(arg[6:])else:dict['LINKFLAGS'].append(arg)elifarg[:4]=='-Wp,':dict['CPPFLAGS'].append(arg)elifarg[:2]=='-D':ifarg[2:]:append_define(arg[2:])else:append_next_arg_to='CPPDEFINES'elifarg=='-framework':append_next_arg_to='FRAMEWORKS'elifarg[:14]=='-frameworkdir=':dict['FRAMEWORKPATH'].append(arg[14:])elifarg[:2]=='-F':ifarg[2:]:dict['FRAMEWORKPATH'].append(arg[2:])else:append_next_arg_to='FRAMEWORKPATH'elifargin['-mno-cygwin','-pthread','-openmp','-fopenmp']:dict['CCFLAGS'].append(arg)dict['LINKFLAGS'].append(arg)elifarg=='-mwindows':dict['LINKFLAGS'].append(arg)elifarg[:5]=='-std=':ifarg[5:].find('++')!=-1:key='CXXFLAGS'else:key='CFLAGS'dict[key].append(arg)elifarg[0]=='+':dict['CCFLAGS'].append(arg)dict['LINKFLAGS'].append(arg)elifargin['-include','-isysroot','-arch']:append_next_arg_to=argelse:dict['CCFLAGS'].append(arg)forarginflags:do_parse(arg)returndictdefMergeFlags(self,args,unique=1,dict=None):""" Merge the dict in args into the construction variables of this env, or the passed-in dict. If args is not a dict, it is converted into a dict using ParseFlags. If unique is not set, the flags are appended rather than merged. """ifdictisNone:dict=selfifnotSCons.Util.is_Dict(args):args=self.ParseFlags(args)ifnotunique:self.Append(**args)returnselfforkey,valueinargs.items():ifnotvalue:continuetry:orig=self[key]exceptKeyError:orig=valueelse:ifnotorig:orig=valueelifvalue:# Add orig and value. The logic here was lifted from# part of env.Append() (see there for a lot of comments# about the order in which things are tried) and is# used mainly to handle coercion of strings to CLVar to# "do the right thing" given (e.g.) an original CCFLAGS# string variable like '-pipe -Wall'.try:orig=orig+valueexcept(KeyError,TypeError):try:add_to_orig=orig.appendexceptAttributeError:value.insert(0,orig)orig=valueelse:add_to_orig(value)t=[]ifkey[-4:]=='PATH':### keep left-most occurenceforvinorig:ifvnotint:t.append(v)else:### keep right-most occurenceorig.reverse()forvinorig:ifvnotint:t.insert(0,v)self[key]=treturnself# def MergeShellPaths(self, args, prepend=1):# """# Merge the dict in args into the shell environment in env['ENV']. # Shell path elements are appended or prepended according to prepend.# Uses Pre/AppendENVPath, so it always appends or prepends uniquely.# Example: env.MergeShellPaths({'LIBPATH': '/usr/local/lib'})# prepends /usr/local/lib to env['ENV']['LIBPATH'].# """# for pathname, pathval in args.items():# if not pathval:# continue# if prepend:# self.PrependENVPath(pathname, pathval)# else:# self.AppendENVPath(pathname, pathval)defdefault_decide_source(dependency,target,prev_ni):f=SCons.Defaults.DefaultEnvironment().decide_sourcereturnf(dependency,target,prev_ni)defdefault_decide_target(dependency,target,prev_ni):f=SCons.Defaults.DefaultEnvironment().decide_targetreturnf(dependency,target,prev_ni)defdefault_copy_from_cache(src,dst):f=SCons.Defaults.DefaultEnvironment().copy_from_cachereturnf(src,dst)classBase(SubstitutionEnvironment):"""Base class for "real" construction Environments. These are the primary objects used to communicate dependency and construction information to the build engine. Keyword arguments supplied when the construction Environment is created are construction variables used to initialize the Environment. """memoizer_counters=[]######################################################################## This is THE class for interacting with the SCons build engine,# and it contains a lot of stuff, so we're going to try to keep this# a little organized by grouping the methods.############################################################################################################################################### Methods that make an Environment act like a dictionary. These have# the expected standard names for Python mapping objects. Note that# we don't actually make an Environment a subclass of UserDict for# performance reasons. Note also that we only supply methods for# dictionary functionality that we actually need and use.#######################################################################def__init__(self,platform=None,tools=None,toolpath=None,variables=None,parse_flags=None,**kw):""" Initialization of a basic SCons construction environment, including setting up special construction variables like BUILDER, PLATFORM, etc., and searching for and applying available Tools. Note that we do *not* call the underlying base class (SubsitutionEnvironment) initialization, because we need to initialize things in a very specific order that doesn't work with the much simpler base class initialization. """if__debug__:logInstanceCreation(self,'Environment.Base')self._memo={}self.fs=SCons.Node.FS.get_default_fs()self.ans=SCons.Node.Alias.default_ansself.lookup_list=SCons.Node.arg2nodes_lookupsself._dict=semi_deepcopy(SCons.Defaults.ConstructionEnvironment)self._init_special()self.added_methods=[]# We don't use AddMethod, or define these as methods in this# class, because we *don't* want these functions to be bound# methods. They need to operate independently so that the# settings will work properly regardless of whether a given# target ends up being built with a Base environment or an# OverrideEnvironment or what have you.self.decide_target=default_decide_targetself.decide_source=default_decide_sourceself.copy_from_cache=default_copy_from_cacheself._dict['BUILDERS']=BuilderDict(self._dict['BUILDERS'],self)ifplatformisNone:platform=self._dict.get('PLATFORM',None)ifplatformisNone:platform=SCons.Platform.Platform()ifSCons.Util.is_String(platform):platform=SCons.Platform.Platform(platform)self._dict['PLATFORM']=str(platform)platform(self)self._dict['HOST_OS']=self._dict.get('HOST_OS',None)self._dict['HOST_ARCH']=self._dict.get('HOST_ARCH',None)# Now set defaults for TARGET_{OS|ARCH}self._dict['TARGET_OS']=self._dict.get('HOST_OS',None)self._dict['TARGET_ARCH']=self._dict.get('HOST_ARCH',None)# Apply the passed-in and customizable variables to the# environment before calling the tools, because they may use# some of them during initialization.if'options'inkw:# Backwards compatibility: they may stll be using the# old "options" keyword.variables=kw['options']delkw['options']self.Replace(**kw)keys=list(kw.keys())ifvariables:keys=keys+list(variables.keys())variables.Update(self)save={}forkinkeys:try:save[k]=self._dict[k]exceptKeyError:# No value may have been set if they tried to pass in a# reserved variable name like TARGETS.passSCons.Tool.Initializers(self)iftoolsisNone:tools=self._dict.get('TOOLS',None)iftoolsisNone:tools=['default']apply_tools(self,tools,toolpath)# Now restore the passed-in and customized variables# to the environment, since the values the user set explicitly# should override any values set by the tools.forkey,valinsave.items():self._dict[key]=val# Finally, apply any flags to be merged inifparse_flags:self.MergeFlags(parse_flags)######################################################################## Utility methods that are primarily for internal use by SCons.# These begin with lower-case letters.#######################################################################defget_builder(self,name):"""Fetch the builder with the specified name from the environment. """try:returnself._dict['BUILDERS'][name]exceptKeyError:returnNonedefget_CacheDir(self):try:path=self._CacheDir_pathexceptAttributeError:path=SCons.Defaults.DefaultEnvironment()._CacheDir_pathtry:ifpath==self._last_CacheDir_path:returnself._last_CacheDirexceptAttributeError:passcd=SCons.CacheDir.CacheDir(path)self._last_CacheDir_path=pathself._last_CacheDir=cdreturncddefget_factory(self,factory,default='File'):"""Return a factory function for creating Nodes for this construction environment. """name=defaulttry:is_node=issubclass(factory,SCons.Node.FS.Base)exceptTypeError:# The specified factory isn't a Node itself--it's# most likely None, or possibly a callable.passelse:ifis_node:# The specified factory is a Node (sub)class. Try to# return the FS method that corresponds to the Node's# name--that is, we return self.fs.Dir if they want a Dir,# self.fs.File for a File, etc.try:name=factory.__name__exceptAttributeError:passelse:factory=Noneifnotfactory:# They passed us None, or we picked up a name from a specified# class, so return the FS method. (Note that we *don't*# use our own self.{Dir,File} methods because that would# cause env.subst() to be called twice on the file name,# interfering with files that have $$ in them.)factory=getattr(self.fs,name)returnfactorymemoizer_counters.append(SCons.Memoize.CountValue('_gsm'))def_gsm(self):try:returnself._memo['_gsm']exceptKeyError:passresult={}try:scanners=self._dict['SCANNERS']exceptKeyError:passelse:# Reverse the scanner list so that, if multiple scanners# claim they can scan the same suffix, earlier scanners# in the list will overwrite later scanners, so that# the result looks like a "first match" to the user.ifnotSCons.Util.is_List(scanners):scanners=[scanners]else:scanners=scanners[:]# copy so reverse() doesn't mod originalscanners.reverse()forscannerinscanners:forkinscanner.get_skeys(self):ifkandself['PLATFORM']=='win32':k=k.lower()result[k]=scannerself._memo['_gsm']=resultreturnresultdefget_scanner(self,skey):"""Find the appropriate scanner given a key (usually a file suffix). """ifskeyandself['PLATFORM']=='win32':skey=skey.lower()returnself._gsm().get(skey)defscanner_map_delete(self,kw=None):"""Delete the cached scanner map (if we need to). """try:delself._memo['_gsm']exceptKeyError:passdef_update(self,dict):"""Update an environment's values directly, bypassing the normal checks that occur when users try to set items. """self._dict.update(dict)defget_src_sig_type(self):try:returnself.src_sig_typeexceptAttributeError:t=SCons.Defaults.DefaultEnvironment().src_sig_typeself.src_sig_type=treturntdefget_tgt_sig_type(self):try:returnself.tgt_sig_typeexceptAttributeError:t=SCons.Defaults.DefaultEnvironment().tgt_sig_typeself.tgt_sig_type=treturnt######################################################################## Public methods for manipulating an Environment. These begin with# upper-case letters. The essential characteristic of methods in# this section is that they do *not* have corresponding same-named# global functions. For example, a stand-alone Append() function# makes no sense, because Append() is all about appending values to# an Environment's construction variables.#######################################################################defAppend(self,**kw):"""Append values to existing construction variables in an Environment. """kw=copy_non_reserved_keywords(kw)forkey,valinkw.items():# It would be easier on the eyes to write this using# "continue" statements whenever we finish processing an item,# but Python 1.5.2 apparently doesn't let you use "continue"# within try:-except: blocks, so we have to nest our code.try:ifkey=='CPPDEFINES'andSCons.Util.is_String(self._dict[key]):self._dict[key]=[self._dict[key]]orig=self._dict[key]exceptKeyError:# No existing variable in the environment, so just set# it to the new value.ifkey=='CPPDEFINES'andSCons.Util.is_String(val):self._dict[key]=[val]else:self._dict[key]=valelse:try:# Check if the original looks like a dictionary.# If it is, we can't just try adding the value because# dictionaries don't have __add__() methods, and# things like UserList will incorrectly coerce the# original dict to a list (which we don't want).update_dict=orig.updateexceptAttributeError:try:# Most straightforward: just try to add them# together. This will work in most cases, when the# original and new values are of compatible types.self._dict[key]=orig+valexcept(KeyError,TypeError):try:# Check if the original is a list.add_to_orig=orig.appendexceptAttributeError:# The original isn't a list, but the new# value is (by process of elimination),# so insert the original in the new value# (if there's one to insert) and replace# the variable with it.iforig:val.insert(0,orig)self._dict[key]=valelse:# The original is a list, so append the new# value to it (if there's a value to append).ifval:add_to_orig(val)else:# The original looks like a dictionary, so update it# based on what we think the value looks like.ifSCons.Util.is_List(val):ifkey=='CPPDEFINES':orig=orig.items()orig+=valself._dict[key]=origelse:forvinval:orig[v]=Noneelse:try:update_dict(val)except(AttributeError,TypeError,ValueError):ifSCons.Util.is_Dict(val):fork,vinval.items():orig[k]=velse:orig[val]=Noneself.scanner_map_delete(kw)# allow Dirs and strings beginning with # for top-relative# Note this uses the current env's fs (in self).def_canonicalize(self,path):ifnotSCons.Util.is_String(path):# typically a Dirpath=str(path)ifpathandpath[0]=='#':path=str(self.fs.Dir(path))returnpathdefAppendENVPath(self,name,newpath,envname='ENV',sep=os.pathsep,delete_existing=1):"""Append path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the end (it will be left where it is). """orig=''ifenvnameinself._dictandnameinself._dict[envname]:orig=self._dict[envname][name]nv=SCons.Util.AppendPath(orig,newpath,sep,delete_existing,canonicalize=self._canonicalize)ifenvnamenotinself._dict:self._dict[envname]={}self._dict[envname][name]=nvdefAppendUnique(self,delete_existing=0,**kw):"""Append values to existing construction variables in an Environment, if they're not already there. If delete_existing is 1, removes existing values first, so values move to end. """kw=copy_non_reserved_keywords(kw)forkey,valinkw.items():ifSCons.Util.is_List(val):val=_delete_duplicates(val,delete_existing)ifkeynotinself._dictorself._dict[key]in('',None):self._dict[key]=valelifSCons.Util.is_Dict(self._dict[key])and \
SCons.Util.is_Dict(val):self._dict[key].update(val)elifSCons.Util.is_List(val):dk=self._dict[key]ifkey=='CPPDEFINES':tmp=[]foriinval:ifSCons.Util.is_List(i):iflen(i)>=2:tmp.append((i[0],i[1]))else:tmp.append((i[0],))elifSCons.Util.is_Tuple(i):tmp.append(i)else:tmp.append((i,))val=tmpifSCons.Util.is_Dict(dk):dk=dk.items()elifSCons.Util.is_String(dk):dk=[(dk,)]else:tmp=[]foriindk:ifSCons.Util.is_List(i):iflen(i)>=2:tmp.append((i[0],i[1]))else:tmp.append((i[0],))elifSCons.Util.is_Tuple(i):tmp.append(i)else:tmp.append((i,))dk=tmpelse:ifnotSCons.Util.is_List(dk):dk=[dk]ifdelete_existing:dk=[xforxindkifxnotinval]else:val=[xforxinvalifxnotindk]self._dict[key]=dk+valelse:dk=self._dict[key]ifSCons.Util.is_List(dk):ifkey=='CPPDEFINES':tmp=[]foriindk:ifSCons.Util.is_List(i):iflen(i)>=2:tmp.append((i[0],i[1]))else:tmp.append((i[0],))elifSCons.Util.is_Tuple(i):tmp.append(i)else:tmp.append((i,))dk=tmpifSCons.Util.is_Dict(val):val=val.items()elifSCons.Util.is_String(val):val=[(val,)]ifdelete_existing:dk=filter(lambdax,val=val:xnotinval,dk)self._dict[key]=dk+valelse:dk=[xforxindkifxnotinval]self._dict[key]=dk+valelse:# By elimination, val is not a list. Since dk is a# list, wrap val in a list first.ifdelete_existing:dk=filter(lambdax,val=val:xnotinval,dk)self._dict[key]=dk+[val]else:ifnotvalindk:self._dict[key]=dk+[val]else:ifkey=='CPPDEFINES':ifSCons.Util.is_String(dk):dk=[dk]elifSCons.Util.is_Dict(dk):dk=dk.items()ifSCons.Util.is_String(val):ifvalindk:val=[]else:val=[val]elifSCons.Util.is_Dict(val):tmp=[]fori,jinval.iteritems():ifjisnotNone:tmp.append((i,j))else:tmp.append(i)val=tmpifdelete_existing:dk=[xforxindkifxnotinval]self._dict[key]=dk+valself.scanner_map_delete(kw)defClone(self,tools=[],toolpath=None,parse_flags=None,**kw):"""Return a copy of a construction Environment. The copy is like a Python "deep copy"--that is, independent copies are made recursively of each objects--except that a reference is copied when an object is not deep-copyable (like a function). There are no references to any mutable objects in the original Environment. """try:builders=self._dict['BUILDERS']exceptKeyError:passclone=copy.copy(self)# BUILDERS is not safe to do a simple copyclone._dict=semi_deepcopy_dict(self._dict,['BUILDERS'])clone._dict['BUILDERS']=BuilderDict(builders,clone)# Check the methods added via AddMethod() and re-bind them to# the cloned environment. Only do this if the attribute hasn't# been overwritten by the user explicitly and still points to# the added method.clone.added_methods=[]formwinself.added_methods:ifmw==getattr(self,mw.name):clone.added_methods.append(mw.clone(clone))clone._memo={}# Apply passed-in variables before the tools# so the tools can use the new variableskw=copy_non_reserved_keywords(kw)new={}forkey,valueinkw.items():new[key]=SCons.Subst.scons_subst_once(value,self,key)clone.Replace(**new)apply_tools(clone,tools,toolpath)# apply them again in case the tools overwrote themclone.Replace(**new)# Finally, apply any flags to be merged inifparse_flags:clone.MergeFlags(parse_flags)if__debug__:logInstanceCreation(self,'Environment.EnvironmentClone')returnclonedefCopy(self,*args,**kw):global_warn_copy_deprecatedif_warn_copy_deprecated:msg="The env.Copy() method is deprecated; use the env.Clone() method instead."SCons.Warnings.warn(SCons.Warnings.DeprecatedCopyWarning,msg)_warn_copy_deprecated=Falsereturnself.Clone(*args,**kw)def_changed_build(self,dependency,target,prev_ni):ifdependency.changed_state(target,prev_ni):return1returnself.decide_source(dependency,target,prev_ni)def_changed_content(self,dependency,target,prev_ni):returndependency.changed_content(target,prev_ni)def_changed_source(self,dependency,target,prev_ni):target_env=dependency.get_build_env()type=target_env.get_tgt_sig_type()iftype=='source':returntarget_env.decide_source(dependency,target,prev_ni)else:returntarget_env.decide_target(dependency,target,prev_ni)def_changed_timestamp_then_content(self,dependency,target,prev_ni):returndependency.changed_timestamp_then_content(target,prev_ni)def_changed_timestamp_newer(self,dependency,target,prev_ni):returndependency.changed_timestamp_newer(target,prev_ni)def_changed_timestamp_match(self,dependency,target,prev_ni):returndependency.changed_timestamp_match(target,prev_ni)def_copy_from_cache(self,src,dst):returnself.fs.copy(src,dst)def_copy2_from_cache(self,src,dst):returnself.fs.copy2(src,dst)defDecider(self,function):copy_function=self._copy2_from_cacheiffunctionin('MD5','content'):ifnotSCons.Util.md5:raiseUserError("MD5 signatures are not available in this version of Python.")function=self._changed_contenteliffunction=='MD5-timestamp':function=self._changed_timestamp_then_contenteliffunctionin('timestamp-newer','make'):function=self._changed_timestamp_newercopy_function=self._copy_from_cacheeliffunction=='timestamp-match':function=self._changed_timestamp_matchelifnotcallable(function):raiseUserError("Unknown Decider value %s"%repr(function))# We don't use AddMethod because we don't want to turn the# function, which only expects three arguments, into a bound# method, which would add self as an initial, fourth argument.self.decide_target=functionself.decide_source=functionself.copy_from_cache=copy_functiondefDetect(self,progs):"""Return the first available program in progs. """ifnotSCons.Util.is_List(progs):progs=[progs]forproginprogs:path=self.WhereIs(prog)ifpath:returnprogreturnNonedefDictionary(self,*args):ifnotargs:returnself._dictdlist=[self._dict[x]forxinargs]iflen(dlist)==1:dlist=dlist[0]returndlistdefDump(self,key=None):""" Using the standard Python pretty printer, dump the contents of the scons build environment to stdout. If the key passed in is anything other than None, then that will be used as an index into the build environment dictionary and whatever is found there will be fed into the pretty printer. Note that this key is case sensitive. """importpprintpp=pprint.PrettyPrinter(indent=2)ifkey:dict=self.Dictionary(key)else:dict=self.Dictionary()returnpp.pformat(dict)defFindIxes(self,paths,prefix,suffix):""" Search a list of paths for something that matches the prefix and suffix. paths - the list of paths or nodes. prefix - construction variable for the prefix. suffix - construction variable for the suffix. """suffix=self.subst('$'+suffix)prefix=self.subst('$'+prefix)forpathinpaths:dir,name=os.path.split(str(path))ifname[:len(prefix)]==prefixandname[-len(suffix):]==suffix:returnpathdefParseConfig(self,command,function=None,unique=1):""" Use the specified function to parse the output of the command in order to modify the current environment. The 'command' can be a string or a list of strings representing a command and its arguments. 'Function' is an optional argument that takes the environment, the output of the command, and the unique flag. If no function is specified, MergeFlags, which treats the output as the result of a typical 'X-config' command (i.e. gtk-config), will merge the output into the appropriate variables. """iffunctionisNone:defparse_conf(env,cmd,unique=unique):returnenv.MergeFlags(cmd,unique)function=parse_confifSCons.Util.is_List(command):command=' '.join(command)command=self.subst(command)returnfunction(self,self.backtick(command))defParseDepends(self,filename,must_exist=None,only_one=0):""" Parse a mkdep-style file for explicit dependencies. This is completely abusable, and should be unnecessary in the "normal" case of proper SCons configuration, but it may help make the transition from a Make hierarchy easier for some people to swallow. It can also be genuinely useful when using a tool that can write a .d file, but for which writing a scanner would be too complicated. """filename=self.subst(filename)try:fp=open(filename,'r')exceptIOError:ifmust_exist:raisereturnlines=SCons.Util.LogicalLines(fp).readlines()lines=[lforlinlinesifl[0]!='#']tdlist=[]forlineinlines:try:target,depends=line.split(':',1)except(AttributeError,ValueError):# Throws AttributeError if line isn't a string. Can throw# ValueError if line doesn't split into two or more elements.passelse:tdlist.append((target.split(),depends.split()))ifonly_one:targets=[]fortdintdlist:targets.extend(td[0])iflen(targets)>1:raiseSCons.Errors.UserError("More than one dependency target found in `%s': %s"%(filename,targets))fortarget,dependsintdlist:self.Depends(target,depends)defPlatform(self,platform):platform=self.subst(platform)returnSCons.Platform.Platform(platform)(self)defPrepend(self,**kw):"""Prepend values to existing construction variables in an Environment. """kw=copy_non_reserved_keywords(kw)forkey,valinkw.items():# It would be easier on the eyes to write this using# "continue" statements whenever we finish processing an item,# but Python 1.5.2 apparently doesn't let you use "continue"# within try:-except: blocks, so we have to nest our code.try:orig=self._dict[key]exceptKeyError:# No existing variable in the environment, so just set# it to the new value.self._dict[key]=valelse:try:# Check if the original looks like a dictionary.# If it is, we can't just try adding the value because# dictionaries don't have __add__() methods, and# things like UserList will incorrectly coerce the# original dict to a list (which we don't want).update_dict=orig.updateexceptAttributeError:try:# Most straightforward: just try to add them# together. This will work in most cases, when the# original and new values are of compatible types.self._dict[key]=val+origexcept(KeyError,TypeError):try:# Check if the added value is a list.add_to_val=val.appendexceptAttributeError:# The added value isn't a list, but the# original is (by process of elimination),# so insert the the new value in the original# (if there's one to insert).ifval:orig.insert(0,val)else:# The added value is a list, so append# the original to it (if there's a value# to append).iforig:add_to_val(orig)self._dict[key]=valelse:# The original looks like a dictionary, so update it# based on what we think the value looks like.ifSCons.Util.is_List(val):forvinval:orig[v]=Noneelse:try:update_dict(val)except(AttributeError,TypeError,ValueError):ifSCons.Util.is_Dict(val):fork,vinval.items():orig[k]=velse:orig[val]=Noneself.scanner_map_delete(kw)defPrependENVPath(self,name,newpath,envname='ENV',sep=os.pathsep,delete_existing=1):"""Prepend path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the front (it will be left where it is). """orig=''ifenvnameinself._dictandnameinself._dict[envname]:orig=self._dict[envname][name]nv=SCons.Util.PrependPath(orig,newpath,sep,delete_existing,canonicalize=self._canonicalize)ifenvnamenotinself._dict:self._dict[envname]={}self._dict[envname][name]=nvdefPrependUnique(self,delete_existing=0,**kw):"""Prepend values to existing construction variables in an Environment, if they're not already there. If delete_existing is 1, removes existing values first, so values move to front. """kw=copy_non_reserved_keywords(kw)forkey,valinkw.items():ifSCons.Util.is_List(val):val=_delete_duplicates(val,notdelete_existing)ifkeynotinself._dictorself._dict[key]in('',None):self._dict[key]=valelifSCons.Util.is_Dict(self._dict[key])and \
SCons.Util.is_Dict(val):self._dict[key].update(val)elifSCons.Util.is_List(val):dk=self._dict[key]ifnotSCons.Util.is_List(dk):dk=[dk]ifdelete_existing:dk=[xforxindkifxnotinval]else:val=[xforxinvalifxnotindk]self._dict[key]=val+dkelse:dk=self._dict[key]ifSCons.Util.is_List(dk):# By elimination, val is not a list. Since dk is a# list, wrap val in a list first.ifdelete_existing:dk=[xforxindkifxnotinval]self._dict[key]=[val]+dkelse:ifnotvalindk:self._dict[key]=[val]+dkelse:ifdelete_existing:dk=[xforxindkifxnotinval]self._dict[key]=val+dkself.scanner_map_delete(kw)defReplace(self,**kw):"""Replace existing construction variables in an Environment with new construction variables and/or values. """try:kwbd=kw['BUILDERS']exceptKeyError:passelse:kwbd=BuilderDict(kwbd,self)delkw['BUILDERS']self.__setitem__('BUILDERS',kwbd)kw=copy_non_reserved_keywords(kw)self._update(semi_deepcopy(kw))self.scanner_map_delete(kw)defReplaceIxes(self,path,old_prefix,old_suffix,new_prefix,new_suffix):""" Replace old_prefix with new_prefix and old_suffix with new_suffix. env - Environment used to interpolate variables. path - the path that will be modified. old_prefix - construction variable for the old prefix. old_suffix - construction variable for the old suffix. new_prefix - construction variable for the new prefix. new_suffix - construction variable for the new suffix. """old_prefix=self.subst('$'+old_prefix)old_suffix=self.subst('$'+old_suffix)new_prefix=self.subst('$'+new_prefix)new_suffix=self.subst('$'+new_suffix)dir,name=os.path.split(str(path))ifname[:len(old_prefix)]==old_prefix:name=name[len(old_prefix):]ifname[-len(old_suffix):]==old_suffix:name=name[:-len(old_suffix)]returnos.path.join(dir,new_prefix+name+new_suffix)defSetDefault(self,**kw):forkinkw.keys():ifkinself._dict:delkw[k]self.Replace(**kw)def_find_toolpath_dir(self,tp):returnself.fs.Dir(self.subst(tp)).srcnode().abspathdefTool(self,tool,toolpath=None,**kw):ifSCons.Util.is_String(tool):tool=self.subst(tool)iftoolpathisNone:toolpath=self.get('toolpath',[])toolpath=list(map(self._find_toolpath_dir,toolpath))tool=SCons.Tool.Tool(tool,toolpath,**kw)tool(self)defWhereIs(self,prog,path=None,pathext=None,reject=[]):"""Find prog in the path. """ifpathisNone:try:path=self['ENV']['PATH']exceptKeyError:passelifSCons.Util.is_String(path):path=self.subst(path)ifpathextisNone:try:pathext=self['ENV']['PATHEXT']exceptKeyError:passelifSCons.Util.is_String(pathext):pathext=self.subst(pathext)prog=self.subst(prog)path=SCons.Util.WhereIs(prog,path,pathext,reject)ifpath:returnpathreturnNone######################################################################## Public methods for doing real "SCons stuff" (manipulating# dependencies, setting attributes on targets, etc.). These begin# with upper-case letters. The essential characteristic of methods# in this section is that they all *should* have corresponding# same-named global functions.#######################################################################defAction(self,*args,**kw):defsubst_string(a,self=self):ifSCons.Util.is_String(a):a=self.subst(a)returnanargs=list(map(subst_string,args))nkw=self.subst_kw(kw)returnSCons.Action.Action(*nargs,**nkw)defAddPreAction(self,files,action):nodes=self.arg2nodes(files,self.fs.Entry)action=SCons.Action.Action(action)uniq={}forexecutorin[n.get_executor()forninnodes]:uniq[executor]=1forexecutorinuniq.keys():executor.add_pre_action(action)returnnodesdefAddPostAction(self,files,action):nodes=self.arg2nodes(files,self.fs.Entry)action=SCons.Action.Action(action)uniq={}forexecutorin[n.get_executor()forninnodes]:uniq[executor]=1forexecutorinuniq.keys():executor.add_post_action(action)returnnodesdefAlias(self,target,source=[],action=None,**kw):tlist=self.arg2nodes(target,self.ans.Alias)ifnotSCons.Util.is_List(source):source=[source]source=[_ffor_finsourceif_f]ifnotaction:ifnotsource:# There are no source files and no action, so just# return a target list of classic Alias Nodes, without# any builder. The externally visible effect is that# this will make the wrapping Script.BuildTask class# say that there's "Nothing to be done" for this Alias,# instead of that it's "up to date."returntlist# No action, but there are sources. Re-call all the target# builders to add the sources to each target.result=[]fortintlist:bld=t.get_builder(AliasBuilder)result.extend(bld(self,t,source))returnresultnkw=self.subst_kw(kw)nkw.update({'action':SCons.Action.Action(action),'source_factory':self.fs.Entry,'multi':1,'is_explicit':None,})bld=SCons.Builder.Builder(**nkw)# Apply the Builder separately to each target so that the Aliases# stay separate. If we did one "normal" Builder call with the# whole target list, then all of the target Aliases would be# associated under a single Executor.result=[]fortintlist:# Calling the convert() method will cause a new Executor to be# created from scratch, so we have to explicitly initialize# it with the target's existing sources, plus our new ones,# so nothing gets lost.b=t.get_builder()ifbisNoneorbisAliasBuilder:b=bldelse:nkw['action']=b.action+actionb=SCons.Builder.Builder(**nkw)t.convert()result.extend(b(self,t,t.sources+source))returnresultdefAlwaysBuild(self,*targets):tlist=[]fortintargets:tlist.extend(self.arg2nodes(t,self.fs.Entry))fortintlist:t.set_always_build()returntlistdefBuildDir(self,*args,**kw):msg="""BuildDir() and the build_dir keyword have been deprecated;\n\tuse VariantDir() and the variant_dir keyword instead."""SCons.Warnings.warn(SCons.Warnings.DeprecatedBuildDirWarning,msg)if'build_dir'inkw:kw['variant_dir']=kw['build_dir']delkw['build_dir']returnself.VariantDir(*args,**kw)defBuilder(self,**kw):nkw=self.subst_kw(kw)returnSCons.Builder.Builder(**nkw)defCacheDir(self,path):importSCons.CacheDirifpathisnotNone:path=self.subst(path)self._CacheDir_path=pathdefClean(self,targets,files):globalCleanTargetstlist=self.arg2nodes(targets,self.fs.Entry)flist=self.arg2nodes(files,self.fs.Entry)fortintlist:try:CleanTargets[t].extend(flist)exceptKeyError:CleanTargets[t]=flistdefConfigure(self,*args,**kw):nargs=[self]ifargs:nargs=nargs+self.subst_list(args)[0]nkw=self.subst_kw(kw)nkw['_depth']=kw.get('_depth',0)+1try:nkw['custom_tests']=self.subst_kw(nkw['custom_tests'])exceptKeyError:passreturnSCons.SConf.SConf(*nargs,**nkw)defCommand(self,target,source,action,**kw):"""Builds the supplied target files from the supplied source files using the supplied action. Action may be any type that the Builder constructor will accept for an action."""bkw={'action':action,'target_factory':self.fs.Entry,'source_factory':self.fs.Entry,}try:bkw['source_scanner']=kw['source_scanner']exceptKeyError:passelse:delkw['source_scanner']bld=SCons.Builder.Builder(**bkw)returnbld(self,target,source,**kw)defDepends(self,target,dependency):"""Explicity specify that 'target's depend on 'dependency'."""tlist=self.arg2nodes(target,self.fs.Entry)dlist=self.arg2nodes(dependency,self.fs.Entry)fortintlist:t.add_dependency(dlist)returntlistdefDir(self,name,*args,**kw):""" """s=self.subst(name)ifSCons.Util.is_Sequence(s):result=[]foreins:result.append(self.fs.Dir(e,*args,**kw))returnresultreturnself.fs.Dir(s,*args,**kw)defNoClean(self,*targets):"""Tags a target so that it will not be cleaned by -c"""tlist=[]fortintargets:tlist.extend(self.arg2nodes(t,self.fs.Entry))fortintlist:t.set_noclean()returntlistdefNoCache(self,*targets):"""Tags a target so that it will not be cached"""tlist=[]fortintargets:tlist.extend(self.arg2nodes(t,self.fs.Entry))fortintlist:t.set_nocache()returntlistdefEntry(self,name,*args,**kw):""" """s=self.subst(name)ifSCons.Util.is_Sequence(s):result=[]foreins:result.append(self.fs.Entry(e,*args,**kw))returnresultreturnself.fs.Entry(s,*args,**kw)defEnvironment(self,**kw):returnSCons.Environment.Environment(**self.subst_kw(kw))defExecute(self,action,*args,**kw):"""Directly execute an action through an Environment """action=self.Action(action,*args,**kw)result=action([],[],self)ifisinstance(result,SCons.Errors.BuildError):errstr=result.errstrifresult.filename:errstr=result.filename+': '+errstrsys.stderr.write("scons: *** %s\n"%errstr)returnresult.statuselse:returnresultdefFile(self,name,*args,**kw):""" """s=self.subst(name)ifSCons.Util.is_Sequence(s):result=[]foreins:result.append(self.fs.File(e,*args,**kw))returnresultreturnself.fs.File(s,*args,**kw)defFindFile(self,file,dirs):file=self.subst(file)nodes=self.arg2nodes(dirs,self.fs.Dir)returnSCons.Node.FS.find_file(file,tuple(nodes))defFlatten(self,sequence):returnSCons.Util.flatten(sequence)defGetBuildPath(self,files):result=list(map(str,self.arg2nodes(files,self.fs.Entry)))ifSCons.Util.is_List(files):returnresultelse:returnresult[0]defGlob(self,pattern,ondisk=True,source=False,strings=False):returnself.fs.Glob(self.subst(pattern),ondisk,source,strings)defIgnore(self,target,dependency):"""Ignore a dependency."""tlist=self.arg2nodes(target,self.fs.Entry)dlist=self.arg2nodes(dependency,self.fs.Entry)fortintlist:t.add_ignore(dlist)returntlistdefLiteral(self,string):returnSCons.Subst.Literal(string)defLocal(self,*targets):ret=[]fortargintargets:ifisinstance(targ,SCons.Node.Node):targ.set_local()ret.append(targ)else:fortinself.arg2nodes(targ,self.fs.Entry):t.set_local()ret.append(t)returnretdefPrecious(self,*targets):tlist=[]fortintargets:tlist.extend(self.arg2nodes(t,self.fs.Entry))fortintlist:t.set_precious()returntlistdefRepository(self,*dirs,**kw):dirs=self.arg2nodes(list(dirs),self.fs.Dir)self.fs.Repository(*dirs,**kw)defRequires(self,target,prerequisite):"""Specify that 'prerequisite' must be built before 'target', (but 'target' does not actually depend on 'prerequisite' and need not be rebuilt if it changes)."""tlist=self.arg2nodes(target,self.fs.Entry)plist=self.arg2nodes(prerequisite,self.fs.Entry)fortintlist:t.add_prerequisite(plist)returntlistdefScanner(self,*args,**kw):nargs=[]forarginargs:ifSCons.Util.is_String(arg):arg=self.subst(arg)nargs.append(arg)nkw=self.subst_kw(kw)returnSCons.Scanner.Base(*nargs,**nkw)defSConsignFile(self,name=".sconsign",dbm_module=None):ifnameisnotNone:name=self.subst(name)ifnotos.path.isabs(name):name=os.path.join(str(self.fs.SConstruct_dir),name)ifname:name=os.path.normpath(name)sconsign_dir=os.path.dirname(name)ifsconsign_dirandnotos.path.exists(sconsign_dir):self.Execute(SCons.Defaults.Mkdir(sconsign_dir))SCons.SConsign.File(name,dbm_module)defSideEffect(self,side_effect,target):"""Tell scons that side_effects are built as side effects of building targets."""side_effects=self.arg2nodes(side_effect,self.fs.Entry)targets=self.arg2nodes(target,self.fs.Entry)forside_effectinside_effects:ifside_effect.multiple_side_effect_has_builder():raiseSCons.Errors.UserError("Multiple ways to build the same target were specified for: %s"%str(side_effect))side_effect.add_source(targets)side_effect.side_effect=1self.Precious(side_effect)fortargetintargets:target.side_effects.append(side_effect)returnside_effectsdefSourceCode(self,entry,builder):"""Arrange for a source code builder for (part of) a tree."""msg="""SourceCode() has been deprecated and there is no replacement.\tIf you need this function, please contact dev@scons.tigris.org."""SCons.Warnings.warn(SCons.Warnings.DeprecatedSourceCodeWarning,msg)entries=self.arg2nodes(entry,self.fs.Entry)forentryinentries:entry.set_src_builder(builder)returnentriesdefSourceSignatures(self,type):global_warn_source_signatures_deprecatedif_warn_source_signatures_deprecated:msg="The env.SourceSignatures() method is deprecated;\n"+ \
"\tconvert your build to use the env.Decider() method instead."SCons.Warnings.warn(SCons.Warnings.DeprecatedSourceSignaturesWarning,msg)_warn_source_signatures_deprecated=Falsetype=self.subst(type)self.src_sig_type=typeiftype=='MD5':ifnotSCons.Util.md5:raiseUserError("MD5 signatures are not available in this version of Python.")self.decide_source=self._changed_contenteliftype=='timestamp':self.decide_source=self._changed_timestamp_matchelse:raiseUserError("Unknown source signature type '%s'"%type)defSplit(self,arg):"""This function converts a string or list into a list of strings or Nodes. This makes things easier for users by allowing files to be specified as a white-space separated list to be split. The input rules are: - A single string containing names separated by spaces. These will be split apart at the spaces. - A single Node instance - A list containing either strings or Node instances. Any strings in the list are not split at spaces. In all cases, the function returns a list of Nodes and strings."""ifSCons.Util.is_List(arg):returnlist(map(self.subst,arg))elifSCons.Util.is_String(arg):returnself.subst(arg).split()else:return[self.subst(arg)]defTargetSignatures(self,type):global_warn_target_signatures_deprecatedif_warn_target_signatures_deprecated:msg="The env.TargetSignatures() method is deprecated;\n"+ \
"\tconvert your build to use the env.Decider() method instead."SCons.Warnings.warn(SCons.Warnings.DeprecatedTargetSignaturesWarning,msg)_warn_target_signatures_deprecated=Falsetype=self.subst(type)self.tgt_sig_type=typeiftypein('MD5','content'):ifnotSCons.Util.md5:raiseUserError("MD5 signatures are not available in this version of Python.")self.decide_target=self._changed_contenteliftype=='timestamp':self.decide_target=self._changed_timestamp_matcheliftype=='build':self.decide_target=self._changed_buildeliftype=='source':self.decide_target=self._changed_sourceelse:raiseUserError("Unknown target signature type '%s'"%type)defValue(self,value,built_value=None):""" """returnSCons.Node.Python.Value(value,built_value)defVariantDir(self,variant_dir,src_dir,duplicate=1):variant_dir=self.arg2nodes(variant_dir,self.fs.Dir)[0]src_dir=self.arg2nodes(src_dir,self.fs.Dir)[0]self.fs.VariantDir(variant_dir,src_dir,duplicate)defFindSourceFiles(self,node='.'):""" returns a list of all source files. """node=self.arg2nodes(node,self.fs.Entry)[0]sources=[]defbuild_source(ss):forsinss:ifisinstance(s,SCons.Node.FS.Dir):build_source(s.all_children())elifs.has_builder():build_source(s.sources)elifisinstance(s.disambiguate(),SCons.Node.FS.File):sources.append(s)build_source(node.all_children())# THIS CODE APPEARS TO HAVE NO EFFECT# # get the final srcnode for all nodes, this means stripping any# # attached build node by calling the srcnode function# for file in sources:# srcnode = file.srcnode()# while srcnode != file.srcnode():# srcnode = file.srcnode()# remove duplicatesreturnlist(set(sources))defFindInstalledFiles(self):""" returns the list of all targets of the Install and InstallAs Builder. """fromSCons.Toolimportinstallifinstall._UNIQUE_INSTALLED_FILESisNone:install._UNIQUE_INSTALLED_FILES=SCons.Util.uniquer_hashables(install._INSTALLED_FILES)returninstall._UNIQUE_INSTALLED_FILESclassOverrideEnvironment(Base):"""A proxy that overrides variables in a wrapped construction environment by returning values from an overrides dictionary in preference to values from the underlying subject environment. This is a lightweight (I hope) proxy that passes through most use of attributes to the underlying Environment.Base class, but has just enough additional methods defined to act like a real construction environment with overridden values. It can wrap either a Base construction environment, or another OverrideEnvironment, which can in turn nest arbitrary OverrideEnvironments... Note that we do *not* call the underlying base class (SubsitutionEnvironment) initialization, because we get most of those from proxying the attributes of the subject construction environment. But because we subclass SubstitutionEnvironment, this class also has inherited arg2nodes() and subst*() methods; those methods can't be proxied because they need *this* object's methods to fetch the values from the overrides dictionary. """def__init__(self,subject,overrides={}):if__debug__:logInstanceCreation(self,'Environment.OverrideEnvironment')self.__dict__['__subject']=subjectself.__dict__['overrides']=overrides# Methods that make this class act like a proxy.def__getattr__(self,name):returngetattr(self.__dict__['__subject'],name)def__setattr__(self,name,value):setattr(self.__dict__['__subject'],name,value)# Methods that make this class act like a dictionary.def__getitem__(self,key):try:returnself.__dict__['overrides'][key]exceptKeyError:returnself.__dict__['__subject'].__getitem__(key)def__setitem__(self,key,value):ifnotis_valid_construction_var(key):raiseSCons.Errors.UserError("Illegal construction variable `%s'"%key)self.__dict__['overrides'][key]=valuedef__delitem__(self,key):try:delself.__dict__['overrides'][key]exceptKeyError:deleted=0else:deleted=1try:result=self.__dict__['__subject'].__delitem__(key)exceptKeyError:ifnotdeleted:raiseresult=Nonereturnresultdefget(self,key,default=None):"""Emulates the get() method of dictionaries."""try:returnself.__dict__['overrides'][key]exceptKeyError:returnself.__dict__['__subject'].get(key,default)defhas_key(self,key):try:self.__dict__['overrides'][key]return1exceptKeyError:returnkeyinself.__dict__['__subject']def__contains__(self,key):ifself.__dict__['overrides'].__contains__(key):return1returnself.__dict__['__subject'].__contains__(key)defDictionary(self):"""Emulates the items() method of dictionaries."""d=self.__dict__['__subject'].Dictionary().copy()d.update(self.__dict__['overrides'])returnddefitems(self):"""Emulates the items() method of dictionaries."""returnlist(self.Dictionary().items())# Overridden private construction environment methods.def_update(self,dict):"""Update an environment's values directly, bypassing the normal checks that occur when users try to set items. """self.__dict__['overrides'].update(dict)defgvars(self):returnself.__dict__['__subject'].gvars()deflvars(self):lvars=self.__dict__['__subject'].lvars()lvars.update(self.__dict__['overrides'])returnlvars# Overridden public construction environment methods.defReplace(self,**kw):kw=copy_non_reserved_keywords(kw)self.__dict__['overrides'].update(semi_deepcopy(kw))# The entry point that will be used by the external world# to refer to a construction environment. This allows the wrapper# interface to extend a construction environment for its own purposes# by subclassing SCons.Environment.Base and then assigning the# class to SCons.Environment.Environment.Environment=Base# An entry point for returning a proxy subclass instance that overrides# the subst*() methods so they don't actually perform construction# variable substitution. This is specifically intended to be the shim# layer in between global function calls (which don't want construction# variable substitution) and the DefaultEnvironment() (which would# substitute variables if left to its own devices)."""## We have to wrap this in a function that allows us to delay definition of# the class until it's necessary, so that when it subclasses Environment# it will pick up whatever Environment subclass the wrapper interface# might have assigned to SCons.Environment.Environment.defNoSubstitutionProxy(subject):class_NoSubstitutionProxy(Environment):def__init__(self,subject):self.__dict__['__subject']=subjectdef__getattr__(self,name):returngetattr(self.__dict__['__subject'],name)def__setattr__(self,name,value):returnsetattr(self.__dict__['__subject'],name,value)defexecutor_to_lvars(self,kwdict):ifkwdict.has_key('executor'):kwdict['lvars']=kwdict['executor'].get_lvars()delkwdict['executor']else:kwdict['lvars']={}defraw_to_mode(self,dict):try:raw=dict['raw']exceptKeyError:passelse:deldict['raw']dict['mode']=rawdefsubst(self,string,*args,**kwargs):returnstringdefsubst_kw(self,kw,*args,**kwargs):returnkwdefsubst_list(self,string,*args,**kwargs):nargs=(string,self,)+argsnkw=kwargs.copy()nkw['gvars']={}self.executor_to_lvars(nkw)self.raw_to_mode(nkw)returnSCons.Subst.scons_subst_list(*nargs,**nkw)defsubst_target_source(self,string,*args,**kwargs):nargs=(string,self,)+argsnkw=kwargs.copy()nkw['gvars']={}self.executor_to_lvars(nkw)self.raw_to_mode(nkw)returnSCons.Subst.scons_subst(*nargs,**nkw)return_NoSubstitutionProxy(subject)# Local Variables:# tab-width:4# indent-tabs-mode:nil# End:# vim: set expandtab tabstop=4 shiftwidth=4: