code
stringlengths
1
1.72M
language
stringclasses
1 value
"""SCons.Tool.rpcgen Tool-specific initialization for RPCGEN tools. Three normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/rpcgen.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Builder import Builder import SCons.Util cmd = "cd ${SOURCE.dir} && $RPCGEN -%s $RPCGENFLAGS %s -o ${TARGET.abspath} ${SOURCE.file}" rpcgen_client = cmd % ('l', '$RPCGENCLIENTFLAGS') rpcgen_header = cmd % ('h', '$RPCGENHEADERFLAGS') rpcgen_service = cmd % ('m', '$RPCGENSERVICEFLAGS') rpcgen_xdr = cmd % ('c', '$RPCGENXDRFLAGS') def generate(env): "Add RPCGEN Builders and construction variables for an Environment." client = Builder(action=rpcgen_client, suffix='_clnt.c', src_suffix='.x') header = Builder(action=rpcgen_header, suffix='.h', src_suffix='.x') service = Builder(action=rpcgen_service, suffix='_svc.c', src_suffix='.x') xdr = Builder(action=rpcgen_xdr, suffix='_xdr.c', src_suffix='.x') env.Append(BUILDERS={'RPCGenClient' : client, 'RPCGenHeader' : header, 'RPCGenService' : service, 'RPCGenXDR' : xdr}) env['RPCGEN'] = 'rpcgen' env['RPCGENFLAGS'] = SCons.Util.CLVar('') env['RPCGENCLIENTFLAGS'] = SCons.Util.CLVar('') env['RPCGENHEADERFLAGS'] = SCons.Util.CLVar('') env['RPCGENSERVICEFLAGS'] = SCons.Util.CLVar('') env['RPCGENXDRFLAGS'] = SCons.Util.CLVar('') def exists(env): return env.Detect('rpcgen') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Perforce.py Tool-specific initialization for Perforce Source Code Management system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/Perforce.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import SCons.Action import SCons.Builder import SCons.Node.FS import SCons.Util # This function should maybe be moved to SCons.Util? from SCons.Tool.PharLapCommon import addPathIfNotExists # Variables that we want to import from the base OS environment. _import_env = [ 'P4PORT', 'P4CLIENT', 'P4USER', 'USER', 'USERNAME', 'P4PASSWD', 'P4CHARSET', 'P4LANGUAGE', 'SystemRoot' ] PerforceAction = SCons.Action.Action('$P4COM', '$P4COMSTR') def generate(env): """Add a Builder factory function and construction variables for Perforce to an Environment.""" def PerforceFactory(env=env): """ """ import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The Perforce() factory is deprecated and there is no replacement.""") return SCons.Builder.Builder(action = PerforceAction, env = env) #setattr(env, 'Perforce', PerforceFactory) env.Perforce = PerforceFactory env['P4'] = 'p4' env['P4FLAGS'] = SCons.Util.CLVar('') env['P4COM'] = '$P4 $P4FLAGS sync $TARGET' try: environ = env['ENV'] except KeyError: environ = {} env['ENV'] = environ # Perforce seems to use the PWD environment variable rather than # calling getcwd() for itself, which is odd. If no PWD variable # is present, p4 WILL call getcwd, but this seems to cause problems # with good ol' Windows's tilde-mangling for long file names. environ['PWD'] = env.Dir('#').get_abspath() for var in _import_env: v = os.environ.get(var) if v: environ[var] = v if SCons.Util.can_read_reg: # If we can read the registry, add the path to Perforce to our environment. try: k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Perforce\\environment') val, tok = SCons.Util.RegQueryValueEx(k, 'P4INSTROOT') addPathIfNotExists(environ, 'PATH', val) except SCons.Util.RegError: # Can't detect where Perforce is, hope the user has it set in the # PATH. pass def exists(env): return env.Detect('p4') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.aixcc Tool-specific initialization for IBM xlc / Visual Age C compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/aixcc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Platform.aix import cc packages = ['vac.C', 'ibmcxx.cmp'] def get_xlc(env): xlc = env.get('CC', 'xlc') xlc_r = env.get('SHCC', 'xlc_r') return SCons.Platform.aix.get_xlc(env, xlc, xlc_r, packages) def generate(env): """Add Builders and construction variables for xlc / Visual Age suite to an Environment.""" path, _cc, _shcc, version = get_xlc(env) if path: _cc = os.path.join(path, _cc) _shcc = os.path.join(path, _shcc) cc.generate(env) env['CC'] = _cc env['SHCC'] = _shcc env['CCVERSION'] = version def exists(env): path, _cc, _shcc, version = get_xlc(env) if path and _cc: xlc = os.path.join(path, _cc) if os.path.exists(xlc): return xlc return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.wix Tool-specific initialization for wix, the Windows Installer XML Tool. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/wix.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Builder import SCons.Action import os def generate(env): """Add Builders and construction variables for WiX to an Environment.""" if not exists(env): return env['WIXCANDLEFLAGS'] = ['-nologo'] env['WIXCANDLEINCLUDE'] = [] env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}' env['WIXLIGHTFLAGS'].append( '-nologo' ) env['WIXLIGHTCOM'] = "$WIXLIGHT $WIXLIGHTFLAGS -out ${TARGET} ${SOURCES}" object_builder = SCons.Builder.Builder( action = '$WIXCANDLECOM', suffix = '.wxiobj', src_suffix = '.wxs') linker_builder = SCons.Builder.Builder( action = '$WIXLIGHTCOM', src_suffix = '.wxiobj', src_builder = object_builder) env['BUILDERS']['WiX'] = linker_builder def exists(env): env['WIXCANDLE'] = 'candle.exe' env['WIXLIGHT'] = 'light.exe' # try to find the candle.exe and light.exe tools and # add the install directory to light libpath. #for path in os.environ['PATH'].split(os.pathsep): for path in os.environ['PATH'].split(os.pathsep): if not path: continue # workaround for some weird python win32 bug. if path[0] == '"' and path[-1:]=='"': path = path[1:-1] # normalize the path path = os.path.normpath(path) # search for the tools in the PATH environment variable try: if env['WIXCANDLE'] in os.listdir(path) and\ env['WIXLIGHT'] in os.listdir(path): env.PrependENVPath('PATH', path) env['WIXLIGHTFLAGS'] = [ os.path.join( path, 'wixui.wixlib' ), '-loc', os.path.join( path, 'WixUI_en-us.wxl' ) ] return 1 except OSError: pass # ignore this, could be a stale PATH entry. return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.javac Tool-specific initialization for javac. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/javac.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Action import SCons.Builder from SCons.Node.FS import _my_normcase from SCons.Tool.JavaCommon import parse_java_file import SCons.Util def classname(path): """Turn a string (path name) into a Java class name.""" return os.path.normpath(path).replace(os.sep, '.') def emit_java_classes(target, source, env): """Create and return lists of source java files and their corresponding target class files. """ java_suffix = env.get('JAVASUFFIX', '.java') class_suffix = env.get('JAVACLASSSUFFIX', '.class') target[0].must_be_same(SCons.Node.FS.Dir) classdir = target[0] s = source[0].rentry().disambiguate() if isinstance(s, SCons.Node.FS.File): sourcedir = s.dir.rdir() elif isinstance(s, SCons.Node.FS.Dir): sourcedir = s.rdir() else: raise SCons.Errors.UserError("Java source must be File or Dir, not '%s'" % s.__class__) slist = [] js = _my_normcase(java_suffix) for entry in source: entry = entry.rentry().disambiguate() if isinstance(entry, SCons.Node.FS.File): slist.append(entry) elif isinstance(entry, SCons.Node.FS.Dir): result = SCons.Util.OrderedDict() dirnode = entry.rdir() def find_java_files(arg, dirpath, filenames): java_files = sorted([n for n in filenames if _my_normcase(n).endswith(js)]) mydir = dirnode.Dir(dirpath) java_paths = [mydir.File(f) for f in java_files] for jp in java_paths: arg[jp] = True for dirpath, dirnames, filenames in os.walk(dirnode.get_abspath()): find_java_files(result, dirpath, filenames) entry.walk(find_java_files, result) slist.extend(list(result.keys())) else: raise SCons.Errors.UserError("Java source must be File or Dir, not '%s'" % entry.__class__) version = env.get('JAVAVERSION', '1.4') full_tlist = [] for f in slist: tlist = [] source_file_based = True pkg_dir = None if not f.is_derived(): pkg_dir, classes = parse_java_file(f.rfile().get_abspath(), version) if classes: source_file_based = False if pkg_dir: d = target[0].Dir(pkg_dir) p = pkg_dir + os.sep else: d = target[0] p = '' for c in classes: t = d.File(c + class_suffix) t.attributes.java_classdir = classdir t.attributes.java_sourcedir = sourcedir t.attributes.java_classname = classname(p + c) tlist.append(t) if source_file_based: base = f.name[:-len(java_suffix)] if pkg_dir: t = target[0].Dir(pkg_dir).File(base + class_suffix) else: t = target[0].File(base + class_suffix) t.attributes.java_classdir = classdir t.attributes.java_sourcedir = f.dir t.attributes.java_classname = classname(base) tlist.append(t) for t in tlist: t.set_specific_source([f]) full_tlist.extend(tlist) return full_tlist, slist JavaAction = SCons.Action.Action('$JAVACCOM', '$JAVACCOMSTR') JavaBuilder = SCons.Builder.Builder(action = JavaAction, emitter = emit_java_classes, target_factory = SCons.Node.FS.Entry, source_factory = SCons.Node.FS.Entry) class pathopt(object): """ Callable object for generating javac-style path options from a construction variable (e.g. -classpath, -sourcepath). """ def __init__(self, opt, var, default=None): self.opt = opt self.var = var self.default = default def __call__(self, target, source, env, for_signature): path = env[self.var] if path and not SCons.Util.is_List(path): path = [path] if self.default: default = env[self.default] if default: if not SCons.Util.is_List(default): default = [default] path = path + default if path: return [self.opt, os.pathsep.join(map(str, path))] else: return [] def Java(env, target, source, *args, **kw): """ A pseudo-Builder wrapper around the separate JavaClass{File,Dir} Builders. """ if not SCons.Util.is_List(target): target = [target] if not SCons.Util.is_List(source): source = [source] # Pad the target list with repetitions of the last element in the # list so we have a target for every source element. target = target + ([target[-1]] * (len(source) - len(target))) java_suffix = env.subst('$JAVASUFFIX') result = [] for t, s in zip(target, source): if isinstance(s, SCons.Node.FS.Base): if isinstance(s, SCons.Node.FS.File): b = env.JavaClassFile else: b = env.JavaClassDir else: if os.path.isfile(s): b = env.JavaClassFile elif os.path.isdir(s): b = env.JavaClassDir elif s[-len(java_suffix):] == java_suffix: b = env.JavaClassFile else: b = env.JavaClassDir result.extend(b(t, s, *args, **kw)) return result def generate(env): """Add Builders and construction variables for javac to an Environment.""" java_file = SCons.Tool.CreateJavaFileBuilder(env) java_class = SCons.Tool.CreateJavaClassFileBuilder(env) java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env) java_class.add_emitter(None, emit_java_classes) java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes) java_class_dir.emitter = emit_java_classes env.AddMethod(Java) env['JAVAC'] = 'javac' env['JAVACFLAGS'] = SCons.Util.CLVar('') env['JAVABOOTCLASSPATH'] = [] env['JAVACLASSPATH'] = [] env['JAVASOURCEPATH'] = [] env['_javapathopt'] = pathopt env['_JAVABOOTCLASSPATH'] = '${_javapathopt("-bootclasspath", "JAVABOOTCLASSPATH")} ' env['_JAVACLASSPATH'] = '${_javapathopt("-classpath", "JAVACLASSPATH")} ' env['_JAVASOURCEPATH'] = '${_javapathopt("-sourcepath", "JAVASOURCEPATH", "_JAVASOURCEPATHDEFAULT")} ' env['_JAVASOURCEPATHDEFAULT'] = '${TARGET.attributes.java_sourcedir}' env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES' env['JAVACCOM'] = "${TEMPFILE('$_JAVACCOM')}" env['JAVACLASSSUFFIX'] = '.class' env['JAVASUFFIX'] = '.java' def exists(env): return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sunf90 Tool-specific initialization for sunf90, the Sun Studio F90 compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/sunf90.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util from FortranCommon import add_all_to_env compilers = ['sunf90', 'f90'] def generate(env): """Add Builders and construction variables for sun f90 compiler to an Environment.""" add_all_to_env(env) fcomp = env.Detect(compilers) or 'f90' env['FORTRAN'] = fcomp env['F90'] = fcomp env['SHFORTRAN'] = '$FORTRAN' env['SHF90'] = '$F90' env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC') env['SHF90FLAGS'] = SCons.Util.CLVar('$F90FLAGS -KPIC') def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.midl Tool-specific initialization for midl (Microsoft IDL compiler). There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/midl.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Scanner.IDL import SCons.Util from MSCommon import msvc_exists def midl_emitter(target, source, env): """Produces a list of outputs from the MIDL compiler""" base, ext = SCons.Util.splitext(str(target[0])) tlb = target[0] incl = base + '.h' interface = base + '_i.c' t = [tlb, incl, interface] midlcom = env['MIDLCOM'] if midlcom.find('/proxy') != -1: proxy = base + '_p.c' t.append(proxy) if midlcom.find('/dlldata') != -1: dlldata = base + '_data.c' t.append(dlldata) return (t,source) idl_scanner = SCons.Scanner.IDL.IDLScan() midl_action = SCons.Action.Action('$MIDLCOM', '$MIDLCOMSTR') midl_builder = SCons.Builder.Builder(action = midl_action, src_suffix = '.idl', suffix='.tlb', emitter = midl_emitter, source_scanner = idl_scanner) def generate(env): """Add Builders and construction variables for midl to an Environment.""" env['MIDL'] = 'MIDL.EXE' env['MIDLFLAGS'] = SCons.Util.CLVar('/nologo') env['MIDLCOM'] = '$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} /h ${TARGETS[1]} /iid ${TARGETS[2]} /proxy ${TARGETS[3]} /dlldata ${TARGETS[4]} $SOURCE 2> NUL' env['BUILDERS']['TypeLibrary'] = midl_builder def exists(env): return msvc_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.f03 Tool-specific initialization for the generic Posix f03 Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/f03.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util import fortran from SCons.Tool.FortranCommon import add_all_to_env, add_f03_to_env compilers = ['f03'] def generate(env): add_all_to_env(env) add_f03_to_env(env) fcomp = env.Detect(compilers) or 'f03' env['F03'] = fcomp env['SHF03'] = fcomp env['FORTRAN'] = fcomp env['SHFORTRAN'] = fcomp def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.gcc Tool-specific initialization for MinGW (http://www.mingw.org/) There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/mingw.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Tool import SCons.Util # This is what we search for to find mingw: key_program = 'mingw32-gcc' def find(env): # First search in the SCons path path=env.WhereIs(key_program) if (path): return path # then the OS path: path=SCons.Util.WhereIs(key_program) if (path): return path # If that doesn't work try default location for mingw save_path=env['ENV']['PATH'] env.AppendENVPath('PATH',r'c:\MinGW\bin') path =env.WhereIs(key_program) if not path: env['ENV']['PATH']=save_path return path def shlib_generator(target, source, env, for_signature): cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS']) dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') if dll: cmd.extend(['-o', dll]) cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS']) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: cmd.append('-Wl,--out-implib,'+implib.get_string(for_signature)) def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') insert_def = env.subst("$WINDOWS_INSERT_DEF") if not insert_def in ['', '0', 0] and def_target: \ cmd.append('-Wl,--output-def,'+def_target.get_string(for_signature)) return [cmd] def shlib_emitter(target, source, env): dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') no_import_lib = env.get('no_import_lib', 0) if not dll: raise SCons.Errors.UserError("A shared library should have exactly one target with the suffix: %s" % env.subst("$SHLIBSUFFIX")) if not no_import_lib and \ not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'): # Create list of target libraries as strings targetStrings=env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'LIBPREFIX', 'LIBSUFFIX') # Now add file nodes to target list target.append(env.fs.File(targetStrings)) # Append a def file target if there isn't already a def file target # or a def file source or the user has explicitly asked for the target # to be emitted. def_source = env.FindIxes(source, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') skip_def_insert = env.subst("$WINDOWS_INSERT_DEF") in ['', '0', 0] if not def_source and not def_target and not skip_def_insert: # Create list of target libraries and def files as strings targetStrings=env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') # Now add file nodes to target list target.append(env.fs.File(targetStrings)) return (target, source) shlib_action = SCons.Action.Action(shlib_generator, generator=1) res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR') res_builder = SCons.Builder.Builder(action=res_action, suffix='.o', source_scanner=SCons.Tool.SourceFileScanner) SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan) def generate(env): mingw = find(env) if mingw: dir = os.path.dirname(mingw) env.PrependENVPath('PATH', dir ) # Most of mingw is the same as gcc and friends... gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas', 'm4'] for tool in gnu_tools: SCons.Tool.Tool(tool)(env) #... but a few things differ: env['CC'] = 'gcc' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['CXX'] = 'g++' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = shlib_action env['LDMODULECOM'] = shlib_action env.Append(SHLIBEMITTER = [shlib_emitter]) env['AS'] = 'as' env['WIN32DEFPREFIX'] = '' env['WIN32DEFSUFFIX'] = '.def' env['WINDOWSDEFPREFIX'] = '${WIN32DEFPREFIX}' env['WINDOWSDEFSUFFIX'] = '${WIN32DEFSUFFIX}' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['RC'] = 'windres' env['RCFLAGS'] = SCons.Util.CLVar('') env['RCINCFLAGS'] = '$( ${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' env['RCINCPREFIX'] = '--include-dir ' env['RCINCSUFFIX'] = '' env['RCCOM'] = '$RC $_CPPDEFFLAGS $RCINCFLAGS ${RCINCPREFIX} ${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET' env['BUILDERS']['RES'] = res_builder # Some setting from the platform also have to be overridden: env['OBJSUFFIX'] = '.o' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' def exists(env): return find(env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.default Initialization with a default tool list. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/default.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Tool def generate(env): """Add default tools.""" for t in SCons.Tool.tool_list(env['PLATFORM'], env): SCons.Tool.Tool(t)(env) def exists(env): return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.filesystem Tool-specific initialization for the filesystem tools. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/filesystem.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons from SCons.Tool.install import copyFunc copyToBuilder, copyAsBuilder = None, None def copyto_emitter(target, source, env): """ changes the path of the source to be under the target (which are assumed to be directories. """ n_target = [] for t in target: n_target = n_target + [t.File( str( s ) ) for s in source] return (n_target, source) def copy_action_func(target, source, env): assert( len(target) == len(source) ), "\ntarget: %s\nsource: %s" %(list(map(str, target)),list(map(str, source))) for t, s in zip(target, source): if copyFunc(t.get_path(), s.get_path(), env): return 1 return 0 def copy_action_str(target, source, env): return env.subst_target_source(env['COPYSTR'], 0, target, source) copy_action = SCons.Action.Action( copy_action_func, copy_action_str ) def generate(env): try: env['BUILDERS']['CopyTo'] env['BUILDERS']['CopyAs'] except KeyError, e: global copyToBuilder if copyToBuilder is None: copyToBuilder = SCons.Builder.Builder( action = copy_action, target_factory = env.fs.Dir, source_factory = env.fs.Entry, multi = 1, emitter = [ copyto_emitter, ] ) global copyAsBuilder if copyAsBuilder is None: copyAsBuilder = SCons.Builder.Builder( action = copy_action, target_factory = env.fs.Entry, source_factory = env.fs.Entry ) env['BUILDERS']['CopyTo'] = copyToBuilder env['BUILDERS']['CopyAs'] = copyAsBuilder env['COPYSTR'] = 'Copy file(s): "$SOURCES" to "$TARGETS"' def exists(env): return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.tex Tool-specific initialization for TeX. Generates .dvi files from .tex files There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Tool/tex.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import re import shutil import sys import platform import glob import SCons.Action import SCons.Node import SCons.Node.FS import SCons.Util import SCons.Scanner.LaTeX Verbose = False must_rerun_latex = True # these are files that just need to be checked for changes and then rerun latex check_suffixes = ['.toc', '.lof', '.lot', '.out', '.nav', '.snm'] # these are files that require bibtex or makeindex to be run when they change all_suffixes = check_suffixes + ['.bbl', '.idx', '.nlo', '.glo', '.acn', '.bcf'] # # regular expressions used to search for Latex features # or outputs that require rerunning latex # # search for all .aux files opened by latex (recorded in the .fls file) openout_aux_re = re.compile(r"OUTPUT *(.*\.aux)") # search for all .bcf files opened by latex (recorded in the .fls file) # for use by biber openout_bcf_re = re.compile(r"OUTPUT *(.*\.bcf)") #printindex_re = re.compile(r"^[^%]*\\printindex", re.MULTILINE) #printnomenclature_re = re.compile(r"^[^%]*\\printnomenclature", re.MULTILINE) #printglossary_re = re.compile(r"^[^%]*\\printglossary", re.MULTILINE) # search to find rerun warnings warning_rerun_str = '(^LaTeX Warning:.*Rerun)|(^Package \w+ Warning:.*Rerun)' warning_rerun_re = re.compile(warning_rerun_str, re.MULTILINE) # search to find citation rerun warnings rerun_citations_str = "^LaTeX Warning:.*\n.*Rerun to get citations correct" rerun_citations_re = re.compile(rerun_citations_str, re.MULTILINE) # search to find undefined references or citations warnings undefined_references_str = '(^LaTeX Warning:.*undefined references)|(^Package \w+ Warning:.*undefined citations)' undefined_references_re = re.compile(undefined_references_str, re.MULTILINE) # used by the emitter auxfile_re = re.compile(r".", re.MULTILINE) tableofcontents_re = re.compile(r"^[^%\n]*\\tableofcontents", re.MULTILINE) makeindex_re = re.compile(r"^[^%\n]*\\makeindex", re.MULTILINE) bibliography_re = re.compile(r"^[^%\n]*\\bibliography", re.MULTILINE) bibunit_re = re.compile(r"^[^%\n]*\\begin\{bibunit\}", re.MULTILINE) multibib_re = re.compile(r"^[^%\n]*\\newcites\{([^\}]*)\}", re.MULTILINE) addbibresource_re = re.compile(r"^[^%\n]*\\(addbibresource|addglobalbib|addsectionbib)", re.MULTILINE) listoffigures_re = re.compile(r"^[^%\n]*\\listoffigures", re.MULTILINE) listoftables_re = re.compile(r"^[^%\n]*\\listoftables", re.MULTILINE) hyperref_re = re.compile(r"^[^%\n]*\\usepackage.*\{hyperref\}", re.MULTILINE) makenomenclature_re = re.compile(r"^[^%\n]*\\makenomenclature", re.MULTILINE) makeglossary_re = re.compile(r"^[^%\n]*\\makeglossary", re.MULTILINE) makeglossaries_re = re.compile(r"^[^%\n]*\\makeglossaries", re.MULTILINE) makeacronyms_re = re.compile(r"^[^%\n]*\\makeglossaries", re.MULTILINE) beamer_re = re.compile(r"^[^%\n]*\\documentclass\{beamer\}", re.MULTILINE) # search to find all files included by Latex include_re = re.compile(r'^[^%\n]*\\(?:include|input){([^}]*)}', re.MULTILINE) includeOnly_re = re.compile(r'^[^%\n]*\\(?:include){([^}]*)}', re.MULTILINE) # search to find all graphics files included by Latex includegraphics_re = re.compile(r'^[^%\n]*\\(?:includegraphics(?:\[[^\]]+\])?){([^}]*)}', re.MULTILINE) # search to find all files opened by Latex (recorded in .log file) openout_re = re.compile(r"OUTPUT *(.*)") # list of graphics file extensions for TeX and LaTeX TexGraphics = SCons.Scanner.LaTeX.TexGraphics LatexGraphics = SCons.Scanner.LaTeX.LatexGraphics # An Action sufficient to build any generic tex file. TeXAction = None # An action to build a latex file. This action might be needed more # than once if we are dealing with labels and bibtex. LaTeXAction = None # An action to run BibTeX on a file. BibTeXAction = None # An action to run MakeIndex on a file. MakeIndexAction = None # An action to run MakeIndex (for nomencl) on a file. MakeNclAction = None # An action to run MakeIndex (for glossary) on a file. MakeGlossaryAction = None # An action to run MakeIndex (for acronyms) on a file. MakeAcronymsAction = None # Used as a return value of modify_env_var if the variable is not set. _null = SCons.Scanner.LaTeX._null modify_env_var = SCons.Scanner.LaTeX.modify_env_var def check_file_error_message(utility, filename='log'): msg = '%s returned an error, check the %s file\n' % (utility, filename) sys.stdout.write(msg) def FindFile(name,suffixes,paths,env,requireExt=False): if requireExt: name,ext = SCons.Util.splitext(name) # if the user gave an extension use it. if ext: name = name + ext if Verbose: print " searching for '%s' with extensions: " % name,suffixes for path in paths: testName = os.path.join(path,name) if Verbose: print " look for '%s'" % testName if os.path.isfile(testName): if Verbose: print " found '%s'" % testName return env.fs.File(testName) else: name_ext = SCons.Util.splitext(testName)[1] if name_ext: continue # if no suffix try adding those passed in for suffix in suffixes: testNameExt = testName + suffix if Verbose: print " look for '%s'" % testNameExt if os.path.isfile(testNameExt): if Verbose: print " found '%s'" % testNameExt return env.fs.File(testNameExt) if Verbose: print " did not find '%s'" % name return None def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None): """A builder for LaTeX files that checks the output in the aux file and decides how many times to use LaTeXAction, and BibTeXAction.""" global must_rerun_latex # This routine is called with two actions. In this file for DVI builds # with LaTeXAction and from the pdflatex.py with PDFLaTeXAction # set this up now for the case where the user requests a different extension # for the target filename if (XXXLaTeXAction == LaTeXAction): callerSuffix = ".dvi" else: callerSuffix = env['PDFSUFFIX'] basename = SCons.Util.splitext(str(source[0]))[0] basedir = os.path.split(str(source[0]))[0] basefile = os.path.split(str(basename))[1] abspath = os.path.abspath(basedir) targetext = os.path.splitext(str(target[0]))[1] targetdir = os.path.split(str(target[0]))[0] saved_env = {} for var in SCons.Scanner.LaTeX.LaTeX.env_variables: saved_env[var] = modify_env_var(env, var, abspath) # Create base file names with the target directory since the auxiliary files # will be made there. That's because the *COM variables have the cd # command in the prolog. We check # for the existence of files before opening them--even ones like the # aux file that TeX always creates--to make it possible to write tests # with stubs that don't necessarily generate all of the same files. targetbase = os.path.join(targetdir, basefile) # if there is a \makeindex there will be a .idx and thus # we have to run makeindex at least once to keep the build # happy even if there is no index. # Same for glossaries, nomenclature, and acronyms src_content = source[0].get_text_contents() run_makeindex = makeindex_re.search(src_content) and not os.path.isfile(targetbase + '.idx') run_nomenclature = makenomenclature_re.search(src_content) and not os.path.isfile(targetbase + '.nlo') run_glossary = makeglossary_re.search(src_content) and not os.path.isfile(targetbase + '.glo') run_glossaries = makeglossaries_re.search(src_content) and not os.path.isfile(targetbase + '.glo') run_acronyms = makeacronyms_re.search(src_content) and not os.path.isfile(targetbase + '.acn') saved_hashes = {} suffix_nodes = {} for suffix in all_suffixes: theNode = env.fs.File(targetbase + suffix) suffix_nodes[suffix] = theNode saved_hashes[suffix] = theNode.get_csig() if Verbose: print "hashes: ",saved_hashes must_rerun_latex = True # .aux files already processed by BibTex already_bibtexed = [] # # routine to update MD5 hash and compare # def check_MD5(filenode, suffix): global must_rerun_latex # two calls to clear old csig filenode.clear_memoized_values() filenode.ninfo = filenode.new_ninfo() new_md5 = filenode.get_csig() if saved_hashes[suffix] == new_md5: if Verbose: print "file %s not changed" % (targetbase+suffix) return False # unchanged saved_hashes[suffix] = new_md5 must_rerun_latex = True if Verbose: print "file %s changed, rerunning Latex, new hash = " % (targetbase+suffix), new_md5 return True # changed # generate the file name that latex will generate resultfilename = targetbase + callerSuffix count = 0 while (must_rerun_latex and count < int(env.subst('$LATEXRETRIES'))) : result = XXXLaTeXAction(target, source, env) if result != 0: return result count = count + 1 must_rerun_latex = False # Decide if various things need to be run, or run again. # Read the log file to find warnings/errors logfilename = targetbase + '.log' logContent = '' if os.path.isfile(logfilename): logContent = open(logfilename, "rb").read() # Read the fls file to find all .aux files flsfilename = targetbase + '.fls' flsContent = '' auxfiles = [] if os.path.isfile(flsfilename): flsContent = open(flsfilename, "rb").read() auxfiles = openout_aux_re.findall(flsContent) # remove duplicates dups = {} for x in auxfiles: dups[x] = 1 auxfiles = list(dups.keys()) bcffiles = [] if os.path.isfile(flsfilename): flsContent = open(flsfilename, "rb").read() bcffiles = openout_bcf_re.findall(flsContent) # remove duplicates dups = {} for x in bcffiles: dups[x] = 1 bcffiles = list(dups.keys()) if Verbose: print "auxfiles ",auxfiles print "bcffiles ",bcffiles # Now decide if bibtex will need to be run. # The information that bibtex reads from the .aux file is # pass-independent. If we find (below) that the .bbl file is unchanged, # then the last latex saw a correct bibliography. # Therefore only do this once # Go through all .aux files and remember the files already done. for auxfilename in auxfiles: if auxfilename not in already_bibtexed: already_bibtexed.append(auxfilename) target_aux = os.path.join(targetdir, auxfilename) if os.path.isfile(target_aux): content = open(target_aux, "rb").read() if content.find("bibdata") != -1: if Verbose: print "Need to run bibtex on ",auxfilename bibfile = env.fs.File(SCons.Util.splitext(target_aux)[0]) result = BibTeXAction(bibfile, bibfile, env) if result != 0: check_file_error_message(env['BIBTEX'], 'blg') must_rerun_latex = True # Now decide if biber will need to be run. # The information that bibtex reads from the .bcf file is # pass-independent. If we find (below) that the .bbl file is unchanged, # then the last latex saw a correct bibliography. # Therefore only do this once # Go through all .bcf files and remember the files already done. for bcffilename in bcffiles: if bcffilename not in already_bibtexed: already_bibtexed.append(bcffilename) target_bcf = os.path.join(targetdir, bcffilename) if os.path.isfile(target_bcf): content = open(target_bcf, "rb").read() if content.find("bibdata") != -1: if Verbose: print "Need to run bibtex on ",bcffilename bibfile = env.fs.File(SCons.Util.splitext(target_bcf)[0]) result = BibTeXAction(bibfile, bibfile, env) if result != 0: check_file_error_message(env['BIBTEX'], 'blg') must_rerun_latex = True # Now decide if latex will need to be run again due to index. if check_MD5(suffix_nodes['.idx'],'.idx') or (count == 1 and run_makeindex): # We must run makeindex if Verbose: print "Need to run makeindex" idxfile = suffix_nodes['.idx'] result = MakeIndexAction(idxfile, idxfile, env) if result != 0: check_file_error_message(env['MAKEINDEX'], 'ilg') return result # TO-DO: need to add a way for the user to extend this list for whatever # auxiliary files they create in other (or their own) packages # Harder is case is where an action needs to be called -- that should be rare (I hope?) for index in check_suffixes: check_MD5(suffix_nodes[index],index) # Now decide if latex will need to be run again due to nomenclature. if check_MD5(suffix_nodes['.nlo'],'.nlo') or (count == 1 and run_nomenclature): # We must run makeindex if Verbose: print "Need to run makeindex for nomenclature" nclfile = suffix_nodes['.nlo'] result = MakeNclAction(nclfile, nclfile, env) if result != 0: check_file_error_message('%s (nomenclature)' % env['MAKENCL'], 'nlg') #return result # Now decide if latex will need to be run again due to glossary. if check_MD5(suffix_nodes['.glo'],'.glo') or (count == 1 and run_glossaries) or (count == 1 and run_glossary): # We must run makeindex if Verbose: print "Need to run makeindex for glossary" glofile = suffix_nodes['.glo'] result = MakeGlossaryAction(glofile, glofile, env) if result != 0: check_file_error_message('%s (glossary)' % env['MAKEGLOSSARY'], 'glg') #return result # Now decide if latex will need to be run again due to acronyms. if check_MD5(suffix_nodes['.acn'],'.acn') or (count == 1 and run_acronyms): # We must run makeindex if Verbose: print "Need to run makeindex for acronyms" acrfile = suffix_nodes['.acn'] result = MakeAcronymsAction(acrfile, acrfile, env) if result != 0: check_file_error_message('%s (acronyms)' % env['MAKEACRONYMS'], 'alg') return result # Now decide if latex needs to be run yet again to resolve warnings. if warning_rerun_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to latex or package rerun warning" if rerun_citations_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to 'Rerun to get citations correct' warning" if undefined_references_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to undefined references or citations" if (count >= int(env.subst('$LATEXRETRIES')) and must_rerun_latex): print "reached max number of retries on Latex ,",int(env.subst('$LATEXRETRIES')) # end of while loop # rename Latex's output to what the target name is if not (str(target[0]) == resultfilename and os.path.isfile(resultfilename)): if os.path.isfile(resultfilename): print "move %s to %s" % (resultfilename, str(target[0]), ) shutil.move(resultfilename,str(target[0])) # Original comment (when TEXPICTS was not restored): # The TEXPICTS enviroment variable is needed by a dvi -> pdf step # later on Mac OSX so leave it # # It is also used when searching for pictures (implicit dependencies). # Why not set the variable again in the respective builder instead # of leaving local modifications in the environment? What if multiple # latex builds in different directories need different TEXPICTS? for var in SCons.Scanner.LaTeX.LaTeX.env_variables: if var == 'TEXPICTS': continue if saved_env[var] is _null: try: del env['ENV'][var] except KeyError: pass # was never set else: env['ENV'][var] = saved_env[var] return result def LaTeXAuxAction(target = None, source= None, env=None): result = InternalLaTeXAuxAction( LaTeXAction, target, source, env ) return result LaTeX_re = re.compile("\\\\document(style|class)") def is_LaTeX(flist,env,abspath): """Scan a file list to decide if it's TeX- or LaTeX-flavored.""" # We need to scan files that are included in case the # \documentclass command is in them. # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var(env, 'TEXINPUTS', abspath) paths = env['ENV']['TEXINPUTS'] if SCons.Util.is_List(paths): pass else: # Split at os.pathsep to convert into absolute path paths = paths.split(os.pathsep) # now that we have the path list restore the env if savedpath is _null: try: del env['ENV']['TEXINPUTS'] except KeyError: pass # was never set else: env['ENV']['TEXINPUTS'] = savedpath if Verbose: print "is_LaTeX search path ",paths print "files to search :",flist # Now that we have the search path and file list, check each one for f in flist: if Verbose: print " checking for Latex source ",str(f) content = f.get_text_contents() if LaTeX_re.search(content): if Verbose: print "file %s is a LaTeX file" % str(f) return 1 if Verbose: print "file %s is not a LaTeX file" % str(f) # now find included files inc_files = [ ] inc_files.extend( include_re.findall(content) ) if Verbose: print "files included by '%s': "%str(f),inc_files # inc_files is list of file names as given. need to find them # using TEXINPUTS paths. # search the included files for src in inc_files: srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False) # make this a list since is_LaTeX takes a list. fileList = [srcNode,] if Verbose: print "FindFile found ",srcNode if srcNode is not None: file_test = is_LaTeX(fileList, env, abspath) # return on first file that finds latex is needed. if file_test: return file_test if Verbose: print " done scanning ",str(f) return 0 def TeXLaTeXFunction(target = None, source= None, env=None): """A builder for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then executes the appropriate program.""" # find these paths for use in is_LaTeX to search for included files basedir = os.path.split(str(source[0]))[0] abspath = os.path.abspath(basedir) if is_LaTeX(source,env,abspath): result = LaTeXAuxAction(target,source,env) if result != 0: check_file_error_message(env['LATEX']) else: result = TeXAction(target,source,env) if result != 0: check_file_error_message(env['TEX']) return result def TeXLaTeXStrFunction(target = None, source= None, env=None): """A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string.""" if env.GetOption("no_exec"): # find these paths for use in is_LaTeX to search for included files basedir = os.path.split(str(source[0]))[0] abspath = os.path.abspath(basedir) if is_LaTeX(source,env,abspath): result = env.subst('$LATEXCOM',0,target,source)+" ..." else: result = env.subst("$TEXCOM",0,target,source)+" ..." else: result = '' return result def tex_eps_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing tex or latex. It will accept .ps and .eps graphics files """ (target, source) = tex_emitter_core(target, source, env, TexGraphics) return (target, source) def tex_pdf_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing pdftex or pdflatex. It will accept graphics files of types .pdf, .jpg, .png, .gif, and .tif """ (target, source) = tex_emitter_core(target, source, env, LatexGraphics) return (target, source) def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files): """ For theFile (a Node) update any file_tests and search for graphics files then find all included files and call ScanFiles recursively for each of them""" content = theFile.get_text_contents() if Verbose: print " scanning ",str(theFile) for i in range(len(file_tests_search)): if file_tests[i][0] is None: file_tests[i][0] = file_tests_search[i].search(content) if Verbose and file_tests[i][0]: print " found match for ",file_tests[i][-1][-1] incResult = includeOnly_re.search(content) if incResult: aux_files.append(os.path.join(targetdir, incResult.group(1))) if Verbose: print "\include file names : ", aux_files # recursively call this on each of the included files inc_files = [ ] inc_files.extend( include_re.findall(content) ) if Verbose: print "files included by '%s': "%str(theFile),inc_files # inc_files is list of file names as given. need to find them # using TEXINPUTS paths. for src in inc_files: srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False) if srcNode is not None: file_tests = ScanFiles(srcNode, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files) if Verbose: print " done scanning ",str(theFile) return file_tests def tex_emitter_core(target, source, env, graphics_extensions): """An emitter for TeX and LaTeX sources. For LaTeX sources we try and find the common created files that are needed on subsequent runs of latex to finish tables of contents, bibliographies, indices, lists of figures, and hyperlink references. """ basename = SCons.Util.splitext(str(source[0]))[0] basefile = os.path.split(str(basename))[1] targetdir = os.path.split(str(target[0]))[0] targetbase = os.path.join(targetdir, basefile) basedir = os.path.split(str(source[0]))[0] abspath = os.path.abspath(basedir) target[0].attributes.path = abspath # # file names we will make use of in searching the sources and log file # emit_suffixes = ['.aux', '.log', '.ilg', '.blg', '.nls', '.nlg', '.gls', '.glg', '.alg'] + all_suffixes auxfilename = targetbase + '.aux' logfilename = targetbase + '.log' flsfilename = targetbase + '.fls' env.SideEffect(auxfilename,target[0]) env.SideEffect(logfilename,target[0]) env.SideEffect(flsfilename,target[0]) if Verbose: print "side effect :",auxfilename,logfilename,flsfilename env.Clean(target[0],auxfilename) env.Clean(target[0],logfilename) env.Clean(target[0],flsfilename) content = source[0].get_text_contents() # These variables are no longer used. #idx_exists = os.path.isfile(targetbase + '.idx') #nlo_exists = os.path.isfile(targetbase + '.nlo') #glo_exists = os.path.isfile(targetbase + '.glo') #acr_exists = os.path.isfile(targetbase + '.acn') # set up list with the regular expressions # we use to find features used file_tests_search = [auxfile_re, makeindex_re, bibliography_re, bibunit_re, multibib_re, addbibresource_re, tableofcontents_re, listoffigures_re, listoftables_re, hyperref_re, makenomenclature_re, makeglossary_re, makeglossaries_re, makeacronyms_re, beamer_re ] # set up list with the file suffixes that need emitting # when a feature is found file_tests_suff = [['.aux','aux_file'], ['.idx', '.ind', '.ilg','makeindex'], ['.bbl', '.blg','bibliography'], ['.bbl', '.blg','bibunit'], ['.bbl', '.blg','multibib'], ['.bbl', '.blg','.bcf','addbibresource'], ['.toc','contents'], ['.lof','figures'], ['.lot','tables'], ['.out','hyperref'], ['.nlo', '.nls', '.nlg','nomenclature'], ['.glo', '.gls', '.glg','glossary'], ['.glo', '.gls', '.glg','glossaries'], ['.acn', '.acr', '.alg','acronyms'], ['.nav', '.snm', '.out', '.toc','beamer'] ] # build the list of lists file_tests = [] for i in range(len(file_tests_search)): file_tests.append( [None, file_tests_suff[i]] ) # TO-DO: need to add a way for the user to extend this list for whatever # auxiliary files they create in other (or their own) packages # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var(env, 'TEXINPUTS', abspath) paths = env['ENV']['TEXINPUTS'] if SCons.Util.is_List(paths): pass else: # Split at os.pathsep to convert into absolute path paths = paths.split(os.pathsep) # now that we have the path list restore the env if savedpath is _null: try: del env['ENV']['TEXINPUTS'] except KeyError: pass # was never set else: env['ENV']['TEXINPUTS'] = savedpath if Verbose: print "search path ",paths aux_files = [] file_tests = ScanFiles(source[0], target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files) for (theSearch,suffix_list) in file_tests: # add side effects if feature is present.If file is to be generated,add all side effects if Verbose and theSearch: print "check side effects for ",suffix_list[-1] if (theSearch != None) or (not source[0].exists() ): file_list = [targetbase,] # for bibunit we need a list of files if suffix_list[-1] == 'bibunit': file_basename = os.path.join(targetdir, 'bu*.aux') file_list = glob.glob(file_basename) # remove the suffix '.aux' for i in range(len(file_list)): file_list.append(SCons.Util.splitext(file_list[i])[0]) # for multibib we need a list of files if suffix_list[-1] == 'multibib': for multibibmatch in multibib_re.finditer(content): if Verbose: print "multibib match ",multibibmatch.group(1) if multibibmatch != None: baselist = multibibmatch.group(1).split(',') if Verbose: print "multibib list ", baselist for i in range(len(baselist)): file_list.append(os.path.join(targetdir, baselist[i])) # now define the side effects for file_name in file_list: for suffix in suffix_list[:-1]: env.SideEffect(file_name + suffix,target[0]) if Verbose: print "side effect tst :",file_name + suffix, " target is ",str(target[0]) env.Clean(target[0],file_name + suffix) for aFile in aux_files: aFile_base = SCons.Util.splitext(aFile)[0] env.SideEffect(aFile_base + '.aux',target[0]) if Verbose: print "side effect aux :",aFile_base + '.aux' env.Clean(target[0],aFile_base + '.aux') # read fls file to get all other files that latex creates and will read on the next pass # remove files from list that we explicitly dealt with above if os.path.isfile(flsfilename): content = open(flsfilename, "rb").read() out_files = openout_re.findall(content) myfiles = [auxfilename, logfilename, flsfilename, targetbase+'.dvi',targetbase+'.pdf'] for filename in out_files[:]: if filename in myfiles: out_files.remove(filename) env.SideEffect(out_files,target[0]) if Verbose: print "side effect fls :",out_files env.Clean(target[0],out_files) return (target, source) TeXLaTeXAction = None def generate(env): """Add Builders and construction variables for TeX to an Environment.""" global TeXLaTeXAction if TeXLaTeXAction is None: TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction, strfunction=TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) generate_common(env) import dvi dvi.generate(env) bld = env['BUILDERS']['DVI'] bld.add_action('.tex', TeXLaTeXAction) bld.add_emitter('.tex', tex_eps_emitter) def generate_darwin(env): try: environ = env['ENV'] except KeyError: environ = {} env['ENV'] = environ if (platform.system() == 'Darwin'): try: ospath = env['ENV']['PATHOSX'] except: ospath = None if ospath: env.AppendENVPath('PATH', ospath) def generate_common(env): """Add internal Builders and construction variables for LaTeX to an Environment.""" # Add OSX system paths so TeX tools can be found # when a list of tools is given the exists() method is not called generate_darwin(env) # A generic tex file Action, sufficient for all tex files. global TeXAction if TeXAction is None: TeXAction = SCons.Action.Action("$TEXCOM", "$TEXCOMSTR") # An Action to build a latex file. This might be needed more # than once if we are dealing with labels and bibtex. global LaTeXAction if LaTeXAction is None: LaTeXAction = SCons.Action.Action("$LATEXCOM", "$LATEXCOMSTR") # Define an action to run BibTeX on a file. global BibTeXAction if BibTeXAction is None: BibTeXAction = SCons.Action.Action("$BIBTEXCOM", "$BIBTEXCOMSTR") # Define an action to run MakeIndex on a file. global MakeIndexAction if MakeIndexAction is None: MakeIndexAction = SCons.Action.Action("$MAKEINDEXCOM", "$MAKEINDEXCOMSTR") # Define an action to run MakeIndex on a file for nomenclatures. global MakeNclAction if MakeNclAction is None: MakeNclAction = SCons.Action.Action("$MAKENCLCOM", "$MAKENCLCOMSTR") # Define an action to run MakeIndex on a file for glossaries. global MakeGlossaryAction if MakeGlossaryAction is None: MakeGlossaryAction = SCons.Action.Action("$MAKEGLOSSARYCOM", "$MAKEGLOSSARYCOMSTR") # Define an action to run MakeIndex on a file for acronyms. global MakeAcronymsAction if MakeAcronymsAction is None: MakeAcronymsAction = SCons.Action.Action("$MAKEACRONYMSCOM", "$MAKEACRONYMSCOMSTR") try: environ = env['ENV'] except KeyError: environ = {} env['ENV'] = environ # Some Linux platforms have pdflatex set up in a way # that requires that the HOME environment variable be set. # Add it here if defined. v = os.environ.get('HOME') if v: environ['HOME'] = v CDCOM = 'cd ' if platform.system() == 'Windows': # allow cd command to change drives on Windows CDCOM = 'cd /D ' env['TEX'] = 'tex' env['TEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder') env['TEXCOM'] = CDCOM + '${TARGET.dir} && $TEX $TEXFLAGS ${SOURCE.file}' env['PDFTEX'] = 'pdftex' env['PDFTEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder') env['PDFTEXCOM'] = CDCOM + '${TARGET.dir} && $PDFTEX $PDFTEXFLAGS ${SOURCE.file}' env['LATEX'] = 'latex' env['LATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder') env['LATEXCOM'] = CDCOM + '${TARGET.dir} && $LATEX $LATEXFLAGS ${SOURCE.file}' env['LATEXRETRIES'] = 4 env['PDFLATEX'] = 'pdflatex' env['PDFLATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder') env['PDFLATEXCOM'] = CDCOM + '${TARGET.dir} && $PDFLATEX $PDFLATEXFLAGS ${SOURCE.file}' env['BIBTEX'] = 'bibtex' env['BIBTEXFLAGS'] = SCons.Util.CLVar('') env['BIBTEXCOM'] = CDCOM + '${TARGET.dir} && $BIBTEX $BIBTEXFLAGS ${SOURCE.filebase}' env['MAKEINDEX'] = 'makeindex' env['MAKEINDEXFLAGS'] = SCons.Util.CLVar('') env['MAKEINDEXCOM'] = CDCOM + '${TARGET.dir} && $MAKEINDEX $MAKEINDEXFLAGS ${SOURCE.file}' env['MAKEGLOSSARY'] = 'makeindex' env['MAKEGLOSSARYSTYLE'] = '${SOURCE.filebase}.ist' env['MAKEGLOSSARYFLAGS'] = SCons.Util.CLVar('-s ${MAKEGLOSSARYSTYLE} -t ${SOURCE.filebase}.glg') env['MAKEGLOSSARYCOM'] = CDCOM + '${TARGET.dir} && $MAKEGLOSSARY ${SOURCE.filebase}.glo $MAKEGLOSSARYFLAGS -o ${SOURCE.filebase}.gls' env['MAKEACRONYMS'] = 'makeindex' env['MAKEACRONYMSSTYLE'] = '${SOURCE.filebase}.ist' env['MAKEACRONYMSFLAGS'] = SCons.Util.CLVar('-s ${MAKEACRONYMSSTYLE} -t ${SOURCE.filebase}.alg') env['MAKEACRONYMSCOM'] = CDCOM + '${TARGET.dir} && $MAKEACRONYMS ${SOURCE.filebase}.acn $MAKEACRONYMSFLAGS -o ${SOURCE.filebase}.acr' env['MAKENCL'] = 'makeindex' env['MAKENCLSTYLE'] = 'nomencl.ist' env['MAKENCLFLAGS'] = '-s ${MAKENCLSTYLE} -t ${SOURCE.filebase}.nlg' env['MAKENCLCOM'] = CDCOM + '${TARGET.dir} && $MAKENCL ${SOURCE.filebase}.nlo $MAKENCLFLAGS -o ${SOURCE.filebase}.nls' def exists(env): generate_darwin(env) return env.Detect('tex') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. # __doc__ = """ io compatibility module for older (pre-2.6) Python versions This does not not NOT (repeat, *NOT*) provide complete io functionality. It only wraps the portions of io functionality used by SCons, in an interface that looks enough like io for our purposes. """ __revision__ = "src/engine/SCons/compat/_scons_io.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" # Use the "imp" module to protect the imports below from fixers. import imp _cStringIO = imp.load_module('cStringIO', *imp.find_module('cStringIO')) StringIO = _cStringIO.StringIO del _cStringIO # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""Classes to represent arbitrary sets (including sets of sets). This module implements sets using dictionaries whose values are ignored. The usual operations (union, intersection, deletion, etc.) are provided as both methods and operators. Important: sets are not sequences! While they support 'x in s', 'len(s)', and 'for x in s', none of those operations are unique for sequences; for example, mappings support all three as well. The characteristic operation for sequences is subscripting with small integers: s[i], for i in range(len(s)). Sets don't support subscripting at all. Also, sequences allow multiple occurrences and their elements have a definite order; sets on the other hand don't record multiple occurrences and don't remember the order of element insertion (which is why they don't support s[i]). The following classes are provided: BaseSet -- All the operations common to both mutable and immutable sets. This is an abstract class, not meant to be directly instantiated. Set -- Mutable sets, subclass of BaseSet; not hashable. ImmutableSet -- Immutable sets, subclass of BaseSet; hashable. An iterable argument is mandatory to create an ImmutableSet. _TemporarilyImmutableSet -- A wrapper around a Set, hashable, giving the same hash value as the immutable set equivalent would have. Do not use this class directly. Only hashable objects can be added to a Set. In particular, you cannot really add a Set as an element to another Set; if you try, what is actually added is an ImmutableSet built from it (it compares equal to the one you tried adding). When you ask if `x in y' where x is a Set and y is a Set or ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and what's tested is actually `z in y'. """ # Code history: # # - Greg V. Wilson wrote the first version, using a different approach # to the mutable/immutable problem, and inheriting from dict. # # - Alex Martelli modified Greg's version to implement the current # Set/ImmutableSet approach, and make the data an attribute. # # - Guido van Rossum rewrote much of the code, made some API changes, # and cleaned up the docstrings. # # - Raymond Hettinger added a number of speedups and other # improvements. # protect this import from the fixers... exec('from itertools import ifilterfalse as filterfalse') __all__ = ['BaseSet', 'Set', 'ImmutableSet'] class BaseSet(object): """Common base class for mutable and immutable sets.""" __slots__ = ['_data'] # Constructor def __init__(self): """This is an abstract class.""" # Don't call this from a concrete subclass! if self.__class__ is BaseSet: raise TypeError("BaseSet is an abstract class. " "Use Set or ImmutableSet.") # Standard protocols: __len__, __repr__, __str__, __iter__ def __len__(self): """Return the number of elements of a set.""" return len(self._data) def __repr__(self): """Return string representation of a set. This looks like 'Set([<list of elements>])'. """ return self._repr() # __str__ is the same as __repr__ __str__ = __repr__ def _repr(self, sort_them=False): elements = list(self._data.keys()) if sort_them: elements.sort() return '%s(%r)' % (self.__class__.__name__, elements) def __iter__(self): """Return an iterator over the elements or a set. This is the keys iterator for the underlying dict. """ # Wrapping name in () prevents fixer from "fixing" this return (self._data.iterkeys)() # Three-way comparison is not supported. However, because __eq__ is # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and # then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this # case). def __cmp__(self, other): raise TypeError("can't compare sets using cmp()") # Equality comparisons using the underlying dicts. Mixed-type comparisons # are allowed here, where Set == z for non-Set z always returns False, # and Set != z always True. This allows expressions like "x in y" to # give the expected result when y is a sequence of mixed types, not # raising a pointless TypeError just because y contains a Set, or x is # a Set and y contain's a non-set ("in" invokes only __eq__). # Subtle: it would be nicer if __eq__ and __ne__ could return # NotImplemented instead of True or False. Then the other comparand # would get a chance to determine the result, and if the other comparand # also returned NotImplemented then it would fall back to object address # comparison (which would always return False for __eq__ and always # True for __ne__). However, that doesn't work, because this type # *also* implements __cmp__: if, e.g., __eq__ returns NotImplemented, # Python tries __cmp__ next, and the __cmp__ here then raises TypeError. def __eq__(self, other): if isinstance(other, BaseSet): return self._data == other._data else: return False def __ne__(self, other): if isinstance(other, BaseSet): return self._data != other._data else: return True # Copying operations def copy(self): """Return a shallow copy of a set.""" result = self.__class__() result._data.update(self._data) return result __copy__ = copy # For the copy module def __deepcopy__(self, memo): """Return a deep copy of a set; used by copy module.""" # This pre-creates the result and inserts it in the memo # early, in case the deep copy recurses into another reference # to this same set. A set can't be an element of itself, but # it can certainly contain an object that has a reference to # itself. from copy import deepcopy result = self.__class__() memo[id(self)] = result data = result._data value = True for elt in self: data[deepcopy(elt, memo)] = value return result # Standard set operations: union, intersection, both differences. # Each has an operator version (e.g. __or__, invoked with |) and a # method version (e.g. union). # Subtle: Each pair requires distinct code so that the outcome is # correct when the type of other isn't suitable. For example, if # we did "union = __or__" instead, then Set().union(3) would return # NotImplemented instead of raising TypeError (albeit that *why* it # raises TypeError as-is is also a bit subtle). def __or__(self, other): """Return the union of two sets as a new set. (I.e. all elements that are in either set.) """ if not isinstance(other, BaseSet): return NotImplemented return self.union(other) def union(self, other): """Return the union of two sets as a new set. (I.e. all elements that are in either set.) """ result = self.__class__(self) result._update(other) return result def __and__(self, other): """Return the intersection of two sets as a new set. (I.e. all elements that are in both sets.) """ if not isinstance(other, BaseSet): return NotImplemented return self.intersection(other) def intersection(self, other): """Return the intersection of two sets as a new set. (I.e. all elements that are in both sets.) """ if not isinstance(other, BaseSet): other = Set(other) if len(self) <= len(other): little, big = self, other else: little, big = other, self common = iter(filter(big._data.has_key, little)) return self.__class__(common) def __xor__(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.) """ if not isinstance(other, BaseSet): return NotImplemented return self.symmetric_difference(other) def symmetric_difference(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.) """ result = self.__class__() data = result._data value = True selfdata = self._data try: otherdata = other._data except AttributeError: otherdata = Set(other)._data for elt in filterfalse(otherdata.has_key, selfdata): data[elt] = value for elt in filterfalse(selfdata.has_key, otherdata): data[elt] = value return result def __sub__(self, other): """Return the difference of two sets as a new Set. (I.e. all elements that are in this set and not in the other.) """ if not isinstance(other, BaseSet): return NotImplemented return self.difference(other) def difference(self, other): """Return the difference of two sets as a new Set. (I.e. all elements that are in this set and not in the other.) """ result = self.__class__() data = result._data try: otherdata = other._data except AttributeError: otherdata = Set(other)._data value = True for elt in filterfalse(otherdata.has_key, self): data[elt] = value return result # Membership test def __contains__(self, element): """Report whether an element is a member of a set. (Called in response to the expression `element in self'.) """ try: return element in self._data except TypeError: transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught return transform() in self._data # Subset and superset test def issubset(self, other): """Report whether another set contains this set.""" self._binary_sanity_check(other) if len(self) > len(other): # Fast check for obvious cases return False for elt in filterfalse(other._data.has_key, self): return False return True def issuperset(self, other): """Report whether this set contains another set.""" self._binary_sanity_check(other) if len(self) < len(other): # Fast check for obvious cases return False for elt in filterfalse(self._data.has_key, other): return False return True # Inequality comparisons using the is-subset relation. __le__ = issubset __ge__ = issuperset def __lt__(self, other): self._binary_sanity_check(other) return len(self) < len(other) and self.issubset(other) def __gt__(self, other): self._binary_sanity_check(other) return len(self) > len(other) and self.issuperset(other) # Assorted helpers def _binary_sanity_check(self, other): # Check that the other argument to a binary operation is also # a set, raising a TypeError otherwise. if not isinstance(other, BaseSet): raise TypeError("Binary operation only permitted between sets") def _compute_hash(self): # Calculate hash code for a set by xor'ing the hash codes of # the elements. This ensures that the hash code does not depend # on the order in which elements are added to the set. This is # not called __hash__ because a BaseSet should not be hashable; # only an ImmutableSet is hashable. result = 0 for elt in self: result ^= hash(elt) return result def _update(self, iterable): # The main loop for update() and the subclass __init__() methods. data = self._data # Use the fast update() method when a dictionary is available. if isinstance(iterable, BaseSet): data.update(iterable._data) return value = True if type(iterable) in (list, tuple, xrange): # Optimized: we know that __iter__() and next() can't # raise TypeError, so we can move 'try:' out of the loop. it = iter(iterable) while True: try: for element in it: data[element] = value return except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught data[transform()] = value else: # Safe: only catch TypeError where intended for element in iterable: try: data[element] = value except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught data[transform()] = value class ImmutableSet(BaseSet): """Immutable set class.""" __slots__ = ['_hashcode'] # BaseSet + hashing def __init__(self, iterable=None): """Construct an immutable set from an optional iterable.""" self._hashcode = None self._data = {} if iterable is not None: self._update(iterable) def __hash__(self): if self._hashcode is None: self._hashcode = self._compute_hash() return self._hashcode def __getstate__(self): return self._data, self._hashcode def __setstate__(self, state): self._data, self._hashcode = state class Set(BaseSet): """ Mutable set class.""" __slots__ = [] # BaseSet + operations requiring mutability; no hashing def __init__(self, iterable=None): """Construct a set from an optional iterable.""" self._data = {} if iterable is not None: self._update(iterable) def __getstate__(self): # getstate's results are ignored if it is not return self._data, def __setstate__(self, data): self._data, = data def __hash__(self): """A Set cannot be hashed.""" # We inherit object.__hash__, so we must deny this explicitly raise TypeError("Can't hash a Set, only an ImmutableSet.") # In-place union, intersection, differences. # Subtle: The xyz_update() functions deliberately return None, # as do all mutating operations on built-in container types. # The __xyz__ spellings have to return self, though. def __ior__(self, other): """Update a set with the union of itself and another.""" self._binary_sanity_check(other) self._data.update(other._data) return self def union_update(self, other): """Update a set with the union of itself and another.""" self._update(other) def __iand__(self, other): """Update a set with the intersection of itself and another.""" self._binary_sanity_check(other) self._data = (self & other)._data return self def intersection_update(self, other): """Update a set with the intersection of itself and another.""" if isinstance(other, BaseSet): self &= other else: self._data = (self.intersection(other))._data def __ixor__(self, other): """Update a set with the symmetric difference of itself and another.""" self._binary_sanity_check(other) self.symmetric_difference_update(other) return self def symmetric_difference_update(self, other): """Update a set with the symmetric difference of itself and another.""" data = self._data value = True if not isinstance(other, BaseSet): other = Set(other) if self is other: self.clear() for elt in other: if elt in data: del data[elt] else: data[elt] = value def __isub__(self, other): """Remove all elements of another set from this set.""" self._binary_sanity_check(other) self.difference_update(other) return self def difference_update(self, other): """Remove all elements of another set from this set.""" data = self._data if not isinstance(other, BaseSet): other = Set(other) if self is other: self.clear() for elt in filter(data.has_key, other): del data[elt] # Python dict-like mass mutations: update, clear def update(self, iterable): """Add all values from an iterable (such as a list or file).""" self._update(iterable) def clear(self): """Remove all elements from this set.""" self._data.clear() # Single-element mutations: add, remove, discard def add(self, element): """Add an element to a set. This has no effect if the element is already present. """ try: self._data[element] = True except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught self._data[transform()] = True def remove(self, element): """Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ try: del self._data[element] except TypeError: transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught del self._data[transform()] def discard(self, element): """Remove an element from a set if it is a member. If the element is not a member, do nothing. """ try: self.remove(element) except KeyError: pass def pop(self): """Remove and return an arbitrary set element.""" return self._data.popitem()[0] def __as_immutable__(self): # Return a copy of self as an immutable set return ImmutableSet(self) def __as_temporarily_immutable__(self): # Return self wrapped in a temporarily immutable set return _TemporarilyImmutableSet(self) class _TemporarilyImmutableSet(BaseSet): # Wrap a mutable set as if it was temporarily immutable. # This only supplies hashing and equality comparisons. def __init__(self, set): self._set = set self._data = set._data # Needed by ImmutableSet.__eq__() def __hash__(self): return self._set._compute_hash() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. # # Portions of the following are derived from the compat.py file in # Twisted, under the following copyright: # # Copyright (c) 2001-2004 Twisted Matrix Laboratories __doc__ = """ Compatibility idioms for builtins names This module adds names to the builtins module for things that we want to use in SCons but which don't show up until later Python versions than the earliest ones we support. This module checks for the following builtins names: all() any() sorted() memoryview() Implementations of functions are *NOT* guaranteed to be fully compliant with these functions in later versions of Python. We are only concerned with adding functionality that we actually use in SCons, so be wary if you lift this code for other uses. (That said, making these more nearly the same as later, official versions is still a desirable goal, we just don't need to be obsessive about it.) If you're looking at this with pydoc and various names don't show up in the FUNCTIONS or DATA output, that means those names are already built in to this version of Python and we don't need to add them from this module. """ __revision__ = "src/engine/SCons/compat/_scons_builtins.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import builtins try: all except NameError: # Pre-2.5 Python has no all() function. def all(iterable): """ Returns True if all elements of the iterable are true. """ for element in iterable: if not element: return False return True builtins.all = all all = all try: any except NameError: # Pre-2.5 Python has no any() function. def any(iterable): """ Returns True if any element of the iterable is true. """ for element in iterable: if element: return True return False builtins.any = any any = any try: memoryview except NameError: # Pre-2.7 doesn't have the memoryview() built-in. class memoryview(object): def __init__(self, obj): # wrapping buffer in () keeps the fixer from changing it self.obj = (buffer)(obj) def __getitem__(self, indx): if isinstance(indx, slice): return self.obj[indx.start:indx.stop] else: return self.obj[indx] builtins.memoryview = memoryview try: sorted except NameError: # Pre-2.4 Python has no sorted() function. # # The pre-2.4 Python list.sort() method does not support # list.sort(key=) nor list.sort(reverse=) keyword arguments, so # we must implement the functionality of those keyword arguments # by hand instead of passing them to list.sort(). def sorted(iterable, cmp=None, key=None, reverse=False): if key is not None: result = [(key(x), x) for x in iterable] else: result = iterable[:] if cmp is None: # Pre-2.3 Python does not support list.sort(None). result.sort() else: result.sort(cmp) if key is not None: result = [t1 for t0,t1 in result] if reverse: result.reverse() return result builtins.sorted = sorted #if sys.version_info[:3] in ((2, 2, 0), (2, 2, 1)): # def lstrip(s, c=string.whitespace): # while s and s[0] in c: # s = s[1:] # return s # def rstrip(s, c=string.whitespace): # while s and s[-1] in c: # s = s[:-1] # return s # def strip(s, c=string.whitespace, l=lstrip, r=rstrip): # return l(r(s, c), c) # # object.__setattr__(str, 'lstrip', lstrip) # object.__setattr__(str, 'rstrip', rstrip) # object.__setattr__(str, 'strip', strip) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. # __doc__ = """ hashlib backwards-compatibility module for older (pre-2.5) Python versions This does not not NOT (repeat, *NOT*) provide complete hashlib functionality. It only wraps the portions of MD5 functionality used by SCons, in an interface that looks like hashlib (or enough for our purposes, anyway). In fact, this module will raise an ImportError if the underlying md5 module isn't available. """ __revision__ = "src/engine/SCons/compat/_scons_hashlib.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import md5 from string import hexdigits class md5obj(object): md5_module = md5 def __init__(self, name, string=''): if not name in ('MD5', 'md5'): raise ValueError("unsupported hash type") self.name = 'md5' self.m = self.md5_module.md5() def __repr__(self): return '<%s HASH object @ %#x>' % (self.name, id(self)) def copy(self): import copy result = copy.copy(self) result.m = self.m.copy() return result def digest(self): return self.m.digest() def update(self, arg): return self.m.update(arg) def hexdigest(self): return self.m.hexdigest() new = md5obj def md5(string=''): return md5obj('md5', string) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# subprocess - Subprocesses with accessible I/O streams # # For more information about this module, see PEP 324. # # This module should remain compatible with Python 2.2, see PEP 291. # # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se> # # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/2.4/license for licensing details. r"""subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* Information about how the subprocess module can be used to replace these modules and functions can be found below. Using the subprocess module =========================== This module defines one class called Popen: class Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): Arguments are: args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or string, but can be explicitly set by using the executable argument. On UNIX, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. A string will be treated as a sequence with the string as the only item (the program to execute). On UNIX, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments. On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline method. Please note that not all MS Windows applications interpret the command line the same way: The list2cmdline is designed for applications using the same rules as the MS C runtime. bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered). stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. if shell is true, the specified command will be executed through the shell. If cwd is not None, the current directory will be changed to cwd before the child is executed. If env is not None, it defines the environment variables for the new process. If universal_newlines is true, the file objects stdout and stderr are opened as a text files, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program. Note: This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method. The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only) This module also defines two shortcut functions: call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) check_call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) Exceptions ---------- Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called 'child_traceback', which is a string containing traceback information from the childs point of view. The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSErrors. A ValueError will be raised if Popen is called with invalid arguments. check_call() will raise CalledProcessError, if the called process returns a non-zero return code. Security -------- Unlike some other popen functions, this implementation will never call /bin/sh implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Popen objects ============= Instances of the Popen class have the following methods: poll() Check if child process has terminated. Returns returncode attribute. wait() Wait for child process to terminate. Returns returncode attribute. communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional stdin argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. The following attributes are also available: stdin If the stdin argument is PIPE, this attribute is a file object that provides input to the child process. Otherwise, it is None. stdout If the stdout argument is PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None. stderr If the stderr argument is PIPE, this attribute is file object that provides error output from the child process. Otherwise, it is None. pid The process ID of the child process. returncode The child return code. A None value indicates that the process hasn't terminated yet. A negative value -N indicates that the child was terminated by signal N (UNIX only). Replacing older functions with the subprocess module ==================================================== In this section, "a ==> b" means that b can be used as a replacement for a. Note: All functions in this section fail (more or less) silently if the executed program cannot be found; this module raises an OSError exception. In the following examples, we assume that the subprocess module is imported with "from subprocess import *". Replacing /bin/sh shell backquote --------------------------------- output=`mycmd myarg` ==> output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] Replacing shell pipe line ------------------------- output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] Replacing os.system() --------------------- sts = os.system("mycmd" + " myarg") ==> p = Popen("mycmd" + " myarg", shell=True) pid, sts = os.waitpid(p.pid, 0) Note: * Calling the program through the shell is usually not required. * It's easier to look at the returncode attribute than the exitstatus. A more real-world example would look like this: try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e Replacing os.spawn* ------------------- P_NOWAIT example: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid P_WAIT example: retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) Vector example: os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) Environment example: os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) Replacing os.popen* ------------------- pipe = os.popen(cmd, mode='r', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout pipe = os.popen(cmd, mode='w', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) Replacing popen2.* ------------------ Note: If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen(["somestring"], shell=True, bufsize=bufsize stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen, except that: * subprocess.Popen raises an exception if the execution fails * the capturestderr argument is replaced with the stderr argument. * stdin=PIPE and stdout=PIPE must be specified. * popen2 closes all filedescriptors by default, but you have to specify close_fds=True with subprocess.Popen. """ import sys mswindows = (sys.platform == "win32") import os import types import traceback # Exception classes used by this module. class CalledProcessError(Exception): """This exception is raised when a process run by check_call() returns a non-zero exit status. The exit status will be stored in the returncode attribute.""" def __init__(self, returncode, cmd): self.returncode = returncode self.cmd = cmd def __str__(self): return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) if mswindows: try: import threading except ImportError: # SCons: the threading module is only used by the communicate() # method, which we don't actually use, so don't worry if we # can't import it. pass import msvcrt try: # Try to get _subprocess from _subprocess import * class STARTUPINFO(object): dwFlags = 0 hStdInput = None hStdOutput = None hStdError = None wShowWindow = 0 class pywintypes(object): error = IOError except ImportError: # If not there, then drop back to requiring pywin32 # TODO: Should this be wrapped in try as well? To notify user to install # pywin32 ? With URL to it? import pywintypes from win32api import GetStdHandle, STD_INPUT_HANDLE, \ STD_OUTPUT_HANDLE, STD_ERROR_HANDLE from win32api import GetCurrentProcess, DuplicateHandle, \ GetModuleFileName, GetVersion from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE from win32pipe import CreatePipe from win32process import CreateProcess, STARTUPINFO, \ GetExitCodeProcess, STARTF_USESTDHANDLES, \ STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 else: import select import errno import fcntl import pickle try: fcntl.F_GETFD except AttributeError: fcntl.F_GETFD = 1 try: fcntl.F_SETFD except AttributeError: fcntl.F_SETFD = 2 __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"] try: MAXFD = os.sysconf("SC_OPEN_MAX") except KeyboardInterrupt: raise # SCons: don't swallow keyboard interrupts except: MAXFD = 256 try: isinstance(1, int) except TypeError: def is_int(obj): return isinstance(obj, type(1)) def is_int_or_long(obj): return type(obj) in (type(1), type(1L)) else: def is_int(obj): return isinstance(obj, int) def is_int_or_long(obj): return isinstance(obj, (int, long)) try: types.StringTypes except AttributeError: try: types.StringTypes = (str, unicode) except NameError: types.StringTypes = (str,) def is_string(obj): return isinstance(obj, types.StringTypes) _active = [] def _cleanup(): for inst in _active[:]: if inst.poll(_deadstate=sys.maxsize) >= 0: try: _active.remove(inst) except ValueError: # This can happen if two threads create a new Popen instance. # It's harmless that it was already removed, so ignore. pass PIPE = -1 STDOUT = -2 def call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ return apply(Popen, popenargs, kwargs).wait() def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] if retcode: raise CalledProcessError(retcode, cmd) return retcode def list2cmdline(seq): """ Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3) A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4) Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5) If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. """ # See # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp result = [] needquote = False for arg in seq: bs_buf = [] # Add a space to separate this argument from the others if result: result.append(' ') needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') for c in arg: if c == '\\': # Don't know if we need to double yet. bs_buf.append(c) elif c == '"': # Double backspaces. result.append('\\' * len(bs_buf)*2) bs_buf = [] result.append('\\"') else: # Normal char if bs_buf: result.extend(bs_buf) bs_buf = [] result.append(c) # Add remaining backspaces, if any. if bs_buf: result.extend(bs_buf) if needquote: result.extend(bs_buf) result.append('"') return ''.join(result) class Popen(object): def __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): """Create new Popen instance.""" _cleanup() self._child_created = False if not is_int_or_long(bufsize): raise TypeError("bufsize must be an integer") if mswindows: if preexec_fn is not None: raise ValueError("preexec_fn is not supported on Windows " "platforms") if close_fds: raise ValueError("close_fds is not supported on Windows " "platforms") else: # POSIX if startupinfo is not None: raise ValueError("startupinfo is only supported on Windows " "platforms") if creationflags != 0: raise ValueError("creationflags is only supported on Windows " "platforms") self.stdin = None self.stdout = None self.stderr = None self.pid = None self.returncode = None self.universal_newlines = universal_newlines # Input and output objects. The general principle is like # this: # # Parent Child # ------ ----- # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite # # On POSIX, the child objects are file descriptors. On # Windows, these are Windows file handles. The parent objects # are file descriptors on both platforms. The parent objects # are None when not using PIPEs. The child objects are None # when not redirecting. (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) self._execute_child(args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) if p2cwrite: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) if c2pread: if universal_newlines: self.stdout = os.fdopen(c2pread, 'rU', bufsize) else: self.stdout = os.fdopen(c2pread, 'rb', bufsize) if errread: if universal_newlines: self.stderr = os.fdopen(errread, 'rU', bufsize) else: self.stderr = os.fdopen(errread, 'rb', bufsize) def _translate_newlines(self, data): data = data.replace("\r\n", "\n") data = data.replace("\r", "\n") return data def __del__(self): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. self.poll(_deadstate=sys.maxsize) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) def communicate(self, input=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).""" # Optimization: If we are only using one pipe, or no pipe at # all, using select() or threads is unnecessary. if [self.stdin, self.stdout, self.stderr].count(None) >= 2: stdout = None stderr = None if self.stdin: if input: self.stdin.write(input) self.stdin.close() elif self.stdout: stdout = self.stdout.read() elif self.stderr: stderr = self.stderr.read() self.wait() return (stdout, stderr) return self._communicate(input) if mswindows: # # Windows methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin is None and stdout is None and stderr is None: return (None, None, None, None, None, None) p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) elif stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) elif is_int(stdin): p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object p2cread = msvcrt.get_osfhandle(stdin.fileno()) p2cread = self._make_inheritable(p2cread) if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) elif stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() c2pread = msvcrt.open_osfhandle(c2pread, 0) elif is_int(stdout): c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) c2pwrite = self._make_inheritable(c2pwrite) if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) elif stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() errread = msvcrt.open_osfhandle(errread, 0) elif stderr == STDOUT: errwrite = c2pwrite elif is_int(stderr): errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object errwrite = msvcrt.get_osfhandle(stderr.fileno()) errwrite = self._make_inheritable(errwrite) return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS) def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)""" if not isinstance(args, types.StringTypes): args = list2cmdline(args) # Process startup details if startupinfo is None: startupinfo = STARTUPINFO() if None not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags = startupinfo.dwFlags | STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite if shell: startupinfo.dwFlags = startupinfo.dwFlags | STARTF_USESHOWWINDOW startupinfo.wShowWindow = SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = comspec + " /c " + args if (GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == "command.com"): # Win9x, or using command.com on NT. We need to # use the w9xpopen intermediate program. For more # information, see KB Q150956 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) w9xpopen = self._find_w9xpopen() args = '"%s" %s' % (w9xpopen, args) # Not passing CREATE_NEW_CONSOLE has been known to # cause random failures on win9x. Specifically a # dialog: "Your program accessed mem currently in # use at xxx" and a hopeful warning about the # stability of your system. Cost is Ctrl+C wont # kill children. creationflags = creationflags | CREATE_NEW_CONSOLE # Start the process try: hp, ht, pid, tid = CreateProcess(executable, args, # no special security None, None, # must inherit handles to pass std # handles 1, creationflags, env, cwd, startupinfo) except pywintypes.error, e: # Translate pywintypes.error to WindowsError, which is # a subclass of OSError. FIXME: We should really # translate errno using _sys_errlist (or simliar), but # how can this be done from Python? raise WindowsError(*e.args) # Retain the process handle, but close the thread handle self._child_created = True self._handle = hp self.pid = pid ht.Close() # Child is launched. Close the parent's copy of those pipe # handles that only the child should have open. You need # to make sure that no handles to the write end of the # output pipe are maintained in this process or else the # pipe will not close when the child process exits and the # ReadFile will hang. if p2cread is not None: p2cread.Close() if c2pwrite is not None: c2pwrite.Close() if errwrite is not None: errwrite.Close() def poll(self, _deadstate=None): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode is None: if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: self.returncode = GetExitCodeProcess(self._handle) return self.returncode def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: obj = WaitForSingleObject(self._handle, INFINITE) self.returncode = GetExitCodeProcess(self._handle) return self.returncode def _readerthread(self, fh, buffer): buffer.append(fh.read()) def _communicate(self, input): stdout = None # Return stderr = None # Return if self.stdout: stdout = [] stdout_thread = threading.Thread(target=self._readerthread, args=(self.stdout, stdout)) stdout_thread.setDaemon(True) stdout_thread.start() if self.stderr: stderr = [] stderr_thread = threading.Thread(target=self._readerthread, args=(self.stderr, stderr)) stderr_thread.setDaemon(True) stderr_thread.start() if self.stdin: if input is not None: self.stdin.write(input) self.stdin.close() if self.stdout: stdout_thread.join() if self.stderr: stderr_thread.join() # All data exchanged. Translate lists into strings. if stdout is not None: stdout = stdout[0] if stderr is not None: stderr = stderr[0] # Translate newlines, if requested. We cannot let the file # object do the translation: It is based on stdio, which is # impossible to combine with select (unless forcing no # buffering). if self.universal_newlines and hasattr(file, 'newlines'): if stdout: stdout = self._translate_newlines(stdout) if stderr: stderr = self._translate_newlines(stderr) self.wait() return (stdout, stderr) else: # # POSIX methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin is None: pass elif stdin == PIPE: p2cread, p2cwrite = os.pipe() elif is_int(stdin): p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout is None: pass elif stdout == PIPE: c2pread, c2pwrite = os.pipe() elif is_int(stdout): c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr is None: pass elif stderr == PIPE: errread, errwrite = os.pipe() elif stderr == STDOUT: errwrite = c2pwrite elif is_int(stderr): errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _set_cloexec_flag(self, fd): try: cloexec_flag = fcntl.FD_CLOEXEC except AttributeError: cloexec_flag = 1 old = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) def _close_fds(self, but): for i in range(3, MAXFD): if i == but: continue try: os.close(i) except KeyboardInterrupt: raise # SCons: don't swallow keyboard interrupts except: pass def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (POSIX version)""" if is_string(args): args = [args] if shell: args = ["/bin/sh", "-c"] + args if executable is None: executable = args[0] # For transferring possible exec failure from child to parent # The first char specifies the exception type: 0 means # OSError, 1 means some other error. errpipe_read, errpipe_write = os.pipe() self._set_cloexec_flag(errpipe_write) self.pid = os.fork() self._child_created = True if self.pid == 0: # Child try: # Close parent's pipe ends if p2cwrite: os.close(p2cwrite) if c2pread: os.close(c2pread) if errread: os.close(errread) os.close(errpipe_read) # Dup fds for child if p2cread: os.dup2(p2cread, 0) if c2pwrite: os.dup2(c2pwrite, 1) if errwrite: os.dup2(errwrite, 2) # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. try: set except NameError: # Fall-back for earlier Python versions, so epydoc # can use this module directly to execute things. if p2cread: os.close(p2cread) if c2pwrite and c2pwrite not in (p2cread,): os.close(c2pwrite) if errwrite and errwrite not in (p2cread, c2pwrite): os.close(errwrite) else: for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)): if fd: os.close(fd) # Close all other fds, if asked for if close_fds: self._close_fds(but=errpipe_write) if cwd is not None: os.chdir(cwd) if preexec_fn: apply(preexec_fn) if env is None: os.execvp(executable, args) else: os.execvpe(executable, args, env) except KeyboardInterrupt: raise # SCons: don't swallow keyboard interrupts except: exc_type, exc_value, tb = sys.exc_info() # Save the traceback and attach it to the exception object exc_lines = traceback.format_exception(exc_type, exc_value, tb) exc_value.child_traceback = ''.join(exc_lines) os.write(errpipe_write, pickle.dumps(exc_value)) # This exitcode won't be reported to applications, so it # really doesn't matter what we return. os._exit(255) # Parent os.close(errpipe_write) if p2cread and p2cwrite: os.close(p2cread) if c2pwrite and c2pread: os.close(c2pwrite) if errwrite and errread: os.close(errwrite) # Wait for exec to fail or succeed; possibly raising exception data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB os.close(errpipe_read) if data != "": os.waitpid(self.pid, 0) child_exception = pickle.loads(data) raise child_exception def _handle_exitstatus(self, sts): if os.WIFSIGNALED(sts): self.returncode = -os.WTERMSIG(sts) elif os.WIFEXITED(sts): self.returncode = os.WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") def poll(self, _deadstate=None): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode is None: try: pid, sts = os.waitpid(self.pid, os.WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) except os.error: if _deadstate is not None: self.returncode = _deadstate return self.returncode def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: pid, sts = os.waitpid(self.pid, 0) self._handle_exitstatus(sts) return self.returncode def _communicate(self, input): read_set = [] write_set = [] stdout = None # Return stderr = None # Return if self.stdin: # Flush stdio buffer. This might block, if the user has # been writing to .stdin in an uncontrolled fashion. self.stdin.flush() if input: write_set.append(self.stdin) else: self.stdin.close() if self.stdout: read_set.append(self.stdout) stdout = [] if self.stderr: read_set.append(self.stderr) stderr = [] input_offset = 0 while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) if self.stdin in wlist: # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 m = memoryview(input)[input_offset:input_offset+512] bytes_written = os.write(self.stdin.fileno(), m) input_offset = input_offset + bytes_written if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) if self.stdout in rlist: data = os.read(self.stdout.fileno(), 1024) if data == "": self.stdout.close() read_set.remove(self.stdout) stdout.append(data) if self.stderr in rlist: data = os.read(self.stderr.fileno(), 1024) if data == "": self.stderr.close() read_set.remove(self.stderr) stderr.append(data) # All data exchanged. Translate lists into strings. if stdout is not None: stdout = ''.join(stdout) if stderr is not None: stderr = ''.join(stderr) # Translate newlines, if requested. We cannot let the file # object do the translation: It is based on stdio, which is # impossible to combine with select (unless forcing no # buffering). if self.universal_newlines and hasattr(file, 'newlines'): if stdout: stdout = self._translate_newlines(stdout) if stderr: stderr = self._translate_newlines(stderr) self.wait() return (stdout, stderr) def _demo_posix(): # # Example 1: Simple redirection: Get process list # plist = Popen(["ps"], stdout=PIPE).communicate()[0] print "Process list:" print plist # # Example 2: Change uid before executing child # if os.getuid() == 0: p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) p.wait() # # Example 3: Connecting several subprocesses # print "Looking for 'hda'..." p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) print repr(p2.communicate()[0]) # # Example 4: Catch execution error # print print "Trying a weird file..." try: print Popen(["/this/path/does/not/exist"]).communicate() except OSError, e: if e.errno == errno.ENOENT: print "The file didn't exist. I thought so..." print "Child traceback:" print e.child_traceback else: print "Error", e.errno else: sys.stderr.write( "Gosh. No error.\n" ) def _demo_windows(): # # Example 1: Connecting several subprocesses # print "Looking for 'PROMPT' in set output..." p1 = Popen("set", stdout=PIPE, shell=True) p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) print repr(p2.communicate()[0]) # # Example 2: Simple execution of program # print "Executing calc..." p = Popen("calc") p.wait() if __name__ == "__main__": if mswindows: _demo_windows() else: _demo_posix() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. # __doc__ = """ dbm compatibility module for Python versions that don't have dbm. This does not not NOT (repeat, *NOT*) provide complete dbm functionality. It's just a stub on which to hang just enough pieces of dbm functionality that the whichdb.whichdb() implementstation in the various 2.X versions of Python won't blow up even if dbm wasn't compiled in. """ __revision__ = "src/engine/SCons/compat/_scons_dbm.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" class error(Exception): pass def open(*args, **kw): raise error() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. # __doc__ = """ collections compatibility module for older (pre-2.4) Python versions This does not not NOT (repeat, *NOT*) provide complete collections functionality. It only wraps the portions of collections functionality used by SCons, in an interface that looks enough like collections for our purposes. """ __revision__ = "src/engine/SCons/compat/_scons_collections.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" # Use exec to hide old names from fixers. exec("""if True: from UserDict import UserDict from UserList import UserList from UserString import UserString""") # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. # __doc__ = """ SCons compatibility package for old Python versions This subpackage holds modules that provide backwards-compatible implementations of various things that we'd like to use in SCons but which only show up in later versions of Python than the early, old version(s) we still support. Other code will not generally reference things in this package through the SCons.compat namespace. The modules included here add things to the builtins namespace or the global module list so that the rest of our code can use the objects and names imported here regardless of Python version. Simply enough, things that go in the builtins name space come from our _scons_builtins module. The rest of the things here will be in individual compatibility modules that are either: 1) suitably modified copies of the future modules that we want to use; or 2) backwards compatible re-implementations of the specific portions of a future module's API that we want to use. GENERAL WARNINGS: Implementations of functions in the SCons.compat modules are *NOT* guaranteed to be fully compliant with these functions in later versions of Python. We are only concerned with adding functionality that we actually use in SCons, so be wary if you lift this code for other uses. (That said, making these more nearly the same as later, official versions is still a desirable goal, we just don't need to be obsessive about it.) We name the compatibility modules with an initial '_scons_' (for example, _scons_subprocess.py is our compatibility module for subprocess) so that we can still try to import the real module name and fall back to our compatibility module if we get an ImportError. The import_as() function defined below loads the module as the "real" name (without the '_scons'), after which all of the "import {module}" statements in the rest of our code will find our pre-loaded compatibility module. """ __revision__ = "src/engine/SCons/compat/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import sys import imp # Use the "imp" module to protect imports from fixers. def import_as(module, name): """ Imports the specified module (from our local directory) as the specified name, returning the loaded module object. """ dir = os.path.split(__file__)[0] return imp.load_module(name, *imp.find_module(module, [dir])) def rename_module(new, old): """ Attempts to import the old module and load it under the new name. Used for purely cosmetic name changes in Python 3.x. """ try: sys.modules[new] = imp.load_module(old, *imp.find_module(old)) return True except ImportError: return False rename_module('builtins', '__builtin__') import _scons_builtins try: import hashlib except ImportError: # Pre-2.5 Python has no hashlib module. try: import_as('_scons_hashlib', 'hashlib') except ImportError: # If we failed importing our compatibility module, it probably # means this version of Python has no md5 module. Don't do # anything and let the higher layer discover this fact, so it # can fall back to using timestamp. pass try: set except NameError: # Pre-2.4 Python has no native set type import_as('_scons_sets', 'sets') import builtins, sets builtins.set = sets.Set try: import collections except ImportError: # Pre-2.4 Python has no collections module. import_as('_scons_collections', 'collections') else: try: collections.UserDict except AttributeError: exec('from UserDict import UserDict as _UserDict') collections.UserDict = _UserDict del _UserDict try: collections.UserList except AttributeError: exec('from UserList import UserList as _UserList') collections.UserList = _UserList del _UserList try: collections.UserString except AttributeError: exec('from UserString import UserString as _UserString') collections.UserString = _UserString del _UserString try: import io except ImportError: # Pre-2.6 Python has no io module. import_as('_scons_io', 'io') try: os.devnull except AttributeError: # Pre-2.4 Python has no os.devnull attribute _names = sys.builtin_module_names if 'posix' in _names: os.devnull = '/dev/null' elif 'nt' in _names: os.devnull = 'nul' os.path.devnull = os.devnull try: os.path.lexists except AttributeError: # Pre-2.4 Python has no os.path.lexists function def lexists(path): return os.path.exists(path) or os.path.islink(path) os.path.lexists = lexists # When we're using the '-3' option during regression tests, importing # cPickle gives a warning no matter how it's done, so always use the # real profile module, whether it's fast or not. if os.environ.get('SCONS_HORRIBLE_REGRESSION_TEST_HACK') is None: # Not a regression test with '-3', so try to use faster version. # In 3.x, 'pickle' automatically loads the fast version if available. rename_module('pickle', 'cPickle') # In 3.x, 'profile' automatically loads the fast version if available. rename_module('profile', 'cProfile') # Before Python 3.0, the 'queue' module was named 'Queue'. rename_module('queue', 'Queue') # Before Python 3.0, the 'winreg' module was named '_winreg' rename_module('winreg', '_winreg') try: import subprocess except ImportError: # Pre-2.4 Python has no subprocess module. import_as('_scons_subprocess', 'subprocess') try: sys.intern except AttributeError: # Pre-2.6 Python has no sys.intern() function. import builtins try: sys.intern = builtins.intern except AttributeError: # Pre-2.x Python has no builtin intern() function. def intern(x): return x sys.intern = intern del intern try: sys.maxsize except AttributeError: # Pre-2.6 Python has no sys.maxsize attribute # Wrapping sys in () is silly, but protects it from 2to3 renames fixer sys.maxsize = (sys).maxint if os.environ.get('SCONS_HORRIBLE_REGRESSION_TEST_HACK') is not None: # We can't apply the 'callable' fixer until the floor is 2.6, but the # '-3' option to Python 2.6 and 2.7 generates almost ten thousand # warnings. This hack allows us to run regression tests with the '-3' # option by replacing the callable() built-in function with a hack # that performs the same function but doesn't generate the warning. # Note that this hack is ONLY intended to be used for regression # testing, and should NEVER be used for real runs. from types import ClassType def callable(obj): if hasattr(obj, '__call__'): return True if isinstance(obj, (ClassType, type)): return True return False import builtins builtins.callable = callable del callable # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.Fortran This module implements the dependency scanner for Fortran code. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/Fortran.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import re import SCons.Node import SCons.Node.FS import SCons.Scanner import SCons.Util import SCons.Warnings class F90Scanner(SCons.Scanner.Classic): """ A Classic Scanner subclass for Fortran source files which takes into account both USE and INCLUDE statements. This scanner will work for both F77 and F90 (and beyond) compilers. Currently, this scanner assumes that the include files do not contain USE statements. To enable the ability to deal with USE statements in include files, add logic right after the module names are found to loop over each include file, search for and locate each USE statement, and append each module name to the list of dependencies. Caching the search results in a common dictionary somewhere so that the same include file is not searched multiple times would be a smart thing to do. """ def __init__(self, name, suffixes, path_variable, use_regex, incl_regex, def_regex, *args, **kw): self.cre_use = re.compile(use_regex, re.M) self.cre_incl = re.compile(incl_regex, re.M) self.cre_def = re.compile(def_regex, re.M) def _scan(node, env, path, self=self): node = node.rfile() if not node.exists(): return [] return self.scan(node, env, path) kw['function'] = _scan kw['path_function'] = SCons.Scanner.FindPathDirs(path_variable) kw['recursive'] = 1 kw['skeys'] = suffixes kw['name'] = name SCons.Scanner.Current.__init__(self, *args, **kw) def scan(self, node, env, path=()): # cache the includes list in node so we only scan it once: if node.includes != None: mods_and_includes = node.includes else: # retrieve all included filenames includes = self.cre_incl.findall(node.get_text_contents()) # retrieve all USE'd module names modules = self.cre_use.findall(node.get_text_contents()) # retrieve all defined module names defmodules = self.cre_def.findall(node.get_text_contents()) # Remove all USE'd module names that are defined in the same file # (case-insensitively) d = {} for m in defmodules: d[m.lower()] = 1 modules = [m for m in modules if m.lower() not in d] # Convert module name to a .mod filename suffix = env.subst('$FORTRANMODSUFFIX') modules = [x.lower() + suffix for x in modules] # Remove unique items from the list mods_and_includes = SCons.Util.unique(includes+modules) node.includes = mods_and_includes # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the USE or INCLUDE line, which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally. nodes = [] source_dir = node.get_dir() if callable(path): path = path() for dep in mods_and_includes: n, i = self.find_include(dep, source_dir, path) if n is None: SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (referenced by: %s) -- file not found" % (i, node)) else: sortkey = self.sort_key(dep) nodes.append((sortkey, n)) return [pair[1] for pair in sorted(nodes)] def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements""" # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: module_name # # Limitations # # -- While the regex can handle multiple USE statements on one line, # it cannot properly handle them if they are commented out. # In either of the following cases: # # ! USE mod_a ; USE mod_b [entire line is commented out] # USE mod_a ! ; USE mod_b [in-line comment of second USE statement] # # the second module name (mod_b) will be picked up as a dependency # even though it should be ignored. The only way I can see # to rectify this would be to modify the scanner to eliminate # the call to re.findall, read in the contents of the file, # treating the comment character as an end-of-line character # in addition to the normal linefeed, loop over each line, # weeding out the comments, and looking for the USE statements. # One advantage to this is that the regex passed to the scanner # would no longer need to match a semicolon. # # -- I question whether or not we need to detect dependencies to # INTRINSIC modules because these are built-in to the compiler. # If we consider them a dependency, will SCons look for them, not # find them, and kill the build? Or will we there be standard # compiler-specific directories we will need to point to so the # compiler and SCons can locate the proper object and mod files? # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^ : start of line # (?: : group a collection of regex symbols without saving the match as a "group" # ^|; : matches either the start of the line or a semicolon - semicolon # ) : end the unsaved grouping # \s* : any amount of white space # USE : match the string USE, case insensitive # (?: : group a collection of regex symbols without saving the match as a "group" # \s+| : match one or more whitespace OR .... (the next entire grouped set of regex symbols) # (?: : group a collection of regex symbols without saving the match as a "group" # (?: : establish another unsaved grouping of regex symbols # \s* : any amount of white space # , : match a comma # \s* : any amount of white space # (?:NON_)? : optionally match the prefix NON_, case insensitive # INTRINSIC : match the string INTRINSIC, case insensitive # )? : optionally match the ", INTRINSIC/NON_INTRINSIC" grouped expression # \s* : any amount of white space # :: : match a double colon that must appear after the INTRINSIC/NON_INTRINSIC attribute # ) : end the unsaved grouping # ) : end the unsaved grouping # \s* : match any amount of white space # (\w+) : match the module name that is being USE'd # # use_regex = "(?i)(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)" # The INCLUDE statement regex matches the following: # # INCLUDE 'some_Text' # INCLUDE "some_Text" # INCLUDE "some_Text" ; INCLUDE "some_Text" # INCLUDE kind_"some_Text" # INCLUDE kind_'some_Text" # # where some_Text can include any alphanumeric and/or special character # as defined by the Fortran 2003 standard. # # Limitations: # # -- The Fortran standard dictates that a " or ' in the INCLUDE'd # string must be represented as a "" or '', if the quotes that wrap # the entire string are either a ' or ", respectively. While the # regular expression below can detect the ' or " characters just fine, # the scanning logic, presently is unable to detect them and reduce # them to a single instance. This probably isn't an issue since, # in practice, ' or " are not generally used in filenames. # # -- This regex will not properly deal with multiple INCLUDE statements # when the entire line has been commented out, ala # # ! INCLUDE 'some_file' ; INCLUDE 'some_file' # # In such cases, it will properly ignore the first INCLUDE file, # but will actually still pick up the second. Interestingly enough, # the regex will properly deal with these cases: # # INCLUDE 'some_file' # INCLUDE 'some_file' !; INCLUDE 'some_file' # # To get around the above limitation, the FORTRAN programmer could # simply comment each INCLUDE statement separately, like this # # ! INCLUDE 'some_file' !; INCLUDE 'some_file' # # The way I see it, the only way to get around this limitation would # be to modify the scanning logic to replace the calls to re.findall # with a custom loop that processes each line separately, throwing # away fully commented out lines before attempting to match against # the INCLUDE syntax. # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # (?: : begin a non-saving group that matches the following: # ^ : either the start of the line # | : or # ['">]\s*; : a semicolon that follows a single quote, # double quote or greater than symbol (with any # amount of whitespace in between). This will # allow the regex to match multiple INCLUDE # statements per line (although it also requires # the positive lookahead assertion that is # used below). It will even properly deal with # (i.e. ignore) cases in which the additional # INCLUDES are part of an in-line comment, ala # " INCLUDE 'someFile' ! ; INCLUDE 'someFile2' " # ) : end of non-saving group # \s* : any amount of white space # INCLUDE : match the string INCLUDE, case insensitive # \s+ : match one or more white space characters # (?\w+_)? : match the optional "kind-param _" prefix allowed by the standard # [<"'] : match the include delimiter - an apostrophe, double quote, or less than symbol # (.+?) : match one or more characters that make up # the included path and file name and save it # in a group. The Fortran standard allows for # any non-control character to be used. The dot # operator will pick up any character, including # control codes, but I can't conceive of anyone # putting control codes in their file names. # The question mark indicates it is non-greedy so # that regex will match only up to the next quote, # double quote, or greater than symbol # (?=["'>]) : positive lookahead assertion to match the include # delimiter - an apostrophe, double quote, or # greater than symbol. This level of complexity # is required so that the include delimiter is # not consumed by the match, thus allowing the # sub-regex discussed above to uniquely match a # set of semicolon-separated INCLUDE statements # (as allowed by the F2003 standard) include_regex = """(?i)(?:^|['">]\s*;)\s*INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])""" # The MODULE statement regex finds module definitions by matching # the following: # # MODULE module_name # # but *not* the following: # # MODULE PROCEDURE procedure_name # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^\s* : any amount of white space # MODULE : match the string MODULE, case insensitive # \s+ : match one or more white space characters # (?!PROCEDURE) : but *don't* match if the next word matches # PROCEDURE (negative lookahead assertion), # case insensitive # (\w+) : match one or more alphanumeric characters # that make up the defined module name and # save it in a group def_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)""" scanner = F90Scanner("FortranScan", "$FORTRANSUFFIXES", path_variable, use_regex, include_regex, def_regex) return scanner # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.LaTeX This module implements the dependency scanner for LaTeX code. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/LaTeX.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import re import SCons.Scanner import SCons.Util # list of graphics file extensions for TeX and LaTeX TexGraphics = ['.eps', '.ps'] LatexGraphics = ['.pdf', '.png', '.jpg', '.gif', '.tif'] # Used as a return value of modify_env_var if the variable is not set. class _Null(object): pass _null = _Null # The user specifies the paths in env[variable], similar to other builders. # They may be relative and must be converted to absolute, as expected # by LaTeX and Co. The environment may already have some paths in # env['ENV'][var]. These paths are honored, but the env[var] paths have # higher precedence. All changes are un-done on exit. def modify_env_var(env, var, abspath): try: save = env['ENV'][var] except KeyError: save = _null env.PrependENVPath(var, abspath) try: if SCons.Util.is_List(env[var]): env.PrependENVPath(var, [os.path.abspath(str(p)) for p in env[var]]) else: # Split at os.pathsep to convert into absolute path env.PrependENVPath(var, [os.path.abspath(p) for p in str(env[var]).split(os.pathsep)]) except KeyError: pass # Convert into a string explicitly to append ":" (without which it won't search system # paths as well). The problem is that env.AppendENVPath(var, ":") # does not work, refuses to append ":" (os.pathsep). if SCons.Util.is_List(env['ENV'][var]): env['ENV'][var] = os.pathsep.join(env['ENV'][var]) # Append the trailing os.pathsep character here to catch the case with no env[var] env['ENV'][var] = env['ENV'][var] + os.pathsep return save class FindENVPathDirs(object): """A class to bind a specific *PATH variable name to a function that will return all of the *path directories.""" def __init__(self, variable): self.variable = variable def __call__(self, env, dir=None, target=None, source=None, argument=None): import SCons.PathList try: path = env['ENV'][self.variable] except KeyError: return () dir = dir or env.fs._cwd path = SCons.PathList.PathList(path).subst_path(env, target, source) return tuple(dir.Rfindalldirs(path)) def LaTeXScanner(): """Return a prototype Scanner instance for scanning LaTeX source files when built with latex. """ ds = LaTeX(name = "LaTeXScanner", suffixes = '$LATEXSUFFIXES', # in the search order, see below in LaTeX class docstring graphics_extensions = TexGraphics, recursive = 0) return ds def PDFLaTeXScanner(): """Return a prototype Scanner instance for scanning LaTeX source files when built with pdflatex. """ ds = LaTeX(name = "PDFLaTeXScanner", suffixes = '$LATEXSUFFIXES', # in the search order, see below in LaTeX class docstring graphics_extensions = LatexGraphics, recursive = 0) return ds class LaTeX(SCons.Scanner.Base): """Class for scanning LaTeX files for included files. Unlike most scanners, which use regular expressions that just return the included file name, this returns a tuple consisting of the keyword for the inclusion ("include", "includegraphics", "input", or "bibliography"), and then the file name itself. Based on a quick look at LaTeX documentation, it seems that we should append .tex suffix for the "include" keywords, append .tex if there is no extension for the "input" keyword, and need to add .bib for the "bibliography" keyword that does not accept extensions by itself. Finally, if there is no extension for an "includegraphics" keyword latex will append .ps or .eps to find the file, while pdftex may use .pdf, .jpg, .tif, .mps, or .png. The actual subset and search order may be altered by DeclareGraphicsExtensions command. This complication is ignored. The default order corresponds to experimentation with teTeX $ latex --version pdfeTeX 3.141592-1.21a-2.2 (Web2C 7.5.4) kpathsea version 3.5.4 The order is: ['.eps', '.ps'] for latex ['.png', '.pdf', '.jpg', '.tif']. Another difference is that the search path is determined by the type of the file being searched: env['TEXINPUTS'] for "input" and "include" keywords env['TEXINPUTS'] for "includegraphics" keyword env['TEXINPUTS'] for "lstinputlisting" keyword env['BIBINPUTS'] for "bibliography" keyword env['BSTINPUTS'] for "bibliographystyle" keyword env['INDEXSTYLE'] for "makeindex" keyword, no scanning support needed just allows user to set it if needed. FIXME: also look for the class or style in document[class|style]{} FIXME: also look for the argument of bibliographystyle{} """ keyword_paths = {'include': 'TEXINPUTS', 'input': 'TEXINPUTS', 'includegraphics': 'TEXINPUTS', 'bibliography': 'BIBINPUTS', 'bibliographystyle': 'BSTINPUTS', 'addbibresource': 'BIBINPUTS', 'addglobalbib': 'BIBINPUTS', 'addsectionbib': 'BIBINPUTS', 'makeindex': 'INDEXSTYLE', 'usepackage': 'TEXINPUTS', 'lstinputlisting': 'TEXINPUTS'} env_variables = SCons.Util.unique(list(keyword_paths.values())) def __init__(self, name, suffixes, graphics_extensions, *args, **kw): # We have to include \n with the % we exclude from the first part # part of the regex because the expression is compiled with re.M. # Without the \n, the ^ could match the beginning of a *previous* # line followed by one or more newline characters (i.e. blank # lines), interfering with a match on the next line. # add option for whitespace before the '[options]' or the '{filename}' regex = r'^[^%\n]*\\(include|includegraphics(?:\s*\[[^\]]+\])?|lstinputlisting(?:\[[^\]]+\])?|input|bibliography|addbibresource|addglobalbib|addsectionbib|usepackage)\s*{([^}]*)}' self.cre = re.compile(regex, re.M) self.comment_re = re.compile(r'^((?:(?:\\%)|[^%\n])*)(.*)$', re.M) self.graphics_extensions = graphics_extensions def _scan(node, env, path=(), self=self): node = node.rfile() if not node.exists(): return [] return self.scan_recurse(node, path) class FindMultiPathDirs(object): """The stock FindPathDirs function has the wrong granularity: it is called once per target, while we need the path that depends on what kind of included files is being searched. This wrapper hides multiple instances of FindPathDirs, one per the LaTeX path variable in the environment. When invoked, the function calculates and returns all the required paths as a dictionary (converted into a tuple to become hashable). Then the scan function converts it back and uses a dictionary of tuples rather than a single tuple of paths. """ def __init__(self, dictionary): self.dictionary = {} for k,n in dictionary.items(): self.dictionary[k] = ( SCons.Scanner.FindPathDirs(n), FindENVPathDirs(n) ) def __call__(self, env, dir=None, target=None, source=None, argument=None): di = {} for k,(c,cENV) in self.dictionary.items(): di[k] = ( c(env, dir=None, target=None, source=None, argument=None) , cENV(env, dir=None, target=None, source=None, argument=None) ) # To prevent "dict is not hashable error" return tuple(di.items()) class LaTeXScanCheck(object): """Skip all but LaTeX source files, i.e., do not scan *.eps, *.pdf, *.jpg, etc. """ def __init__(self, suffixes): self.suffixes = suffixes def __call__(self, node, env): current = not node.has_builder() or node.is_up_to_date() scannable = node.get_suffix() in env.subst_list(self.suffixes)[0] # Returning false means that the file is not scanned. return scannable and current kw['function'] = _scan kw['path_function'] = FindMultiPathDirs(LaTeX.keyword_paths) kw['recursive'] = 0 kw['skeys'] = suffixes kw['scan_check'] = LaTeXScanCheck(suffixes) kw['name'] = name SCons.Scanner.Base.__init__(self, *args, **kw) def _latex_names(self, include): filename = include[1] if include[0] == 'input': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.tex'] if (include[0] == 'include'): return [filename + '.tex'] if include[0] == 'bibliography': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.bib'] if include[0] == 'usepackage': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.sty'] if include[0] == 'includegraphics': base, ext = os.path.splitext( filename ) if ext == "": #return [filename+e for e in self.graphics_extensions + TexGraphics] # use the line above to find dependencies for the PDF builder # when only an .eps figure is present. Since it will be found # if the user tells scons how to make the pdf figure, leave # it out for now. return [filename+e for e in self.graphics_extensions] return [filename] def sort_key(self, include): return SCons.Node.FS._my_normcase(str(include)) def find_include(self, include, source_dir, path): try: sub_path = path[include[0]] except (IndexError, KeyError): sub_path = () try_names = self._latex_names(include) for n in try_names: # see if we find it using the path in env[var] i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path[0]) if i: return i, include # see if we find it using the path in env['ENV'][var] i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path[1]) if i: return i, include return i, include def canonical_text(self, text): """Standardize an input TeX-file contents. Currently: * removes comments, unwrapping comment-wrapped lines. """ out = [] line_continues_a_comment = False for line in text.splitlines(): line,comment = self.comment_re.findall(line)[0] if line_continues_a_comment == True: out[-1] = out[-1] + line.lstrip() else: out.append(line) line_continues_a_comment = len(comment) > 0 return '\n'.join(out).rstrip()+'\n' def scan(self, node): # Modify the default scan function to allow for the regular # expression to return a comma separated list of file names # as can be the case with the bibliography keyword. # Cache the includes list in node so we only scan it once: # path_dict = dict(list(path)) # add option for whitespace (\s) before the '[' noopt_cre = re.compile('\s*\[.*$') if node.includes != None: includes = node.includes else: text = self.canonical_text(node.get_text_contents()) includes = self.cre.findall(text) # 1. Split comma-separated lines, e.g. # ('bibliography', 'phys,comp') # should become two entries # ('bibliography', 'phys') # ('bibliography', 'comp') # 2. Remove the options, e.g., such as # ('includegraphics[clip,width=0.7\\linewidth]', 'picture.eps') # should become # ('includegraphics', 'picture.eps') split_includes = [] for include in includes: inc_type = noopt_cre.sub('', include[0]) inc_list = include[1].split(',') for j in range(len(inc_list)): split_includes.append( (inc_type, inc_list[j]) ) # includes = split_includes node.includes = includes return includes def scan_recurse(self, node, path=()): """ do a recursive scan of the top level target file This lets us search for included files based on the directory of the main file just as latex does""" path_dict = dict(list(path)) queue = [] queue.extend( self.scan(node) ) seen = {} # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the \include, \input, etc. line. # TODO: what about the comment in the original Classic scanner: # """which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally.""" nodes = [] source_dir = node.get_dir() #for include in includes: while queue: include = queue.pop() try: if seen[include[1]] == 1: continue except KeyError: seen[include[1]] = 1 # # Handle multiple filenames in include[1] # n, i = self.find_include(include, source_dir, path_dict) if n is None: # Do not bother with 'usepackage' warnings, as they most # likely refer to system-level files if include[0] != 'usepackage': SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node)) else: sortkey = self.sort_key(n) nodes.append((sortkey, n)) # recurse down queue.extend( self.scan(n) ) return [pair[1] for pair in sorted(nodes)] # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.D Scanner for the Digital Mars "D" programming language. Coded by Andy Friesen 17 Nov 2003 """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/D.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import re import SCons.Scanner def DScanner(): """Return a prototype Scanner instance for scanning D source files""" ds = D() return ds class D(SCons.Scanner.Classic): def __init__ (self): SCons.Scanner.Classic.__init__ (self, name = "DScanner", suffixes = '$DSUFFIXES', path_variable = 'DPATH', regex = 'import\s+(?:[a-zA-Z0-9_.]+)\s*(?:,\s*(?:[a-zA-Z0-9_.]+)\s*)*;') self.cre2 = re.compile ('(?:import\s)?\s*([a-zA-Z0-9_.]+)\s*(?:,|;)', re.M) def find_include(self, include, source_dir, path): # translate dots (package separators) to slashes inc = include.replace('.', '/') i = SCons.Node.FS.find_file(inc + '.d', (source_dir,) + path) if i is None: i = SCons.Node.FS.find_file (inc + '.di', (source_dir,) + path) return i, include def find_include_names(self, node): includes = [] for i in self.cre.findall(node.get_text_contents()): includes = includes + self.cre2.findall(i) return includes # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.RC This module implements the depenency scanner for RC (Interface Definition Language) files. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/RC.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node.FS import SCons.Scanner import re def RCScan(): """Return a prototype Scanner instance for scanning RC source files""" res_re= r'^(?:\s*#\s*(?:include)|' \ '.*?\s+(?:ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)' \ '\s*.*?)' \ '\s*(<|"| )([^>"\s]+)(?:[>"\s])*$' resScanner = SCons.Scanner.ClassicCPP( "ResourceScanner", "$RCSUFFIXES", "CPPPATH", res_re ) return resScanner # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/Prog.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node import SCons.Node.FS import SCons.Scanner import SCons.Util # global, set by --debug=findlibs print_find_libs = None def ProgramScanner(**kw): """Return a prototype Scanner instance for scanning executable files for static-lib dependencies""" kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps def scan(node, env, libpath = ()): """ This scanner scans program files for static-library dependencies. It will search the LIBPATH environment variable for libraries specified in the LIBS variable, returning any files it finds as dependencies. """ try: libs = env['LIBS'] except KeyError: # There are no LIBS in this environment, so just return a null list: return [] if SCons.Util.is_String(libs): libs = libs.split() else: libs = SCons.Util.flatten(libs) try: prefix = env['LIBPREFIXES'] if not SCons.Util.is_List(prefix): prefix = [ prefix ] except KeyError: prefix = [ '' ] try: suffix = env['LIBSUFFIXES'] if not SCons.Util.is_List(suffix): suffix = [ suffix ] except KeyError: suffix = [ '' ] pairs = [] for suf in map(env.subst, suffix): for pref in map(env.subst, prefix): pairs.append((pref, suf)) result = [] if callable(libpath): libpath = libpath() find_file = SCons.Node.FS.find_file adjustixes = SCons.Util.adjustixes for lib in libs: if SCons.Util.is_String(lib): lib = env.subst(lib) for pref, suf in pairs: l = adjustixes(lib, pref, suf) l = find_file(l, libpath, verbose=print_find_libs) if l: result.append(l) else: result.append(lib) return result # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner The Scanner package for the SCons software construction utility. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import re import SCons.Node.FS import SCons.Util class _Null(object): pass # This is used instead of None as a default argument value so None can be # used as an actual argument value. _null = _Null def Scanner(function, *args, **kw): """ Public interface factory function for creating different types of Scanners based on the different types of "functions" that may be supplied. TODO: Deprecate this some day. We've moved the functionality inside the Base class and really don't need this factory function any more. It was, however, used by some of our Tool modules, so the call probably ended up in various people's custom modules patterned on SCons code. """ if SCons.Util.is_Dict(function): return Selector(function, *args, **kw) else: return Base(function, *args, **kw) class FindPathDirs(object): """A class to bind a specific *PATH variable name to a function that will return all of the *path directories.""" def __init__(self, variable): self.variable = variable def __call__(self, env, dir=None, target=None, source=None, argument=None): import SCons.PathList try: path = env[self.variable] except KeyError: return () dir = dir or env.fs._cwd path = SCons.PathList.PathList(path).subst_path(env, target, source) return tuple(dir.Rfindalldirs(path)) class Base(object): """ The base class for dependency scanners. This implements straightforward, single-pass scanning of a single file. """ def __init__(self, function, name = "NONE", argument = _null, skeys = _null, path_function = None, # Node.FS.Base so that, by default, it's okay for a # scanner to return a Dir, File or Entry. node_class = SCons.Node.FS.Base, node_factory = None, scan_check = None, recursive = None): """ Construct a new scanner object given a scanner function. 'function' - a scanner function taking two or three arguments and returning a list of strings. 'name' - a name for identifying this scanner object. 'argument' - an optional argument that, if specified, will be passed to both the scanner function and the path_function. 'skeys' - an optional list argument that can be used to determine which scanner should be used for a given Node. In the case of File nodes, for example, the 'skeys' would be file suffixes. 'path_function' - a function that takes four or five arguments (a construction environment, Node for the directory containing the SConscript file that defined the primary target, list of target nodes, list of source nodes, and optional argument for this instance) and returns a tuple of the directories that can be searched for implicit dependency files. May also return a callable() which is called with no args and returns the tuple (supporting Bindable class). 'node_class' - the class of Nodes which this scan will return. If node_class is None, then this scanner will not enforce any Node conversion and will return the raw results from the underlying scanner function. 'node_factory' - the factory function to be called to translate the raw results returned by the scanner function into the expected node_class objects. 'scan_check' - a function to be called to first check whether this node really needs to be scanned. 'recursive' - specifies that this scanner should be invoked recursively on all of the implicit dependencies it returns (the canonical example being #include lines in C source files). May be a callable, which will be called to filter the list of nodes found to select a subset for recursive scanning (the canonical example being only recursively scanning subdirectories within a directory). The scanner function's first argument will be a Node that should be scanned for dependencies, the second argument will be an Environment object, the third argument will be the tuple of paths returned by the path_function, and the fourth argument will be the value passed into 'argument', and the returned list should contain the Nodes for all the direct dependencies of the file. Examples: s = Scanner(my_scanner_function) s = Scanner(function = my_scanner_function) s = Scanner(function = my_scanner_function, argument = 'foo') """ # Note: this class could easily work with scanner functions that take # something other than a filename as an argument (e.g. a database # node) and a dependencies list that aren't file names. All that # would need to be changed is the documentation. self.function = function self.path_function = path_function self.name = name self.argument = argument if skeys is _null: if SCons.Util.is_Dict(function): skeys = list(function.keys()) else: skeys = [] self.skeys = skeys self.node_class = node_class self.node_factory = node_factory self.scan_check = scan_check if callable(recursive): self.recurse_nodes = recursive elif recursive: self.recurse_nodes = self._recurse_all_nodes else: self.recurse_nodes = self._recurse_no_nodes def path(self, env, dir=None, target=None, source=None): if not self.path_function: return () if not self.argument is _null: return self.path_function(env, dir, target, source, self.argument) else: return self.path_function(env, dir, target, source) def __call__(self, node, env, path = ()): """ This method scans a single object. 'node' is the node that will be passed to the scanner function, and 'env' is the environment that will be passed to the scanner function. A list of direct dependency nodes for the specified node will be returned. """ if self.scan_check and not self.scan_check(node, env): return [] self = self.select(node) if not self.argument is _null: list = self.function(node, env, path, self.argument) else: list = self.function(node, env, path) kw = {} if hasattr(node, 'dir'): kw['directory'] = node.dir node_factory = env.get_factory(self.node_factory) nodes = [] for l in list: if self.node_class and not isinstance(l, self.node_class): l = node_factory(l, **kw) nodes.append(l) return nodes def __cmp__(self, other): try: return cmp(self.__dict__, other.__dict__) except AttributeError: # other probably doesn't have a __dict__ return cmp(self.__dict__, other) def __hash__(self): return id(self) def __str__(self): return self.name def add_skey(self, skey): """Add a skey to the list of skeys""" self.skeys.append(skey) def get_skeys(self, env=None): if env and SCons.Util.is_String(self.skeys): return env.subst_list(self.skeys)[0] return self.skeys def select(self, node): if SCons.Util.is_Dict(self.function): key = node.scanner_key() try: return self.function[key] except KeyError: return None else: return self def _recurse_all_nodes(self, nodes): return nodes def _recurse_no_nodes(self, nodes): return [] recurse_nodes = _recurse_no_nodes def add_scanner(self, skey, scanner): self.function[skey] = scanner self.add_skey(skey) class Selector(Base): """ A class for selecting a more specific scanner based on the scanner_key() (suffix) for a specific Node. TODO: This functionality has been moved into the inner workings of the Base class, and this class will be deprecated at some point. (It was never exposed directly as part of the public interface, although it is used by the Scanner() factory function that was used by various Tool modules and therefore was likely a template for custom modules that may be out there.) """ def __init__(self, dict, *args, **kw): Base.__init__(self, None, *args, **kw) self.dict = dict self.skeys = list(dict.keys()) def __call__(self, node, env, path = ()): return self.select(node)(node, env, path) def select(self, node): try: return self.dict[node.scanner_key()] except KeyError: return None def add_scanner(self, skey, scanner): self.dict[skey] = scanner self.add_skey(skey) class Current(Base): """ A class for scanning files that are source files (have no builder) or are derived files and are current (which implies that they exist, either locally or in a repository). """ def __init__(self, *args, **kw): def current_check(node, env): return not node.has_builder() or node.is_up_to_date() kw['scan_check'] = current_check Base.__init__(self, *args, **kw) class Classic(Current): """ A Scanner subclass to contain the common logic for classic CPP-style include scanning, but which can be customized to use different regular expressions to find the includes. Note that in order for this to work "out of the box" (without overriding the find_include() and sort_key() methods), the regular expression passed to the constructor must return the name of the include file in group 0. """ def __init__(self, name, suffixes, path_variable, regex, *args, **kw): self.cre = re.compile(regex, re.M) def _scan(node, env, path=(), self=self): node = node.rfile() if not node.exists(): return [] return self.scan(node, path) kw['function'] = _scan kw['path_function'] = FindPathDirs(path_variable) kw['recursive'] = 1 kw['skeys'] = suffixes kw['name'] = name Current.__init__(self, *args, **kw) def find_include(self, include, source_dir, path): n = SCons.Node.FS.find_file(include, (source_dir,) + tuple(path)) return n, include def sort_key(self, include): return SCons.Node.FS._my_normcase(include) def find_include_names(self, node): return self.cre.findall(node.get_text_contents()) def scan(self, node, path=()): # cache the includes list in node so we only scan it once: if node.includes is not None: includes = node.includes else: includes = self.find_include_names (node) # Intern the names of the include files. Saves some memory # if the same header is included many times. node.includes = list(map(SCons.Util.silent_intern, includes)) # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the #include line (including the # " or <, since that may affect what file is found), which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally. nodes = [] source_dir = node.get_dir() if callable(path): path = path() for include in includes: n, i = self.find_include(include, source_dir, path) if n is None: SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node)) else: nodes.append((self.sort_key(include), n)) return [pair[1] for pair in sorted(nodes)] class ClassicCPP(Classic): """ A Classic Scanner subclass which takes into account the type of bracketing used to include the file, and uses classic CPP rules for searching for the files based on the bracketing. Note that in order for this to work, the regular expression passed to the constructor must return the leading bracket in group 0, and the contained filename in group 1. """ def find_include(self, include, source_dir, path): if include[0] == '"': paths = (source_dir,) + tuple(path) else: paths = tuple(path) + (source_dir,) n = SCons.Node.FS.find_file(include[1], paths) i = SCons.Util.silent_intern(include[1]) return n, i def sort_key(self, include): return SCons.Node.FS._my_normcase(' '.join(include)) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/Dir.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node.FS import SCons.Scanner def only_dirs(nodes): is_Dir = lambda n: isinstance(n.disambiguate(), SCons.Node.FS.Dir) return list(filter(is_Dir, nodes)) def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw) def DirEntryScanner(**kw): """Return a prototype Scanner instance for "scanning" directory Nodes for their in-memory entries""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) skip_entry = {} skip_entry_list = [ '.', '..', '.sconsign', # Used by the native dblite.py module. '.sconsign.dblite', # Used by dbm and dumbdbm. '.sconsign.dir', # Used by dbm. '.sconsign.pag', # Used by dumbdbm. '.sconsign.dat', '.sconsign.bak', # Used by some dbm emulations using Berkeley DB. '.sconsign.db', ] for skip in skip_entry_list: skip_entry[skip] = 1 skip_entry[SCons.Node.FS._my_normcase(skip)] = 1 do_not_scan = lambda k: k not in skip_entry def scan_on_disk(node, env, path=()): """ Scans a directory for on-disk files and directories therein. Looking up the entries will add these to the in-memory Node tree representation of the file system, so all we have to do is just that and then call the in-memory scanning function. """ try: flist = node.fs.listdir(node.abspath) except (IOError, OSError): return [] e = node.Entry for f in filter(do_not_scan, flist): # Add ./ to the beginning of the file name so if it begins with a # '#' we don't look it up relative to the top-level directory. e('./' + f) return scan_in_memory(node, env, path) def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing # mixed Node types (Dirs and Files, for example) has a Dir as # the first entry. return [] entry_list = sorted(filter(do_not_scan, list(entries.keys()))) return [entries[n] for n in entry_list] # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.IDL This module implements the depenency scanner for IDL (Interface Definition Language) files. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/IDL.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node.FS import SCons.Scanner def IDLScan(): """Return a prototype Scanner instance for scanning IDL source files""" cs = SCons.Scanner.ClassicCPP("IDLScan", "$IDLSUFFIXES", "CPPPATH", '^[ \t]*(?:#[ \t]*include|[ \t]*import)[ \t]+(<|")([^>"]+)(>|")') return cs # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.C This module implements the depenency scanner for C/C++ code. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Scanner/C.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node.FS import SCons.Scanner import SCons.Util import SCons.cpp class SConsCPPScanner(SCons.cpp.PreProcessor): """ SCons-specific subclass of the cpp.py module's processing. We subclass this so that: 1) we can deal with files represented by Nodes, not strings; 2) we can keep track of the files that are missing. """ def __init__(self, *args, **kw): SCons.cpp.PreProcessor.__init__(self, *args, **kw) self.missing = [] def initialize_result(self, fname): self.result = SCons.Util.UniqueList([fname]) def finalize_result(self, fname): return self.result[1:] def find_include_file(self, t): keyword, quote, fname = t result = SCons.Node.FS.find_file(fname, self.searchpath[quote]) if not result: self.missing.append((fname, self.current_file)) return result def read_file(self, file): try: fp = open(str(file.rfile())) except EnvironmentError, e: self.missing.append((file, self.current_file)) return '' else: return fp.read() def dictify_CPPDEFINES(env): cppdefines = env.get('CPPDEFINES', {}) if cppdefines is None: return {} if SCons.Util.is_Sequence(cppdefines): result = {} for c in cppdefines: if SCons.Util.is_Sequence(c): result[c[0]] = c[1] else: result[c] = None return result if not SCons.Util.is_Dict(cppdefines): return {cppdefines : None} return cppdefines class SConsCPPScannerWrapper(object): """ The SCons wrapper around a cpp.py scanner. This is the actual glue between the calling conventions of generic SCons scanners, and the (subclass of) cpp.py class that knows how to look for #include lines with reasonably real C-preprocessor-like evaluation of #if/#ifdef/#else/#elif lines. """ def __init__(self, name, variable): self.name = name self.path = SCons.Scanner.FindPathDirs(variable) def __call__(self, node, env, path = ()): cpp = SConsCPPScanner(current = node.get_dir(), cpppath = path, dict = dictify_CPPDEFINES(env)) result = cpp(node) for included, includer in cpp.missing: fmt = "No dependency generated for file: %s (included from: %s) -- file not found" SCons.Warnings.warn(SCons.Warnings.DependencyWarning, fmt % (included, includer)) return result def recurse_nodes(self, nodes): return nodes def select(self, node): return self def CScanner(): """Return a prototype Scanner instance for scanning source files that use the C pre-processor""" # Here's how we would (or might) use the CPP scanner code above that # knows how to evaluate #if/#ifdef/#else/#elif lines when searching # for #includes. This is commented out for now until we add the # right configurability to let users pick between the scanners. #return SConsCPPScannerWrapper("CScanner", "CPPPATH") cs = SCons.Scanner.ClassicCPP("CScanner", "$CPPSUFFIXES", "CPPPATH", '^[ \t]*#[ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")') return cs # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Sig.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Sig module hierarchy This is no longer used, but code out there (such as the NSIS module on the SCons wiki) may try to import SCons.Sig. If so, we generate a warning that points them to the line that caused the import, and don't die. If someone actually tried to use the sub-modules or functions within the package (for example, SCons.Sig.MD5.signature()), then they'll still get an AttributeError, but at least they'll know where to start looking. """ import SCons.Util import SCons.Warnings msg = 'The SCons.Sig module no longer exists.\n' \ ' Remove the following "import SCons.Sig" line to eliminate this warning:' SCons.Warnings.warn(SCons.Warnings.DeprecatedSigModuleWarning, msg) default_calc = None default_module = None class MD5Null(SCons.Util.Null): def __repr__(self): return "MD5Null()" class TimeStampNull(SCons.Util.Null): def __repr__(self): return "TimeStampNull()" MD5 = MD5Null() TimeStamp = TimeStampNull() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Script This file implements the main() function used by the scons script. Architecturally, this *is* the scons script, and will likely only be called from the external "scons" wrapper. Consequently, anything here should not be, or be considered, part of the build engine. If it's something that we expect other software to want to use, it should go in some 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 (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Script/Main.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import os import sys import time import traceback # 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:] import SCons.CacheDir import SCons.Debug import SCons.Defaults import SCons.Environment import SCons.Errors import SCons.Job import SCons.Node import SCons.Node.FS import SCons.Platform import SCons.SConf import SCons.Script import SCons.Taskmaster import SCons.Util import SCons.Warnings import SCons.Script.Interactive def fetch_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. import SCons.Platform.win32 return SCons.Platform.win32.parallel_msg # class SConsPrintHelpException(Exception): pass display = SCons.Util.display progress_display = SCons.Util.DisplayEngine() first_command_start = None last_command_end = None class Progressor(object): prev = '' count = 0 target_string = '$TARGET' def __init__(self, obj, interval=1, file=None, overwrite=False): if file is None: file = sys.stdout self.obj = obj self.file = file self.interval = interval self.overwrite = overwrite if callable(obj): self.func = obj elif SCons.Util.is_List(obj): self.func = self.spinner elif obj.find(self.target_string) != -1: self.func = self.replace_string else: self.func = self.string def write(self, s): self.file.write(s) self.file.flush() self.prev = s def erase_previous(self): if self.prev: length = len(self.prev) if self.prev[-1] in ('\n', '\r'): length = length - 1 self.write(' ' * length + '\r') self.prev = '' def spinner(self, node): self.write(self.obj[self.count % len(self.obj)]) def string(self, node): self.write(self.obj) def replace_string(self, node): self.write(self.obj.replace(self.target_string, str(node))) def __call__(self, node): self.count = self.count + 1 if (self.count % self.interval) == 0: if self.overwrite: self.erase_previous() self.func(node) ProgressObject = SCons.Util.Null() def Progress(*args, **kw): global ProgressObject ProgressObject = Progressor(*args, **kw) # Task control. # _BuildFailures = [] def GetBuildFailures(): return _BuildFailures class BuildTask(SCons.Taskmaster.OutOfDateTask): """An SCons build task.""" progress = ProgressObject def display(self, message): display('scons: ' + message) def prepare(self): self.progress(self.targets[0]) return SCons.Taskmaster.OutOfDateTask.prepare(self) def needs_execute(self): if SCons.Taskmaster.OutOfDateTask.needs_execute(self): return True if self.top and self.targets[0].has_builder(): display("scons: `%s' is up to date." % str(self.node)) return False def execute(self): if print_time: start_time = time.time() global first_command_start if first_command_start is None: first_command_start = start_time SCons.Taskmaster.OutOfDateTask.execute(self) if print_time: global cumulative_command_time global last_command_end finish_time = time.time() last_command_end = finish_time cumulative_command_time = cumulative_command_time+finish_time-start_time sys.stdout.write("Command execution time: %f seconds\n"%(finish_time-start_time)) def do_failed(self, status=2): _BuildFailures.append(self.exception[1]) global exit_status global this_build_status if self.options.ignore_errors: SCons.Taskmaster.OutOfDateTask.executed(self) elif self.options.keep_going: SCons.Taskmaster.OutOfDateTask.fail_continue(self) exit_status = status this_build_status = status else: SCons.Taskmaster.OutOfDateTask.fail_stop(self) exit_status = status this_build_status = status def executed(self): t = self.targets[0] if self.top and not t.has_builder() and not t.side_effect: if not t.exists(): if t.__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) if not self.options.keep_going: sys.stderr.write(" Stop.") sys.stderr.write("\n") try: raise SCons.Errors.BuildError(t, errstr) except KeyboardInterrupt: raise except: self.exception_set() self.do_failed() else: print "scons: Nothing to be done for `%s'." % t SCons.Taskmaster.OutOfDateTask.executed(self) else: SCons.Taskmaster.OutOfDateTask.executed(self) def failed(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_info except ValueError: t, e = exc_info tb = None if t is None: # The Taskmaster didn't record an exception for this Task; # see if the sys module has one. try: t, e, tb = sys.exc_info()[:] except ValueError: t, e = exc_info tb = None # Deprecated string exceptions will have their string stored # in the first entry of the tuple. if e is None: e = t buildError = SCons.Errors.convert_to_BuildError(e) if not buildError.node: buildError.node = self.node node = buildError.node if not SCons.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] and buildError.exc_info[1] and not isinstance( buildError.exc_info[1], (EnvironmentError, SCons.Errors.StopError, SCons.Errors.UserError))): type, value, trace = buildError.exc_info traceback.print_exception(type, value, trace) elif tb and print_stacktrace: sys.stderr.write("scons: internal stack trace:\n") traceback.print_tb(tb, file=sys.stderr) self.exception = (e, buildError, tb) # type, value, traceback self.do_failed(buildError.exitstatus) self.exc_clear() def postprocess(self): if self.top: t = self.targets[0] for tp in self.options.tree_printers: tp.display(t) if self.options.debug_includes: tree = t.render_include_tree() if tree: print print tree SCons.Taskmaster.OutOfDateTask.postprocess(self) def make_ready(self): """Make a task ready for execution""" SCons.Taskmaster.OutOfDateTask.make_ready(self) if self.out_of_date and self.options.debug_explain: explanation = self.out_of_date[0].explain() if explanation: sys.stdout.write("scons: " + explanation) class CleanTask(SCons.Taskmaster.AlwaysTask): """An SCons clean task.""" def fs_delete(self, path, pathstr, remove=1): try: if os.path.lexists(path): if os.path.isfile(path) or os.path.islink(path): if remove: os.unlink(path) display("Removed " + pathstr) elif os.path.isdir(path) and not os.path.islink(path): # delete everything in the dir for e in sorted(os.listdir(path)): p = os.path.join(path, e) s = os.path.join(pathstr, e) if os.path.isfile(p): if remove: os.unlink(p) display("Removed " + s) else: self.fs_delete(p, s, remove) # then delete dir itself if remove: os.rmdir(path) display("Removed directory " + pathstr) else: errstr = "Path '%s' exists but isn't a file or directory." raise SCons.Errors.UserError(errstr % (pathstr)) except SCons.Errors.UserError, e: print e except (IOError, OSError), e: print "scons: Could not remove '%s':" % pathstr, e.strerror def show(self): target = self.targets[0] if (target.has_builder() or target.side_effect) and not target.noclean: for t in self.targets: if not t.isdir(): display("Removed " + str(t)) if target in SCons.Environment.CleanTargets: files = SCons.Environment.CleanTargets[target] for f in files: self.fs_delete(f.abspath, str(f), 0) def remove(self): target = self.targets[0] if (target.has_builder() or target.side_effect) and not target.noclean: for t in self.targets: try: removed = t.remove() except OSError, 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.strerror else: if removed: display("Removed " + str(t)) if target in SCons.Environment.CleanTargets: files = SCons.Environment.CleanTargets[target] for f in files: 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_all def prepare(self): pass class QuestionTask(SCons.Taskmaster.AlwaysTask): """An SCons task for the -q (question) option.""" def prepare(self): pass def execute(self): if self.targets[0].get_state() != SCons.Node.up_to_date or \ (self.top and not self.targets[0].exists()): global exit_status global this_build_status exit_status = 1 this_build_status = 1 self.tm.stop() def executed(self): pass class TreePrinter(object): def __init__(self, derived=False, prune=False, status=False): self.derived = derived self.prune = prune self.status = status def get_all_children(self, node): return node.all_children() def get_derived_children(self, node): children = node.all_children(None) return [x for x in children if x.has_builder()] def display(self, t): if self.derived: func = self.get_derived_children else: func = self.get_all_children s = self.status and 2 or 0 SCons.Util.print_tree(t, func, prune=self.prune, showtags=s) def python_version_string(): return sys.version.split()[0] def python_version_unsupported(version=sys.version_info): return version < unsupported_python_version def python_version_deprecated(version=sys.version_info): return version < deprecated_python_version # Global variables print_objects = 0 print_memoizer = 0 print_stacktrace = 0 print_time = 0 sconscript_time = 0 cumulative_command_time = 0 exit_status = 0 # final exit status, assume success by default this_build_status = 0 # "exit status" of an individual build num_jobs = None delayed_warnings = [] class FakeOptionParser(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. """ class FakeOptionValues(object): def __getattr__(self, attr): return None values = FakeOptionValues() def add_local_option(self, *args, **kw): pass OptionsParser = FakeOptionParser() def AddOption(*args, **kw): if 'default' not in kw: kw['default'] = None result = OptionsParser.add_local_option(*args, **kw) return result def GetOption(name): return getattr(OptionsParser.values, name) def SetOption(name, value): return OptionsParser.values.set_option(name, value) # class Stats(object): def __init__(self): self.stats = [] self.labels = [] self.append = self.do_nothing self.print_stats = self.do_nothing def enable(self, outfp): self.outfp = outfp self.append = self.do_append self.print_stats = self.do_print def do_nothing(self, *args, **kw): pass class CountStats(Stats): def do_append(self, label): self.labels.append(label) self.stats.append(SCons.Debug.fetchLoggedInstances()) def do_print(self): stats_table = {} for s in self.stats: for n in [t[0] for t in s]: stats_table[n] = [0, 0, 0, 0] i = 0 for s in self.stats: for n, c in s: stats_table[n][i] = c i = i + 1 self.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] for x in labels])) self.outfp.write(fmt1 % tuple([x[1] for x in labels])) for k in sorted(stats_table.keys()): r = stats_table[k][:l] + [k] self.outfp.write(fmt2 % tuple(r)) count_stats = CountStats() class MemStats(Stats): def do_append(self, label): self.labels.append(label) self.stats.append(SCons.Debug.memory()) def do_print(self): fmt = 'Memory %-32s %12d\n' for label, stats in zip(self.labels, self.stats): self.outfp.write(fmt % (label, stats)) memory_stats = MemStats() # utility functions def _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) for line in lines: sys.stderr.write(line+'\n') sys.exit(2) def find_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: for frame in tb: filename = frame[0] if filename.find(os.sep+'SCons'+os.sep) == -1: return frame return tb[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. """ global print_stacktrace etype, value, tb = sys.exc_info() if print_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. """ if not filelist: filelist = ['SConstruct', 'Sconstruct', 'sconstruct'] for file in filelist: sfile = os.path.join(dirname, file) if os.path.isfile(sfile): return sfile if not os.path.isabs(sfile): for rep in repositories: if os.path.isfile(os.path.join(rep, sfile)): return sfile return None def _set_debug_values(options): global print_memoizer, print_objects, print_stacktrace, print_time debug_values = options.debug if "count" in debug_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 = False if __debug__: enable_count = True if enable_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" in debug_values: options.tree_printers.append(TreePrinter(derived=True)) options.debug_explain = ("explain" in debug_values) if "findlibs" in debug_values: SCons.Scanner.Prog.print_find_libs = "findlibs" options.debug_includes = ("includes" in debug_values) print_memoizer = ("memoizer" in debug_values) if "memory" in debug_values: memory_stats.enable(sys.stdout) print_objects = ("objects" in debug_values) if "presub" in debug_values: SCons.Action.print_actions_presub = 1 if "stacktrace" in debug_values: print_stacktrace = 1 if "stree" in debug_values: options.tree_printers.append(TreePrinter(status=True)) if "time" in debug_values: print_time = 1 if "tree" in debug_values: options.tree_printers.append(TreePrinter()) if "prepare" in debug_values: SCons.Taskmaster.print_prepare = 1 if "duplicate" in debug_values: SCons.Node.FS.print_duplicate = 1 def _create_path(plist): path = '.' for d in plist: if os.path.isabs(d): path = d else: path = path + '/' + d return path def _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.""" if site_dir_name: err_if_not_found = True # user specified: err if missing else: site_dir_name = "site_scons" err_if_not_found = False site_dir = os.path.join(topdir, site_dir_name) if not os.path.exists(site_dir): if err_if_not_found: raise SCons.Errors.UserError("site dir %s not found."%site_dir) return site_init_filename = "site_init.py" site_init_modname = "site_init" site_tools_dirname = "site_tools" # prepend to sys.path sys.path = [os.path.abspath(site_dir)] + sys.path site_init_file = os.path.join(site_dir, site_init_filename) site_tools_dir = os.path.join(site_dir, site_tools_dirname) if os.path.exists(site_init_file): import imp, 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'] except Exception, e: fmt = 'cannot import site_init.py: missing SCons.Script module %s' raise SCons.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("__[^_]+__") for k in m.__dict__.keys(): if not re_special.match(k): site_m[k] = m.__dict__[k] # This is the magic. exec fp in site_m except KeyboardInterrupt: raise except Exception, e: fmt = '*** Error loading site_init file %s:\n' sys.stderr.write(fmt % repr(site_init_file)) raise else: for k in site_m: if not re_special.match(k): m.__dict__[k] = site_m[k] except KeyboardInterrupt: raise except ImportError, e: fmt = '*** cannot import site init file %s:\n' sys.stderr.write(fmt % repr(site_init_file)) raise finally: if fp: fp.close() if os.path.exists(site_tools_dir): # prepend to DefaultToolpath SCons.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() def homedir(d): return os.path.expanduser('~/'+d) if platform == 'win32' or platform == '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') if appdatadir not in sysdirs: sysdirs.append(appdatadir) sysdirs.append(homedir('.scons')) elif platform == 'darwin': # MacOS X sysdirs=['/Library/Application Support/SCons', '/opt/local/share/scons', # (for MacPorts) '/sw/share/scons', # (for Fink) homedir('Library/Application Support/SCons'), homedir('.scons')] elif platform == 'sunos': # Solaris sysdirs=['/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] for d in dirs: if verbose: # this is used by unit tests. print "Loading site dir ", d _load_site_scons_dir(d) def test_load_all_site_scons_dirs(d): _load_all_site_scons_dirs(d, True) def version_string(label, module): version = module.__version__ build = module.__build__ if build: if build[0] != '.': build = '.' + build version = version + build fmt = "\t%s: v%s, %s, by %s on %s\n" return fmt % (label, version, module.__date__, module.__developer__, module.__buildsys__) def path_string(label, module): path = module.__path__ return "\t%s path: %s\n"%(label,path) def _main(parser): global exit_status global this_build_status options = 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, ] for warning in default_warnings: SCons.Warnings.enableWarningClass(warning) SCons.Warnings._warningOut = _scons_internal_warning SCons.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_warnings except AttributeError: pass else: delayed_warnings.extend(dw) for warning_type, message in delayed_warnings: SCons.Warnings.warn(warning_type, message) if options.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). if options.directory: script_dir = os.path.abspath(_create_path(options.directory)) else: script_dir = os.getcwd() target_top = None if options.climb_up: target_top = '.' # directory to prepend to targets while script_dir and not _SConstruct_exists(script_dir, options.repository, options.file): script_dir, last_part = os.path.split(script_dir) if last_part: target_top = os.path.join(last_part, target_top) else: script_dir = '' if script_dir and script_dir != os.getcwd(): if not options.silent: display("scons: Entering directory `%s'" % script_dir) try: os.chdir(script_dir) except OSError: 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() for rep in options.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 = [] if options.file: scripts.extend(options.file) if not scripts: sfile = _SConstruct_exists(repositories=options.repository, filelist=options.file) if sfile: scripts.append(sfile) if not scripts: if options.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. raise SConsPrintHelpException raise SCons.Errors.UserError("No SConstruct file found.") if scripts[0] == "-": d = fs.getcwd() else: d = fs.File(scripts[0]).dir fs.set_SConstruct_dir(d) _set_debug_values(options) SCons.Node.implicit_cache = options.implicit_cache SCons.Node.implicit_deps_changed = options.implicit_deps_changed SCons.Node.implicit_deps_unchanged = options.implicit_deps_unchanged if options.no_exec: SCons.SConf.dryrun = 1 SCons.Action.execute_actions = None if options.question: SCons.SConf.dryrun = 1 if options.clean: SCons.SConf.SetBuildType('clean') if options.help: SCons.SConf.SetBuildType('help') SCons.SConf.SetCacheMode(options.config) SCons.SConf.SetProgressDisplay(progress_display) if options.no_progress or options.silent: progress_display.set_mode(0) if options.site_dir: _load_site_scons_dir(d.path, options.site_dir) elif not options.no_site_dir: _load_all_site_scons_dirs(d.path) if options.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 = [] for a in parser.largs: if a[:1] == '-': continue if '=' in a: 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. if not hasattr(sys.stdout, 'isatty') or not sys.stdout.isatty(): sys.stdout = SCons.Util.Unbuffered(sys.stdout) if not hasattr(sys.stderr, 'isatty') or not sys.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: for script in scripts: SCons.Script._SConscript._SConscript(fs, script) except SCons.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 = 2 sys.exit(exit_status) global sconscript_time sconscript_time = time.time() - start_time progress_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. if python_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()) if not options.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 = False parser.parse_args(parser.largs, options) if options.help: help_text = SCons.Script.help_text if help_text is None: # They specified -h, but there was no Help() inside the # SConscript files. Give them the options usage. raise SConsPrintHelpException else: print help_text print "Use scons -H for help about command-line options." exit_status = 0 return # 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_cache SCons.Node.FS.set_duplicate(options.duplicate) fs.set_max_drift(options.max_drift) SCons.Job.explicit_stack_size = options.stack_size if options.md5_chunksize: SCons.Node.FS.File.md5_chunksize = options.md5_chunksize platform = SCons.Platform.platform_module() if options.interactive: SCons.Script.Interactive.interact(fs, OptionsParser, options, targets, target_top) else: # Build the targets nodes = _build_targets(fs, options, targets, target_top) if not nodes: exit_status = 2 def _build_targets(fs, options, targets, target_top): global this_build_status this_build_status = 0 progress_display.set_mode(not (options.no_progress or options.silent)) display.set_mode(not options.silent) SCons.Action.print_actions = not options.silent SCons.Action.execute_actions = not options.no_exec SCons.Node.FS.do_store_info = not options.no_exec SCons.SConf.dryrun = options.no_exec if options.diskcheck: SCons.Node.FS.set_diskcheck(options.diskcheck) SCons.CacheDir.cache_enabled = not options.cache_disable SCons.CacheDir.cache_debug = options.cache_debug SCons.CacheDir.cache_force = options.cache_force SCons.CacheDir.cache_show = options.cache_show if options.no_exec: CleanTask.execute = CleanTask.show else: CleanTask.execute = CleanTask.remove lookup_top = None if targets or SCons.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. if target_top: lookup_top = fs.Dir(target_top) target_top = None targets = SCons.Script.BUILD_TARGETS else: # 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 = None if target_top: if options.climb_up == 1: # -u, local directory and below target_top = fs.Dir(target_top) lookup_top = target_top elif options.climb_up == 2: # -D, all Default() targets target_top = None lookup_top = None elif options.climb_up == 3: # -U, local SConscript Default() targets target_top = fs.Dir(target_top) def check_dir(x, target_top=target_top): if hasattr(x, 'cwd') and not x.cwd is None: cwd = x.cwd.srcnode() return cwd == target_top else: # 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: return 1 d = list(filter(check_dir, SCons.Script.DEFAULT_TARGETS)) SCons.Script.DEFAULT_TARGETS[:] = d target_top = None lookup_top = None targets = SCons.Script._Get_Default_Targets(d, fs) if not targets: sys.stderr.write("scons: *** No targets specified and no Default() targets found. Stop.\n") return None def Entry(x, ltop=lookup_top, ttop=target_top, fs=fs): if isinstance(x, SCons.Node.Node): node = x else: node = None # Why would ltop be None? Unfortunately this happens. if ltop is None: 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)) for lookup in SCons.Node.arg2nodes_lookups: node = lookup(x, curdir=curdir) if node is not None: break if node is None: node = fs.Entry(x, directory=ltop, create=1) if ttop and not node.is_under(ttop): if isinstance(node, SCons.Node.FS.Dir) and ttop.is_under(node): node = ttop else: node = None return node nodes = [_f for _f in map(Entry, targets) if _f] task_class = BuildTask # default action is to build targets opening_message = "Building targets ..." closing_message = "done building targets." if options.keep_going: failure_message = "done building targets (errors occurred during build)." else: failure_message = "building terminated because of errors." if options.question: task_class = QuestionTask try: if options.clean: task_class = CleanTask opening_message = "Cleaning targets ..." closing_message = "done cleaning targets." if options.keep_going: failure_message = "done cleaning targets (errors occurred during clean)." else: failure_message = "cleaning terminated because of errors." except AttributeError: pass task_class.progress = ProgressObject if options.random: def order(dependencies): """Randomize the dependencies.""" import random # This is cribbed from the implementation of # random.shuffle() in Python 2.X. d = dependencies for i in range(len(d)-1, 0, -1): j = int(random.random() * (i+1)) d[i], d[j] = d[j], d[i] return d else: def order(dependencies): """Leave the order of dependencies alone.""" return dependencies if options.taskmastertrace_file == '-': tmtrace = sys.stdout elif options.taskmastertrace_file: tmtrace = open(options.taskmastertrace_file, 'wb') else: tmtrace = None taskmaster = 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 = options global num_jobs num_jobs = options.num_jobs jobs = SCons.Job.Jobs(num_jobs, taskmaster) if num_jobs > 1: msg = None if jobs.num_jobs == 1: msg = "parallel builds are unsupported by this version of Python;\n" + \ "\tignoring -j or num_jobs option.\n" elif sys.platform == 'win32': msg = fetch_win32_parallel_msg() if msg: SCons.Warnings.warn(SCons.Warnings.NoParallelSupportWarning, msg) memory_stats.append('before building targets:') count_stats.append(('pre-', 'build')) def jobs_postfunc( jobs=jobs, options=options, closing_message=closing_message, failure_message=failure_message ): if jobs.were_interrupted(): if not options.no_progress and not options.silent: sys.stderr.write("scons: Build interrupted.\n") global exit_status global this_build_status exit_status = 2 this_build_status = 2 if this_build_status: progress_display("scons: " + failure_message) else: progress_display("scons: " + closing_message) if not options.no_exec: if jobs.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')) return nodes def _exec_main(parser, values): sconsflags = os.environ.get('SCONSFLAGS', '') all_args = sconsflags.split() + sys.argv[1:] options, args = parser.parse_args(all_args, values) if isinstance(options.debug, list) and "pdb" in options.debug: import pdb pdb.Pdb().runcall(_main, parser) elif options.profile_file: # compat layer imports "cProfile" for us if it's available. from profile import Profile # 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.dispatch except AttributeError: pass else: dispatch['c_exception'] = Profile.trace_dispatch_return prof = Profile() try: prof.runcall(_main, parser) except SConsPrintHelpException, e: prof.dump_stats(options.profile_file) raise e except SystemExit: pass prof.dump_stats(options.profile_file) else: _main(parser) def main(): global OptionsParser global exit_status global first_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. if python_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. pass parts.append(version_string("engine", SCons)) parts.append(path_string("engine", SCons)) parts.append("Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation") version = ''.join(parts) import SConsOptions parser = SConsOptions.Parser(version) values = SConsOptions.SConsValues(parser.get_default_values()) OptionsParser = parser try: _exec_main(parser, values) except SystemExit, s: if s: exit_status = s except KeyboardInterrupt: print("scons: Build interrupted.") sys.exit(2) except SyntaxError, e: _scons_syntax_error(e) except SCons.Errors.InternalError: _scons_internal_error() except SCons.Errors.UserError, e: _scons_user_error(e) except SConsPrintHelpException: parser.print_help() exit_status = 0 except SCons.Errors.BuildError, e: exit_status = e.exitstatus except: # 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() if print_objects: SCons.Debug.listLoggedInstances('*') #SCons.Debug.dumpLoggedInstances('*') if print_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() if print_time: total_time = time.time() - SCons.Script.start_time if num_jobs == 1: ct = cumulative_command_time else: if last_command_end is None or first_command_start is None: ct = 0.0 else: ct = last_command_end - first_command_start scons_time = total_time - sconscript_time - ct print "Total build time: %f seconds"%total_time print "Total SConscript file execution time: %f seconds"%sconscript_time print "Total SCons execution time: %f seconds"%scons_time print "Total command execution time: %f seconds"%ct sys.exit(exit_status) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Script.SConscript This module defines the Python API provided to SConscript and SConstruct files. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. from __future__ import division __revision__ = "src/engine/SCons/Script/SConscript.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Environment import SCons.Errors import SCons.Node import SCons.Node.Alias import SCons.Node.FS import SCons.Platform import SCons.SConf import SCons.Script.Main import SCons.Tool import SCons.Util import collections import os import os.path import re import sys import traceback # The following variables used to live in this module. Some # SConscript files out there may have referred to them directly as # SCons.Script.SConscript.*. This is now supported by some special # handling towards the bottom of the SConscript.__init__.py module. #Arguments = {} #ArgList = [] #BuildTargets = TargetList() #CommandLineTargets = [] #DefaultTargets = [] class SConscriptReturn(Exception): pass launch_dir = os.path.abspath(os.curdir) GlobalDict = None # global exports set by Export(): global_exports = {} # chdir flag sconscript_chdir = 1 def get_calling_namespaces(): """Return the locals and globals for the function that called into this module in the current call stack.""" try: 1//0 except ZeroDivisionError: # Don't start iterating with the current stack-frame to # prevent creating reference cycles (f_back is safe). frame = sys.exc_info()[2].tb_frame.f_back # Find the first frame that *isn't* from this file. This means # that we expect all of the SCons frames that implement an Export() # or SConscript() call to be in this file, so that we can identify # the first non-Script.SConscript frame as the user's local calling # environment, and the locals and globals dictionaries from that # frame as the calling namespaces. See the comment below preceding # the DefaultEnvironmentCall block for even more explanation. while frame.f_globals.get("__name__") == __name__: frame = frame.f_back return frame.f_locals, frame.f_globals def compute_exports(exports): """Compute a dictionary of exports given one of the parameters to the Export() function or the exports argument to SConscript().""" loc, glob = get_calling_namespaces() retval = {} try: for export in exports: if SCons.Util.is_Dict(export): retval.update(export) else: try: retval[export] = loc[export] except KeyError: retval[export] = glob[export] except KeyError, x: raise SCons.Errors.UserError("Export of non-existent variable '%s'"%x) return retval class Frame(object): """A frame on the SConstruct/SConscript call stack""" def __init__(self, fs, exports, sconscript): self.globals = BuildDefaultGlobals() self.retval = None self.prev_dir = fs.getcwd() self.exports = compute_exports(exports) # exports from the calling SConscript # make sure the sconscript attr is a Node. if isinstance(sconscript, SCons.Node.Node): self.sconscript = sconscript elif sconscript == '-': self.sconscript = None else: self.sconscript = fs.File(str(sconscript)) # the SConstruct/SConscript call stack: call_stack = [] # For documentation on the methods in this file, see the scons man-page def Return(*vars, **kw): retval = [] try: fvars = SCons.Util.flatten(vars) for var in fvars: for v in var.split(): retval.append(call_stack[-1].globals[v]) except KeyError, x: raise SCons.Errors.UserError("Return of non-existent variable '%s'"%x) if len(retval) == 1: call_stack[-1].retval = retval[0] else: call_stack[-1].retval = tuple(retval) stop = kw.get('stop', True) if stop: raise SConscriptReturn stack_bottom = '% Stack boTTom %' # hard to define a variable w/this name :) def _SConscript(fs, *files, **kw): top = fs.Top sd = fs.SConstruct_dir.rdir() exports = kw.get('exports', []) # evaluate each SConscript file results = [] for fn in files: call_stack.append(Frame(fs, exports, fn)) old_sys_path = sys.path try: SCons.Script.sconscript_reading = SCons.Script.sconscript_reading + 1 if fn == "-": exec sys.stdin in call_stack[-1].globals else: if isinstance(fn, SCons.Node.Node): f = fn else: f = fs.File(str(fn)) _file_ = None # Change directory to the top of the source # tree to make sure the os's cwd and the cwd of # fs match so we can open the SConscript. fs.chdir(top, change_os_dir=1) if f.rexists(): actual = f.rfile() _file_ = open(actual.get_abspath(), "r") elif f.srcnode().rexists(): actual = f.srcnode().rfile() _file_ = open(actual.get_abspath(), "r") elif f.has_src_builder(): # The SConscript file apparently exists in a source # code management system. Build it, but then clear # the builder so that it doesn't get built *again* # during the actual build phase. f.build() f.built() f.builder_set(None) if f.exists(): _file_ = open(f.get_abspath(), "r") if _file_: # Chdir to the SConscript directory. Use a path # name relative to the SConstruct file so that if # we're using the -f option, we're essentially # creating a parallel SConscript directory structure # in our local directory tree. # # XXX This is broken for multiple-repository cases # where the SConstruct and SConscript files might be # in different Repositories. For now, cross that # bridge when someone comes to it. try: src_dir = kw['src_dir'] except KeyError: ldir = fs.Dir(f.dir.get_path(sd)) else: ldir = fs.Dir(src_dir) if not ldir.is_under(f.dir): # They specified a source directory, but # it's above the SConscript directory. # Do the sensible thing and just use the # SConcript directory. ldir = fs.Dir(f.dir.get_path(sd)) try: fs.chdir(ldir, change_os_dir=sconscript_chdir) except OSError: # There was no local directory, so we should be # able to chdir to the Repository directory. # Note that we do this directly, not through # fs.chdir(), because we still need to # interpret the stuff within the SConscript file # relative to where we are logically. fs.chdir(ldir, change_os_dir=0) os.chdir(actual.dir.get_abspath()) # Append the SConscript directory to the beginning # of sys.path so Python modules in the SConscript # directory can be easily imported. sys.path = [ f.dir.get_abspath() ] + sys.path # This is the magic line that actually reads up # and executes the stuff in the SConscript file. # The locals for this frame contain the special # bottom-of-the-stack marker so that any # exceptions that occur when processing this # SConscript can base the printed frames at this # level and not show SCons internals as well. call_stack[-1].globals.update({stack_bottom:1}) old_file = call_stack[-1].globals.get('__file__') try: del call_stack[-1].globals['__file__'] except KeyError: pass try: try: exec _file_ in call_stack[-1].globals except SConscriptReturn: pass finally: if old_file is not None: call_stack[-1].globals.update({__file__:old_file}) else: SCons.Warnings.warn(SCons.Warnings.MissingSConscriptWarning, "Ignoring missing SConscript '%s'" % f.path) finally: SCons.Script.sconscript_reading = SCons.Script.sconscript_reading - 1 sys.path = old_sys_path frame = call_stack.pop() try: fs.chdir(frame.prev_dir, change_os_dir=sconscript_chdir) except OSError: # There was no local directory, so chdir to the # Repository directory. Like above, we do this # directly. fs.chdir(frame.prev_dir, change_os_dir=0) rdir = frame.prev_dir.rdir() rdir._create() # Make sure there's a directory there. try: os.chdir(rdir.get_abspath()) except OSError, e: # We still couldn't chdir there, so raise the error, # but only if actions are being executed. # # If the -n option was used, the directory would *not* # have been created and we should just carry on and # let things muddle through. This isn't guaranteed # to work if the SConscript files are reading things # from disk (for example), but it should work well # enough for most configurations. if SCons.Action.execute_actions: raise e results.append(frame.retval) # if we only have one script, don't return a tuple if len(results) == 1: return results[0] else: return tuple(results) def SConscript_exception(file=sys.stderr): """Print an exception stack trace just for the SConscript file(s). This will show users who have Python errors where the problem is, without cluttering the output with all of the internal calls leading up to where we exec the SConscript.""" exc_type, exc_value, exc_tb = sys.exc_info() tb = exc_tb while tb and stack_bottom not in tb.tb_frame.f_locals: tb = tb.tb_next if not tb: # We did not find our exec statement, so this was actually a bug # in SCons itself. Show the whole stack. tb = exc_tb stack = traceback.extract_tb(tb) try: type = exc_type.__name__ except AttributeError: type = str(exc_type) if type[:11] == "exceptions.": type = type[11:] file.write('%s: %s:\n' % (type, exc_value)) for fname, line, func, text in stack: file.write(' File "%s", line %d:\n' % (fname, line)) file.write(' %s\n' % text) def annotate(node): """Annotate a node with the stack frame describing the SConscript file and line number that created it.""" tb = sys.exc_info()[2] while tb and stack_bottom not in tb.tb_frame.f_locals: tb = tb.tb_next if not tb: # We did not find any exec of an SConscript file: what?! raise SCons.Errors.InternalError("could not find SConscript stack frame") node.creator = traceback.extract_stack(tb)[0] # The following line would cause each Node to be annotated using the # above function. Unfortunately, this is a *huge* performance hit, so # leave this disabled until we find a more efficient mechanism. #SCons.Node.Annotate = annotate class SConsEnvironment(SCons.Environment.Base): """An Environment subclass that contains all of the methods that are particular to the wrapper SCons interface and which aren't (or shouldn't be) part of the build engine itself. Note that not all of the methods of this class have corresponding global functions, there are some private methods. """ # # Private methods of an SConsEnvironment. # def _exceeds_version(self, major, minor, v_major, v_minor): """Return 1 if 'major' and 'minor' are greater than the version in 'v_major' and 'v_minor', and 0 otherwise.""" return (major > v_major or (major == v_major and minor > v_minor)) def _get_major_minor_revision(self, version_string): """Split a version string into major, minor and (optionally) revision parts. This is complicated by the fact that a version string can be something like 3.2b1.""" version = version_string.split(' ')[0].split('.') v_major = int(version[0]) v_minor = int(re.match('\d+', version[1]).group()) if len(version) >= 3: v_revision = int(re.match('\d+', version[2]).group()) else: v_revision = 0 return v_major, v_minor, v_revision def _get_SConscript_filenames(self, ls, kw): """ Convert the parameters passed to SConscript() calls into a list of files and export variables. If the parameters are invalid, throws SCons.Errors.UserError. Returns a tuple (l, e) where l is a list of SConscript filenames and e is a list of exports. """ exports = [] if len(ls) == 0: try: dirs = kw["dirs"] except KeyError: raise SCons.Errors.UserError("Invalid SConscript usage - no parameters") if not SCons.Util.is_List(dirs): dirs = [ dirs ] dirs = list(map(str, dirs)) name = kw.get('name', 'SConscript') files = [os.path.join(n, name) for n in dirs] elif len(ls) == 1: files = ls[0] elif len(ls) == 2: files = ls[0] exports = self.Split(ls[1]) else: raise SCons.Errors.UserError("Invalid SConscript() usage - too many arguments") if not SCons.Util.is_List(files): files = [ files ] if kw.get('exports'): exports.extend(self.Split(kw['exports'])) variant_dir = kw.get('variant_dir') or kw.get('build_dir') if variant_dir: if len(files) != 1: raise SCons.Errors.UserError("Invalid SConscript() usage - can only specify one SConscript with a variant_dir") duplicate = kw.get('duplicate', 1) src_dir = kw.get('src_dir') if not src_dir: src_dir, fname = os.path.split(str(files[0])) files = [os.path.join(str(variant_dir), fname)] else: if not isinstance(src_dir, SCons.Node.Node): src_dir = self.fs.Dir(src_dir) fn = files[0] if not isinstance(fn, SCons.Node.Node): fn = self.fs.File(fn) if fn.is_under(src_dir): # Get path relative to the source directory. fname = fn.get_path(src_dir) files = [os.path.join(str(variant_dir), fname)] else: files = [fn.abspath] kw['src_dir'] = variant_dir self.fs.VariantDir(variant_dir, src_dir, duplicate) return (files, exports) # # Public methods of an SConsEnvironment. These get # entry points in the global name space so they can be called # as global functions. # def Configure(self, *args, **kw): if not SCons.Script.sconscript_reading: raise SCons.Errors.UserError("Calling Configure from Builders is not supported.") kw['_depth'] = kw.get('_depth', 0) + 1 return SCons.Environment.Base.Configure(self, *args, **kw) def Default(self, *targets): SCons.Script._Set_Default_Targets(self, targets) def EnsureSConsVersion(self, major, minor, revision=0): """Exit abnormally if the SCons version is not late enough.""" scons_ver = self._get_major_minor_revision(SCons.__version__) if scons_ver < (major, minor, revision): if revision: scons_ver_string = '%d.%d.%d' % (major, minor, revision) else: scons_ver_string = '%d.%d' % (major, minor) print "SCons %s or greater required, but you have SCons %s" % \ (scons_ver_string, SCons.__version__) sys.exit(2) def EnsurePythonVersion(self, major, minor): """Exit abnormally if the Python version is not late enough.""" try: v_major, v_minor, v_micro, release, serial = sys.version_info python_ver = (v_major, v_minor) except AttributeError: python_ver = self._get_major_minor_revision(sys.version)[:2] if python_ver < (major, minor): v = sys.version.split(" ", 1)[0] print "Python %d.%d or greater required, but you have Python %s" %(major,minor,v) sys.exit(2) def Exit(self, value=0): sys.exit(value) def Export(self, *vars, **kw): for var in vars: global_exports.update(compute_exports(self.Split(var))) global_exports.update(kw) def GetLaunchDir(self): global launch_dir return launch_dir def GetOption(self, name): name = self.subst(name) return SCons.Script.Main.GetOption(name) def Help(self, text): text = self.subst(text, raw=1) SCons.Script.HelpFunction(text) def Import(self, *vars): try: frame = call_stack[-1] globals = frame.globals exports = frame.exports for var in vars: var = self.Split(var) for v in var: if v == '*': globals.update(global_exports) globals.update(exports) else: if v in exports: globals[v] = exports[v] else: globals[v] = global_exports[v] except KeyError,x: raise SCons.Errors.UserError("Import of non-existent variable '%s'"%x) def SConscript(self, *ls, **kw): if 'build_dir' in kw: msg = """The build_dir keyword has been deprecated; use the variant_dir keyword instead.""" SCons.Warnings.warn(SCons.Warnings.DeprecatedBuildDirWarning, msg) def subst_element(x, subst=self.subst): if SCons.Util.is_List(x): x = list(map(subst, x)) else: x = subst(x) return x ls = list(map(subst_element, ls)) subst_kw = {} for key, val in kw.items(): if SCons.Util.is_String(val): val = self.subst(val) elif SCons.Util.is_List(val): result = [] for v in val: if SCons.Util.is_String(v): v = self.subst(v) result.append(v) val = result subst_kw[key] = val files, exports = self._get_SConscript_filenames(ls, subst_kw) subst_kw['exports'] = exports return _SConscript(self.fs, *files, **subst_kw) def SConscriptChdir(self, flag): global sconscript_chdir sconscript_chdir = flag def SetOption(self, name, value): name = self.subst(name) SCons.Script.Main.SetOption(name, value) # # # SCons.Environment.Environment = SConsEnvironment def Configure(*args, **kw): if not SCons.Script.sconscript_reading: raise SCons.Errors.UserError("Calling Configure from Builders is not supported.") kw['_depth'] = 1 return SCons.SConf.SConf(*args, **kw) # It's very important that the DefaultEnvironmentCall() class stay in this # file, with the get_calling_namespaces() function, the compute_exports() # function, the Frame class and the SConsEnvironment.Export() method. # These things make up the calling stack leading up to the actual global # Export() or SConscript() call that the user issued. We want to allow # users to export local variables that they define, like so: # # def func(): # x = 1 # Export('x') # # To support this, the get_calling_namespaces() function assumes that # the *first* stack frame that's not from this file is the local frame # for the Export() or SConscript() call. _DefaultEnvironmentProxy = None def get_DefaultEnvironmentProxy(): global _DefaultEnvironmentProxy if not _DefaultEnvironmentProxy: default_env = SCons.Defaults.DefaultEnvironment() _DefaultEnvironmentProxy = SCons.Environment.NoSubstitutionProxy(default_env) return _DefaultEnvironmentProxy class DefaultEnvironmentCall(object): """A class that implements "global function" calls of Environment methods by fetching the specified method from the DefaultEnvironment's class. Note that this uses an intermediate proxy class instead of calling the DefaultEnvironment method directly so that the proxy can override the subst() method and thereby prevent expansion of construction variables (since from the user's point of view this was called as a global function, with no associated construction environment).""" def __init__(self, method_name, subst=0): self.method_name = method_name if subst: self.factory = SCons.Defaults.DefaultEnvironment else: self.factory = get_DefaultEnvironmentProxy def __call__(self, *args, **kw): env = self.factory() method = getattr(env, self.method_name) return method(*args, **kw) def BuildDefaultGlobals(): """ Create a dictionary containing all the default globals for SConstruct and SConscript files. """ global GlobalDict if GlobalDict is None: GlobalDict = {} import SCons.Script d = SCons.Script.__dict__ def not_a_module(m, d=d, mtype=type(SCons.Script)): return not isinstance(d[m], mtype) for m in filter(not_a_module, dir(SCons.Script)): GlobalDict[m] = d[m] return GlobalDict.copy() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Script/Interactive.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """ SCons interactive mode """ # TODO: # # This has the potential to grow into something with a really big life # of its own, which might or might not be a good thing. Nevertheless, # here are some enhancements that will probably be requested some day # and are worth keeping in mind (assuming this takes off): # # - A command to re-read / re-load the SConscript files. This may # involve allowing people to specify command-line options (e.g. -f, # -I, --no-site-dir) that affect how the SConscript files are read. # # - Additional command-line options on the "build" command. # # Of the supported options that seemed to make sense (after a quick # pass through the list), the ones that seemed likely enough to be # used are listed in the man page and have explicit test scripts. # # These had code changed in Script/Main.py to support them, but didn't # seem likely to be used regularly, so had no test scripts added: # # build --diskcheck=* # build --implicit-cache=* # build --implicit-deps-changed=* # build --implicit-deps-unchanged=* # # These look like they should "just work" with no changes to the # existing code, but like those above, look unlikely to be used and # therefore had no test scripts added: # # build --random # # These I'm not sure about. They might be useful for individual # "build" commands, and may even work, but they seem unlikely enough # that we'll wait until they're requested before spending any time on # writing test scripts for them, or investigating whether they work. # # build -q [??? is there a useful analog to the exit status?] # build --duplicate= # build --profile= # build --max-drift= # build --warn=* # build --Y # # - Most of the SCons command-line options that the "build" command # supports should be settable as default options that apply to all # subsequent "build" commands. Maybe a "set {option}" command that # maps to "SetOption('{option}')". # # - Need something in the 'help' command that prints the -h output. # # - A command to run the configure subsystem separately (must see how # this interacts with the new automake model). # # - Command-line completion of target names; maybe even of SCons options? # Completion is something that's supported by the Python cmd module, # so this should be doable without too much trouble. # import cmd import copy import os import re import shlex import sys try: import readline except ImportError: pass class SConsInteractiveCmd(cmd.Cmd): """\ build [TARGETS] Build the specified TARGETS and their dependencies. 'b' is a synonym. clean [TARGETS] Clean (remove) the specified TARGETS and their dependencies. 'c' is a synonym. exit Exit SCons interactive mode. help [COMMAND] Prints help for the specified COMMAND. 'h' and '?' are synonyms. shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and '!' are synonyms. version Prints SCons version information. """ synonyms = { 'b' : 'build', 'c' : 'clean', 'h' : 'help', 'scons' : 'build', 'sh' : 'shell', } def __init__(self, **kw): cmd.Cmd.__init__(self) for key, val in kw.items(): setattr(self, key, val) if sys.platform == 'win32': self.shell_variable = 'COMSPEC' else: self.shell_variable = 'SHELL' def default(self, argv): print "*** Unknown command: %s" % argv[0] def onecmd(self, line): line = line.strip() if not line: print self.lastcmd return self.emptyline() self.lastcmd = line if line[0] == '!': line = 'shell ' + line[1:] elif line[0] == '?': line = 'help ' + line[1:] if os.sep == '\\': line = line.replace('\\', '\\\\') argv = shlex.split(line) argv[0] = self.synonyms.get(argv[0], argv[0]) if not argv[0]: return self.default(line) else: try: func = getattr(self, 'do_' + argv[0]) except AttributeError: return self.default(argv) return func(argv) def do_build(self, argv): """\ build [TARGETS] Build the specified TARGETS and their dependencies. 'b' is a synonym. """ import SCons.Node import SCons.SConsign import SCons.Script.Main options = copy.deepcopy(self.options) options, targets = self.parser.parse_args(argv[1:], values=options) SCons.Script.COMMAND_LINE_TARGETS = targets if targets: SCons.Script.BUILD_TARGETS = targets else: # If the user didn't specify any targets on the command line, # use the list of default targets. SCons.Script.BUILD_TARGETS = SCons.Script._build_plus_default nodes = SCons.Script.Main._build_targets(self.fs, options, targets, self.target_top) if not nodes: return # Call each of the Node's alter_targets() methods, which may # provide additional targets that ended up as part of the build # (the canonical example being a VariantDir() when we're building # from a source directory) and which we therefore need their # state cleared, too. x = [] for n in nodes: x.extend(n.alter_targets()[0]) nodes.extend(x) # Clean up so that we can perform the next build correctly. # # We do this by walking over all the children of the targets, # and clearing their state. # # We currently have to re-scan each node to find their # children, because built nodes have already been partially # cleared and don't remember their children. (In scons # 0.96.1 and earlier, this wasn't the case, and we didn't # have to re-scan the nodes.) # # Because we have to re-scan each node, we can't clear the # nodes as we walk over them, because we may end up rescanning # a cleared node as we scan a later node. Therefore, only # store the list of nodes that need to be cleared as we walk # the tree, and clear them in a separate pass. # # XXX: Someone more familiar with the inner workings of scons # may be able to point out a more efficient way to do this. SCons.Script.Main.progress_display("scons: Clearing cached node information ...") seen_nodes = {} def get_unseen_children(node, parent, seen_nodes=seen_nodes): def is_unseen(node, seen_nodes=seen_nodes): return node not in seen_nodes return list(filter(is_unseen, node.children(scan=1))) def add_to_seen_nodes(node, parent, seen_nodes=seen_nodes): seen_nodes[node] = 1 # If this file is in a VariantDir and has a # corresponding source file in the source tree, remember the # node in the source tree, too. This is needed in # particular to clear cached implicit dependencies on the # source file, since the scanner will scan it if the # VariantDir was created with duplicate=0. try: rfile_method = node.rfile except AttributeError: return else: rfile = rfile_method() if rfile != node: seen_nodes[rfile] = 1 for node in nodes: walker = SCons.Node.Walker(node, kids_func=get_unseen_children, eval_func=add_to_seen_nodes) n = walker.get_next() while n: n = walker.get_next() for node in seen_nodes.keys(): # Call node.clear() to clear most of the state node.clear() # node.clear() doesn't reset node.state, so call # node.set_state() to reset it manually node.set_state(SCons.Node.no_state) node.implicit = None # Debug: Uncomment to verify that all Taskmaster reference # counts have been reset to zero. #if node.ref_count != 0: # from SCons.Debug import Trace # Trace('node %s, ref_count %s !!!\n' % (node, node.ref_count)) SCons.SConsign.Reset() SCons.Script.Main.progress_display("scons: done clearing node information.") def do_clean(self, argv): """\ clean [TARGETS] Clean (remove) the specified TARGETS and their dependencies. 'c' is a synonym. """ return self.do_build(['build', '--clean'] + argv[1:]) def do_EOF(self, argv): print self.do_exit(argv) def _do_one_help(self, arg): try: # If help_<arg>() exists, then call it. func = getattr(self, 'help_' + arg) except AttributeError: try: func = getattr(self, 'do_' + arg) except AttributeError: doc = None else: doc = self._doc_to_help(func) if doc: sys.stdout.write(doc + '\n') sys.stdout.flush() else: doc = self.strip_initial_spaces(func()) if doc: sys.stdout.write(doc + '\n') sys.stdout.flush() def _doc_to_help(self, obj): doc = obj.__doc__ if doc is None: return '' return self._strip_initial_spaces(doc) def _strip_initial_spaces(self, s): #lines = s.split('\n') lines = s.split('\n') spaces = re.match(' *', lines[0]).group(0) #def strip_spaces(l): # if l.startswith(spaces): # l = l[len(spaces):] # return l #return '\n'.join([ strip_spaces(l) for l in lines ]) def strip_spaces(l, spaces=spaces): if l[:len(spaces)] == spaces: l = l[len(spaces):] return l lines = list(map(strip_spaces, lines)) return '\n'.join(lines) def do_exit(self, argv): """\ exit Exit SCons interactive mode. """ sys.exit(0) def do_help(self, argv): """\ help [COMMAND] Prints help for the specified COMMAND. 'h' and '?' are synonyms. """ if argv[1:]: for arg in argv[1:]: if self._do_one_help(arg): break else: # If bare 'help' is called, print this class's doc # string (if it has one). doc = self._doc_to_help(self.__class__) if doc: sys.stdout.write(doc + '\n') sys.stdout.flush() def do_shell(self, argv): """\ shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and '!' are synonyms. """ import subprocess argv = argv[1:] if not argv: argv = os.environ[self.shell_variable] try: # Per "[Python-Dev] subprocess insufficiently platform-independent?" # http://mail.python.org/pipermail/python-dev/2008-August/081979.html "+ # Doing the right thing with an argument list currently # requires different shell= values on Windows and Linux. p = subprocess.Popen(argv, shell=(sys.platform=='win32')) except EnvironmentError, e: sys.stderr.write('scons: %s: %s\n' % (argv[0], e.strerror)) else: p.wait() def do_version(self, argv): """\ version Prints SCons version information. """ sys.stdout.write(self.parser.version + '\n') def interact(fs, parser, options, targets, target_top): c = SConsInteractiveCmd(prompt = 'scons>>> ', fs = fs, parser = parser, options = options, targets = targets, target_top = target_top) c.cmdloop() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Script/SConsOptions.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import optparse import re import sys import textwrap no_hyphen_re = re.compile(r'(\s+|(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') try: from gettext import gettext except ImportError: def gettext(message): return message _ = gettext import SCons.Node.FS import SCons.Warnings OptionValueError = optparse.OptionValueError SUPPRESS_HELP = optparse.SUPPRESS_HELP diskcheck_all = SCons.Node.FS.diskcheck_types() def diskcheck_convert(value): if value is None: return [] if not SCons.Util.is_List(value): value = value.split(',') result = [] for v in value: v = v.lower() if v == 'all': result = diskcheck_all elif v == 'none': result = [] elif v in diskcheck_all: result.append(v) else: raise ValueError(v) return result class SConsValues(optparse.Values): """ Holder class for uniform access to SCons options, regardless of whether or not they can be set on the command line or in the SConscript files (using the SetOption() function). A SCons option value can originate three different ways: 1) set on the command line; 2) set in an SConscript file; 3) the default setting (from the the op.add_option() calls in the Parser() function, below). The command line always overrides a value set in a SConscript file, which in turn always overrides default settings. Because we want to support user-specified options in the SConscript file itself, though, we may not know about all of the options when the command line is first parsed, so we can't make all the necessary precedence decisions at the time the option is configured. The solution implemented in this class is to keep these different sets of settings separate (command line, SConscript file, and default) and to override the __getattr__() method to check them in turn. This should allow the rest of the code to just fetch values as attributes of an instance of this class, without having to worry about where they came from. Note that not all command line options are settable from SConscript files, and the ones that are must be explicitly added to the "settable" list in this class, and optionally validated and coerced in the set_option() method. """ def __init__(self, defaults): self.__dict__['__defaults__'] = defaults self.__dict__['__SConscript_settings__'] = {} def __getattr__(self, attr): """ Fetches an options value, checking first for explicit settings from the command line (which are direct attributes), then the SConscript file settings, then the default values. """ try: return self.__dict__[attr] except KeyError: try: return self.__dict__['__SConscript_settings__'][attr] except KeyError: return getattr(self.__dict__['__defaults__'], attr) settable = [ 'clean', 'diskcheck', 'duplicate', 'help', 'implicit_cache', 'max_drift', 'md5_chunksize', 'no_exec', 'num_jobs', 'random', 'stack_size', 'warn', ] def set_option(self, name, value): """ Sets an option from an SConscript file. """ if not name in self.settable: raise SCons.Errors.UserError("This option is not settable from a SConscript file: %s"%name) if name == 'num_jobs': try: value = int(value) if value < 1: raise ValueError except ValueError: raise SCons.Errors.UserError("A positive integer is required: %s"%repr(value)) elif name == 'max_drift': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'duplicate': try: value = str(value) except ValueError: raise SCons.Errors.UserError("A string is required: %s"%repr(value)) if not value in SCons.Node.FS.Valid_Duplicates: raise SCons.Errors.UserError("Not a valid duplication style: %s" % value) # Set the duplicate style right away so it can affect linking # of SConscript files. SCons.Node.FS.set_duplicate(value) elif name == 'diskcheck': try: value = diskcheck_convert(value) except ValueError, v: raise SCons.Errors.UserError("Not a valid diskcheck value: %s"%v) if 'diskcheck' not in self.__dict__: # No --diskcheck= option was specified on the command line. # Set this right away so it can affect the rest of the # file/Node lookups while processing the SConscript files. SCons.Node.FS.set_diskcheck(value) elif name == 'stack_size': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'md5_chunksize': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'warn': if SCons.Util.is_String(value): value = [value] value = self.__SConscript_settings__.get(name, []) + value SCons.Warnings.process_warn_strings(value) self.__SConscript_settings__[name] = value class SConsOption(optparse.Option): def convert_value(self, opt, value): if value is not None: if self.nargs in (1, '?'): return self.check_value(opt, value) else: return tuple([self.check_value(opt, v) for v in value]) def process(self, opt, value, values, parser): # First, convert the value(s) to the right type. Howl if any # value(s) are bogus. value = self.convert_value(opt, value) # And then take whatever action is expected of us. # This is a separate method to make life easier for # subclasses to add new actions. return self.take_action( self.action, self.dest, opt, value, values, parser) def _check_nargs_optional(self): if self.nargs == '?' and self._short_opts: fmt = "option %s: nargs='?' is incompatible with short options" raise SCons.Errors.UserError(fmt % self._short_opts[0]) try: _orig_CONST_ACTIONS = optparse.Option.CONST_ACTIONS _orig_CHECK_METHODS = optparse.Option.CHECK_METHODS except AttributeError: # optparse.Option had no CONST_ACTIONS before Python 2.5. _orig_CONST_ACTIONS = ("store_const",) def _check_const(self): if self.action not in self.CONST_ACTIONS and self.const is not None: raise OptionError( "'const' must not be supplied for action %r" % self.action, self) # optparse.Option collects its list of unbound check functions # up front. This sucks because it means we can't just override # the _check_const() function like a normal method, we have to # actually replace it in the list. This seems to be the most # straightforward way to do that. _orig_CHECK_METHODS = [optparse.Option._check_action, optparse.Option._check_type, optparse.Option._check_choice, optparse.Option._check_dest, _check_const, optparse.Option._check_nargs, optparse.Option._check_callback] CHECK_METHODS = _orig_CHECK_METHODS + [_check_nargs_optional] CONST_ACTIONS = _orig_CONST_ACTIONS + optparse.Option.TYPED_ACTIONS class SConsOptionGroup(optparse.OptionGroup): """ A subclass for SCons-specific option groups. The only difference between this and the base class is that we print the group's help text flush left, underneath their own title but lined up with the normal "SCons Options". """ def format_help(self, formatter): """ Format an option group's help text, outdenting the title so it's flush with the "SCons Options" title we print at the top. """ formatter.dedent() result = formatter.format_heading(self.title) formatter.indent() result = result + optparse.OptionContainer.format_help(self, formatter) return result class SConsOptionParser(optparse.OptionParser): preserve_unknown_options = False def error(self, msg): self.print_usage(sys.stderr) sys.stderr.write("SCons error: %s\n" % msg) sys.exit(2) def _process_long_opt(self, rargs, values): """ SCons-specific processing of long options. This is copied directly from the normal optparse._process_long_opt() method, except that, if configured to do so, we catch the exception thrown when an unknown option is encountered and just stick it back on the "leftover" arguments for later (re-)processing. """ arg = rargs.pop(0) # Value explicitly attached to arg? Pretend it's the next # argument. if "=" in arg: (opt, next_arg) = arg.split("=", 1) rargs.insert(0, next_arg) had_explicit_value = True else: opt = arg had_explicit_value = False try: opt = self._match_long_opt(opt) except optparse.BadOptionError: if self.preserve_unknown_options: # SCons-specific: if requested, add unknown options to # the "leftover arguments" list for later processing. self.largs.append(arg) if had_explicit_value: # The unknown option will be re-processed later, # so undo the insertion of the explicit value. rargs.pop(0) return raise option = self._long_opt[opt] if option.takes_value(): nargs = option.nargs if nargs == '?': if had_explicit_value: value = rargs.pop(0) else: value = option.const elif len(rargs) < nargs: if nargs == 1: self.error(_("%s option requires an argument") % opt) else: self.error(_("%s option requires %d arguments") % (opt, nargs)) elif nargs == 1: value = rargs.pop(0) else: value = tuple(rargs[0:nargs]) del rargs[0:nargs] elif had_explicit_value: self.error(_("%s option does not take a value") % opt) else: value = None option.process(opt, value, values, self) def add_local_option(self, *args, **kw): """ Adds a local option to the parser. This is initiated by a SetOption() call to add a user-defined command-line option. We add the option to a separate option group for the local options, creating the group if necessary. """ try: group = self.local_option_group except AttributeError: group = SConsOptionGroup(self, 'Local Options') group = self.add_option_group(group) self.local_option_group = group result = group.add_option(*args, **kw) if result: # The option was added succesfully. We now have to add the # default value to our object that holds the default values # (so that an attempt to fetch the option's attribute will # yield the default value when not overridden) and then # we re-parse the leftover command-line options, so that # any value overridden on the command line is immediately # available if the user turns around and does a GetOption() # right away. setattr(self.values.__defaults__, result.dest, result.default) self.parse_args(self.largs, self.values) return result class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter): def format_usage(self, usage): return "usage: %s\n" % usage def format_heading(self, heading): """ This translates any heading of "options" or "Options" into "SCons Options." Unfortunately, we have to do this here, because those titles are hard-coded in the optparse calls. """ if heading == 'options': # The versions of optparse.py shipped with Pythons 2.3 and # 2.4 pass this in uncapitalized; override that so we get # consistent output on all versions. heading = "Options" if heading == 'Options': heading = "SCons Options" return optparse.IndentedHelpFormatter.format_heading(self, heading) def format_option(self, option): """ A copy of the normal optparse.IndentedHelpFormatter.format_option() method. This has been snarfed so we can modify text wrapping to out liking: -- add our own regular expression that doesn't break on hyphens (so things like --no-print-directory don't get broken); -- wrap the list of options themselves when it's too long (the wrapper.fill(opts) call below); -- set the subsequent_indent when wrapping the help_text. """ # The help for each option consists of two parts: # * the opt strings and metavars # eg. ("-x", or "-fFILENAME, --file=FILENAME") # * the user-supplied help string # eg. ("turn on expert mode", "read data from FILENAME") # # If possible, we write both of these on the same line: # -x turn on expert mode # # But if the opt string list is too long, we put the help # string on a second line, indented to the same column it would # start in if it fit on the first line. # -fFILENAME, --file=FILENAME # read data from FILENAME result = [] try: opts = self.option_strings[option] except AttributeError: # The Python 2.3 version of optparse attaches this to # to the option argument, not to this object. opts = option.option_strings opt_width = self.help_position - self.current_indent - 2 if len(opts) > opt_width: wrapper = textwrap.TextWrapper(width=self.width, initial_indent = ' ', subsequent_indent = ' ') wrapper.wordsep_re = no_hyphen_re opts = wrapper.fill(opts) + '\n' indent_first = self.help_position else: # start help on same line as opts opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) indent_first = 0 result.append(opts) if option.help: try: expand_default = self.expand_default except AttributeError: # The HelpFormatter base class in the Python 2.3 version # of optparse has no expand_default() method. help_text = option.help else: help_text = expand_default(option) # SCons: indent every line of the help text but the first. wrapper = textwrap.TextWrapper(width=self.help_width, subsequent_indent = ' ') wrapper.wordsep_re = no_hyphen_re help_lines = wrapper.wrap(help_text) result.append("%*s%s\n" % (indent_first, "", help_lines[0])) for line in help_lines[1:]: result.append("%*s%s\n" % (self.help_position, "", line)) elif opts[-1] != "\n": result.append("\n") return "".join(result) # For consistent help output across Python versions, we provide a # subclass copy of format_option_strings() and these two variables. # This is necessary (?) for Python2.3, which otherwise concatenates # a short option with its metavar. _short_opt_fmt = "%s %s" _long_opt_fmt = "%s=%s" def format_option_strings(self, option): """Return a comma-separated list of option strings & metavariables.""" if option.takes_value(): metavar = option.metavar or option.dest.upper() short_opts = [] for sopt in option._short_opts: short_opts.append(self._short_opt_fmt % (sopt, metavar)) long_opts = [] for lopt in option._long_opts: long_opts.append(self._long_opt_fmt % (lopt, metavar)) else: short_opts = option._short_opts long_opts = option._long_opts if self.short_first: opts = short_opts + long_opts else: opts = long_opts + short_opts return ", ".join(opts) def Parser(version): """ Returns an options parser object initialized with the standard SCons options. """ formatter = SConsIndentedHelpFormatter(max_help_position=30) op = SConsOptionParser(option_class=SConsOption, add_help_option=False, formatter=formatter, usage="usage: scons [OPTION] [TARGET] ...",) op.preserve_unknown_options = True op.version = version # Add the options to the parser we just created. # # These are in the order we want them to show up in the -H help # text, basically alphabetical. Each op.add_option() call below # should have a consistent format: # # op.add_option("-L", "--long-option-name", # nargs=1, type="string", # dest="long_option_name", default='foo', # action="callback", callback=opt_long_option, # help="help text goes here", # metavar="VAR") # # Even though the optparse module constructs reasonable default # destination names from the long option names, we're going to be # explicit about each one for easier readability and so this code # will at least show up when grepping the source for option attribute # names, or otherwise browsing the source code. # options ignored for compatibility def opt_ignore(option, opt, value, parser): sys.stderr.write("Warning: ignoring %s option\n" % opt) op.add_option("-b", "-d", "-e", "-m", "-S", "-t", "-w", "--environment-overrides", "--no-keep-going", "--no-print-directory", "--print-directory", "--stop", "--touch", action="callback", callback=opt_ignore, help="Ignored for compatibility.") op.add_option('-c', '--clean', '--remove', dest="clean", default=False, action="store_true", help="Remove specified targets and dependencies.") op.add_option('-C', '--directory', nargs=1, type="string", dest="directory", default=[], action="append", help="Change to DIR before doing anything.", metavar="DIR") op.add_option('--cache-debug', nargs=1, dest="cache_debug", default=None, action="store", help="Print CacheDir debug info to FILE.", metavar="FILE") op.add_option('--cache-disable', '--no-cache', dest='cache_disable', default=False, action="store_true", help="Do not retrieve built targets from CacheDir.") op.add_option('--cache-force', '--cache-populate', dest='cache_force', default=False, action="store_true", help="Copy already-built targets into the CacheDir.") op.add_option('--cache-show', dest='cache_show', default=False, action="store_true", help="Print build actions for files from CacheDir.") config_options = ["auto", "force" ,"cache"] def opt_config(option, opt, value, parser, c_options=config_options): if not value in c_options: raise OptionValueError("Warning: %s is not a valid config type" % value) setattr(parser.values, option.dest, value) opt_config_help = "Controls Configure subsystem: %s." \ % ", ".join(config_options) op.add_option('--config', nargs=1, type="string", dest="config", default="auto", action="callback", callback=opt_config, help = opt_config_help, metavar="MODE") op.add_option('-D', dest="climb_up", default=None, action="store_const", const=2, help="Search up directory tree for SConstruct, " "build all Default() targets.") deprecated_debug_options = { "dtree" : '; please use --tree=derived instead', "nomemoizer" : ' and has no effect', "stree" : '; please use --tree=all,status instead', "tree" : '; please use --tree=all instead', } debug_options = ["count", "duplicate", "explain", "findlibs", "includes", "memoizer", "memory", "objects", "pdb", "prepare", "presub", "stacktrace", "time"] + list(deprecated_debug_options.keys()) def opt_debug(option, opt, value, parser, debug_options=debug_options, deprecated_debug_options=deprecated_debug_options): if value in debug_options: parser.values.debug.append(value) if value in deprecated_debug_options.keys(): try: parser.values.delayed_warnings except AttributeError: parser.values.delayed_warnings = [] msg = deprecated_debug_options[value] w = "The --debug=%s option is deprecated%s." % (value, msg) t = (SCons.Warnings.DeprecatedDebugOptionsWarning, w) parser.values.delayed_warnings.append(t) else: raise OptionValueError("Warning: %s is not a valid debug type" % value) opt_debug_help = "Print various types of debugging information: %s." \ % ", ".join(debug_options) op.add_option('--debug', nargs=1, type="string", dest="debug", default=[], action="callback", callback=opt_debug, help=opt_debug_help, metavar="TYPE") def opt_diskcheck(option, opt, value, parser): try: diskcheck_value = diskcheck_convert(value) except ValueError, e: raise OptionValueError("Warning: `%s' is not a valid diskcheck type" % e) setattr(parser.values, option.dest, diskcheck_value) op.add_option('--diskcheck', nargs=1, type="string", dest='diskcheck', default=None, action="callback", callback=opt_diskcheck, help="Enable specific on-disk checks.", metavar="TYPE") def opt_duplicate(option, opt, value, parser): if not value in SCons.Node.FS.Valid_Duplicates: raise OptionValueError("`%s' is not a valid duplication style." % value) setattr(parser.values, option.dest, value) # Set the duplicate style right away so it can affect linking # of SConscript files. SCons.Node.FS.set_duplicate(value) opt_duplicate_help = "Set the preferred duplication methods. Must be one of " \ + ", ".join(SCons.Node.FS.Valid_Duplicates) op.add_option('--duplicate', nargs=1, type="string", dest="duplicate", default='hard-soft-copy', action="callback", callback=opt_duplicate, help=opt_duplicate_help) op.add_option('-f', '--file', '--makefile', '--sconstruct', nargs=1, type="string", dest="file", default=[], action="append", help="Read FILE as the top-level SConstruct file.") op.add_option('-h', '--help', dest="help", default=False, action="store_true", help="Print defined help message, or this one.") op.add_option("-H", "--help-options", action="help", help="Print this message and exit.") op.add_option('-i', '--ignore-errors', dest='ignore_errors', default=False, action="store_true", help="Ignore errors from build actions.") op.add_option('-I', '--include-dir', nargs=1, dest='include_dir', default=[], action="append", help="Search DIR for imported Python modules.", metavar="DIR") op.add_option('--implicit-cache', dest='implicit_cache', default=False, action="store_true", help="Cache implicit dependencies") def opt_implicit_deps(option, opt, value, parser): setattr(parser.values, 'implicit_cache', True) setattr(parser.values, option.dest, True) op.add_option('--implicit-deps-changed', dest="implicit_deps_changed", default=False, action="callback", callback=opt_implicit_deps, help="Ignore cached implicit dependencies.") op.add_option('--implicit-deps-unchanged', dest="implicit_deps_unchanged", default=False, action="callback", callback=opt_implicit_deps, help="Ignore changes in implicit dependencies.") op.add_option('--interact', '--interactive', dest='interactive', default=False, action="store_true", help="Run in interactive mode.") op.add_option('-j', '--jobs', nargs=1, type="int", dest="num_jobs", default=1, action="store", help="Allow N jobs at once.", metavar="N") op.add_option('-k', '--keep-going', dest='keep_going', default=False, action="store_true", help="Keep going when a target can't be made.") op.add_option('--max-drift', nargs=1, type="int", dest='max_drift', default=SCons.Node.FS.default_max_drift, action="store", help="Set maximum system clock drift to N seconds.", metavar="N") op.add_option('--md5-chunksize', nargs=1, type="int", dest='md5_chunksize', default=SCons.Node.FS.File.md5_chunksize, action="store", help="Set chunk-size for MD5 signature computation to N kilobytes.", metavar="N") op.add_option('-n', '--no-exec', '--just-print', '--dry-run', '--recon', dest='no_exec', default=False, action="store_true", help="Don't build; just print commands.") op.add_option('--no-site-dir', dest='no_site_dir', default=False, action="store_true", help="Don't search or use the usual site_scons dir.") op.add_option('--profile', nargs=1, dest="profile_file", default=None, action="store", help="Profile SCons and put results in FILE.", metavar="FILE") op.add_option('-q', '--question', dest="question", default=False, action="store_true", help="Don't build; exit status says if up to date.") op.add_option('-Q', dest='no_progress', default=False, action="store_true", help="Suppress \"Reading/Building\" progress messages.") op.add_option('--random', dest="random", default=False, action="store_true", help="Build dependencies in random order.") op.add_option('-s', '--silent', '--quiet', dest="silent", default=False, action="store_true", help="Don't print commands.") op.add_option('--site-dir', nargs=1, dest='site_dir', default=None, action="store", help="Use DIR instead of the usual site_scons dir.", metavar="DIR") op.add_option('--stack-size', nargs=1, type="int", dest='stack_size', action="store", help="Set the stack size of the threads used to run jobs to N kilobytes.", metavar="N") op.add_option('--taskmastertrace', nargs=1, dest="taskmastertrace_file", default=None, action="store", help="Trace Node evaluation to FILE.", metavar="FILE") tree_options = ["all", "derived", "prune", "status"] def opt_tree(option, opt, value, parser, tree_options=tree_options): import Main tp = Main.TreePrinter() for o in value.split(','): if o == 'all': tp.derived = False elif o == 'derived': tp.derived = True elif o == 'prune': tp.prune = True elif o == 'status': tp.status = True else: raise OptionValueError("Warning: %s is not a valid --tree option" % o) parser.values.tree_printers.append(tp) opt_tree_help = "Print a dependency tree in various formats: %s." \ % ", ".join(tree_options) op.add_option('--tree', nargs=1, type="string", dest="tree_printers", default=[], action="callback", callback=opt_tree, help=opt_tree_help, metavar="OPTIONS") op.add_option('-u', '--up', '--search-up', dest="climb_up", default=0, action="store_const", const=1, help="Search up directory tree for SConstruct, " "build targets at or below current directory.") op.add_option('-U', dest="climb_up", default=0, action="store_const", const=3, help="Search up directory tree for SConstruct, " "build Default() targets from local SConscript.") def opt_version(option, opt, value, parser): sys.stdout.write(parser.version + '\n') sys.exit(0) op.add_option("-v", "--version", action="callback", callback=opt_version, help="Print the SCons version number and exit.") def opt_warn(option, opt, value, parser, tree_options=tree_options): if SCons.Util.is_String(value): value = value.split(',') parser.values.warn.extend(value) op.add_option('--warn', '--warning', nargs=1, type="string", dest="warn", default=[], action="callback", callback=opt_warn, help="Enable or disable warnings.", metavar="WARNING-SPEC") op.add_option('-Y', '--repository', '--srcdir', nargs=1, dest="repository", default=[], action="append", help="Search REPOSITORY for source and target files.") # Options from Make and Cons classic that we do not yet support, # but which we may support someday and whose (potential) meanings # we don't want to change. These all get a "the -X option is not # yet implemented" message and don't show up in the help output. def opt_not_yet(option, opt, value, parser): msg = "Warning: the %s option is not yet implemented\n" % opt sys.stderr.write(msg) op.add_option('-l', '--load-average', '--max-load', nargs=1, type="float", dest="load_average", default=0, action="callback", callback=opt_not_yet, # action="store", # help="Don't start multiple jobs unless load is below " # "LOAD-AVERAGE." help=SUPPRESS_HELP) op.add_option('--list-actions', dest="list_actions", action="callback", callback=opt_not_yet, # help="Don't build; list files and build actions." help=SUPPRESS_HELP) op.add_option('--list-derived', dest="list_derived", action="callback", callback=opt_not_yet, # help="Don't build; list files that would be built." help=SUPPRESS_HELP) op.add_option('--list-where', dest="list_where", action="callback", callback=opt_not_yet, # help="Don't build; list files and where defined." help=SUPPRESS_HELP) op.add_option('-o', '--old-file', '--assume-old', nargs=1, type="string", dest="old_file", default=[], action="callback", callback=opt_not_yet, # action="append", # help = "Consider FILE to be old; don't rebuild it." help=SUPPRESS_HELP) op.add_option('--override', nargs=1, type="string", action="callback", callback=opt_not_yet, dest="override", # help="Override variables as specified in FILE." help=SUPPRESS_HELP) op.add_option('-p', action="callback", callback=opt_not_yet, dest="p", # help="Print internal environments/objects." help=SUPPRESS_HELP) op.add_option('-r', '-R', '--no-builtin-rules', '--no-builtin-variables', action="callback", callback=opt_not_yet, dest="no_builtin_rules", # help="Clear default environments and variables." help=SUPPRESS_HELP) op.add_option('--write-filenames', nargs=1, type="string", dest="write_filenames", action="callback", callback=opt_not_yet, # help="Write all filenames examined into FILE." help=SUPPRESS_HELP) op.add_option('-W', '--new-file', '--assume-new', '--what-if', nargs=1, type="string", dest="new_file", action="callback", callback=opt_not_yet, # help="Consider FILE to be changed." help=SUPPRESS_HELP) op.add_option('--warn-undefined-variables', dest="warn_undefined_variables", action="callback", callback=opt_not_yet, # help="Warn when an undefined variable is referenced." help=SUPPRESS_HELP) return op # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Script This file implements the main() function used by the scons script. Architecturally, this *is* the scons script, and will likely only be called from the external "scons" wrapper. Consequently, anything here should not be, or be considered, part of the build engine. If it's something that we expect other software to want to use, it should go in some other module. If it's specific to the "scons" script invocation, it goes here. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Script/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import time start_time = time.time() import collections import os import sys # Special chicken-and-egg handling of the "--debug=memoizer" flag: # # SCons.Memoize contains a metaclass implementation that affects how # the other classes are instantiated. The Memoizer may add shim methods # to classes that have methods that cache computed values in order to # count and report the hits and misses. # # If we wait to enable the Memoization until after we've parsed the # command line options normally, it will be too late, because the Memoizer # will have already analyzed the classes that it's Memoizing and decided # to not add the shims. So we use a special-case, up-front check for # the "--debug=memoizer" flag and enable Memoizer before we import any # of the other modules that use it. _args = sys.argv + os.environ.get('SCONSFLAGS', '').split() if "--debug=memoizer" in _args: import SCons.Memoize import SCons.Warnings try: SCons.Memoize.EnableMemoization() except SCons.Warnings.Warning: # Some warning was thrown. Arrange for it to be displayed # or not after warnings are configured. import Main exc_type, exc_value, tb = sys.exc_info() Main.delayed_warnings.append((exc_type, exc_value)) del _args import SCons.Action import SCons.Builder import SCons.Environment import SCons.Node.FS import SCons.Options import SCons.Platform import SCons.Scanner import SCons.SConf import SCons.Subst import SCons.Tool import SCons.Util import SCons.Variables import SCons.Defaults import Main main = Main.main # The following are global class definitions and variables that used to # live directly in this module back before 0.96.90, when it contained # a lot of code. Some SConscript files in widely-distributed packages # (Blender is the specific example) actually reached into SCons.Script # directly to use some of these. Rather than break those SConscript # files, we're going to propagate these names into the SCons.Script # namespace here. # # Some of these are commented out because it's *really* unlikely anyone # used them, but we're going to leave the comment here to try to make # it obvious what to do if the situation arises. BuildTask = Main.BuildTask CleanTask = Main.CleanTask QuestionTask = Main.QuestionTask #PrintHelp = Main.PrintHelp #SConscriptSettableOptions = Main.SConscriptSettableOptions AddOption = Main.AddOption GetOption = Main.GetOption SetOption = Main.SetOption Progress = Main.Progress GetBuildFailures = Main.GetBuildFailures #keep_going_on_error = Main.keep_going_on_error #print_dtree = Main.print_dtree #print_explanations = Main.print_explanations #print_includes = Main.print_includes #print_objects = Main.print_objects #print_time = Main.print_time #print_tree = Main.print_tree #memory_stats = Main.memory_stats #ignore_errors = Main.ignore_errors #sconscript_time = Main.sconscript_time #command_time = Main.command_time #exit_status = Main.exit_status #profiling = Main.profiling #repositories = Main.repositories # import SConscript _SConscript = SConscript call_stack = _SConscript.call_stack # Action = SCons.Action.Action AddMethod = SCons.Util.AddMethod AllowSubstExceptions = SCons.Subst.SetAllowableExceptions Builder = SCons.Builder.Builder Configure = _SConscript.Configure Environment = SCons.Environment.Environment #OptParser = SCons.SConsOptions.OptParser FindPathDirs = SCons.Scanner.FindPathDirs Platform = SCons.Platform.Platform Return = _SConscript.Return Scanner = SCons.Scanner.Base Tool = SCons.Tool.Tool WhereIs = SCons.Util.WhereIs # BoolVariable = SCons.Variables.BoolVariable EnumVariable = SCons.Variables.EnumVariable ListVariable = SCons.Variables.ListVariable PackageVariable = SCons.Variables.PackageVariable PathVariable = SCons.Variables.PathVariable # Deprecated names that will go away some day. BoolOption = SCons.Options.BoolOption EnumOption = SCons.Options.EnumOption ListOption = SCons.Options.ListOption PackageOption = SCons.Options.PackageOption PathOption = SCons.Options.PathOption # Action factories. Chmod = SCons.Defaults.Chmod Copy = SCons.Defaults.Copy Delete = SCons.Defaults.Delete Mkdir = SCons.Defaults.Mkdir Move = SCons.Defaults.Move Touch = SCons.Defaults.Touch # Pre-made, public scanners. CScanner = SCons.Tool.CScanner DScanner = SCons.Tool.DScanner DirScanner = SCons.Defaults.DirScanner ProgramScanner = SCons.Tool.ProgramScanner SourceFileScanner = SCons.Tool.SourceFileScanner # Functions we might still convert to Environment methods. CScan = SCons.Defaults.CScan DefaultEnvironment = SCons.Defaults.DefaultEnvironment # Other variables we provide. class TargetList(collections.UserList): def _do_nothing(self, *args, **kw): pass def _add_Default(self, list): self.extend(list) def _clear(self): del self[:] ARGUMENTS = {} ARGLIST = [] BUILD_TARGETS = TargetList() COMMAND_LINE_TARGETS = [] DEFAULT_TARGETS = [] # BUILD_TARGETS can be modified in the SConscript files. If so, we # want to treat the modified BUILD_TARGETS list as if they specified # targets on the command line. To do that, though, we need to know if # BUILD_TARGETS was modified through "official" APIs or by hand. We do # this by updating two lists in parallel, the documented BUILD_TARGETS # list, above, and this internal _build_plus_default targets list which # should only have "official" API changes. Then Script/Main.py can # compare these two afterwards to figure out if the user added their # own targets to BUILD_TARGETS. _build_plus_default = TargetList() def _Add_Arguments(alist): for arg in alist: a, b = arg.split('=', 1) ARGUMENTS[a] = b ARGLIST.append((a, b)) def _Add_Targets(tlist): if tlist: COMMAND_LINE_TARGETS.extend(tlist) BUILD_TARGETS.extend(tlist) BUILD_TARGETS._add_Default = BUILD_TARGETS._do_nothing BUILD_TARGETS._clear = BUILD_TARGETS._do_nothing _build_plus_default.extend(tlist) _build_plus_default._add_Default = _build_plus_default._do_nothing _build_plus_default._clear = _build_plus_default._do_nothing def _Set_Default_Targets_Has_Been_Called(d, fs): return DEFAULT_TARGETS def _Set_Default_Targets_Has_Not_Been_Called(d, fs): if d is None: d = [fs.Dir('.')] return d _Get_Default_Targets = _Set_Default_Targets_Has_Not_Been_Called def _Set_Default_Targets(env, tlist): global DEFAULT_TARGETS global _Get_Default_Targets _Get_Default_Targets = _Set_Default_Targets_Has_Been_Called for t in tlist: if t is None: # Delete the elements from the list in-place, don't # reassign an empty list to DEFAULT_TARGETS, so that the # variables will still point to the same object we point to. del DEFAULT_TARGETS[:] BUILD_TARGETS._clear() _build_plus_default._clear() elif isinstance(t, SCons.Node.Node): DEFAULT_TARGETS.append(t) BUILD_TARGETS._add_Default([t]) _build_plus_default._add_Default([t]) else: nodes = env.arg2nodes(t, env.fs.Entry) DEFAULT_TARGETS.extend(nodes) BUILD_TARGETS._add_Default(nodes) _build_plus_default._add_Default(nodes) # help_text = None def HelpFunction(text): global help_text if SCons.Script.help_text is None: SCons.Script.help_text = text else: help_text = help_text + text # # Will be non-zero if we are reading an SConscript file. sconscript_reading = 0 # def Variables(files=[], args=ARGUMENTS): return SCons.Variables.Variables(files, args) def Options(files=[], args=ARGUMENTS): return SCons.Options.Options(files, args) # The list of global functions to add to the SConscript name space # that end up calling corresponding methods or Builders in the # DefaultEnvironment(). GlobalDefaultEnvironmentFunctions = [ # Methods from the SConsEnvironment class, above. 'Default', 'EnsurePythonVersion', 'EnsureSConsVersion', 'Exit', 'Export', 'GetLaunchDir', 'Help', 'Import', #'SConscript', is handled separately, below. 'SConscriptChdir', # Methods from the Environment.Base class. 'AddPostAction', 'AddPreAction', 'Alias', 'AlwaysBuild', 'BuildDir', 'CacheDir', 'Clean', #The Command() method is handled separately, below. 'Decider', 'Depends', 'Dir', 'NoClean', 'NoCache', 'Entry', 'Execute', 'File', 'FindFile', 'FindInstalledFiles', 'FindSourceFiles', 'Flatten', 'GetBuildPath', 'Glob', 'Ignore', 'Install', 'InstallAs', 'Literal', 'Local', 'ParseDepends', 'Precious', 'Repository', 'Requires', 'SConsignFile', 'SideEffect', 'SourceCode', 'SourceSignatures', 'Split', 'Tag', 'TargetSignatures', 'Value', 'VariantDir', ] GlobalDefaultBuilders = [ # Supported builders. 'CFile', 'CXXFile', 'DVI', 'Jar', 'Java', 'JavaH', 'Library', 'M4', 'MSVSProject', 'Object', 'PCH', 'PDF', 'PostScript', 'Program', 'RES', 'RMIC', 'SharedLibrary', 'SharedObject', 'StaticLibrary', 'StaticObject', 'Tar', 'TypeLibrary', 'Zip', 'Package', ] for name in GlobalDefaultEnvironmentFunctions + GlobalDefaultBuilders: exec "%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name)) del name # There are a handful of variables that used to live in the # Script/SConscript.py module that some SConscript files out there were # accessing directly as SCons.Script.SConscript.*. The problem is that # "SConscript" in this namespace is no longer a module, it's a global # function call--or more precisely, an object that implements a global # function call through the default Environment. Nevertheless, we can # maintain backwards compatibility for SConscripts that were reaching in # this way by hanging some attributes off the "SConscript" object here. SConscript = _SConscript.DefaultEnvironmentCall('SConscript') # Make SConscript look enough like the module it used to be so # that pychecker doesn't barf. SConscript.__name__ = 'SConscript' SConscript.Arguments = ARGUMENTS SConscript.ArgList = ARGLIST SConscript.BuildTargets = BUILD_TARGETS SConscript.CommandLineTargets = COMMAND_LINE_TARGETS SConscript.DefaultTargets = DEFAULT_TARGETS # The global Command() function must be handled differently than the # global functions for other construction environment methods because # we want people to be able to use Actions that must expand $TARGET # and $SOURCE later, when (and if) the Action is invoked to build # the target(s). We do this with the subst=1 argument, which creates # a DefaultEnvironmentCall instance that wraps up a normal default # construction environment that performs variable substitution, not a # proxy that doesn't. # # There's a flaw here, though, because any other $-variables on a command # line will *also* be expanded, each to a null string, but that should # only be a problem in the unusual case where someone was passing a '$' # on a command line and *expected* the $ to get through to the shell # because they were calling Command() and not env.Command()... This is # unlikely enough that we're going to leave this as is and cross that # bridge if someone actually comes to it. Command = _SConscript.DefaultEnvironmentCall('Command', subst=1) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Options/ListOption.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Options module hierarchy This is for backwards compatibility. The new equivalent is the Variables/ class hierarchy. These will have deprecation warnings added (some day), and will then be removed entirely (some day). """ import SCons.Variables import SCons.Warnings warned = False def ListOption(*args, **kw): global warned if not warned: msg = "The ListOption() function is deprecated; use the ListVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True return SCons.Variables.ListVariable(*args, **kw) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Options/BoolOption.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Options module hierarchy This is for backwards compatibility. The new equivalent is the Variables/ class hierarchy. These will have deprecation warnings added (some day), and will then be removed entirely (some day). """ import SCons.Variables import SCons.Warnings warned = False def BoolOption(*args, **kw): global warned if not warned: msg = "The BoolOption() function is deprecated; use the BoolVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True return SCons.Variables.BoolVariable(*args, **kw) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Options/PathOption.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Options module hierarchy This is for backwards compatibility. The new equivalent is the Variables/ class hierarchy. These will have deprecation warnings added (some day), and will then be removed entirely (some day). """ import SCons.Variables import SCons.Warnings warned = False class _PathOptionClass(object): def warn(self): global warned if not warned: msg = "The PathOption() function is deprecated; use the PathVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True def __call__(self, *args, **kw): self.warn() return SCons.Variables.PathVariable(*args, **kw) def PathAccept(self, *args, **kw): self.warn() return SCons.Variables.PathVariable.PathAccept(*args, **kw) def PathIsDir(self, *args, **kw): self.warn() return SCons.Variables.PathVariable.PathIsDir(*args, **kw) def PathIsDirCreate(self, *args, **kw): self.warn() return SCons.Variables.PathVariable.PathIsDirCreate(*args, **kw) def PathIsFile(self, *args, **kw): self.warn() return SCons.Variables.PathVariable.PathIsFile(*args, **kw) def PathExists(self, *args, **kw): self.warn() return SCons.Variables.PathVariable.PathExists(*args, **kw) PathOption = _PathOptionClass() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Options/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Options module hierarchy This is for backwards compatibility. The new equivalent is the Variables/ class hierarchy. These will have deprecation warnings added (some day), and will then be removed entirely (some day). """ import SCons.Variables import SCons.Warnings from BoolOption import BoolOption # okay from EnumOption import EnumOption # okay from ListOption import ListOption # naja from PackageOption import PackageOption # naja from PathOption import PathOption # okay warned = False class Options(SCons.Variables.Variables): def __init__(self, *args, **kw): global warned if not warned: msg = "The Options class is deprecated; use the Variables class instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True SCons.Variables.Variables.__init__(self, *args, **kw) def AddOptions(self, *args, **kw): return SCons.Variables.Variables.AddVariables(self, *args, **kw) def UnknownOptions(self, *args, **kw): return SCons.Variables.Variables.UnknownVariables(self, *args, **kw) def FormatOptionHelpText(self, *args, **kw): return SCons.Variables.Variables.FormatVariableHelpText(self, *args, **kw) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Options/EnumOption.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Options module hierarchy This is for backwards compatibility. The new equivalent is the Variables/ class hierarchy. These will have deprecation warnings added (some day), and will then be removed entirely (some day). """ import SCons.Variables import SCons.Warnings warned = False def EnumOption(*args, **kw): global warned if not warned: msg = "The EnumOption() function is deprecated; use the EnumVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True return SCons.Variables.EnumVariable(*args, **kw) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Options/PackageOption.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Options module hierarchy This is for backwards compatibility. The new equivalent is the Variables/ class hierarchy. These will have deprecation warnings added (some day), and will then be removed entirely (some day). """ import SCons.Variables import SCons.Warnings warned = False def PackageOption(*args, **kw): global warned if not warned: msg = "The PackageOption() function is deprecated; use the PackageVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True return SCons.Variables.PackageVariable(*args, **kw) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. # """SCons.Warnings This file implements the warnings framework for SCons. """ __revision__ = "src/engine/SCons/Warnings.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import sys import SCons.Errors class Warning(SCons.Errors.UserError): pass class WarningOnByDefault(Warning): pass # NOTE: If you add a new warning class, add it to the man page, too! class CacheWriteErrorWarning(Warning): pass class CorruptSConsignWarning(WarningOnByDefault): pass class DependencyWarning(Warning): pass class DuplicateEnvironmentWarning(WarningOnByDefault): pass class FutureReservedVariableWarning(WarningOnByDefault): pass class LinkWarning(WarningOnByDefault): pass class MisleadingKeywordsWarning(WarningOnByDefault): pass class MissingSConscriptWarning(WarningOnByDefault): pass class NoMD5ModuleWarning(WarningOnByDefault): pass class NoMetaclassSupportWarning(WarningOnByDefault): pass class NoObjectCountWarning(WarningOnByDefault): pass class NoParallelSupportWarning(WarningOnByDefault): pass class ReservedVariableWarning(WarningOnByDefault): pass class StackSizeWarning(WarningOnByDefault): pass class VisualCMissingWarning(WarningOnByDefault): pass # Used when MSVC_VERSION and MSVS_VERSION do not point to the # same version (MSVS_VERSION is deprecated) class VisualVersionMismatch(WarningOnByDefault): pass class VisualStudioMissingWarning(Warning): pass class FortranCxxMixWarning(LinkWarning): pass # Deprecation warnings class FutureDeprecatedWarning(Warning): pass class DeprecatedWarning(Warning): pass class MandatoryDeprecatedWarning(DeprecatedWarning): pass # Special case; base always stays DeprecatedWarning class PythonVersionWarning(DeprecatedWarning): pass class DeprecatedSourceCodeWarning(FutureDeprecatedWarning): pass class DeprecatedBuildDirWarning(DeprecatedWarning): pass class TaskmasterNeedsExecuteWarning(DeprecatedWarning): pass class DeprecatedCopyWarning(MandatoryDeprecatedWarning): pass class DeprecatedOptionsWarning(MandatoryDeprecatedWarning): pass class DeprecatedSourceSignaturesWarning(MandatoryDeprecatedWarning): pass class DeprecatedTargetSignaturesWarning(MandatoryDeprecatedWarning): pass class DeprecatedDebugOptionsWarning(MandatoryDeprecatedWarning): pass class DeprecatedSigModuleWarning(MandatoryDeprecatedWarning): pass class DeprecatedBuilderKeywordsWarning(MandatoryDeprecatedWarning): pass # The below is a list of 2-tuples. The first element is a class object. # The second element is true if that class is enabled, false if it is disabled. _enabled = [] # If set, raise the warning as an exception _warningAsException = 0 # If not None, a function to call with the warning _warningOut = None def suppressWarningClass(clazz): """Suppresses all warnings that are of type clazz or derived from clazz.""" _enabled.insert(0, (clazz, 0)) def enableWarningClass(clazz): """Enables all warnings that are of type clazz or derived from clazz.""" _enabled.insert(0, (clazz, 1)) def warningAsException(flag=1): """Turn warnings into exceptions. Returns the old value of the flag.""" global _warningAsException old = _warningAsException _warningAsException = flag return old def warn(clazz, *args): global _enabled, _warningAsException, _warningOut warning = clazz(args) for clazz, flag in _enabled: if isinstance(warning, clazz): if flag: if _warningAsException: raise warning if _warningOut: _warningOut(warning) break def process_warn_strings(arguments): """Process string specifications of enabling/disabling warnings, as passed to the --warn option or the SetOption('warn') function. An argument to this option should be of the form <warning-class> or no-<warning-class>. The warning class is munged in order to get an actual class name from the classes above, which we need to pass to the {enable,disable}WarningClass() functions. The supplied <warning-class> is split on hyphens, each element is capitalized, then smushed back together. Then the string "Warning" is appended to get the class name. For example, 'deprecated' will enable the DeprecatedWarning class. 'no-dependency' will disable the DependencyWarning class. As a special case, --warn=all and --warn=no-all will enable or disable (respectively) the base Warning class of all warnings. """ def _capitalize(s): if s[:5] == "scons": return "SCons" + s[5:] else: return s.capitalize() for arg in arguments: elems = arg.lower().split('-') enable = 1 if elems[0] == 'no': enable = 0 del elems[0] if len(elems) == 1 and elems[0] == 'all': class_name = "Warning" else: class_name = ''.join(map(_capitalize, elems)) + "Warning" try: clazz = globals()[class_name] except KeyError: sys.stderr.write("No warning type: '%s'\n" % arg) else: if enable: enableWarningClass(clazz) elif issubclass(clazz, MandatoryDeprecatedWarning): fmt = "Can not disable mandataory warning: '%s'\n" sys.stderr.write(fmt % arg) else: suppressWarningClass(clazz) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# dblite.py module contributed by Ralf W. Grosse-Kunstleve. # Extended for Unicode by Steven Knight. import SCons.compat import builtins import os # compat layer imports "cPickle" for us if it's available. import pickle import shutil import time keep_all_files = 00000 ignore_corrupt_dbfiles = 0 def corruption_warning(filename): print "Warning: Discarding corrupt database:", filename try: unicode except NameError: def is_string(s): return isinstance(s, str) else: def is_string(s): return type(s) in (str, unicode) try: unicode('a') except NameError: def unicode(s): return s dblite_suffix = '.dblite' tmp_suffix = '.tmp' class dblite(object): # Squirrel away references to the functions in various modules # that we'll use when our __del__() method calls our sync() method # during shutdown. We might get destroyed when Python is in the midst # of tearing down the different modules we import in an essentially # arbitrary order, and some of the various modules's global attributes # may already be wiped out from under us. # # See the discussion at: # http://mail.python.org/pipermail/python-bugs-list/2003-March/016877.html _open = builtins.open _pickle_dump = staticmethod(pickle.dump) _os_chmod = os.chmod try: _os_chown = os.chown except AttributeError: _os_chown = None _os_rename = os.rename _os_unlink = os.unlink _shutil_copyfile = shutil.copyfile _time_time = time.time def __init__(self, file_base_name, flag, mode): assert flag in (None, "r", "w", "c", "n") if (flag is None): flag = "r" base, ext = os.path.splitext(file_base_name) if ext == dblite_suffix: # There's already a suffix on the file name, don't add one. self._file_name = file_base_name self._tmp_name = base + tmp_suffix else: self._file_name = file_base_name + dblite_suffix self._tmp_name = file_base_name + tmp_suffix self._flag = flag self._mode = mode self._dict = {} self._needs_sync = 00000 if self._os_chown is not None and (os.geteuid()==0 or os.getuid()==0): # running as root; chown back to current owner/group when done try: statinfo = os.stat(self._file_name) self._chown_to = statinfo.st_uid self._chgrp_to = statinfo.st_gid except OSError, e: # db file doesn't exist yet. # Check os.environ for SUDO_UID, use if set self._chown_to = int(os.environ.get('SUDO_UID', -1)) self._chgrp_to = int(os.environ.get('SUDO_GID', -1)) else: self._chown_to = -1 # don't chown self._chgrp_to = -1 # don't chgrp if (self._flag == "n"): self._open(self._file_name, "wb", self._mode) else: try: f = self._open(self._file_name, "rb") except IOError, e: if (self._flag != "c"): raise e self._open(self._file_name, "wb", self._mode) else: p = f.read() if (len(p) > 0): try: self._dict = pickle.loads(p) except (pickle.UnpicklingError, EOFError): if (ignore_corrupt_dbfiles == 0): raise if (ignore_corrupt_dbfiles == 1): corruption_warning(self._file_name) def close(self): if (self._needs_sync): self.sync() def __del__(self): self.close() def sync(self): self._check_writable() f = self._open(self._tmp_name, "wb", self._mode) self._pickle_dump(self._dict, f, 1) f.close() # Windows doesn't allow renaming if the file exists, so unlink # it first, chmod'ing it to make sure we can do so. On UNIX, we # may not be able to chmod the file if it's owned by someone else # (e.g. from a previous run as root). We should still be able to # unlink() the file if the directory's writable, though, so ignore # any OSError exception thrown by the chmod() call. try: self._os_chmod(self._file_name, 0777) except OSError: pass self._os_unlink(self._file_name) self._os_rename(self._tmp_name, self._file_name) if self._os_chown is not None and self._chown_to > 0: # don't chown to root or -1 try: self._os_chown(self._file_name, self._chown_to, self._chgrp_to) except OSError: pass self._needs_sync = 00000 if (keep_all_files): self._shutil_copyfile( self._file_name, self._file_name + "_" + str(int(self._time_time()))) def _check_writable(self): if (self._flag == "r"): raise IOError("Read-only database: %s" % self._file_name) def __getitem__(self, key): return self._dict[key] def __setitem__(self, key, value): self._check_writable() if (not is_string(key)): raise TypeError("key `%s' must be a string but is %s" % (key, type(key))) if (not is_string(value)): raise TypeError("value `%s' must be a string but is %s" % (value, type(value))) self._dict[key] = value self._needs_sync = 0001 def keys(self): return list(self._dict.keys()) def has_key(self, key): return key in self._dict def __contains__(self, key): return key in self._dict def iterkeys(self): # Wrapping name in () prevents fixer from "fixing" this return (self._dict.iterkeys)() __iter__ = iterkeys def __len__(self): return len(self._dict) def open(file, flag=None, mode=0666): return dblite(file, flag, mode) def _exercise(): db = open("tmp", "n") assert len(db) == 0 db["foo"] = "bar" assert db["foo"] == "bar" db[unicode("ufoo")] = unicode("ubar") assert db[unicode("ufoo")] == unicode("ubar") db.sync() db = open("tmp", "c") assert len(db) == 2, len(db) assert db["foo"] == "bar" db["bar"] = "foo" assert db["bar"] == "foo" db[unicode("ubar")] = unicode("ufoo") assert db[unicode("ubar")] == unicode("ufoo") db.sync() db = open("tmp", "r") assert len(db) == 4, len(db) assert db["foo"] == "bar" assert db["bar"] == "foo" assert db[unicode("ufoo")] == unicode("ubar") assert db[unicode("ubar")] == unicode("ufoo") try: db.sync() except IOError, e: assert str(e) == "Read-only database: tmp.dblite" else: raise RuntimeError("IOError expected.") db = open("tmp", "w") assert len(db) == 4 db["ping"] = "pong" db.sync() try: db[(1,2)] = "tuple" except TypeError, e: assert str(e) == "key `(1, 2)' must be a string but is <type 'tuple'>", str(e) else: raise RuntimeError("TypeError exception expected") try: db["list"] = [1,2] except TypeError, e: assert str(e) == "value `[1, 2]' must be a string but is <type 'list'>", str(e) else: raise RuntimeError("TypeError exception expected") db = open("tmp", "r") assert len(db) == 5 db = open("tmp", "n") assert len(db) == 0 dblite._open("tmp.dblite", "w") db = open("tmp", "r") dblite._open("tmp.dblite", "w").write("x") try: db = open("tmp", "r") except pickle.UnpicklingError: pass else: raise RuntimeError("pickle exception expected.") global ignore_corrupt_dbfiles ignore_corrupt_dbfiles = 2 db = open("tmp", "r") assert len(db) == 0 os.unlink("tmp.dblite") try: db = open("tmp", "w") except IOError, e: assert str(e) == "[Errno 2] No such file or directory: 'tmp.dblite'", str(e) else: raise RuntimeError("IOError expected.") print "OK" if (__name__ == "__main__"): _exercise() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.exitfuncs Register functions which are executed when SCons exits for any reason. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/exitfuncs.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" _exithandlers = [] def _run_exitfuncs(): """run any registered exit functions _exithandlers is traversed in reverse order so functions are executed last in, first out. """ while _exithandlers: func, targs, kargs = _exithandlers.pop() func(*targs, **kargs) def register(func, *targs, **kargs): """register a function to be executed upon normal program termination func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func """ _exithandlers.append((func, targs, kargs)) import sys try: x = sys.exitfunc # if x isn't our own exit func executive, assume it's another # registered exit function - append it to our list... if x != _run_exitfuncs: register(x) except AttributeError: pass # make our exit function get run by python when it exits: sys.exitfunc = _run_exitfuncs del sys # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Executor A module for executing actions with specific lists of target and source Nodes. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Executor.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import collections from SCons.Debug import logInstanceCreation import SCons.Errors import SCons.Memoize class Batch(object): """Remembers exact association between targets and sources of executor.""" def __init__(self, targets=[], sources=[]): self.targets = targets self.sources = sources class TSList(collections.UserList): """A class that implements $TARGETS or $SOURCES expansions by wrapping an executor Method. This class is used in the Executor.lvars() to delay creation of NodeList objects until they're needed. Note that we subclass collections.UserList purely so that the is_Sequence() function will identify an object of this class as a list during variable expansion. We're not really using any collections.UserList methods in practice. """ def __init__(self, func): self.func = func def __getattr__(self, attr): nl = self.func() return getattr(nl, attr) def __getitem__(self, i): nl = self.func() return nl[i] def __getslice__(self, i, j): nl = self.func() i = max(i, 0); j = max(j, 0) return nl[i:j] def __str__(self): nl = self.func() return str(nl) def __repr__(self): nl = self.func() return repr(nl) class TSObject(object): """A class that implements $TARGET or $SOURCE expansions by wrapping an Executor method. """ def __init__(self, func): self.func = func def __getattr__(self, attr): n = self.func() return getattr(n, attr) def __str__(self): n = self.func() if n: return str(n) return '' def __repr__(self): n = self.func() if n: return repr(n) return '' def rfile(node): """ A function to return the results of a Node's rfile() method, if it exists, and the Node itself otherwise (if it's a Value Node, e.g.). """ try: rfile = node.rfile except AttributeError: return node else: return rfile() class Executor(object): """A class for controlling instances of executing an action. This largely exists to hold a single association of an action, environment, list of environment override dictionaries, targets and sources for later processing as needed. """ if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass memoizer_counters = [] def __init__(self, action, env=None, overridelist=[{}], targets=[], sources=[], builder_kw={}): if __debug__: logInstanceCreation(self, 'Executor.Executor') self.set_action_list(action) self.pre_actions = [] self.post_actions = [] self.env = env self.overridelist = overridelist if targets or sources: self.batches = [Batch(targets[:], sources[:])] else: self.batches = [] self.builder_kw = builder_kw self._memo = {} def get_lvars(self): try: return self.lvars except AttributeError: self.lvars = { 'CHANGED_SOURCES' : TSList(self._get_changed_sources), 'CHANGED_TARGETS' : TSList(self._get_changed_targets), 'SOURCE' : TSObject(self._get_source), 'SOURCES' : TSList(self._get_sources), 'TARGET' : TSObject(self._get_target), 'TARGETS' : TSList(self._get_targets), 'UNCHANGED_SOURCES' : TSList(self._get_unchanged_sources), 'UNCHANGED_TARGETS' : TSList(self._get_unchanged_targets), } return self.lvars def _get_changes(self): cs = [] ct = [] us = [] ut = [] for b in self.batches: if b.targets[0].is_up_to_date(): us.extend(list(map(rfile, b.sources))) ut.extend(b.targets) else: cs.extend(list(map(rfile, b.sources))) ct.extend(b.targets) self._changed_sources_list = SCons.Util.NodeList(cs) self._changed_targets_list = SCons.Util.NodeList(ct) self._unchanged_sources_list = SCons.Util.NodeList(us) self._unchanged_targets_list = SCons.Util.NodeList(ut) def _get_changed_sources(self, *args, **kw): try: return self._changed_sources_list except AttributeError: self._get_changes() return self._changed_sources_list def _get_changed_targets(self, *args, **kw): try: return self._changed_targets_list except AttributeError: self._get_changes() return self._changed_targets_list def _get_source(self, *args, **kw): #return SCons.Util.NodeList([rfile(self.batches[0].sources[0]).get_subst_proxy()]) return rfile(self.batches[0].sources[0]).get_subst_proxy() def _get_sources(self, *args, **kw): return SCons.Util.NodeList([rfile(n).get_subst_proxy() for n in self.get_all_sources()]) def _get_target(self, *args, **kw): #return SCons.Util.NodeList([self.batches[0].targets[0].get_subst_proxy()]) return self.batches[0].targets[0].get_subst_proxy() def _get_targets(self, *args, **kw): return SCons.Util.NodeList([n.get_subst_proxy() for n in self.get_all_targets()]) def _get_unchanged_sources(self, *args, **kw): try: return self._unchanged_sources_list except AttributeError: self._get_changes() return self._unchanged_sources_list def _get_unchanged_targets(self, *args, **kw): try: return self._unchanged_targets_list except AttributeError: self._get_changes() return self._unchanged_targets_list def get_action_targets(self): if not self.action_list: return [] targets_string = self.action_list[0].get_targets(self.env, self) if targets_string[0] == '$': targets_string = targets_string[1:] return self.get_lvars()[targets_string] def set_action_list(self, action): import SCons.Util if not SCons.Util.is_List(action): if not action: import SCons.Errors raise SCons.Errors.UserError("Executor must have an action.") action = [action] self.action_list = action def get_action_list(self): return self.pre_actions + self.action_list + self.post_actions def get_all_targets(self): """Returns all targets for all batches of this Executor.""" result = [] for batch in self.batches: result.extend(batch.targets) return result def get_all_sources(self): """Returns all sources for all batches of this Executor.""" result = [] for batch in self.batches: result.extend(batch.sources) return result def get_all_children(self): """Returns all unique children (dependencies) for all batches of this Executor. The Taskmaster can recognize when it's already evaluated a Node, so we don't have to make this list unique for its intended canonical use case, but we expect there to be a lot of redundancy (long lists of batched .cc files #including the same .h files over and over), so removing the duplicates once up front should save the Taskmaster a lot of work. """ result = SCons.Util.UniqueList([]) for target in self.get_all_targets(): result.extend(target.children()) return result def get_all_prerequisites(self): """Returns all unique (order-only) prerequisites for all batches of this Executor. """ result = SCons.Util.UniqueList([]) for target in self.get_all_targets(): result.extend(target.prerequisites) return result def get_action_side_effects(self): """Returns all side effects for all batches of this Executor used by the underlying Action. """ result = SCons.Util.UniqueList([]) for target in self.get_action_targets(): result.extend(target.side_effects) return result memoizer_counters.append(SCons.Memoize.CountValue('get_build_env')) def get_build_env(self): """Fetch or create the appropriate build Environment for this Executor. """ try: return self._memo['get_build_env'] except KeyError: pass # Create the build environment instance with appropriate # overrides. These get evaluated against the current # environment's construction variables so that users can # add to existing values by referencing the variable in # the expansion. overrides = {} for odict in self.overridelist: overrides.update(odict) import SCons.Defaults env = self.env or SCons.Defaults.DefaultEnvironment() build_env = env.Override(overrides) self._memo['get_build_env'] = build_env return build_env def get_build_scanner_path(self, scanner): """Fetch the scanner path for this executor's targets and sources. """ env = self.get_build_env() try: cwd = self.batches[0].targets[0].cwd except (IndexError, AttributeError): cwd = None return scanner.path(env, cwd, self.get_all_targets(), self.get_all_sources()) def get_kw(self, kw={}): result = self.builder_kw.copy() result.update(kw) result['executor'] = self return result def do_nothing(self, target, kw): return 0 def do_execute(self, target, kw): """Actually execute the action list.""" env = self.get_build_env() kw = self.get_kw(kw) status = 0 for act in self.get_action_list(): #args = (self.get_all_targets(), self.get_all_sources(), env) args = ([], [], env) status = act(*args, **kw) if isinstance(status, SCons.Errors.BuildError): status.executor = self raise status elif status: msg = "Error %s" % status raise SCons.Errors.BuildError( errstr=msg, node=self.batches[0].targets, executor=self, action=act) return status # use extra indirection because with new-style objects (Python 2.2 # and above) we can't override special methods, and nullify() needs # to be able to do this. def __call__(self, target, **kw): return self.do_execute(target, kw) def cleanup(self): self._memo = {} def add_sources(self, sources): """Add source files to this Executor's list. This is necessary for "multi" Builders that can be called repeatedly to build up a source file list for a given target.""" # TODO(batch): extend to multiple batches assert (len(self.batches) == 1) # TODO(batch): remove duplicates? sources = [x for x in sources if x not in self.batches[0].sources] self.batches[0].sources.extend(sources) def get_sources(self): return self.batches[0].sources def add_batch(self, targets, sources): """Add pair of associated target and source to this Executor's list. This is necessary for "batch" Builders that can be called repeatedly to build up a list of matching target and source files that will be used in order to update multiple target files at once from multiple corresponding source files, for tools like MSVC that support it.""" self.batches.append(Batch(targets, sources)) def prepare(self): """ Preparatory checks for whether this Executor can go ahead and (try to) build its targets. """ for s in self.get_all_sources(): if s.missing(): msg = "Source `%s' not found, needed by target `%s'." raise SCons.Errors.StopError(msg % (s, self.batches[0].targets[0])) def add_pre_action(self, action): self.pre_actions.append(action) def add_post_action(self, action): self.post_actions.append(action) # another extra indirection for new-style objects and nullify... def my_str(self): env = self.get_build_env() return "\n".join([action.genstring(self.get_all_targets(), self.get_all_sources(), env) for action in self.get_action_list()]) def __str__(self): return self.my_str() def nullify(self): self.cleanup() self.do_execute = self.do_nothing self.my_str = lambda: '' memoizer_counters.append(SCons.Memoize.CountValue('get_contents')) def get_contents(self): """Fetch the signature contents. This is the main reason this class exists, so we can compute this once and cache it regardless of how many target or source Nodes there are. """ try: return self._memo['get_contents'] except KeyError: pass env = self.get_build_env() result = "".join([action.get_contents(self.get_all_targets(), self.get_all_sources(), env) for action in self.get_action_list()]) self._memo['get_contents'] = result return result def get_timestamp(self): """Fetch a time stamp for this Executor. We don't have one, of course (only files do), but this is the interface used by the timestamp module. """ return 0 def scan_targets(self, scanner): # TODO(batch): scan by batches self.scan(scanner, self.get_all_targets()) def scan_sources(self, scanner): # TODO(batch): scan by batches if self.batches[0].sources: self.scan(scanner, self.get_all_sources()) def scan(self, scanner, node_list): """Scan a list of this Executor's files (targets or sources) for implicit dependencies and update all of the targets with them. This essentially short-circuits an N*M scan of the sources for each individual target, which is a hell of a lot more efficient. """ env = self.get_build_env() # TODO(batch): scan by batches) deps = [] if scanner: for node in node_list: node.disambiguate() s = scanner.select(node) if not s: continue path = self.get_build_scanner_path(s) deps.extend(node.get_implicit_deps(env, s, path)) else: kw = self.get_kw() for node in node_list: node.disambiguate() scanner = node.get_env_scanner(env, kw) if not scanner: continue scanner = scanner.select(node) if not scanner: continue path = self.get_build_scanner_path(scanner) deps.extend(node.get_implicit_deps(env, scanner, path)) deps.extend(self.get_implicit_deps()) for tgt in self.get_all_targets(): tgt.add_to_implicit(deps) def _get_unignored_sources_key(self, node, ignore=()): return (node,) + tuple(ignore) memoizer_counters.append(SCons.Memoize.CountDict('get_unignored_sources', _get_unignored_sources_key)) def get_unignored_sources(self, node, ignore=()): key = (node,) + tuple(ignore) try: memo_dict = self._memo['get_unignored_sources'] except KeyError: memo_dict = {} self._memo['get_unignored_sources'] = memo_dict else: try: return memo_dict[key] except KeyError: pass if node: # TODO: better way to do this (it's a linear search, # but it may not be critical path)? sourcelist = [] for b in self.batches: if node in b.targets: sourcelist = b.sources break else: sourcelist = self.get_all_sources() if ignore: idict = {} for i in ignore: idict[i] = 1 sourcelist = [s for s in sourcelist if s not in idict] memo_dict[key] = sourcelist return sourcelist def get_implicit_deps(self): """Return the executor's implicit dependencies, i.e. the nodes of the commands to be executed.""" result = [] build_env = self.get_build_env() for act in self.get_action_list(): deps = act.get_implicit_deps(self.get_all_targets(), self.get_all_sources(), build_env) result.extend(deps) return result _batch_executors = {} def GetBatchExecutor(key): return _batch_executors[key] def AddBatchExecutor(key, executor): assert key not in _batch_executors _batch_executors[key] = executor nullenv = None def get_NullEnvironment(): """Use singleton pattern for Null Environments.""" global nullenv import SCons.Util class NullEnvironment(SCons.Util.Null): import SCons.CacheDir _CacheDir_path = None _CacheDir = SCons.CacheDir.CacheDir(None) def get_CacheDir(self): return self._CacheDir if not nullenv: nullenv = NullEnvironment() return nullenv class Null(object): """A null Executor, with a null build Environment, that does nothing when the rest of the methods call it. This might be able to disapper when we refactor things to disassociate Builders from Nodes entirely, so we're not going to worry about unit tests for this--at least for now. """ def __init__(self, *args, **kw): if __debug__: logInstanceCreation(self, 'Executor.Null') self.batches = [Batch(kw['targets'][:], [])] def get_build_env(self): return get_NullEnvironment() def get_build_scanner_path(self): return None def cleanup(self): pass def prepare(self): pass def get_unignored_sources(self, *args, **kw): return tuple(()) def get_action_targets(self): return [] def get_action_list(self): return [] def get_all_targets(self): return self.batches[0].targets def get_all_sources(self): return self.batches[0].targets[0].sources def get_all_children(self): return self.batches[0].targets[0].children() def get_all_prerequisites(self): return [] def get_action_side_effects(self): return [] def __call__(self, *args, **kw): return 0 def get_contents(self): return '' def _morph(self): """Morph this Null executor to a real Executor object.""" batches = self.batches self.__class__ = Executor self.__init__([]) self.batches = batches # The following methods require morphing this Null Executor to a # real Executor object. def add_pre_action(self, action): self._morph() self.add_pre_action(action) def add_post_action(self, action): self._morph() self.add_post_action(action) def set_action_list(self, action): self._morph() self.set_action_list(action) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Action This encapsulates information about executing any sort of action that can build one or more target Nodes (typically files) from one or more source Nodes (also typically files) given a specific Environment. The base class here is ActionBase. The base class supplies just a few OO utility methods and some generic methods for displaying information about an Action in response to the various commands that control printing. A second-level base class is _ActionAction. This extends ActionBase by providing the methods that can be used to show and perform an action. True Action objects will subclass _ActionAction; Action factory class objects will subclass ActionBase. The heavy lifting is handled by subclasses for the different types of actions we might execute: CommandAction CommandGeneratorAction FunctionAction ListAction The subclasses supply the following public interface methods used by other modules: __call__() THE public interface, "calling" an Action object executes the command or Python function. This also takes care of printing a pre-substitution command for debugging purposes. get_contents() Fetches the "contents" of an Action for signature calculation plus the varlist. This is what gets MD5 checksummed to decide if a target needs to be rebuilt because its action changed. genstring() Returns a string representation of the Action *without* command substitution, but allows a CommandGeneratorAction to generate the right action based on the specified target, source and env. This is used by the Signature subsystem (through the Executor) to obtain an (imprecise) representation of the Action operation for informative purposes. Subclasses also supply the following methods for internal use within this module: __str__() Returns a string approximation of the Action; no variable substitution is performed. execute() The internal method that really, truly, actually handles the execution of a command or Python function. This is used so that the __call__() methods can take care of displaying any pre-substitution representations, and *then* execute an action without worrying about the specific Actions involved. get_presig() Fetches the "contents" of a subclass for signature calculation. The varlist is added to this to produce the Action's contents. strfunction() Returns a substituted string representation of the Action. This is used by the _ActionAction.show() command to display the command/function that will be executed to generate the target(s). There is a related independent ActionCaller class that looks like a regular Action, and which serves as a wrapper for arbitrary functions that we want to let the user specify the arguments to now, but actually execute later (when an out-of-date check determines that it's needed to be executed, for example). Objects of this class are returned by an ActionFactory class that provides a __call__() method as a convenient way for wrapping up the functions. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Action.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import dis import os # compat layer imports "cPickle" for us if it's available. import pickle import re import sys import subprocess from SCons.Debug import logInstanceCreation import SCons.Errors import SCons.Executor import SCons.Util import SCons.Subst # we use these a lot, so try to optimize them is_String = SCons.Util.is_String is_List = SCons.Util.is_List class _null(object): pass print_actions = 1 execute_actions = 1 print_actions_presub = 0 def rfile(n): try: return n.rfile() except AttributeError: return n def default_exitstatfunc(s): return s try: SET_LINENO = dis.SET_LINENO HAVE_ARGUMENT = dis.HAVE_ARGUMENT except AttributeError: remove_set_lineno_codes = lambda x: x else: def remove_set_lineno_codes(code): result = [] n = len(code) i = 0 while i < n: c = code[i] op = ord(c) if op >= HAVE_ARGUMENT: if op != SET_LINENO: result.append(code[i:i+3]) i = i+3 else: result.append(c) i = i+1 return ''.join(result) strip_quotes = re.compile('^[\'"](.*)[\'"]$') def _callable_contents(obj): """Return the signature contents of a callable Python object. """ try: # Test if obj is a method. return _function_contents(obj.im_func) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.im_func) except AttributeError: try: # Test if obj is a code object. return _code_contents(obj) except AttributeError: # Test if obj is a function object. return _function_contents(obj) def _object_contents(obj): """Return the signature contents of any Python object. We have to handle the case where object contains a code object since it can be pickled directly. """ try: # Test if obj is a method. return _function_contents(obj.im_func) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.im_func) except AttributeError: try: # Test if obj is a code object. return _code_contents(obj) except AttributeError: try: # Test if obj is a function object. return _function_contents(obj) except AttributeError: # Should be a pickable Python object. try: return pickle.dumps(obj) except (pickle.PicklingError, TypeError): # This is weird, but it seems that nested classes # are unpickable. The Python docs say it should # always be a PicklingError, but some Python # versions seem to return TypeError. Just do # the best we can. return str(obj) def _code_contents(code): """Return the signature contents of a code object. By providing direct access to the code object of the function, Python makes this extremely easy. Hooray! Unfortunately, older versions of Python include line number indications in the compiled byte code. Boo! So we remove the line number byte codes to prevent recompilations from moving a Python function. """ contents = [] # The code contents depends on the number of local variables # but not their actual names. contents.append("%s,%s" % (code.co_argcount, len(code.co_varnames))) try: contents.append(",%s,%s" % (len(code.co_cellvars), len(code.co_freevars))) except AttributeError: # Older versions of Python do not support closures. contents.append(",0,0") # The code contents depends on any constants accessed by the # function. Note that we have to call _object_contents on each # constants because the code object of nested functions can # show-up among the constants. # # Note that we also always ignore the first entry of co_consts # which contains the function doc string. We assume that the # function does not access its doc string. contents.append(',(' + ','.join(map(_object_contents,code.co_consts[1:])) + ')') # The code contents depends on the variable names used to # accessed global variable, as changing the variable name changes # the variable actually accessed and therefore changes the # function result. contents.append(',(' + ','.join(map(_object_contents,code.co_names)) + ')') # The code contents depends on its actual code!!! contents.append(',(' + str(remove_set_lineno_codes(code.co_code)) + ')') return ''.join(contents) def _function_contents(func): """Return the signature contents of a function.""" contents = [_code_contents(func.func_code)] # The function contents depends on the value of defaults arguments if func.func_defaults: contents.append(',(' + ','.join(map(_object_contents,func.func_defaults)) + ')') else: contents.append(',()') # The function contents depends on the closure captured cell values. try: closure = func.func_closure or [] except AttributeError: # Older versions of Python do not support closures. closure = [] #xxx = [_object_contents(x.cell_contents) for x in closure] try: xxx = [_object_contents(x.cell_contents) for x in closure] except AttributeError: xxx = [] contents.append(',(' + ','.join(xxx) + ')') return ''.join(contents) def _actionAppend(act1, act2): # This function knows how to slap two actions together. # Mainly, it handles ListActions by concatenating into # a single ListAction. a1 = Action(act1) a2 = Action(act2) if a1 is None: return a2 if a2 is None: return a1 if isinstance(a1, ListAction): if isinstance(a2, ListAction): return ListAction(a1.list + a2.list) else: return ListAction(a1.list + [ a2 ]) else: if isinstance(a2, ListAction): return ListAction([ a1 ] + a2.list) else: return ListAction([ a1, a2 ]) def _do_create_keywords(args, kw): """This converts any arguments after the action argument into their equivalent keywords and adds them to the kw argument. """ v = kw.get('varlist', ()) # prevent varlist="FOO" from being interpreted as ['F', 'O', 'O'] if is_String(v): v = (v,) kw['varlist'] = tuple(v) if args: # turn positional args into equivalent keywords cmdstrfunc = args[0] if cmdstrfunc is None or is_String(cmdstrfunc): kw['cmdstr'] = cmdstrfunc elif callable(cmdstrfunc): kw['strfunction'] = cmdstrfunc else: raise SCons.Errors.UserError( 'Invalid command display variable type. ' 'You must either pass a string or a callback which ' 'accepts (target, source, env) as parameters.') if len(args) > 1: kw['varlist'] = args[1:] + kw['varlist'] if kw.get('strfunction', _null) is not _null \ and kw.get('cmdstr', _null) is not _null: raise SCons.Errors.UserError( 'Cannot have both strfunction and cmdstr args to Action()') def _do_create_action(act, kw): """This is the actual "implementation" for the Action factory method, below. This handles the fact that passing lists to Action() itself has different semantics than passing lists as elements of lists. The former will create a ListAction, the latter will create a CommandAction by converting the inner list elements to strings.""" if isinstance(act, ActionBase): return act if is_List(act): return CommandAction(act, **kw) if callable(act): try: gen = kw['generator'] del kw['generator'] except KeyError: gen = 0 if gen: action_type = CommandGeneratorAction else: action_type = FunctionAction return action_type(act, kw) if is_String(act): var=SCons.Util.get_environment_var(act) if var: # This looks like a string that is purely an Environment # variable reference, like "$FOO" or "${FOO}". We do # something special here...we lazily evaluate the contents # of that Environment variable, so a user could put something # like a function or a CommandGenerator in that variable # instead of a string. return LazyAction(var, kw) commands = str(act).split('\n') if len(commands) == 1: return CommandAction(commands[0], **kw) # The list of string commands may include a LazyAction, so we # reprocess them via _do_create_list_action. return _do_create_list_action(commands, kw) # Catch a common error case with a nice message: if isinstance(act, int) or isinstance(act, float): raise TypeError("Don't know how to create an Action from a number (%s)"%act) # Else fail silently (???) return None def _do_create_list_action(act, kw): """A factory for list actions. Convert the input list into Actions and then wrap them in a ListAction.""" acts = [] for a in act: aa = _do_create_action(a, kw) if aa is not None: acts.append(aa) if not acts: return ListAction([]) elif len(acts) == 1: return acts[0] else: return ListAction(acts) def Action(act, *args, **kw): """A factory for action objects.""" # Really simple: the _do_create_* routines do the heavy lifting. _do_create_keywords(args, kw) if is_List(act): return _do_create_list_action(act, kw) return _do_create_action(act, kw) class ActionBase(object): """Base class for all types of action objects that can be held by other objects (Builders, Executors, etc.) This provides the common methods for manipulating and combining those actions.""" def __cmp__(self, other): return cmp(self.__dict__, other) def no_batch_key(self, env, target, source): return None batch_key = no_batch_key def genstring(self, target, source, env): return str(self) def get_contents(self, target, source, env): result = [ self.get_presig(target, source, env) ] # This should never happen, as the Action() factory should wrap # the varlist, but just in case an action is created directly, # we duplicate this check here. vl = self.get_varlist(target, source, env) if is_String(vl): vl = (vl,) for v in vl: result.append(env.subst('${'+v+'}')) return ''.join(result) def __add__(self, other): return _actionAppend(self, other) def __radd__(self, other): return _actionAppend(other, self) def presub_lines(self, env): # CommandGeneratorAction needs a real environment # in order to return the proper string here, since # it may call LazyAction, which looks up a key # in that env. So we temporarily remember the env here, # and CommandGeneratorAction will use this env # when it calls its _generate method. self.presub_env = env lines = str(self).split('\n') self.presub_env = None # don't need this any more return lines def get_varlist(self, target, source, env, executor=None): return self.varlist def get_targets(self, env, executor): """ Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action. """ return self.targets class _ActionAction(ActionBase): """Base class for actions that create output objects.""" def __init__(self, cmdstr=_null, strfunction=_null, varlist=(), presub=_null, chdir=None, exitstatfunc=None, batch_key=None, targets='$TARGETS', **kw): self.cmdstr = cmdstr if strfunction is not _null: if strfunction is None: self.cmdstr = None else: self.strfunction = strfunction self.varlist = varlist self.presub = presub self.chdir = chdir if not exitstatfunc: exitstatfunc = default_exitstatfunc self.exitstatfunc = exitstatfunc self.targets = targets if batch_key: if not callable(batch_key): # They have set batch_key, but not to their own # callable. The default behavior here will batch # *all* targets+sources using this action, separated # for each construction environment. def default_batch_key(self, env, target, source): return (id(self), id(env)) batch_key = default_batch_key SCons.Util.AddMethod(self, batch_key, 'batch_key') def print_cmd_line(self, s, target, source, env): # In python 3, and in some of our tests, sys.stdout is # a String io object, and it takes unicode strings only # In other cases it's a regular Python 2.x file object # which takes strings (bytes), and if you pass those a # unicode object they try to decode with 'ascii' codec # which fails if the cmd line has any hi-bit-set chars. # This code assumes s is a regular string, but should # work if it's unicode too. try: sys.stdout.write(unicode(s + "\n")) except UnicodeDecodeError: sys.stdout.write(s + "\n") def __call__(self, target, source, env, exitstatfunc=_null, presub=_null, show=_null, execute=_null, chdir=_null, executor=None): if not is_List(target): target = [target] if not is_List(source): source = [source] if presub is _null: presub = self.presub if presub is _null: presub = print_actions_presub if exitstatfunc is _null: exitstatfunc = self.exitstatfunc if show is _null: show = print_actions if execute is _null: execute = execute_actions if chdir is _null: chdir = self.chdir save_cwd = None if chdir: save_cwd = os.getcwd() try: chdir = str(chdir.abspath) except AttributeError: if not is_String(chdir): if executor: chdir = str(executor.batches[0].targets[0].dir) else: chdir = str(target[0].dir) if presub: if executor: target = executor.get_all_targets() source = executor.get_all_sources() t = ' and '.join(map(str, target)) l = '\n '.join(self.presub_lines(env)) out = u"Building %s with action:\n %s\n" % (t, l) sys.stdout.write(out) cmd = None if show and self.strfunction: if executor: target = executor.get_all_targets() source = executor.get_all_sources() try: cmd = self.strfunction(target, source, env, executor) except TypeError: cmd = self.strfunction(target, source, env) if cmd: if chdir: cmd = ('os.chdir(%s)\n' % repr(chdir)) + cmd try: get = env.get except AttributeError: print_func = self.print_cmd_line else: print_func = get('PRINT_CMD_LINE_FUNC') if not print_func: print_func = self.print_cmd_line print_func(cmd, target, source, env) stat = 0 if execute: if chdir: os.chdir(chdir) try: stat = self.execute(target, source, env, executor=executor) if isinstance(stat, SCons.Errors.BuildError): s = exitstatfunc(stat.status) if s: stat.status = s else: stat = s else: stat = exitstatfunc(stat) finally: if save_cwd: os.chdir(save_cwd) if cmd and save_cwd: print_func('os.chdir(%s)' % repr(save_cwd), target, source, env) return stat def _string_from_cmd_list(cmd_list): """Takes a list of command line arguments and returns a pretty representation for printing.""" cl = [] for arg in map(str, cmd_list): if ' ' in arg or '\t' in arg: arg = '"' + arg + '"' cl.append(arg) return ' '.join(cl) # A fiddlin' little function that has an 'import SCons.Environment' which # can't be moved to the top level without creating an import loop. Since # this import creates a local variable named 'SCons', it blocks access to # the global variable, so we move it here to prevent complaints about local # variables being used uninitialized. default_ENV = None def get_default_ENV(env): global default_ENV try: return env['ENV'] except KeyError: if not default_ENV: import SCons.Environment # This is a hideously expensive way to get a default shell # environment. What it really should do is run the platform # setup to get the default ENV. Fortunately, it's incredibly # rare for an Environment not to have a shell environment, so # we're not going to worry about it overmuch. default_ENV = SCons.Environment.Environment()['ENV'] return default_ENV # This function is still in draft mode. We're going to need something like # it in the long run as more and more places use subprocess, but I'm sure # it'll have to be tweaked to get the full desired functionality. # one special arg (so far?), 'error', to tell what to do with exceptions. def _subproc(scons_env, cmd, error = 'ignore', **kw): """Do common setup for a subprocess.Popen() call""" # allow std{in,out,err} to be "'devnull'" io = kw.get('stdin') if is_String(io) and io == 'devnull': kw['stdin'] = open(os.devnull) io = kw.get('stdout') if is_String(io) and io == 'devnull': kw['stdout'] = open(os.devnull, 'w') io = kw.get('stderr') if is_String(io) and io == 'devnull': kw['stderr'] = open(os.devnull, 'w') # Figure out what shell environment to use ENV = kw.get('env', None) if ENV is None: ENV = get_default_ENV(scons_env) # Ensure that the ENV values are all strings: new_env = {} for key, value in ENV.items(): if is_List(value): # If the value is a list, then we assume it is a path list, # because that's a pretty common list-like value to stick # in an environment variable: value = SCons.Util.flatten_sequence(value) new_env[key] = os.pathsep.join(map(str, value)) else: # It's either a string or something else. If it's a string, # we still want to call str() because it might be a *Unicode* # string, which makes subprocess.Popen() gag. If it isn't a # string or a list, then we just coerce it to a string, which # is the proper way to handle Dir and File instances and will # produce something reasonable for just about everything else: new_env[key] = str(value) kw['env'] = new_env try: return subprocess.Popen(cmd, **kw) except EnvironmentError, e: if error == 'raise': raise # return a dummy Popen instance that only returns error class dummyPopen(object): def __init__(self, e): self.exception = e def communicate(self): return ('','') def wait(self): return -self.exception.errno stdin = None class f(object): def read(self): return '' def readline(self): return '' stdout = stderr = f() return dummyPopen(e) class CommandAction(_ActionAction): """Class for command-execution actions.""" def __init__(self, cmd, **kw): # Cmd can actually be a list or a single item; if it's a # single item it should be the command string to execute; if a # list then it should be the words of the command string to # execute. Only a single command should be executed by this # object; lists of commands should be handled by embedding # these objects in a ListAction object (which the Action() # factory above does). cmd will be passed to # Environment.subst_list() for substituting environment # variables. if __debug__: logInstanceCreation(self, 'Action.CommandAction') _ActionAction.__init__(self, **kw) if is_List(cmd): if list(filter(is_List, cmd)): raise TypeError("CommandAction should be given only " \ "a single command") self.cmd_list = cmd def __str__(self): if is_List(self.cmd_list): return ' '.join(map(str, self.cmd_list)) return str(self.cmd_list) def process(self, target, source, env, executor=None): if executor: result = env.subst_list(self.cmd_list, 0, executor=executor) else: result = env.subst_list(self.cmd_list, 0, target, source) silent = None ignore = None while True: try: c = result[0][0][0] except IndexError: c = None if c == '@': silent = 1 elif c == '-': ignore = 1 else: break result[0][0] = result[0][0][1:] try: if not result[0][0]: result[0] = result[0][1:] except IndexError: pass return result, ignore, silent def strfunction(self, target, source, env, executor=None): if self.cmdstr is None: return None if self.cmdstr is not _null: from SCons.Subst import SUBST_RAW if executor: c = env.subst(self.cmdstr, SUBST_RAW, executor=executor) else: c = env.subst(self.cmdstr, SUBST_RAW, target, source) if c: return c cmd_list, ignore, silent = self.process(target, source, env, executor) if silent: return '' return _string_from_cmd_list(cmd_list[0]) def execute(self, target, source, env, executor=None): """Execute a command action. This will handle lists of commands as well as individual commands, because construction variable substitution may turn a single "command" into a list. This means that this class can actually handle lists of commands, even though that's not how we use it externally. """ escape_list = SCons.Subst.escape_list flatten_sequence = SCons.Util.flatten_sequence try: shell = env['SHELL'] except KeyError: raise SCons.Errors.UserError('Missing SHELL construction variable.') try: spawn = env['SPAWN'] except KeyError: raise SCons.Errors.UserError('Missing SPAWN construction variable.') else: if is_String(spawn): spawn = env.subst(spawn, raw=1, conv=lambda x: x) escape = env.get('ESCAPE', lambda x: x) ENV = get_default_ENV(env) # Ensure that the ENV values are all strings: for key, value in ENV.items(): if not is_String(value): if is_List(value): # If the value is a list, then we assume it is a # path list, because that's a pretty common list-like # value to stick in an environment variable: value = flatten_sequence(value) ENV[key] = os.pathsep.join(map(str, value)) else: # If it isn't a string or a list, then we just coerce # it to a string, which is the proper way to handle # Dir and File instances and will produce something # reasonable for just about everything else: ENV[key] = str(value) if executor: target = executor.get_all_targets() source = executor.get_all_sources() cmd_list, ignore, silent = self.process(target, list(map(rfile, source)), env, executor) # Use len() to filter out any "command" that's zero-length. for cmd_line in filter(len, cmd_list): # Escape the command line for the interpreter we are using. cmd_line = escape_list(cmd_line, escape) result = spawn(shell, escape, cmd_line[0], cmd_line, ENV) if not ignore and result: msg = "Error %s" % result return SCons.Errors.BuildError(errstr=msg, status=result, action=self, command=cmd_line) return 0 def get_presig(self, target, source, env, executor=None): """Return the signature contents of this action's command line. This strips $(-$) and everything in between the string, since those parts don't affect signatures. """ from SCons.Subst import SUBST_SIG cmd = self.cmd_list if is_List(cmd): cmd = ' '.join(map(str, cmd)) else: cmd = str(cmd) if executor: return env.subst_target_source(cmd, SUBST_SIG, executor=executor) else: return env.subst_target_source(cmd, SUBST_SIG, target, source) def get_implicit_deps(self, target, source, env, executor=None): icd = env.get('IMPLICIT_COMMAND_DEPENDENCIES', True) if is_String(icd) and icd[:1] == '$': icd = env.subst(icd) if not icd or icd in ('0', 'None'): return [] from SCons.Subst import SUBST_SIG if executor: cmd_list = env.subst_list(self.cmd_list, SUBST_SIG, executor=executor) else: cmd_list = env.subst_list(self.cmd_list, SUBST_SIG, target, source) res = [] for cmd_line in cmd_list: if cmd_line: d = str(cmd_line[0]) m = strip_quotes.match(d) if m: d = m.group(1) d = env.WhereIs(d) if d: res.append(env.fs.File(d)) return res class CommandGeneratorAction(ActionBase): """Class for command-generator actions.""" def __init__(self, generator, kw): if __debug__: logInstanceCreation(self, 'Action.CommandGeneratorAction') self.generator = generator self.gen_kw = kw self.varlist = kw.get('varlist', ()) self.targets = kw.get('targets', '$TARGETS') def _generate(self, target, source, env, for_signature, executor=None): # ensure that target is a list, to make it easier to write # generator functions: if not is_List(target): target = [target] if executor: target = executor.get_all_targets() source = executor.get_all_sources() ret = self.generator(target=target, source=source, env=env, for_signature=for_signature) gen_cmd = Action(ret, **self.gen_kw) if not gen_cmd: raise SCons.Errors.UserError("Object returned from command generator: %s cannot be used to create an Action." % repr(ret)) return gen_cmd def __str__(self): try: env = self.presub_env except AttributeError: env = None if env is None: env = SCons.Defaults.DefaultEnvironment() act = self._generate([], [], env, 1) return str(act) def batch_key(self, env, target, source): return self._generate(target, source, env, 1).batch_key(env, target, source) def genstring(self, target, source, env, executor=None): return self._generate(target, source, env, 1, executor).genstring(target, source, env) def __call__(self, target, source, env, exitstatfunc=_null, presub=_null, show=_null, execute=_null, chdir=_null, executor=None): act = self._generate(target, source, env, 0, executor) if act is None: raise SCons.Errors.UserError("While building `%s': " "Cannot deduce file extension from source files: %s" % (repr(list(map(str, target))), repr(list(map(str, source))))) return act(target, source, env, exitstatfunc, presub, show, execute, chdir, executor) def get_presig(self, target, source, env, executor=None): """Return the signature contents of this action's command line. This strips $(-$) and everything in between the string, since those parts don't affect signatures. """ return self._generate(target, source, env, 1, executor).get_presig(target, source, env) def get_implicit_deps(self, target, source, env, executor=None): return self._generate(target, source, env, 1, executor).get_implicit_deps(target, source, env) def get_varlist(self, target, source, env, executor=None): return self._generate(target, source, env, 1, executor).get_varlist(target, source, env, executor) def get_targets(self, env, executor): return self._generate(None, None, env, 1, executor).get_targets(env, executor) # A LazyAction is a kind of hybrid generator and command action for # strings of the form "$VAR". These strings normally expand to other # strings (think "$CCCOM" to "$CC -c -o $TARGET $SOURCE"), but we also # want to be able to replace them with functions in the construction # environment. Consequently, we want lazy evaluation and creation of # an Action in the case of the function, but that's overkill in the more # normal case of expansion to other strings. # # So we do this with a subclass that's both a generator *and* # a command action. The overridden methods all do a quick check # of the construction variable, and if it's a string we just call # the corresponding CommandAction method to do the heavy lifting. # If not, then we call the same-named CommandGeneratorAction method. # The CommandGeneratorAction methods work by using the overridden # _generate() method, that is, our own way of handling "generation" of # an action based on what's in the construction variable. class LazyAction(CommandGeneratorAction, CommandAction): def __init__(self, var, kw): if __debug__: logInstanceCreation(self, 'Action.LazyAction') #FUTURE CommandAction.__init__(self, '${'+var+'}', **kw) CommandAction.__init__(self, '${'+var+'}', **kw) self.var = SCons.Util.to_String(var) self.gen_kw = kw def get_parent_class(self, env): c = env.get(self.var) if is_String(c) and not '\n' in c: return CommandAction return CommandGeneratorAction def _generate_cache(self, env): if env: c = env.get(self.var, '') else: c = '' gen_cmd = Action(c, **self.gen_kw) if not gen_cmd: raise SCons.Errors.UserError("$%s value %s cannot be used to create an Action." % (self.var, repr(c))) return gen_cmd def _generate(self, target, source, env, for_signature, executor=None): return self._generate_cache(env) def __call__(self, target, source, env, *args, **kw): c = self.get_parent_class(env) return c.__call__(self, target, source, env, *args, **kw) def get_presig(self, target, source, env): c = self.get_parent_class(env) return c.get_presig(self, target, source, env) def get_varlist(self, target, source, env, executor=None): c = self.get_parent_class(env) return c.get_varlist(self, target, source, env, executor) class FunctionAction(_ActionAction): """Class for Python function actions.""" def __init__(self, execfunction, kw): if __debug__: logInstanceCreation(self, 'Action.FunctionAction') self.execfunction = execfunction try: self.funccontents = _callable_contents(execfunction) except AttributeError: try: # See if execfunction will do the heavy lifting for us. self.gc = execfunction.get_contents except AttributeError: # This is weird, just do the best we can. self.funccontents = _object_contents(execfunction) _ActionAction.__init__(self, **kw) def function_name(self): try: return self.execfunction.__name__ except AttributeError: try: return self.execfunction.__class__.__name__ except AttributeError: return "unknown_python_function" def strfunction(self, target, source, env, executor=None): if self.cmdstr is None: return None if self.cmdstr is not _null: from SCons.Subst import SUBST_RAW if executor: c = env.subst(self.cmdstr, SUBST_RAW, executor=executor) else: c = env.subst(self.cmdstr, SUBST_RAW, target, source) if c: return c def array(a): def quote(s): try: str_for_display = s.str_for_display except AttributeError: s = repr(s) else: s = str_for_display() return s return '[' + ", ".join(map(quote, a)) + ']' try: strfunc = self.execfunction.strfunction except AttributeError: pass else: if strfunc is None: return None if callable(strfunc): return strfunc(target, source, env) name = self.function_name() tstr = array(target) sstr = array(source) return "%s(%s, %s)" % (name, tstr, sstr) def __str__(self): name = self.function_name() if name == 'ActionCaller': return str(self.execfunction) return "%s(target, source, env)" % name def execute(self, target, source, env, executor=None): exc_info = (None,None,None) try: if executor: target = executor.get_all_targets() source = executor.get_all_sources() rsources = list(map(rfile, source)) try: result = self.execfunction(target=target, source=rsources, env=env) except KeyboardInterrupt, e: raise except SystemExit, e: raise except Exception, e: result = e exc_info = sys.exc_info() if result: result = SCons.Errors.convert_to_BuildError(result, exc_info) result.node=target result.action=self try: result.command=self.strfunction(target, source, env, executor) except TypeError: result.command=self.strfunction(target, source, env) # FIXME: This maintains backward compatibility with respect to # which type of exceptions were returned by raising an # exception and which ones were returned by value. It would # probably be best to always return them by value here, but # some codes do not check the return value of Actions and I do # not have the time to modify them at this point. if (exc_info[1] and not isinstance(exc_info[1],EnvironmentError)): raise result return result finally: # Break the cycle between the traceback object and this # function stack frame. See the sys.exc_info() doc info for # more information about this issue. del exc_info def get_presig(self, target, source, env): """Return the signature contents of this callable action.""" try: return self.gc(target, source, env) except AttributeError: return self.funccontents def get_implicit_deps(self, target, source, env): return [] class ListAction(ActionBase): """Class for lists of other actions.""" def __init__(self, actionlist): if __debug__: logInstanceCreation(self, 'Action.ListAction') def list_of_actions(x): if isinstance(x, ActionBase): return x return Action(x) self.list = list(map(list_of_actions, actionlist)) # our children will have had any varlist # applied; we don't need to do it again self.varlist = () self.targets = '$TARGETS' def genstring(self, target, source, env): return '\n'.join([a.genstring(target, source, env) for a in self.list]) def __str__(self): return '\n'.join(map(str, self.list)) def presub_lines(self, env): return SCons.Util.flatten_sequence( [a.presub_lines(env) for a in self.list]) def get_presig(self, target, source, env): """Return the signature contents of this action list. Simple concatenation of the signatures of the elements. """ return "".join([x.get_contents(target, source, env) for x in self.list]) def __call__(self, target, source, env, exitstatfunc=_null, presub=_null, show=_null, execute=_null, chdir=_null, executor=None): if executor: target = executor.get_all_targets() source = executor.get_all_sources() for act in self.list: stat = act(target, source, env, exitstatfunc, presub, show, execute, chdir, executor) if stat: return stat return 0 def get_implicit_deps(self, target, source, env): result = [] for act in self.list: result.extend(act.get_implicit_deps(target, source, env)) return result def get_varlist(self, target, source, env, executor=None): result = SCons.Util.OrderedDict() for act in self.list: for var in act.get_varlist(target, source, env, executor): result[var] = True return list(result.keys()) class ActionCaller(object): """A class for delaying calling an Action function with specific (positional and keyword) arguments until the Action is actually executed. This class looks to the rest of the world like a normal Action object, but what it's really doing is hanging on to the arguments until we have a target, source and env to use for the expansion. """ def __init__(self, parent, args, kw): self.parent = parent self.args = args self.kw = kw def get_contents(self, target, source, env): actfunc = self.parent.actfunc try: # "self.actfunc" is a function. contents = str(actfunc.func_code.co_code) except AttributeError: # "self.actfunc" is a callable object. try: contents = str(actfunc.__call__.im_func.func_code.co_code) except AttributeError: # No __call__() method, so it might be a builtin # or something like that. Do the best we can. contents = str(actfunc) contents = remove_set_lineno_codes(contents) return contents def subst(self, s, target, source, env): # If s is a list, recursively apply subst() # to every element in the list if is_List(s): result = [] for elem in s: result.append(self.subst(elem, target, source, env)) return self.parent.convert(result) # Special-case hack: Let a custom function wrapped in an # ActionCaller get at the environment through which the action # was called by using this hard-coded value as a special return. if s == '$__env__': return env elif is_String(s): return env.subst(s, 1, target, source) return self.parent.convert(s) def subst_args(self, target, source, env): return [self.subst(x, target, source, env) for x in self.args] def subst_kw(self, target, source, env): kw = {} for key in self.kw.keys(): kw[key] = self.subst(self.kw[key], target, source, env) return kw def __call__(self, target, source, env, executor=None): args = self.subst_args(target, source, env) kw = self.subst_kw(target, source, env) return self.parent.actfunc(*args, **kw) def strfunction(self, target, source, env): args = self.subst_args(target, source, env) kw = self.subst_kw(target, source, env) return self.parent.strfunc(*args, **kw) def __str__(self): return self.parent.strfunc(*self.args, **self.kw) class ActionFactory(object): """A factory class that will wrap up an arbitrary function as an SCons-executable Action object. The real heavy lifting here is done by the ActionCaller class. We just collect the (positional and keyword) arguments that we're called with and give them to the ActionCaller object we create, so it can hang onto them until it needs them. """ def __init__(self, actfunc, strfunc, convert=lambda x: x): self.actfunc = actfunc self.strfunc = strfunc self.convert = convert def __call__(self, *args, **kw): ac = ActionCaller(self, args, kw) action = Action(ac, strfunction=ac.strfunction) return action # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Variables.BoolVariable This file defines the option type for SCons implementing true/false values. Usage example: opts = Variables() opts.Add(BoolVariable('embedded', 'build for an embedded system', 0)) ... if env['embedded'] == 1: ... """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Variables/BoolVariable.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __all__ = ['BoolVariable',] import SCons.Errors __true_strings = ('y', 'yes', 'true', 't', '1', 'on' , 'all' ) __false_strings = ('n', 'no', 'false', 'f', '0', 'off', 'none') def _text2bool(val): """ Converts strings to True/False depending on the 'truth' expressed by the string. If the string can't be converted, the original value will be returned. See '__true_strings' and '__false_strings' for values considered 'true' or 'false respectivly. This is usable as 'converter' for SCons' Variables. """ lval = val.lower() if lval in __true_strings: return True if lval in __false_strings: return False raise ValueError("Invalid value for boolean option: %s" % val) def _validator(key, val, env): """ Validates the given value to be either '0' or '1'. This is usable as 'validator' for SCons' Variables. """ if not env[key] in (True, False): raise SCons.Errors.UserError( 'Invalid value for boolean option %s: %s' % (key, env[key])) def BoolVariable(key, help, default): """ The input parameters describe a boolen option, thus they are returned with the correct converter and validator appended. The 'help' text will by appended by '(yes|no) to show the valid valued. The result is usable for input to opts.Add(). """ return (key, '%s (yes|no)' % help, default, _validator, _text2bool) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Variables.PackageVariable This file defines the option type for SCons implementing 'package activation'. To be used whenever a 'package' may be enabled/disabled and the package path may be specified. Usage example: Examples: x11=no (disables X11 support) x11=yes (will search for the package installation dir) x11=/usr/local/X11 (will check this path for existance) To replace autoconf's --with-xxx=yyy opts = Variables() opts.Add(PackageVariable('x11', 'use X11 installed here (yes = search some places', 'yes')) ... if env['x11'] == True: dir = ... search X11 in some standard places ... env['x11'] = dir if env['x11']: ... build with x11 ... """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Variables/PackageVariable.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __all__ = ['PackageVariable',] import SCons.Errors __enable_strings = ('1', 'yes', 'true', 'on', 'enable', 'search') __disable_strings = ('0', 'no', 'false', 'off', 'disable') def _converter(val): """ """ lval = val.lower() if lval in __enable_strings: return True if lval in __disable_strings: return False #raise ValueError("Invalid value for boolean option: %s" % val) return val def _validator(key, val, env, searchfunc): # NB: searchfunc is currenty undocumented and unsupported """ """ # todo: write validator, check for path import os if env[key] is True: if searchfunc: env[key] = searchfunc(key, val) elif env[key] and not os.path.exists(val): raise SCons.Errors.UserError( 'Path does not exist for option %s: %s' % (key, val)) def PackageVariable(key, help, default, searchfunc=None): # NB: searchfunc is currenty undocumented and unsupported """ The input parameters describe a 'package list' option, thus they are returned with the correct converter and validator appended. The result is usable for input to opts.Add() . A 'package list' option may either be 'all', 'none' or a list of package names (seperated by space). """ help = '\n '.join( (help, '( yes | no | /path/to/%s )' % key)) return (key, help, default, lambda k, v, e: _validator(k,v,e,searchfunc), _converter) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Variables.EnumVariable This file defines the option type for SCons allowing only specified input-values. Usage example: opts = Variables() opts.Add(EnumVariable('debug', 'debug output and symbols', 'no', allowed_values=('yes', 'no', 'full'), map={}, ignorecase=2)) ... if env['debug'] == 'full': ... """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Variables/EnumVariable.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __all__ = ['EnumVariable',] import SCons.Errors def _validator(key, val, env, vals): if not val in vals: raise SCons.Errors.UserError( 'Invalid value for option %s: %s. Valid values are: %s' % (key, val, vals)) def EnumVariable(key, help, default, allowed_values, map={}, ignorecase=0): """ The input parameters describe a option with only certain values allowed. They are returned with an appropriate converter and validator appended. The result is usable for input to Variables.Add(). 'key' and 'default' are the values to be passed on to Variables.Add(). 'help' will be appended by the allowed values automatically 'allowed_values' is a list of strings, which are allowed as values for this option. The 'map'-dictionary may be used for converting the input value into canonical values (eg. for aliases). 'ignorecase' defines the behaviour of the validator: If ignorecase == 0, the validator/converter are case-sensitive. If ignorecase == 1, the validator/converter are case-insensitive. If ignorecase == 2, the validator/converter is case-insensitive and the converted value will always be lower-case. The 'validator' tests whether the value is in the list of allowed values. The 'converter' converts input values according to the given 'map'-dictionary (unmapped input values are returned unchanged). """ help = '%s (%s)' % (help, '|'.join(allowed_values)) # define validator if ignorecase >= 1: validator = lambda key, val, env: \ _validator(key, val.lower(), env, allowed_values) else: validator = lambda key, val, env: \ _validator(key, val, env, allowed_values) # define converter if ignorecase == 2: converter = lambda val: map.get(val.lower(), val).lower() elif ignorecase == 1: converter = lambda val: map.get(val.lower(), val) else: converter = lambda val: map.get(val, val) return (key, help, default, validator, converter) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Variables This file defines the Variables class that is used to add user-friendly customizable variables to an SCons build. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Variables/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import sys import SCons.Environment import SCons.Errors import SCons.Util import SCons.Warnings from BoolVariable import BoolVariable # okay from EnumVariable import EnumVariable # okay from ListVariable import ListVariable # naja from PackageVariable import PackageVariable # naja from PathVariable import PathVariable # okay class Variables(object): instance=None """ Holds all the options, updates the environment with the variables, and renders the help text. """ def __init__(self, files=[], args={}, is_global=1): """ files - [optional] List of option configuration files to load (backward compatibility) If a single string is passed it is automatically placed in a file list """ self.options = [] self.args = args if not SCons.Util.is_List(files): if files: files = [ files ] else: files = [] self.files = files self.unknown = {} # create the singleton instance if is_global: self=Variables.instance if not Variables.instance: Variables.instance=self def _do_add(self, key, help="", default=None, validator=None, converter=None): class Variable(object): pass option = Variable() # if we get a list or a tuple, we take the first element as the # option key and store the remaining in aliases. if SCons.Util.is_List(key) or SCons.Util.is_Tuple(key): option.key = key[0] option.aliases = key[1:] else: option.key = key option.aliases = [ key ] option.help = help option.default = default option.validator = validator option.converter = converter self.options.append(option) # options might be added after the 'unknown' dict has been set up, # so we remove the key and all its aliases from that dict for alias in list(option.aliases) + [ option.key ]: if alias in self.unknown: del self.unknown[alias] def keys(self): """ Returns the keywords for the options """ return [o.key for o in self.options] def Add(self, key, help="", default=None, validator=None, converter=None, **kw): """ Add an option. key - the name of the variable, or a list or tuple of arguments help - optional help text for the options default - optional default value validator - optional function that is called to validate the option's value Called with (key, value, environment) converter - optional function that is called to convert the option's value before putting it in the environment. """ if SCons.Util.is_List(key) or isinstance(key, tuple): self._do_add(*key) return if not SCons.Util.is_String(key) or \ not SCons.Environment.is_valid_construction_var(key): raise SCons.Errors.UserError("Illegal Variables.Add() key `%s'" % str(key)) self._do_add(key, help, default, validator, converter) def AddVariables(self, *optlist): """ Add a list of options. Each list element is a tuple/list of arguments to be passed on to the underlying method for adding options. Example: opt.AddVariables( ('debug', '', 0), ('CC', 'The C compiler'), ('VALIDATE', 'An option for testing validation', 'notset', validator, None), ) """ for o in optlist: self._do_add(*o) def Update(self, env, args=None): """ Update an environment with the option variables. env - the environment to update. """ values = {} # first set the defaults: for option in self.options: if not option.default is None: values[option.key] = option.default # next set the value specified in the options file for filename in self.files: if os.path.exists(filename): dir = os.path.split(os.path.abspath(filename))[0] if dir: sys.path.insert(0, dir) try: values['__name__'] = filename exec open(filename, 'rU').read() in {}, values finally: if dir: del sys.path[0] del values['__name__'] # set the values specified on the command line if args is None: args = self.args for arg, value in args.items(): added = False for option in self.options: if arg in list(option.aliases) + [ option.key ]: values[option.key] = value added = True if not added: self.unknown[arg] = value # put the variables in the environment: # (don't copy over variables that are not declared as options) for option in self.options: try: env[option.key] = values[option.key] except KeyError: pass # Call the convert functions: for option in self.options: if option.converter and option.key in values: value = env.subst('${%s}'%option.key) try: try: env[option.key] = option.converter(value) except TypeError: env[option.key] = option.converter(value, env) except ValueError, x: raise SCons.Errors.UserError('Error converting option: %s\n%s'%(option.key, x)) # Finally validate the values: for option in self.options: if option.validator and option.key in values: option.validator(option.key, env.subst('${%s}'%option.key), env) def UnknownVariables(self): """ Returns any options in the specified arguments lists that were not known, declared options in this object. """ return self.unknown def Save(self, filename, env): """ Saves all the options in the given file. This file can then be used to load the options next run. This can be used to create an option cache file. filename - Name of the file to save into env - the environment get the option values from """ # Create the file and write out the header try: fh = open(filename, 'w') try: # Make an assignment in the file for each option # within the environment that was assigned a value # other than the default. for option in self.options: try: value = env[option.key] try: prepare = value.prepare_to_store except AttributeError: try: eval(repr(value)) except KeyboardInterrupt: raise except: # Convert stuff that has a repr() that # cannot be evaluated into a string value = SCons.Util.to_String(value) else: value = prepare() defaultVal = env.subst(SCons.Util.to_String(option.default)) if option.converter: defaultVal = option.converter(defaultVal) if str(env.subst('${%s}' % option.key)) != str(defaultVal): fh.write('%s = %s\n' % (option.key, repr(value))) except KeyError: pass finally: fh.close() except IOError, x: raise SCons.Errors.UserError('Error writing options to file: %s\n%s' % (filename, x)) def GenerateHelpText(self, env, sort=None): """ Generate the help text for the options. env - an environment that is used to get the current values of the options. """ if sort: options = sorted(self.options, key=lambda x: x.key) else: options = self.options def format(opt, self=self, env=env): if opt.key in env: actual = env.subst('${%s}' % opt.key) else: actual = None return self.FormatVariableHelpText(env, opt.key, opt.help, opt.default, actual, opt.aliases) lines = [_f for _f in map(format, options) if _f] return ''.join(lines) format = '\n%s: %s\n default: %s\n actual: %s\n' format_ = '\n%s: %s\n default: %s\n actual: %s\n aliases: %s\n' def FormatVariableHelpText(self, env, key, help, default, actual, aliases=[]): # Don't display the key name itself as an alias. aliases = [a for a in aliases if a != key] if len(aliases)==0: return self.format % (key, help, default, actual) else: return self.format_ % (key, help, default, actual, aliases) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Variables.PathVariable This file defines an option type for SCons implementing path settings. To be used whenever a a user-specified path override should be allowed. Arguments to PathVariable are: option-name = name of this option on the command line (e.g. "prefix") option-help = help string for option option-dflt = default value for this option validator = [optional] validator for option value. Predefined validators are: PathAccept -- accepts any path setting; no validation PathIsDir -- path must be an existing directory PathIsDirCreate -- path must be a dir; will create PathIsFile -- path must be a file PathExists -- path must exist (any type) [default] The validator is a function that is called and which should return True or False to indicate if the path is valid. The arguments to the validator function are: (key, val, env). The key is the name of the option, the val is the path specified for the option, and the env is the env to which the Otions have been added. Usage example: Examples: prefix=/usr/local opts = Variables() opts = Variables() opts.Add(PathVariable('qtdir', 'where the root of Qt is installed', qtdir, PathIsDir)) opts.Add(PathVariable('qt_includes', 'where the Qt includes are installed', '$qtdir/includes', PathIsDirCreate)) opts.Add(PathVariable('qt_libraries', 'where the Qt library is installed', '$qtdir/lib')) """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Variables/PathVariable.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __all__ = ['PathVariable',] import os import os.path import SCons.Errors class _PathVariableClass(object): def PathAccept(self, key, val, env): """Accepts any path, no checking done.""" pass def PathIsDir(self, key, val, env): """Validator to check if Path is a directory.""" if not os.path.isdir(val): if os.path.isfile(val): m = 'Directory path for option %s is a file: %s' else: m = 'Directory path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val)) def PathIsDirCreate(self, key, val, env): """Validator to check if Path is a directory, creating it if it does not exist.""" if os.path.isfile(val): m = 'Path for option %s is a file, not a directory: %s' raise SCons.Errors.UserError(m % (key, val)) if not os.path.isdir(val): os.makedirs(val) def PathIsFile(self, key, val, env): """validator to check if Path is a file""" if not os.path.isfile(val): if os.path.isdir(val): m = 'File path for option %s is a directory: %s' else: m = 'File path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val)) def PathExists(self, key, val, env): """validator to check if Path exists""" if not os.path.exists(val): m = 'Path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val)) def __call__(self, key, help, default, validator=None): # NB: searchfunc is currenty undocumented and unsupported """ The input parameters describe a 'path list' option, thus they are returned with the correct converter and validator appended. The result is usable for input to opts.Add() . The 'default' option specifies the default path to use if the user does not specify an override with this option. validator is a validator, see this file for examples """ if validator is None: validator = self.PathExists if SCons.Util.is_List(key) or SCons.Util.is_Tuple(key): return (key, '%s ( /path/to/%s )' % (help, key[0]), default, validator, None) else: return (key, '%s ( /path/to/%s )' % (help, key), default, validator, None) PathVariable = _PathVariableClass() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Variables.ListVariable This file defines the option type for SCons implementing 'lists'. A 'list' option may either be 'all', 'none' or a list of names separated by comma. After the option has been processed, the option value holds either the named list elements, all list elemens or no list elements at all. Usage example: list_of_libs = Split('x11 gl qt ical') opts = Variables() opts.Add(ListVariable('shared', 'libraries to build as shared libraries', 'all', elems = list_of_libs)) ... for lib in list_of_libs: if lib in env['shared']: env.SharedObject(...) else: env.Object(...) """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Variables/ListVariable.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" # Know Bug: This should behave like a Set-Type, but does not really, # since elements can occur twice. __all__ = ['ListVariable',] import collections import SCons.Util class _ListVariable(collections.UserList): def __init__(self, initlist=[], allowedElems=[]): collections.UserList.__init__(self, [_f for _f in initlist if _f]) self.allowedElems = sorted(allowedElems) def __cmp__(self, other): raise NotImplementedError def __eq__(self, other): raise NotImplementedError def __ge__(self, other): raise NotImplementedError def __gt__(self, other): raise NotImplementedError def __le__(self, other): raise NotImplementedError def __lt__(self, other): raise NotImplementedError def __str__(self): if len(self) == 0: return 'none' self.data.sort() if self.data == self.allowedElems: return 'all' else: return ','.join(self) def prepare_to_store(self): return self.__str__() def _converter(val, allowedElems, mapdict): """ """ if val == 'none': val = [] elif val == 'all': val = allowedElems else: val = [_f for _f in val.split(',') if _f] val = [mapdict.get(v, v) for v in val] notAllowed = [v for v in val if not v in allowedElems] if notAllowed: raise ValueError("Invalid value(s) for option: %s" % ','.join(notAllowed)) return _ListVariable(val, allowedElems) ## def _validator(key, val, env): ## """ ## """ ## # todo: write validater for pgk list ## return 1 def ListVariable(key, help, default, names, map={}): """ The input parameters describe a 'package list' option, thus they are returned with the correct converter and validater appended. The result is usable for input to opts.Add() . A 'package list' option may either be 'all', 'none' or a list of package names (separated by space). """ names_str = 'allowed names: %s' % ' '.join(names) if SCons.Util.is_List(default): default = ','.join(default) help = '\n '.join( (help, '(all|none|comma-separated list of names)', names_str)) return (key, help, default, None, #_validator, lambda val: _converter(val, names, map)) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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. __doc__ = """ Generic Taskmaster module for the SCons build engine. This module contains the primary interface(s) between a wrapping user interface and the SCons build engine. There are two key classes here: Taskmaster This is the main engine for walking the dependency graph and calling things to decide what does or doesn't need to be built. Task This is the base class for allowing a wrapping interface to decide what does or doesn't actually need to be done. The intention is for a wrapping interface to subclass this as appropriate for different types of behavior it may need. The canonical example is the SCons native Python interface, which has Task subclasses that handle its specific behavior, like printing "`foo' is up to date" when a top-level target doesn't need to be built, and handling the -c option by removing targets as its "build" action. There is also a separate subclass for suppressing this output when the -q option is used. The Taskmaster instantiates a Task object for each (set of) target(s) that it decides need to be evaluated and/or built. """ __revision__ = "src/engine/SCons/Taskmaster.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from itertools import chain import operator import sys import traceback import SCons.Errors import SCons.Node import SCons.Warnings StateString = SCons.Node.StateString NODE_NO_STATE = SCons.Node.no_state NODE_PENDING = SCons.Node.pending NODE_EXECUTING = SCons.Node.executing NODE_UP_TO_DATE = SCons.Node.up_to_date NODE_EXECUTED = SCons.Node.executed NODE_FAILED = SCons.Node.failed print_prepare = 0 # set by option --debug=prepare # A subsystem for recording stats about how different Nodes are handled by # the main Taskmaster loop. There's no external control here (no need for # a --debug= option); enable it by changing the value of CollectStats. CollectStats = None class Stats(object): """ A simple class for holding statistics about the disposition of a Node by the Taskmaster. If we're collecting statistics, each Node processed by the Taskmaster gets one of these attached, in which case the Taskmaster records its decision each time it processes the Node. (Ideally, that's just once per Node.) """ def __init__(self): """ Instantiates a Taskmaster.Stats object, initializing all appropriate counters to zero. """ self.considered = 0 self.already_handled = 0 self.problem = 0 self.child_failed = 0 self.not_built = 0 self.side_effects = 0 self.build = 0 StatsNodes = [] fmt = "%(considered)3d "\ "%(already_handled)3d " \ "%(problem)3d " \ "%(child_failed)3d " \ "%(not_built)3d " \ "%(side_effects)3d " \ "%(build)3d " def dump_stats(): for n in sorted(StatsNodes, key=lambda a: str(a)): print (fmt % n.stats.__dict__) + str(n) class Task(object): """ Default SCons build engine task. This controls the interaction of the actual building of node and the rest of the engine. This is expected to handle all of the normally-customizable aspects of controlling a build, so any given application *should* be able to do what it wants by sub-classing this class and overriding methods as appropriate. If an application needs to customze something by sub-classing Taskmaster (or some other build engine class), we should first try to migrate that functionality into this class. Note that it's generally a good idea for sub-classes to call these methods explicitly to update state, etc., rather than roll their own interaction with Taskmaster from scratch. """ def __init__(self, tm, targets, top, node): self.tm = tm self.targets = targets self.top = top self.node = node self.exc_clear() def trace_message(self, method, node, description='node'): fmt = '%-20s %s %s\n' return fmt % (method + ':', description, self.tm.trace_node(node)) def display(self, message): """ Hook to allow the calling interface to display a message. This hook gets called as part of preparing a task for execution (that is, a Node to be built). As part of figuring out what Node should be built next, the actually target list may be altered, along with a message describing the alteration. The calling interface can subclass Task and provide a concrete implementation of this method to see those messages. """ pass def prepare(self): """ Called just before the task is executed. This is mainly intended to give the target Nodes a chance to unlink underlying files and make all necessary directories before the Action is actually called to build the targets. """ global print_prepare T = self.tm.trace if T: T.write(self.trace_message(u'Task.prepare()', self.node)) # Now that it's the appropriate time, give the TaskMaster a # chance to raise any exceptions it encountered while preparing # this task. self.exception_raise() if self.tm.message: self.display(self.tm.message) self.tm.message = None # Let the targets take care of any necessary preparations. # This includes verifying that all of the necessary sources # and dependencies exist, removing the target file(s), etc. # # As of April 2008, the get_executor().prepare() method makes # sure that all of the aggregate sources necessary to build this # Task's target(s) exist in one up-front check. The individual # target t.prepare() methods check that each target's explicit # or implicit dependencies exists, and also initialize the # .sconsign info. executor = self.targets[0].get_executor() executor.prepare() for t in executor.get_action_targets(): if print_prepare: print "Preparing target %s..."%t for s in t.side_effects: print "...with side-effect %s..."%s t.prepare() for s in t.side_effects: if print_prepare: print "...Preparing side-effect %s..."%s s.prepare() def get_target(self): """Fetch the target being built or updated by this task. """ return self.node def needs_execute(self): # TODO(deprecate): "return True" is the old default behavior; # change it to NotImplementedError (after running through the # Deprecation Cycle) so the desired behavior is explicitly # determined by which concrete subclass is used. #raise NotImplementedError msg = ('Taskmaster.Task is an abstract base class; instead of\n' '\tusing it directly, ' 'derive from it and override the abstract methods.') SCons.Warnings.warn(SCons.Warnings.TaskmasterNeedsExecuteWarning, msg) return True def execute(self): """ Called to execute the task. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in prepare(), executed() or failed(). """ T = self.tm.trace if T: T.write(self.trace_message(u'Task.execute()', self.node)) try: cached_targets = [] for t in self.targets: if not t.retrieve_from_cache(): break cached_targets.append(t) if len(cached_targets) < len(self.targets): # Remove targets before building. It's possible that we # partially retrieved targets from the cache, leaving # them in read-only mode. That might cause the command # to fail. # for t in cached_targets: try: t.fs.unlink(t.path) except (IOError, OSError): pass self.targets[0].build() else: for t in cached_targets: t.cached = 1 except SystemExit: exc_value = sys.exc_info()[1] raise SCons.Errors.ExplicitExit(self.targets[0], exc_value.code) except SCons.Errors.UserError: raise except SCons.Errors.BuildError: raise except Exception, e: buildError = SCons.Errors.convert_to_BuildError(e) buildError.node = self.targets[0] buildError.exc_info = sys.exc_info() raise buildError def executed_without_callbacks(self): """ Called when the task has been successfully executed and the Taskmaster instance doesn't want to call the Node's callback methods. """ T = self.tm.trace if T: T.write(self.trace_message('Task.executed_without_callbacks()', self.node)) for t in self.targets: if t.get_state() == NODE_EXECUTING: for side_effect in t.side_effects: side_effect.set_state(NODE_NO_STATE) t.set_state(NODE_EXECUTED) def executed_with_callbacks(self): """ Called when the task has been successfully executed and the Taskmaster instance wants to call the Node's callback methods. This may have been a do-nothing operation (to preserve build order), so we must check the node's state before deciding whether it was "built", in which case we call the appropriate Node method. In any event, we always call "visited()", which will handle any post-visit actions that must take place regardless of whether or not the target was an actual built target or a source Node. """ T = self.tm.trace if T: T.write(self.trace_message('Task.executed_with_callbacks()', self.node)) for t in self.targets: if t.get_state() == NODE_EXECUTING: for side_effect in t.side_effects: side_effect.set_state(NODE_NO_STATE) t.set_state(NODE_EXECUTED) if not t.cached: t.push_to_cache() t.built() t.visited() executed = executed_with_callbacks def failed(self): """ Default action when a task fails: stop the build. Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure(). """ self.fail_stop() def fail_stop(self): """ Explicit stop-the-build failure. This sets failure status on the target nodes and all of their dependent parent nodes. Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure(). """ T = self.tm.trace if T: T.write(self.trace_message('Task.failed_stop()', self.node)) # Invoke will_not_build() to clean-up the pending children # list. self.tm.will_not_build(self.targets, lambda n: n.set_state(NODE_FAILED)) # Tell the taskmaster to not start any new tasks self.tm.stop() # We're stopping because of a build failure, but give the # calling Task class a chance to postprocess() the top-level # target under which the build failure occurred. self.targets = [self.tm.current_top] self.top = 1 def fail_continue(self): """ Explicit continue-the-build failure. This sets failure status on the target nodes and all of their dependent parent nodes. Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure(). """ T = self.tm.trace if T: T.write(self.trace_message('Task.failed_continue()', self.node)) self.tm.will_not_build(self.targets, lambda n: n.set_state(NODE_FAILED)) def make_ready_all(self): """ Marks all targets in a task ready for execution. This is used when the interface needs every target Node to be visited--the canonical example being the "scons -c" option. """ T = self.tm.trace if T: T.write(self.trace_message('Task.make_ready_all()', self.node)) self.out_of_date = self.targets[:] for t in self.targets: t.disambiguate().set_state(NODE_EXECUTING) for s in t.side_effects: # add disambiguate here to mirror the call on targets above s.disambiguate().set_state(NODE_EXECUTING) def make_ready_current(self): """ Marks all targets in a task ready for execution if any target is not current. This is the default behavior for building only what's necessary. """ T = self.tm.trace if T: T.write(self.trace_message(u'Task.make_ready_current()', self.node)) self.out_of_date = [] needs_executing = False for t in self.targets: try: t.disambiguate().make_ready() is_up_to_date = not t.has_builder() or \ (not t.always_build and t.is_up_to_date()) except EnvironmentError, e: raise SCons.Errors.BuildError(node=t, errstr=e.strerror, filename=e.filename) if not is_up_to_date: self.out_of_date.append(t) needs_executing = True if needs_executing: for t in self.targets: t.set_state(NODE_EXECUTING) for s in t.side_effects: # add disambiguate here to mirror the call on targets in first loop above s.disambiguate().set_state(NODE_EXECUTING) else: for t in self.targets: # We must invoke visited() to ensure that the node # information has been computed before allowing the # parent nodes to execute. (That could occur in a # parallel build...) t.visited() t.set_state(NODE_UP_TO_DATE) make_ready = make_ready_current def postprocess(self): """ Post-processes a task after it's been executed. This examines all the targets just built (or not, we don't care if the build was successful, or even if there was no build because everything was up-to-date) to see if they have any waiting parent Nodes, or Nodes waiting on a common side effect, that can be put back on the candidates list. """ T = self.tm.trace if T: T.write(self.trace_message(u'Task.postprocess()', self.node)) # We may have built multiple targets, some of which may have # common parents waiting for this build. Count up how many # targets each parent was waiting for so we can subtract the # values later, and so we *don't* put waiting side-effect Nodes # back on the candidates list if the Node is also a waiting # parent. targets = set(self.targets) pending_children = self.tm.pending_children parents = {} for t in targets: # A node can only be in the pending_children set if it has # some waiting_parents. if t.waiting_parents: if T: T.write(self.trace_message(u'Task.postprocess()', t, 'removing')) pending_children.discard(t) for p in t.waiting_parents: parents[p] = parents.get(p, 0) + 1 for t in targets: for s in t.side_effects: if s.get_state() == NODE_EXECUTING: s.set_state(NODE_NO_STATE) for p in s.waiting_parents: parents[p] = parents.get(p, 0) + 1 for p in s.waiting_s_e: if p.ref_count == 0: self.tm.candidates.append(p) for p, subtract in parents.items(): p.ref_count = p.ref_count - subtract if T: T.write(self.trace_message(u'Task.postprocess()', p, 'adjusted parent ref count')) if p.ref_count == 0: self.tm.candidates.append(p) for t in targets: t.postprocess() # Exception handling subsystem. # # Exceptions that occur while walking the DAG or examining Nodes # must be raised, but must be raised at an appropriate time and in # a controlled manner so we can, if necessary, recover gracefully, # possibly write out signature information for Nodes we've updated, # etc. This is done by having the Taskmaster tell us about the # exception, and letting def exc_info(self): """ Returns info about a recorded exception. """ return self.exception def exc_clear(self): """ Clears any recorded exception. This also changes the "exception_raise" attribute to point to the appropriate do-nothing method. """ self.exception = (None, None, None) self.exception_raise = self._no_exception_to_raise def exception_set(self, exception=None): """ Records an exception to be raised at the appropriate time. This also changes the "exception_raise" attribute to point to the method that will, in fact """ if not exception: exception = sys.exc_info() self.exception = exception self.exception_raise = self._exception_raise def _no_exception_to_raise(self): pass def _exception_raise(self): """ Raises a pending exception that was recorded while getting a Task ready for execution. """ exc = self.exc_info()[:] try: exc_type, exc_value, exc_traceback = exc except ValueError: exc_type, exc_value = exc exc_traceback = None raise exc_type, exc_value, exc_traceback class AlwaysTask(Task): def needs_execute(self): """ Always returns True (indicating this Task should always be executed). Subclasses that need this behavior (as opposed to the default of only executing Nodes that are out of date w.r.t. their dependencies) can use this as follows: class MyTaskSubclass(SCons.Taskmaster.Task): needs_execute = SCons.Taskmaster.Task.execute_always """ return True class OutOfDateTask(Task): def needs_execute(self): """ Returns True (indicating this Task should be executed) if this Task's target state indicates it needs executing, which has already been determined by an earlier up-to-date check. """ return self.targets[0].get_state() == SCons.Node.executing def find_cycle(stack, visited): if stack[-1] in visited: return None visited.add(stack[-1]) for n in stack[-1].waiting_parents: stack.append(n) if stack[0] == stack[-1]: return stack if find_cycle(stack, visited): return stack stack.pop() return None class Taskmaster(object): """ The Taskmaster for walking the dependency DAG. """ def __init__(self, targets=[], tasker=None, order=None, trace=None): self.original_top = targets self.top_targets_left = targets[:] self.top_targets_left.reverse() self.candidates = [] if tasker is None: tasker = OutOfDateTask self.tasker = tasker if not order: order = lambda l: l self.order = order self.message = None self.trace = trace self.next_candidate = self.find_next_candidate self.pending_children = set() def find_next_candidate(self): """ Returns the next candidate Node for (potential) evaluation. The candidate list (really a stack) initially consists of all of the top-level (command line) targets provided when the Taskmaster was initialized. While we walk the DAG, visiting Nodes, all the children that haven't finished processing get pushed on to the candidate list. Each child can then be popped and examined in turn for whether *their* children are all up-to-date, in which case a Task will be created for their actual evaluation and potential building. Here is where we also allow candidate Nodes to alter the list of Nodes that should be examined. This is used, for example, when invoking SCons in a source directory. A source directory Node can return its corresponding build directory Node, essentially saying, "Hey, you really need to build this thing over here instead." """ try: return self.candidates.pop() except IndexError: pass try: node = self.top_targets_left.pop() except IndexError: return None self.current_top = node alt, message = node.alter_targets() if alt: self.message = message self.candidates.append(node) self.candidates.extend(self.order(alt)) node = self.candidates.pop() return node def no_next_candidate(self): """ Stops Taskmaster processing by not returning a next candidate. Note that we have to clean-up the Taskmaster candidate list because the cycle detection depends on the fact all nodes have been processed somehow. """ while self.candidates: candidates = self.candidates self.candidates = [] self.will_not_build(candidates) return None def _validate_pending_children(self): """ Validate the content of the pending_children set. Assert if an internal error is found. This function is used strictly for debugging the taskmaster by checking that no invariants are violated. It is not used in normal operation. The pending_children set is used to detect cycles in the dependency graph. We call a "pending child" a child that is found in the "pending" state when checking the dependencies of its parent node. A pending child can occur when the Taskmaster completes a loop through a cycle. For example, lets imagine a graph made of three node (A, B and C) making a cycle. The evaluation starts at node A. The taskmaster first consider whether node A's child B is up-to-date. Then, recursively, node B needs to check whether node C is up-to-date. This leaves us with a dependency graph looking like: Next candidate \ \ Node A (Pending) --> Node B(Pending) --> Node C (NoState) ^ | | | +-------------------------------------+ Now, when the Taskmaster examines the Node C's child Node A, it finds that Node A is in the "pending" state. Therefore, Node A is a pending child of node C. Pending children indicate that the Taskmaster has potentially loop back through a cycle. We say potentially because it could also occur when a DAG is evaluated in parallel. For example, consider the following graph: Node A (Pending) --> Node B(Pending) --> Node C (Pending) --> ... | ^ | | +----------> Node D (NoState) --------+ / Next candidate / The Taskmaster first evaluates the nodes A, B, and C and starts building some children of node C. Assuming, that the maximum parallel level has not been reached, the Taskmaster will examine Node D. It will find that Node C is a pending child of Node D. In summary, evaluating a graph with a cycle will always involve a pending child at one point. A pending child might indicate either a cycle or a diamond-shaped DAG. Only a fraction of the nodes ends-up being a "pending child" of another node. This keeps the pending_children set small in practice. We can differentiate between the two cases if we wait until the end of the build. At this point, all the pending children nodes due to a diamond-shaped DAG will have been properly built (or will have failed to build). But, the pending children involved in a cycle will still be in the pending state. The taskmaster removes nodes from the pending_children set as soon as a pending_children node moves out of the pending state. This also helps to keep the pending_children set small. """ for n in self.pending_children: assert n.state in (NODE_PENDING, NODE_EXECUTING), \ (str(n), StateString[n.state]) assert len(n.waiting_parents) != 0, (str(n), len(n.waiting_parents)) for p in n.waiting_parents: assert p.ref_count > 0, (str(n), str(p), p.ref_count) def trace_message(self, message): return 'Taskmaster: %s\n' % message def trace_node(self, node): return '<%-10s %-3s %s>' % (StateString[node.get_state()], node.ref_count, repr(str(node))) def _find_next_ready_node(self): """ Finds the next node that is ready to be built. This is *the* main guts of the DAG walk. We loop through the list of candidates, looking for something that has no un-built children (i.e., that is a leaf Node or has dependencies that are all leaf Nodes or up-to-date). Candidate Nodes are re-scanned (both the target Node itself and its sources, which are always scanned in the context of a given target) to discover implicit dependencies. A Node that must wait for some children to be built will be put back on the candidates list after the children have finished building. A Node that has been put back on the candidates list in this way may have itself (or its sources) re-scanned, in order to handle generated header files (e.g.) and the implicit dependencies therein. Note that this method does not do any signature calculation or up-to-date check itself. All of that is handled by the Task class. This is purely concerned with the dependency graph walk. """ self.ready_exc = None T = self.trace if T: T.write(u'\n' + self.trace_message('Looking for a node to evaluate')) while True: node = self.next_candidate() if node is None: if T: T.write(self.trace_message('No candidate anymore.') + u'\n') return None node = node.disambiguate() state = node.get_state() # For debugging only: # # try: # self._validate_pending_children() # except: # self.ready_exc = sys.exc_info() # return node if CollectStats: if not hasattr(node, 'stats'): node.stats = Stats() StatsNodes.append(node) S = node.stats S.considered = S.considered + 1 else: S = None if T: T.write(self.trace_message(u' Considering node %s and its children:' % self.trace_node(node))) if state == NODE_NO_STATE: # Mark this node as being on the execution stack: node.set_state(NODE_PENDING) elif state > NODE_PENDING: # Skip this node if it has already been evaluated: if S: S.already_handled = S.already_handled + 1 if T: T.write(self.trace_message(u' already handled (executed)')) continue executor = node.get_executor() try: children = executor.get_all_children() except SystemExit: exc_value = sys.exc_info()[1] e = SCons.Errors.ExplicitExit(node, exc_value.code) self.ready_exc = (SCons.Errors.ExplicitExit, e) if T: T.write(self.trace_message(' SystemExit')) return node except Exception, e: # We had a problem just trying to figure out the # children (like a child couldn't be linked in to a # VariantDir, or a Scanner threw something). Arrange to # raise the exception when the Task is "executed." self.ready_exc = sys.exc_info() if S: S.problem = S.problem + 1 if T: T.write(self.trace_message(' exception %s while scanning children.\n' % e)) return node children_not_visited = [] children_pending = set() children_not_ready = [] children_failed = False for child in chain(executor.get_all_prerequisites(), children): childstate = child.get_state() if T: T.write(self.trace_message(u' ' + self.trace_node(child))) if childstate == NODE_NO_STATE: children_not_visited.append(child) elif childstate == NODE_PENDING: children_pending.add(child) elif childstate == NODE_FAILED: children_failed = True if childstate <= NODE_EXECUTING: children_not_ready.append(child) # These nodes have not even been visited yet. Add # them to the list so that on some next pass we can # take a stab at evaluating them (or their children). children_not_visited.reverse() self.candidates.extend(self.order(children_not_visited)) #if T and children_not_visited: # T.write(self.trace_message(' adding to candidates: %s' % map(str, children_not_visited))) # T.write(self.trace_message(' candidates now: %s\n' % map(str, self.candidates))) # Skip this node if any of its children have failed. # # This catches the case where we're descending a top-level # target and one of our children failed while trying to be # built by a *previous* descent of an earlier top-level # target. # # It can also occur if a node is reused in multiple # targets. One first descends though the one of the # target, the next time occurs through the other target. # # Note that we can only have failed_children if the # --keep-going flag was used, because without it the build # will stop before diving in the other branch. # # Note that even if one of the children fails, we still # added the other children to the list of candidate nodes # to keep on building (--keep-going). if children_failed: for n in executor.get_action_targets(): n.set_state(NODE_FAILED) if S: S.child_failed = S.child_failed + 1 if T: T.write(self.trace_message('****** %s\n' % self.trace_node(node))) continue if children_not_ready: for child in children_not_ready: # We're waiting on one or more derived targets # that have not yet finished building. if S: S.not_built = S.not_built + 1 # Add this node to the waiting parents lists of # anything we're waiting on, with a reference # count so we can be put back on the list for # re-evaluation when they've all finished. node.ref_count = node.ref_count + child.add_to_waiting_parents(node) if T: T.write(self.trace_message(u' adjusted ref count: %s, child %s' % (self.trace_node(node), repr(str(child))))) if T: for pc in children_pending: T.write(self.trace_message(' adding %s to the pending children set\n' % self.trace_node(pc))) self.pending_children = self.pending_children | children_pending continue # Skip this node if it has side-effects that are # currently being built: wait_side_effects = False for se in executor.get_action_side_effects(): if se.get_state() == NODE_EXECUTING: se.add_to_waiting_s_e(node) wait_side_effects = True if wait_side_effects: if S: S.side_effects = S.side_effects + 1 continue # The default when we've gotten through all of the checks above: # this node is ready to be built. if S: S.build = S.build + 1 if T: T.write(self.trace_message(u'Evaluating %s\n' % self.trace_node(node))) # For debugging only: # # try: # self._validate_pending_children() # except: # self.ready_exc = sys.exc_info() # return node return node return None def next_task(self): """ Returns the next task to be executed. This simply asks for the next Node to be evaluated, and then wraps it in the specific Task subclass with which we were initialized. """ node = self._find_next_ready_node() if node is None: return None tlist = node.get_executor().get_all_targets() task = self.tasker(self, tlist, node in self.original_top, node) try: task.make_ready() except: # We had a problem just trying to get this task ready (like # a child couldn't be linked in to a VariantDir when deciding # whether this node is current). Arrange to raise the # exception when the Task is "executed." self.ready_exc = sys.exc_info() if self.ready_exc: task.exception_set(self.ready_exc) self.ready_exc = None return task def will_not_build(self, nodes, node_func=lambda n: None): """ Perform clean-up about nodes that will never be built. Invokes a user defined function on all of these nodes (including all of their parents). """ T = self.trace pending_children = self.pending_children to_visit = set(nodes) pending_children = pending_children - to_visit if T: for n in nodes: T.write(self.trace_message(' removing node %s from the pending children set\n' % self.trace_node(n))) try: while len(to_visit): node = to_visit.pop() node_func(node) # Prune recursion by flushing the waiting children # list immediately. parents = node.waiting_parents node.waiting_parents = set() to_visit = to_visit | parents pending_children = pending_children - parents for p in parents: p.ref_count = p.ref_count - 1 if T: T.write(self.trace_message(' removing parent %s from the pending children set\n' % self.trace_node(p))) except KeyError: # The container to_visit has been emptied. pass # We have the stick back the pending_children list into the # taskmaster because the python 1.5.2 compatibility does not # allow us to use in-place updates self.pending_children = pending_children def stop(self): """ Stops the current build completely. """ self.next_candidate = self.no_next_candidate def cleanup(self): """ Check for dependency cycles. """ if not self.pending_children: return nclist = [(n, find_cycle([n], set())) for n in self.pending_children] genuine_cycles = [ node for node,cycle in nclist if cycle or node.get_state() != NODE_EXECUTED ] if not genuine_cycles: # All of the "cycles" found were single nodes in EXECUTED state, # which is to say, they really weren't cycles. Just return. return desc = 'Found dependency cycle(s):\n' for node, cycle in nclist: if cycle: desc = desc + " " + " -> ".join(map(str, cycle)) + "\n" else: desc = desc + \ " Internal Error: no cycle found for node %s (%s) in state %s\n" % \ (node, repr(node), StateString[node.get_state()]) raise SCons.Errors.UserError(desc) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Debug Code for debugging SCons internal things. Shouldn't be needed by most users. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Debug.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import sys import time import weakref tracked_classes = {} def logInstanceCreation(instance, name=None): if name is None: name = instance.__class__.__name__ if name not in tracked_classes: tracked_classes[name] = [] tracked_classes[name].append(weakref.ref(instance)) def string_to_classes(s): if s == '*': return sorted(tracked_classes.keys()) else: return s.split() def fetchLoggedInstances(classes="*"): classnames = string_to_classes(classes) return [(cn, len(tracked_classes[cn])) for cn in classnames] def countLoggedInstances(classes, file=sys.stdout): for classname in string_to_classes(classes): file.write("%s: %d\n" % (classname, len(tracked_classes[classname]))) def listLoggedInstances(classes, file=sys.stdout): for classname in string_to_classes(classes): file.write('\n%s:\n' % classname) for ref in tracked_classes[classname]: obj = ref() if obj is not None: file.write(' %s\n' % repr(obj)) def dumpLoggedInstances(classes, file=sys.stdout): for classname in string_to_classes(classes): file.write('\n%s:\n' % classname) for ref in tracked_classes[classname]: obj = ref() if obj is not None: file.write(' %s:\n' % obj) for key, value in obj.__dict__.items(): file.write(' %20s : %s\n' % (key, value)) if sys.platform[:5] == "linux": # Linux doesn't actually support memory usage stats from getrusage(). def memory(): mstr = open('/proc/self/stat').read() mstr = mstr.split()[22] return int(mstr) elif sys.platform[:6] == 'darwin': #TODO really get memory stats for OS X def memory(): return 0 else: try: import resource except ImportError: try: import win32process import win32api except ImportError: def memory(): return 0 else: def memory(): process_handle = win32api.GetCurrentProcess() memory_info = win32process.GetProcessMemoryInfo( process_handle ) return memory_info['PeakWorkingSetSize'] else: def memory(): res = resource.getrusage(resource.RUSAGE_SELF) return res[4] # returns caller's stack def caller_stack(*backlist): import traceback if not backlist: backlist = [0] result = [] for back in backlist: tb = traceback.extract_stack(limit=3+back) key = tb[0][:3] result.append('%s:%d(%s)' % func_shorten(key)) return result caller_bases = {} caller_dicts = {} # trace a caller's stack def caller_trace(back=0): import traceback tb = traceback.extract_stack(limit=3+back) tb.reverse() callee = tb[1][:3] caller_bases[callee] = caller_bases.get(callee, 0) + 1 for caller in tb[2:]: caller = callee + caller[:3] try: entry = caller_dicts[callee] except KeyError: caller_dicts[callee] = entry = {} entry[caller] = entry.get(caller, 0) + 1 callee = caller # print a single caller and its callers, if any def _dump_one_caller(key, file, level=0): leader = ' '*level for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]): file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:]))) if c in caller_dicts: _dump_one_caller(c, file, level+1) # print each call tree def dump_caller_counts(file=sys.stdout): for k in sorted(caller_bases.keys()): file.write("Callers of %s:%d(%s), %d calls:\n" % (func_shorten(k) + (caller_bases[k],))) _dump_one_caller(k, file) shorten_list = [ ( '/scons/SCons/', 1), ( '/src/engine/SCons/', 1), ( '/usr/lib/python', 0), ] if os.sep != '/': shorten_list = [(t[0].replace('/', os.sep), t[1]) for t in shorten_list] def func_shorten(func_tuple): f = func_tuple[0] for t in shorten_list: i = f.find(t[0]) if i >= 0: if t[1]: i = i + len(t[0]) return (f[i:],)+func_tuple[1:] return func_tuple TraceFP = {} if sys.platform == 'win32': TraceDefault = 'con' else: TraceDefault = '/dev/tty' TimeStampDefault = None StartTime = time.time() PreviousTime = StartTime def Trace(msg, file=None, mode='w', tstamp=None): """Write a trace message to a file. Whenever a file is specified, it becomes the default for the next call to Trace().""" global TraceDefault global TimeStampDefault global PreviousTime if file is None: file = TraceDefault else: TraceDefault = file if tstamp is None: tstamp = TimeStampDefault else: TimeStampDefault = tstamp try: fp = TraceFP[file] except KeyError: try: fp = TraceFP[file] = open(file, mode) except TypeError: # Assume we were passed an open file pointer. fp = file if tstamp: now = time.time() fp.write('%8.4f %8.4f: ' % (now - StartTime, now - PreviousTime)) PreviousTime = now fp.write(msg) fp.flush() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons The main package for the SCons software construction utility. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __version__ = "2.2.0" __build__ = "issue-2856:2676:d23b7a2f45e8[MODIFIED]" __buildsys__ = "oberbrunner-dev" __date__ = "2012/08/05 15:38:28" __developer__ = "garyo" # make sure compatibility is always in place import SCons.compat # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/cpp.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """ SCons C Pre-Processor module """ #TODO 2.3 and before has no sorted() import SCons.compat import os import re # # First "subsystem" of regular expressions that we set up: # # Stuff to turn the C preprocessor directives in a file's contents into # a list of tuples that we can process easily. # # A table of regular expressions that fetch the arguments from the rest of # a C preprocessor line. Different directives have different arguments # that we want to fetch, using the regular expressions to which the lists # of preprocessor directives map. cpp_lines_dict = { # Fetch the rest of a #if/#elif/#ifdef/#ifndef as one argument, # separated from the keyword by white space. ('if', 'elif', 'ifdef', 'ifndef',) : '\s+(.+)', # Fetch the rest of a #import/#include/#include_next line as one # argument, with white space optional. ('import', 'include', 'include_next',) : '\s*(.+)', # We don't care what comes after a #else or #endif line. ('else', 'endif',) : '', # Fetch three arguments from a #define line: # 1) The #defined keyword. # 2) The optional parentheses and arguments (if it's a function-like # macro, '' if it's not). # 3) The expansion value. ('define',) : '\s+([_A-Za-z][_A-Za-z0-9_]*)(\([^)]*\))?\s*(.*)', # Fetch the #undefed keyword from a #undef line. ('undef',) : '\s+([_A-Za-z][A-Za-z0-9_]*)', } # Create a table that maps each individual C preprocessor directive to # the corresponding compiled regular expression that fetches the arguments # we care about. Table = {} for op_list, expr in cpp_lines_dict.items(): e = re.compile(expr) for op in op_list: Table[op] = e del e del op del op_list # Create a list of the expressions we'll use to match all of the # preprocessor directives. These are the same as the directives # themselves *except* that we must use a negative lookahead assertion # when matching "if" so it doesn't match the "if" in "ifdef." override = { 'if' : 'if(?!def)', } l = [override.get(x, x) for x in Table.keys()] # Turn the list of expressions into one big honkin' regular expression # that will match all the preprocessor lines at once. This will return # a list of tuples, one for each preprocessor line. The preprocessor # directive will be the first element in each tuple, and the rest of # the line will be the second element. e = '^\s*#\s*(' + '|'.join(l) + ')(.*)$' # And last but not least, compile the expression. CPP_Expression = re.compile(e, re.M) # # Second "subsystem" of regular expressions that we set up: # # Stuff to translate a C preprocessor expression (as found on a #if or # #elif line) into an equivalent Python expression that we can eval(). # # A dictionary that maps the C representation of Boolean operators # to their Python equivalents. CPP_to_Python_Ops_Dict = { '!' : ' not ', '!=' : ' != ', '&&' : ' and ', '||' : ' or ', '?' : ' and ', ':' : ' or ', '\r' : '', } CPP_to_Python_Ops_Sub = lambda m: CPP_to_Python_Ops_Dict[m.group(0)] # We have to sort the keys by length so that longer expressions # come *before* shorter expressions--in particular, "!=" must # come before "!" in the alternation. Without this, the Python # re module, as late as version 2.2.2, empirically matches the # "!" in "!=" first, instead of finding the longest match. # What's up with that? l = sorted(CPP_to_Python_Ops_Dict.keys(), key=lambda a: len(a), reverse=True) # Turn the list of keys into one regular expression that will allow us # to substitute all of the operators at once. expr = '|'.join(map(re.escape, l)) # ...and compile the expression. CPP_to_Python_Ops_Expression = re.compile(expr) # A separate list of expressions to be evaluated and substituted # sequentially, not all at once. CPP_to_Python_Eval_List = [ ['defined\s+(\w+)', '"\\1" in __dict__'], ['defined\s*\((\w+)\)', '"\\1" in __dict__'], ['/\*.*\*/', ''], ['/\*.*', ''], ['//.*', ''], ['(0x[0-9A-Fa-f]*)[UL]+', '\\1'], ] # Replace the string representations of the regular expressions in the # list with compiled versions. for l in CPP_to_Python_Eval_List: l[0] = re.compile(l[0]) # Wrap up all of the above into a handy function. def CPP_to_Python(s): """ Converts a C pre-processor expression into an equivalent Python expression that can be evaluated. """ s = CPP_to_Python_Ops_Expression.sub(CPP_to_Python_Ops_Sub, s) for expr, repl in CPP_to_Python_Eval_List: s = expr.sub(repl, s) return s del expr del l del override class FunctionEvaluator(object): """ Handles delayed evaluation of a #define function call. """ def __init__(self, name, args, expansion): """ Squirrels away the arguments and expansion value of a #define macro function for later evaluation when we must actually expand a value that uses it. """ self.name = name self.args = function_arg_separator.split(args) try: expansion = expansion.split('##') except AttributeError: pass self.expansion = expansion def __call__(self, *values): """ Evaluates the expansion of a #define macro function called with the specified values. """ if len(self.args) != len(values): raise ValueError("Incorrect number of arguments to `%s'" % self.name) # Create a dictionary that maps the macro arguments to the # corresponding values in this "call." We'll use this when we # eval() the expansion so that arguments will get expanded to # the right values. locals = {} for k, v in zip(self.args, values): locals[k] = v parts = [] for s in self.expansion: if not s in self.args: s = repr(s) parts.append(s) statement = ' + '.join(parts) return eval(statement, globals(), locals) # Find line continuations. line_continuations = re.compile('\\\\\r?\n') # Search for a "function call" macro on an expansion. Returns the # two-tuple of the "function" name itself, and a string containing the # arguments within the call parentheses. function_name = re.compile('(\S+)\(([^)]*)\)') # Split a string containing comma-separated function call arguments into # the separate arguments. function_arg_separator = re.compile(',\s*') class PreProcessor(object): """ The main workhorse class for handling C pre-processing. """ def __init__(self, current=os.curdir, cpppath=(), dict={}, all=0): global Table cpppath = tuple(cpppath) self.searchpath = { '"' : (current,) + cpppath, '<' : cpppath + (current,), } # Initialize our C preprocessor namespace for tracking the # values of #defined keywords. We use this namespace to look # for keywords on #ifdef/#ifndef lines, and to eval() the # expressions on #if/#elif lines (after massaging them from C to # Python). self.cpp_namespace = dict.copy() self.cpp_namespace['__dict__'] = self.cpp_namespace if all: self.do_include = self.all_include # For efficiency, a dispatch table maps each C preprocessor # directive (#if, #define, etc.) to the method that should be # called when we see it. We accomodate state changes (#if, # #ifdef, #ifndef) by pushing the current dispatch table on a # stack and changing what method gets called for each relevant # directive we might see next at this level (#else, #elif). # #endif will simply pop the stack. d = { 'scons_current_file' : self.scons_current_file } for op in Table.keys(): d[op] = getattr(self, 'do_' + op) self.default_table = d # Controlling methods. def tupleize(self, contents): """ Turns the contents of a file into a list of easily-processed tuples describing the CPP lines in the file. The first element of each tuple is the line's preprocessor directive (#if, #include, #define, etc., minus the initial '#'). The remaining elements are specific to the type of directive, as pulled apart by the regular expression. """ global CPP_Expression, Table contents = line_continuations.sub('', contents) cpp_tuples = CPP_Expression.findall(contents) return [(m[0],) + Table[m[0]].match(m[1]).groups() for m in cpp_tuples] def __call__(self, file): """ Pre-processes a file. This is the main public entry point. """ self.current_file = file return self.process_contents(self.read_file(file), file) def process_contents(self, contents, fname=None): """ Pre-processes a file contents. This is the main internal entry point. """ self.stack = [] self.dispatch_table = self.default_table.copy() self.current_file = fname self.tuples = self.tupleize(contents) self.initialize_result(fname) while self.tuples: t = self.tuples.pop(0) # Uncomment to see the list of tuples being processed (e.g., # to validate the CPP lines are being translated correctly). #print t self.dispatch_table[t[0]](t) return self.finalize_result(fname) # Dispatch table stack manipulation methods. def save(self): """ Pushes the current dispatch table on the stack and re-initializes the current dispatch table to the default. """ self.stack.append(self.dispatch_table) self.dispatch_table = self.default_table.copy() def restore(self): """ Pops the previous dispatch table off the stack and makes it the current one. """ try: self.dispatch_table = self.stack.pop() except IndexError: pass # Utility methods. def do_nothing(self, t): """ Null method for when we explicitly want the action for a specific preprocessor directive to do nothing. """ pass def scons_current_file(self, t): self.current_file = t[1] def eval_expression(self, t): """ Evaluates a C preprocessor expression. This is done by converting it to a Python equivalent and eval()ing it in the C preprocessor namespace we use to track #define values. """ t = CPP_to_Python(' '.join(t[1:])) try: return eval(t, self.cpp_namespace) except (NameError, TypeError): return 0 def initialize_result(self, fname): self.result = [fname] def finalize_result(self, fname): return self.result[1:] def find_include_file(self, t): """ Finds the #include file for a given preprocessor tuple. """ fname = t[2] for d in self.searchpath[t[1]]: if d == os.curdir: f = fname else: f = os.path.join(d, fname) if os.path.isfile(f): return f return None def read_file(self, file): return open(file).read() # Start and stop processing include lines. def start_handling_includes(self, t=None): """ Causes the PreProcessor object to start processing #import, #include and #include_next lines. This method will be called when a #if, #ifdef, #ifndef or #elif evaluates True, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated False. """ d = self.dispatch_table d['import'] = self.do_import d['include'] = self.do_include d['include_next'] = self.do_include def stop_handling_includes(self, t=None): """ Causes the PreProcessor object to stop processing #import, #include and #include_next lines. This method will be called when a #if, #ifdef, #ifndef or #elif evaluates False, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated True. """ d = self.dispatch_table d['import'] = self.do_nothing d['include'] = self.do_nothing d['include_next'] = self.do_nothing # Default methods for handling all of the preprocessor directives. # (Note that what actually gets called for a given directive at any # point in time is really controlled by the dispatch_table.) def _do_if_else_condition(self, condition): """ Common logic for evaluating the conditions on #if, #ifdef and #ifndef lines. """ self.save() d = self.dispatch_table if condition: self.start_handling_includes() d['elif'] = self.stop_handling_includes d['else'] = self.stop_handling_includes else: self.stop_handling_includes() d['elif'] = self.do_elif d['else'] = self.start_handling_includes def do_ifdef(self, t): """ Default handling of a #ifdef line. """ self._do_if_else_condition(t[1] in self.cpp_namespace) def do_ifndef(self, t): """ Default handling of a #ifndef line. """ self._do_if_else_condition(t[1] not in self.cpp_namespace) def do_if(self, t): """ Default handling of a #if line. """ self._do_if_else_condition(self.eval_expression(t)) def do_elif(self, t): """ Default handling of a #elif line. """ d = self.dispatch_table if self.eval_expression(t): self.start_handling_includes() d['elif'] = self.stop_handling_includes d['else'] = self.stop_handling_includes def do_else(self, t): """ Default handling of a #else line. """ pass def do_endif(self, t): """ Default handling of a #endif line. """ self.restore() def do_define(self, t): """ Default handling of a #define line. """ _, name, args, expansion = t try: expansion = int(expansion) except (TypeError, ValueError): pass if args: evaluator = FunctionEvaluator(name, args[1:-1], expansion) self.cpp_namespace[name] = evaluator else: self.cpp_namespace[name] = expansion def do_undef(self, t): """ Default handling of a #undef line. """ try: del self.cpp_namespace[t[1]] except KeyError: pass def do_import(self, t): """ Default handling of a #import line. """ # XXX finish this -- maybe borrow/share logic from do_include()...? pass def do_include(self, t): """ Default handling of a #include line. """ t = self.resolve_include(t) include_file = self.find_include_file(t) if include_file: #print "include_file =", include_file self.result.append(include_file) contents = self.read_file(include_file) new_tuples = [('scons_current_file', include_file)] + \ self.tupleize(contents) + \ [('scons_current_file', self.current_file)] self.tuples[:] = new_tuples + self.tuples # Date: Tue, 22 Nov 2005 20:26:09 -0500 # From: Stefan Seefeld <seefeld@sympatico.ca> # # By the way, #include_next is not the same as #include. The difference # being that #include_next starts its search in the path following the # path that let to the including file. In other words, if your system # include paths are ['/foo', '/bar'], and you are looking at a header # '/foo/baz.h', it might issue an '#include_next <baz.h>' which would # correctly resolve to '/bar/baz.h' (if that exists), but *not* see # '/foo/baz.h' again. See http://www.delorie.com/gnu/docs/gcc/cpp_11.html # for more reasoning. # # I have no idea in what context 'import' might be used. # XXX is #include_next really the same as #include ? do_include_next = do_include # Utility methods for handling resolution of include files. def resolve_include(self, t): """Resolve a tuple-ized #include line. This handles recursive expansion of values without "" or <> surrounding the name until an initial " or < is found, to handle #include FILE where FILE is a #define somewhere else. """ s = t[1] while not s[0] in '<"': #print "s =", s try: s = self.cpp_namespace[s] except KeyError: m = function_name.search(s) s = self.cpp_namespace[m.group(1)] if callable(s): args = function_arg_separator.split(m.group(2)) s = s(*args) if not s: return None return (t[0], s[0], s[1:-1]) def all_include(self, t): """ """ self.result.append(self.resolve_include(t)) class DumbPreProcessor(PreProcessor): """A preprocessor that ignores all #if/#elif/#else/#endif directives and just reports back *all* of the #include files (like the classic SCons scanner did). This is functionally equivalent to using a regular expression to find all of the #include lines, only slower. It exists mainly as an example of how the main PreProcessor class can be sub-classed to tailor its behavior. """ def __init__(self, *args, **kw): PreProcessor.__init__(self, *args, **kw) d = self.default_table for func in ['if', 'elif', 'else', 'endif', 'ifdef', 'ifndef']: d[func] = d[func] = self.do_nothing del __revision__ # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Platform.darwin Platform-specific initialization for Mac OS X systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/darwin.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix import os def generate(env): posix.generate(env) env['SHLIBSUFFIX'] = '.dylib' # put macports paths at front to override Apple's versions, fink path is after # For now let people who want Macports or Fink tools specify it! # env['ENV']['PATH'] = '/opt/local/bin:/opt/local/sbin:' + env['ENV']['PATH'] + ':/sw/bin' # Store extra system paths in env['ENV']['PATHOSX'] filelist = ['/etc/paths',] # make sure this works on Macs with Tiger or earlier try: dirlist = os.listdir('/etc/paths.d') except: dirlist = [] for file in dirlist: filelist.append('/etc/paths.d/'+file) for file in filelist: if os.path.isfile(file): f = open(file, 'r') lines = f.readlines() for line in lines: if line: env.AppendENVPath('PATHOSX', line.strip('\n')) f.close() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.os2 Platform-specific initialization for OS/2 systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/os2.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import win32 def generate(env): if 'ENV' not in env: env['ENV'] = {} env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = '$LIBPREFIX' env['LIBSUFFIXES'] = [ '$LIBSUFFIX', '$SHLIBSUFFIX' ] env['HOST_OS'] = 'os2' env['HOST_ARCH'] = win32.get_architecture().arch # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Platform.aix Platform-specific initialization for IBM AIX systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/aix.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import posix def get_xlc(env, xlc=None, xlc_r=None, packages=[]): # Use the AIX package installer tool lslpp to figure out where a # given xl* compiler is installed and what version it is. xlcPath = None xlcVersion = None if xlc is None: xlc = env.get('CC', 'xlc') if xlc_r is None: xlc_r = xlc + '_r' for package in packages: cmd = "lslpp -fc " + package + " 2>/dev/null | egrep '" + xlc + "([^-_a-zA-Z0-9].*)?$'" line = os.popen(cmd).readline() if line: v, p = line.split(':')[1:3] xlcVersion = v.split()[1] xlcPath = p.split()[0] xlcPath = xlcPath[:xlcPath.rindex('/')] break return (xlcPath, xlc, xlc_r, xlcVersion) def generate(env): posix.generate(env) #Based on AIX 5.2: ARG_MAX=24576 - 3000 for environment expansion env['MAXLINELENGTH'] = 21576 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.win32 Platform-specific initialization for Win32 systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/win32.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import sys import tempfile from SCons.Platform.posix import exitvalmap from SCons.Platform import TempFileMunge import SCons.Util try: import msvcrt import win32api import win32con msvcrt.get_osfhandle win32api.SetHandleInformation win32con.HANDLE_FLAG_INHERIT except ImportError: parallel_msg = \ "you do not seem to have the pywin32 extensions installed;\n" + \ "\tparallel (-j) builds may not work reliably with open Python files." except AttributeError: parallel_msg = \ "your pywin32 extensions do not support file handle operations;\n" + \ "\tparallel (-j) builds may not work reliably with open Python files." else: parallel_msg = None import builtins _builtin_file = builtins.file _builtin_open = builtins.open class _scons_file(_builtin_file): def __init__(self, *args, **kw): _builtin_file.__init__(self, *args, **kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(self.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) def _scons_open(*args, **kw): fp = _builtin_open(*args, **kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(fp.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) return fp builtins.file = _scons_file builtins.open = _scons_open # The upshot of all this is that, if you are using Python 1.5.2, # you had better have cmd or command.com in your PATH when you run # scons. def piped_spawn(sh, escape, cmd, args, env, stdout, stderr): # There is no direct way to do that in python. What we do # here should work for most cases: # In case stdout (stderr) is not redirected to a file, # we redirect it into a temporary file tmpFileStdout # (tmpFileStderr) and copy the contents of this file # to stdout (stderr) given in the argument if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 else: # one temporary file for stdout and stderr tmpFileStdout = os.path.normpath(tempfile.mktemp()) tmpFileStderr = os.path.normpath(tempfile.mktemp()) # check if output is redirected stdoutRedirected = 0 stderrRedirected = 0 for arg in args: # are there more possibilities to redirect stdout ? if (arg.find( ">", 0, 1 ) != -1 or arg.find( "1>", 0, 2 ) != -1): stdoutRedirected = 1 # are there more possibilities to redirect stderr ? if arg.find( "2>", 0, 2 ) != -1: stderrRedirected = 1 # redirect output of non-redirected streams to our tempfiles if stdoutRedirected == 0: args.append(">" + str(tmpFileStdout)) if stderrRedirected == 0: args.append("2>" + str(tmpFileStderr)) # actually do the spawn try: args = [sh, '/C', escape(' '.join(args)) ] ret = os.spawnve(os.P_WAIT, sh, args, env) except OSError, e: # catch any error try: ret = exitvalmap[e[0]] except KeyError: sys.stderr.write("scons: unknown OSError exception code %d - %s: %s\n" % (e[0], cmd, e[1])) if stderr is not None: stderr.write("scons: %s: %s\n" % (cmd, e[1])) # copy child output from tempfiles to our streams # and do clean up stuff if stdout is not None and stdoutRedirected == 0: try: stdout.write(open( tmpFileStdout, "r" ).read()) os.remove( tmpFileStdout ) except (IOError, OSError): pass if stderr is not None and stderrRedirected == 0: try: stderr.write(open( tmpFileStderr, "r" ).read()) os.remove( tmpFileStderr ) except (IOError, OSError): pass return ret def exec_spawn(l, env): try: result = os.spawnve(os.P_WAIT, l[0], l, env) except OSError, e: try: result = exitvalmap[e[0]] sys.stderr.write("scons: %s: %s\n" % (l[0], e[1])) except KeyError: result = 127 if len(l) > 2: if len(l[2]) < 1000: command = ' '.join(l[0:3]) else: command = l[0] else: command = l[0] sys.stderr.write("scons: unknown OSError exception code %d - '%s': %s\n" % (e[0], command, e[1])) return result def spawn(sh, escape, cmd, args, env): if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 return exec_spawn([sh, '/C', escape(' '.join(args))], env) # Windows does not allow special characters in file names anyway, so no # need for a complex escape function, we will just quote the arg, except # that "cmd /c" requires that if an argument ends with a backslash it # needs to be escaped so as not to interfere with closing double quote # that we add. def escape(x): if x[-1] == '\\': x = x + '\\' return '"' + x + '"' # Get the windows system directory name _system_root = None def get_system_root(): global _system_root if _system_root is not None: return _system_root # A resonable default if we can't read the registry val = os.environ.get('SystemRoot', "C:\\WINDOWS") if SCons.Util.can_read_reg: try: # Look for Windows NT system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows NT\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') except SCons.Util.RegError: try: # Okay, try the Windows 9x system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') except KeyboardInterrupt: raise except: pass _system_root = val return val # Get the location of the program files directory def get_program_files_dir(): # Now see if we can look in the registry... val = '' if SCons.Util.can_read_reg: try: # Look for Windows Program Files directory k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir') except SCons.Util.RegError: val = '' pass if val == '': # A reasonable default if we can't read the registry # (Actually, it's pretty reasonable even if we can :-) val = os.path.join(os.path.dirname(get_system_root()),"Program Files") return val # Determine which windows CPU were running on. class ArchDefinition(object): """ A class for defining architecture-specific settings and logic. """ def __init__(self, arch, synonyms=[]): self.arch = arch self.synonyms = synonyms SupportedArchitectureList = [ ArchDefinition( 'x86', ['i386', 'i486', 'i586', 'i686'], ), ArchDefinition( 'x86_64', ['AMD64', 'amd64', 'em64t', 'EM64T', 'x86_64'], ), ArchDefinition( 'ia64', ['IA64'], ), ] SupportedArchitectureMap = {} for a in SupportedArchitectureList: SupportedArchitectureMap[a.arch] = a for s in a.synonyms: SupportedArchitectureMap[s] = a def get_architecture(arch=None): """Returns the definition for the specified architecture string. If no string is specified, the system default is returned (as defined by the PROCESSOR_ARCHITEW6432 or PROCESSOR_ARCHITECTURE environment variables). """ if arch is None: arch = os.environ.get('PROCESSOR_ARCHITEW6432') if not arch: arch = os.environ.get('PROCESSOR_ARCHITECTURE') return SupportedArchitectureMap.get(arch, ArchDefinition('', [''])) def generate(env): # Attempt to find cmd.exe (for WinNT/2k/XP) or # command.com for Win9x cmd_interp = '' # First see if we can look in the registry... if SCons.Util.can_read_reg: try: # Look for Windows NT system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows NT\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') cmd_interp = os.path.join(val, 'System32\\cmd.exe') except SCons.Util.RegError: try: # Okay, try the Windows 9x system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') cmd_interp = os.path.join(val, 'command.com') except KeyboardInterrupt: raise except: pass # For the special case of not having access to the registry, we # use a temporary path and pathext to attempt to find the command # interpreter. If we fail, we try to find the interpreter through # the env's PATH. The problem with that is that it might not # contain an ENV and a PATH. if not cmd_interp: systemroot = get_system_root() tmp_path = systemroot + os.pathsep + \ os.path.join(systemroot,'System32') tmp_pathext = '.com;.exe;.bat;.cmd' if 'PATHEXT' in os.environ: tmp_pathext = os.environ['PATHEXT'] cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext) if not cmd_interp: cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext) if not cmd_interp: cmd_interp = env.Detect('cmd') if not cmd_interp: cmd_interp = env.Detect('command') if 'ENV' not in env: env['ENV'] = {} # Import things from the external environment to the construction # environment's ENV. This is a potential slippery slope, because we # *don't* want to make builds dependent on the user's environment by # default. We're doing this for SystemRoot, though, because it's # needed for anything that uses sockets, and seldom changes, and # for SystemDrive because it's related. # # Weigh the impact carefully before adding other variables to this list. import_env = [ 'SystemDrive', 'SystemRoot', 'TEMP', 'TMP' ] for var in import_env: v = os.environ.get(var) if v: env['ENV'][var] = v if 'COMSPEC' not in env['ENV']: v = os.environ.get("COMSPEC") if v: env['ENV']['COMSPEC'] = v env.AppendENVPath('PATH', get_system_root() + '\System32') env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD' env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = [ '$LIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ] env['PSPAWN'] = piped_spawn env['SPAWN'] = spawn env['SHELL'] = cmd_interp env['TEMPFILE'] = TempFileMunge env['TEMPFILEPREFIX'] = '@' env['MAXLINELENGTH'] = 2048 env['ESCAPE'] = escape env['HOST_OS'] = 'win32' env['HOST_ARCH'] = get_architecture().arch # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.cygwin Platform-specific initialization for Cygwin systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/cygwin.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix from SCons.Platform import TempFileMunge def generate(env): posix.generate(env) env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = [ '$LIBPREFIX', '$SHLIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX', '$SHLIBSUFFIX' ] env['TEMPFILE'] = TempFileMunge env['TEMPFILEPREFIX'] = '@' env['MAXLINELENGTH'] = 2048 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.irix Platform-specific initialization for SGI IRIX systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/irix.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix def generate(env): posix.generate(env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Platform.hpux Platform-specific initialization for HP-UX systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/hpux.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix def generate(env): posix.generate(env) #Based on HP-UX11i: ARG_MAX=2048000 - 3000 for environment expansion env['MAXLINELENGTH'] = 2045000 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.posix Platform-specific initialization for POSIX (Linux, UNIX, etc.) systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/posix.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import errno import os import os.path import subprocess import sys import select import SCons.Util from SCons.Platform import TempFileMunge exitvalmap = { 2 : 127, 13 : 126, } def escape(arg): "escape shell special characters" slash = '\\' special = '"$()' arg = arg.replace(slash, slash+slash) for c in special: arg = arg.replace(c, slash+c) return '"' + arg + '"' def exec_system(l, env): stat = os.system(' '.join(l)) if stat & 0xff: return stat | 0x80 return stat >> 8 def exec_spawnvpe(l, env): stat = os.spawnvpe(os.P_WAIT, l[0], l, env) # os.spawnvpe() returns the actual exit code, not the encoding # returned by os.waitpid() or os.system(). return stat def exec_fork(l, env): pid = os.fork() if not pid: # Child process. exitval = 127 try: os.execvpe(l[0], l, env) except OSError, e: exitval = exitvalmap.get(e[0], e[0]) sys.stderr.write("scons: %s: %s\n" % (l[0], e[1])) os._exit(exitval) else: # Parent process. pid, stat = os.waitpid(pid, 0) if stat & 0xff: return stat | 0x80 return stat >> 8 def _get_env_command(sh, escape, cmd, args, env): s = ' '.join(args) if env: l = ['env', '-'] + \ [escape(t[0])+'='+escape(t[1]) for t in env.items()] + \ [sh, '-c', escape(s)] s = ' '.join(l) return s def env_spawn(sh, escape, cmd, args, env): return exec_system([_get_env_command( sh, escape, cmd, args, env)], env) def spawnvpe_spawn(sh, escape, cmd, args, env): return exec_spawnvpe([sh, '-c', ' '.join(args)], env) def fork_spawn(sh, escape, cmd, args, env): return exec_fork([sh, '-c', ' '.join(args)], env) def process_cmd_output(cmd_stdout, cmd_stderr, stdout, stderr): stdout_eof = stderr_eof = 0 while not (stdout_eof and stderr_eof): try: (i,o,e) = select.select([cmd_stdout, cmd_stderr], [], []) if cmd_stdout in i: str = cmd_stdout.read() if len(str) == 0: stdout_eof = 1 elif stdout is not None: stdout.write(str) if cmd_stderr in i: str = cmd_stderr.read() if len(str) == 0: #sys.__stderr__.write( "stderr_eof=1\n" ) stderr_eof = 1 else: #sys.__stderr__.write( "str(stderr) = %s\n" % str ) stderr.write(str) except select.error, (_errno, _strerror): if _errno != errno.EINTR: raise def exec_popen3(l, env, stdout, stderr): proc = subprocess.Popen(' '.join(l), stdout=stdout, stderr=stderr, shell=True) stat = proc.wait() if stat & 0xff: return stat | 0x80 return stat >> 8 def exec_piped_fork(l, env, stdout, stderr): # spawn using fork / exec and providing a pipe for the command's # stdout / stderr stream if stdout != stderr: (rFdOut, wFdOut) = os.pipe() (rFdErr, wFdErr) = os.pipe() else: (rFdOut, wFdOut) = os.pipe() rFdErr = rFdOut wFdErr = wFdOut # do the fork pid = os.fork() if not pid: # Child process os.close( rFdOut ) if rFdOut != rFdErr: os.close( rFdErr ) os.dup2( wFdOut, 1 ) # is there some symbolic way to do that ? os.dup2( wFdErr, 2 ) os.close( wFdOut ) if stdout != stderr: os.close( wFdErr ) exitval = 127 try: os.execvpe(l[0], l, env) except OSError, e: exitval = exitvalmap.get(e[0], e[0]) stderr.write("scons: %s: %s\n" % (l[0], e[1])) os._exit(exitval) else: # Parent process pid, stat = os.waitpid(pid, 0) os.close( wFdOut ) if stdout != stderr: os.close( wFdErr ) childOut = os.fdopen( rFdOut ) if stdout != stderr: childErr = os.fdopen( rFdErr ) else: childErr = childOut process_cmd_output(childOut, childErr, stdout, stderr) os.close( rFdOut ) if stdout != stderr: os.close( rFdErr ) if stat & 0xff: return stat | 0x80 return stat >> 8 def piped_env_spawn(sh, escape, cmd, args, env, stdout, stderr): # spawn using Popen3 combined with the env command # the command name and the command's stdout is written to stdout # the command's stderr is written to stderr return exec_popen3([_get_env_command(sh, escape, cmd, args, env)], env, stdout, stderr) def piped_fork_spawn(sh, escape, cmd, args, env, stdout, stderr): # spawn using fork / exec and providing a pipe for the command's # stdout / stderr stream return exec_piped_fork([sh, '-c', ' '.join(args)], env, stdout, stderr) def generate(env): # If os.spawnvpe() exists, we use it to spawn commands. Otherwise # if the env utility exists, we use os.system() to spawn commands, # finally we fall back on os.fork()/os.exec(). # # os.spawnvpe() is prefered because it is the most efficient. But # for Python versions without it, os.system() is prefered because it # is claimed that it works better with threads (i.e. -j) and is more # efficient than forking Python. # # NB: Other people on the scons-users mailing list have claimed that # os.fork()/os.exec() works better than os.system(). There may just # not be a default that works best for all users. if 'spawnvpe' in os.__dict__: spawn = spawnvpe_spawn elif env.Detect('env'): spawn = env_spawn else: spawn = fork_spawn if env.Detect('env'): pspawn = piped_env_spawn else: pspawn = piped_fork_spawn if 'ENV' not in env: env['ENV'] = {} env['ENV']['PATH'] = '/usr/local/bin:/opt/bin:/bin:/usr/bin' env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.o' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' env['SHLIBPREFIX'] = '$LIBPREFIX' env['SHLIBSUFFIX'] = '.so' env['LIBPREFIXES'] = [ '$LIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX', '$SHLIBSUFFIX' ] env['PSPAWN'] = pspawn env['SPAWN'] = spawn env['SHELL'] = 'sh' env['ESCAPE'] = escape env['TEMPFILE'] = TempFileMunge env['TEMPFILEPREFIX'] = '@' #Based on LINUX: ARG_MAX=ARG_MAX=131072 - 3000 for environment expansion #Note: specific platforms might rise or lower this value env['MAXLINELENGTH'] = 128072 # This platform supports RPATH specifications. env['__RPATH'] = '$_RPATH' # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform SCons platform selection. This looks for modules that define a callable object that can modify a construction environment as appropriate for a given platform. Note that we take a more simplistic view of "platform" than Python does. We're looking for a single string that determines a set of tool-independent variables with which to initialize a construction environment. Consequently, we'll examine both sys.platform and os.name (and anything else that might come in to play) in order to return some specification which is unique enough for our purposes. Note that because this subsysem just *selects* a callable that can modify a construction environment, it's possible for people to define their own "platform specification" in an arbitrary callable function. No one needs to use or tie in to this subsystem in order to roll their own platform definition. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import imp import os import sys import tempfile import SCons.Errors import SCons.Subst import SCons.Tool def platform_default(): """Return the platform string for our execution environment. The returned value should map to one of the SCons/Platform/*.py files. Since we're architecture independent, though, we don't care about the machine architecture. """ osname = os.name if osname == 'java': osname = os._osType if osname == 'posix': if sys.platform == 'cygwin': return 'cygwin' elif sys.platform.find('irix') != -1: return 'irix' elif sys.platform.find('sunos') != -1: return 'sunos' elif sys.platform.find('hp-ux') != -1: return 'hpux' elif sys.platform.find('aix') != -1: return 'aix' elif sys.platform.find('darwin') != -1: return 'darwin' else: return 'posix' elif os.name == 'os2': return 'os2' else: return sys.platform def platform_module(name = platform_default()): """Return the imported module for the platform. This looks for a module name that matches the specified argument. If the name is unspecified, we fetch the appropriate default for our execution environment. """ full_name = 'SCons.Platform.' + name if full_name not in sys.modules: if os.name == 'java': eval(full_name) else: try: file, path, desc = imp.find_module(name, sys.modules['SCons.Platform'].__path__) try: mod = imp.load_module(full_name, file, path, desc) finally: if file: file.close() except ImportError: try: import zipimport importer = zipimport.zipimporter( sys.modules['SCons.Platform'].__path__[0] ) mod = importer.load_module(full_name) except ImportError: raise SCons.Errors.UserError("No platform named '%s'" % name) setattr(SCons.Platform, name, mod) return sys.modules[full_name] def DefaultToolList(platform, env): """Select a default tool list for the specified platform. """ return SCons.Tool.tool_list(platform, env) class PlatformSpec(object): def __init__(self, name, generate): self.name = name self.generate = generate def __call__(self, *args, **kw): return self.generate(*args, **kw) def __str__(self): return self.name class TempFileMunge(object): """A callable class. You can set an Environment variable to this, then call it with a string argument, then it will perform temporary file substitution on it. This is used to circumvent the long command line limitation. Example usage: env["TEMPFILE"] = TempFileMunge env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}" By default, the name of the temporary file used begins with a prefix of '@'. This may be configred for other tool chains by setting '$TEMPFILEPREFIX'. env["TEMPFILEPREFIX"] = '-@' # diab compiler env["TEMPFILEPREFIX"] = '-via' # arm tool chain """ def __init__(self, cmd): self.cmd = cmd def __call__(self, target, source, env, for_signature): if for_signature: # If we're being called for signature calculation, it's # because we're being called by the string expansion in # Subst.py, which has the logic to strip any $( $) that # may be in the command line we squirreled away. So we # just return the raw command line and let the upper # string substitution layers do their thing. return self.cmd # Now we're actually being called because someone is actually # going to try to execute the command, so we have to do our # own expansion. cmd = env.subst_list(self.cmd, SCons.Subst.SUBST_CMD, target, source)[0] try: maxline = int(env.subst('$MAXLINELENGTH')) except ValueError: maxline = 2048 length = 0 for c in cmd: length += len(c) if length <= maxline: return self.cmd # We do a normpath because mktemp() has what appears to be # a bug in Windows that will use a forward slash as a path # delimiter. Windows's link mistakes that for a command line # switch and barfs. # # We use the .lnk suffix for the benefit of the Phar Lap # linkloc linker, which likes to append an .lnk suffix if # none is given. (fd, tmp) = tempfile.mkstemp('.lnk', text=True) native_tmp = SCons.Util.get_native_path(os.path.normpath(tmp)) if env['SHELL'] and env['SHELL'] == 'sh': # The sh shell will try to escape the backslashes in the # path, so unescape them. native_tmp = native_tmp.replace('\\', r'\\\\') # In Cygwin, we want to use rm to delete the temporary # file, because del does not exist in the sh shell. rm = env.Detect('rm') or 'del' else: # Don't use 'rm' if the shell is not sh, because rm won't # work with the Windows shells (cmd.exe or command.com) or # Windows path names. rm = 'del' prefix = env.subst('$TEMPFILEPREFIX') if not prefix: prefix = '@' args = list(map(SCons.Subst.quote_spaces, cmd[1:])) os.write(fd, " ".join(args) + "\n") os.close(fd) # XXX Using the SCons.Action.print_actions value directly # like this is bogus, but expedient. This class should # really be rewritten as an Action that defines the # __call__() and strfunction() methods and lets the # normal action-execution logic handle whether or not to # print/execute the action. The problem, though, is all # of that is decided before we execute this method as # part of expanding the $TEMPFILE construction variable. # Consequently, refactoring this will have to wait until # we get more flexible with allowing Actions to exist # independently and get strung together arbitrarily like # Ant tasks. In the meantime, it's going to be more # user-friendly to not let obsession with architectural # purity get in the way of just being helpful, so we'll # reach into SCons.Action directly. if SCons.Action.print_actions: print("Using tempfile "+native_tmp+" for command line:\n"+ str(cmd[0]) + " " + " ".join(args)) return [ cmd[0], prefix + native_tmp + '\n' + rm, native_tmp ] def Platform(name = platform_default()): """Select a canned Platform specification. """ module = platform_module(name) spec = PlatformSpec(name, module.generate) return spec # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Platform.sunos Platform-specific initialization for Sun systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Platform/sunos.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix def generate(env): posix.generate(env) # Based on sunSparc 8:32bit # ARG_MAX=1048320 - 3000 for environment expansion env['MAXLINELENGTH'] = 1045320 env['PKGINFO'] = 'pkginfo' env['PKGCHK'] = '/usr/sbin/pkgchk' env['ENV']['PATH'] = env['ENV']['PATH'] + ':/opt/SUNWspro/bin:/usr/ccs/bin' # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Builder Builder object subsystem. A Builder object is a callable that encapsulates information about how to execute actions to create a target Node (file) from source Nodes (files), and how to create those dependencies for tracking. The main entry point here is the Builder() factory method. This provides a procedural interface that creates the right underlying Builder object based on the keyword arguments supplied and the types of the arguments. The goal is for this external interface to be simple enough that the vast majority of users can create new Builders as necessary to support building new types of files in their configurations, without having to dive any deeper into this subsystem. The base class here is BuilderBase. This is a concrete base class which does, in fact, represent the Builder objects that we (or users) create. There is also a proxy that looks like a Builder: CompositeBuilder This proxies for a Builder with an action that is actually a dictionary that knows how to map file suffixes to a specific action. This is so that we can invoke different actions (compilers, compile options) for different flavors of source files. Builders and their proxies have the following public interface methods used by other modules: __call__() THE public interface. Calling a Builder object (with the use of internal helper methods) sets up the target and source dependencies, appropriate mapping to a specific action, and the environment manipulation necessary for overridden construction variable. This also takes care of warning about possible mistakes in keyword arguments. add_emitter() Adds an emitter for a specific file suffix, used by some Tool modules to specify that (for example) a yacc invocation on a .y can create a .h *and* a .c file. add_action() Adds an action for a specific file suffix, heavily used by Tool modules to add their specific action(s) for turning a source file into an object file to the global static and shared object file Builders. There are the following methods for internal use within this module: _execute() The internal method that handles the heavily lifting when a Builder is called. This is used so that the __call__() methods can set up warning about possible mistakes in keyword-argument overrides, and *then* execute all of the steps necessary so that the warnings only occur once. get_name() Returns the Builder's name within a specific Environment, primarily used to try to return helpful information in error messages. adjust_suffix() get_prefix() get_suffix() get_src_suffix() set_src_suffix() Miscellaneous stuff for handling the prefix and suffix manipulation we use in turning source file names into target file names. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Builder.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import collections import SCons.Action from SCons.Debug import logInstanceCreation from SCons.Errors import InternalError, UserError import SCons.Executor import SCons.Memoize import SCons.Node import SCons.Node.FS import SCons.Util import SCons.Warnings class _Null(object): pass _null = _Null def match_splitext(path, suffixes = []): if suffixes: matchsuf = [S for S in suffixes if path[-len(S):] == S] if matchsuf: suf = max([(len(_f),_f) for _f in matchsuf])[1] return [path[:-len(suf)], path[-len(suf):]] return SCons.Util.splitext(path) class DictCmdGenerator(SCons.Util.Selector): """This is a callable class that can be used as a command generator function. It holds on to a dictionary mapping file suffixes to Actions. It uses that dictionary to return the proper action based on the file suffix of the source file.""" def __init__(self, dict=None, source_ext_match=1): SCons.Util.Selector.__init__(self, dict) self.source_ext_match = source_ext_match def src_suffixes(self): return list(self.keys()) def add_action(self, suffix, action): """Add a suffix-action pair to the mapping. """ self[suffix] = action def __call__(self, target, source, env, for_signature): if not source: return [] if self.source_ext_match: suffixes = self.src_suffixes() ext = None for src in map(str, source): my_ext = match_splitext(src, suffixes)[1] if ext and my_ext != ext: raise UserError("While building `%s' from `%s': Cannot build multiple sources with different extensions: %s, %s" % (repr(list(map(str, target))), src, ext, my_ext)) ext = my_ext else: ext = match_splitext(str(source[0]), self.src_suffixes())[1] if not ext: #return ext raise UserError("While building `%s': " "Cannot deduce file extension from source files: %s" % (repr(list(map(str, target))), repr(list(map(str, source))))) try: ret = SCons.Util.Selector.__call__(self, env, source, ext) except KeyError, e: raise UserError("Ambiguous suffixes after environment substitution: %s == %s == %s" % (e.args[0], e.args[1], e.args[2])) if ret is None: raise UserError("While building `%s' from `%s': Don't know how to build from a source file with suffix `%s'. Expected a suffix in this list: %s." % \ (repr(list(map(str, target))), repr(list(map(str, source))), ext, repr(list(self.keys())))) return ret class CallableSelector(SCons.Util.Selector): """A callable dictionary that will, in turn, call the value it finds if it can.""" def __call__(self, env, source): value = SCons.Util.Selector.__call__(self, env, source) if callable(value): value = value(env, source) return value class DictEmitter(SCons.Util.Selector): """A callable dictionary that maps file suffixes to emitters. When called, it finds the right emitter in its dictionary for the suffix of the first source file, and calls that emitter to get the right lists of targets and sources to return. If there's no emitter for the suffix in its dictionary, the original target and source are returned. """ def __call__(self, target, source, env): emitter = SCons.Util.Selector.__call__(self, env, source) if emitter: target, source = emitter(target, source, env) return (target, source) class ListEmitter(collections.UserList): """A callable list of emitters that calls each in sequence, returning the result. """ def __call__(self, target, source, env): for e in self.data: target, source = e(target, source, env) return (target, source) # These are a common errors when calling a Builder; # they are similar to the 'target' and 'source' keyword args to builders, # so we issue warnings when we see them. The warnings can, of course, # be disabled. misleading_keywords = { 'targets' : 'target', 'sources' : 'source', } class OverrideWarner(collections.UserDict): """A class for warning about keyword arguments that we use as overrides in a Builder call. This class exists to handle the fact that a single Builder call can actually invoke multiple builders. This class only emits the warnings once, no matter how many Builders are invoked. """ def __init__(self, dict): collections.UserDict.__init__(self, dict) if __debug__: logInstanceCreation(self, 'Builder.OverrideWarner') self.already_warned = None def warn(self): if self.already_warned: return for k in self.keys(): if k in misleading_keywords: alt = misleading_keywords[k] msg = "Did you mean to use `%s' instead of `%s'?" % (alt, k) SCons.Warnings.warn(SCons.Warnings.MisleadingKeywordsWarning, msg) self.already_warned = 1 def Builder(**kw): """A factory for builder objects.""" composite = None if 'generator' in kw: if 'action' in kw: raise UserError("You must not specify both an action and a generator.") kw['action'] = SCons.Action.CommandGeneratorAction(kw['generator'], {}) del kw['generator'] elif 'action' in kw: source_ext_match = kw.get('source_ext_match', 1) if 'source_ext_match' in kw: del kw['source_ext_match'] if SCons.Util.is_Dict(kw['action']): composite = DictCmdGenerator(kw['action'], source_ext_match) kw['action'] = SCons.Action.CommandGeneratorAction(composite, {}) kw['src_suffix'] = composite.src_suffixes() else: kw['action'] = SCons.Action.Action(kw['action']) if 'emitter' in kw: emitter = kw['emitter'] if SCons.Util.is_String(emitter): # This allows users to pass in an Environment # variable reference (like "$FOO") as an emitter. # We will look in that Environment variable for # a callable to use as the actual emitter. var = SCons.Util.get_environment_var(emitter) if not var: raise UserError("Supplied emitter '%s' does not appear to refer to an Environment variable" % emitter) kw['emitter'] = EmitterProxy(var) elif SCons.Util.is_Dict(emitter): kw['emitter'] = DictEmitter(emitter) elif SCons.Util.is_List(emitter): kw['emitter'] = ListEmitter(emitter) result = BuilderBase(**kw) if not composite is None: result = CompositeBuilder(result, composite) return result def _node_errors(builder, env, tlist, slist): """Validate that the lists of target and source nodes are legal for this builder and environment. Raise errors or issue warnings as appropriate. """ # First, figure out if there are any errors in the way the targets # were specified. for t in tlist: if t.side_effect: raise UserError("Multiple ways to build the same target were specified for: %s" % t) if t.has_explicit_builder(): if not t.env is None and not t.env is env: action = t.builder.action t_contents = action.get_contents(tlist, slist, t.env) contents = action.get_contents(tlist, slist, env) if t_contents == contents: msg = "Two different environments were specified for target %s,\n\tbut they appear to have the same action: %s" % (t, action.genstring(tlist, slist, t.env)) SCons.Warnings.warn(SCons.Warnings.DuplicateEnvironmentWarning, msg) else: msg = "Two environments with different actions were specified for the same target: %s" % t raise UserError(msg) if builder.multi: if t.builder != builder: msg = "Two different builders (%s and %s) were specified for the same target: %s" % (t.builder.get_name(env), builder.get_name(env), t) raise UserError(msg) # TODO(batch): list constructed each time! if t.get_executor().get_all_targets() != tlist: msg = "Two different target lists have a target in common: %s (from %s and from %s)" % (t, list(map(str, t.get_executor().get_all_targets())), list(map(str, tlist))) raise UserError(msg) elif t.sources != slist: msg = "Multiple ways to build the same target were specified for: %s (from %s and from %s)" % (t, list(map(str, t.sources)), list(map(str, slist))) raise UserError(msg) if builder.single_source: if len(slist) > 1: raise UserError("More than one source given for single-source builder: targets=%s sources=%s" % (list(map(str,tlist)), list(map(str,slist)))) class EmitterProxy(object): """This is a callable class that can act as a Builder emitter. It holds on to a string that is a key into an Environment dictionary, and will look there at actual build time to see if it holds a callable. If so, we will call that as the actual emitter.""" def __init__(self, var): self.var = SCons.Util.to_String(var) def __call__(self, target, source, env): emitter = self.var # Recursively substitute the variable. # We can't use env.subst() because it deals only # in strings. Maybe we should change that? while SCons.Util.is_String(emitter) and emitter in env: emitter = env[emitter] if callable(emitter): target, source = emitter(target, source, env) elif SCons.Util.is_List(emitter): for e in emitter: target, source = e(target, source, env) return (target, source) def __cmp__(self, other): return cmp(self.var, other.var) class BuilderBase(object): """Base class for Builders, objects that create output nodes (files) from input nodes (files). """ if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass memoizer_counters = [] def __init__(self, action = None, prefix = '', suffix = '', src_suffix = '', target_factory = None, source_factory = None, target_scanner = None, source_scanner = None, emitter = None, multi = 0, env = None, single_source = 0, name = None, chdir = _null, is_explicit = 1, src_builder = None, ensure_suffix = False, **overrides): if __debug__: logInstanceCreation(self, 'Builder.BuilderBase') self._memo = {} self.action = action self.multi = multi if SCons.Util.is_Dict(prefix): prefix = CallableSelector(prefix) self.prefix = prefix if SCons.Util.is_Dict(suffix): suffix = CallableSelector(suffix) self.env = env self.single_source = single_source if 'overrides' in overrides: SCons.Warnings.warn(SCons.Warnings.DeprecatedBuilderKeywordsWarning, "The \"overrides\" keyword to Builder() creation has been deprecated;\n" +\ "\tspecify the items as keyword arguments to the Builder() call instead.") overrides.update(overrides['overrides']) del overrides['overrides'] if 'scanner' in overrides: SCons.Warnings.warn(SCons.Warnings.DeprecatedBuilderKeywordsWarning, "The \"scanner\" keyword to Builder() creation has been deprecated;\n" "\tuse: source_scanner or target_scanner as appropriate.") del overrides['scanner'] self.overrides = overrides self.set_suffix(suffix) self.set_src_suffix(src_suffix) self.ensure_suffix = ensure_suffix self.target_factory = target_factory self.source_factory = source_factory self.target_scanner = target_scanner self.source_scanner = source_scanner self.emitter = emitter # Optional Builder name should only be used for Builders # that don't get attached to construction environments. if name: self.name = name self.executor_kw = {} if not chdir is _null: self.executor_kw['chdir'] = chdir self.is_explicit = is_explicit if src_builder is None: src_builder = [] elif not SCons.Util.is_List(src_builder): src_builder = [ src_builder ] self.src_builder = src_builder def __nonzero__(self): raise InternalError("Do not test for the Node.builder attribute directly; use Node.has_builder() instead") def get_name(self, env): """Attempts to get the name of the Builder. Look at the BUILDERS variable of env, expecting it to be a dictionary containing this Builder, and return the key of the dictionary. If there's no key, then return a directly-configured name (if there is one) or the name of the class (by default).""" try: index = list(env['BUILDERS'].values()).index(self) return list(env['BUILDERS'].keys())[index] except (AttributeError, KeyError, TypeError, ValueError): try: return self.name except AttributeError: return str(self.__class__) def __cmp__(self, other): return cmp(self.__dict__, other.__dict__) def splitext(self, path, env=None): if not env: env = self.env if env: suffixes = self.src_suffixes(env) else: suffixes = [] return match_splitext(path, suffixes) def _adjustixes(self, files, pre, suf, ensure_suffix=False): if not files: return [] result = [] if not SCons.Util.is_List(files): files = [files] for f in files: if SCons.Util.is_String(f): f = SCons.Util.adjustixes(f, pre, suf, ensure_suffix) result.append(f) return result def _create_nodes(self, env, target = None, source = None): """Create and return lists of target and source nodes. """ src_suf = self.get_src_suffix(env) target_factory = env.get_factory(self.target_factory) source_factory = env.get_factory(self.source_factory) source = self._adjustixes(source, None, src_suf) slist = env.arg2nodes(source, source_factory) pre = self.get_prefix(env, slist) suf = self.get_suffix(env, slist) if target is None: try: t_from_s = slist[0].target_from_source except AttributeError: raise UserError("Do not know how to create a target from source `%s'" % slist[0]) except IndexError: tlist = [] else: splitext = lambda S: self.splitext(S,env) tlist = [ t_from_s(pre, suf, splitext) ] else: target = self._adjustixes(target, pre, suf, self.ensure_suffix) tlist = env.arg2nodes(target, target_factory, target=target, source=source) if self.emitter: # The emitter is going to do str(node), but because we're # being called *from* a builder invocation, the new targets # don't yet have a builder set on them and will look like # source files. Fool the emitter's str() calls by setting # up a temporary builder on the new targets. new_targets = [] for t in tlist: if not t.is_derived(): t.builder_set(self) new_targets.append(t) orig_tlist = tlist[:] orig_slist = slist[:] target, source = self.emitter(target=tlist, source=slist, env=env) # Now delete the temporary builders that we attached to any # new targets, so that _node_errors() doesn't do weird stuff # to them because it thinks they already have builders. for t in new_targets: if t.builder is self: # Only delete the temporary builder if the emitter # didn't change it on us. t.builder_set(None) # Have to call arg2nodes yet again, since it is legal for # emitters to spit out strings as well as Node instances. tlist = env.arg2nodes(target, target_factory, target=orig_tlist, source=orig_slist) slist = env.arg2nodes(source, source_factory, target=orig_tlist, source=orig_slist) return tlist, slist def _execute(self, env, target, source, overwarn={}, executor_kw={}): # We now assume that target and source are lists or None. if self.src_builder: source = self.src_builder_sources(env, source, overwarn) if self.single_source and len(source) > 1 and target is None: result = [] if target is None: target = [None]*len(source) for tgt, src in zip(target, source): if not tgt is None: tgt = [tgt] if not src is None: src = [src] result.extend(self._execute(env, tgt, src, overwarn)) return SCons.Node.NodeList(result) overwarn.warn() tlist, slist = self._create_nodes(env, target, source) # Check for errors with the specified target/source lists. _node_errors(self, env, tlist, slist) # The targets are fine, so find or make the appropriate Executor to # build this particular list of targets from this particular list of # sources. executor = None key = None if self.multi: try: executor = tlist[0].get_executor(create = 0) except (AttributeError, IndexError): pass else: executor.add_sources(slist) if executor is None: if not self.action: fmt = "Builder %s must have an action to build %s." raise UserError(fmt % (self.get_name(env or self.env), list(map(str,tlist)))) key = self.action.batch_key(env or self.env, tlist, slist) if key: try: executor = SCons.Executor.GetBatchExecutor(key) except KeyError: pass else: executor.add_batch(tlist, slist) if executor is None: executor = SCons.Executor.Executor(self.action, env, [], tlist, slist, executor_kw) if key: SCons.Executor.AddBatchExecutor(key, executor) # Now set up the relevant information in the target Nodes themselves. for t in tlist: t.cwd = env.fs.getcwd() t.builder_set(self) t.env_set(env) t.add_source(slist) t.set_executor(executor) t.set_explicit(self.is_explicit) return SCons.Node.NodeList(tlist) def __call__(self, env, target=None, source=None, chdir=_null, **kw): # We now assume that target and source are lists or None. # The caller (typically Environment.BuilderWrapper) is # responsible for converting any scalar values to lists. if chdir is _null: ekw = self.executor_kw else: ekw = self.executor_kw.copy() ekw['chdir'] = chdir if kw: if 'srcdir' in kw: def prependDirIfRelative(f, srcdir=kw['srcdir']): import os.path if SCons.Util.is_String(f) and not os.path.isabs(f): f = os.path.join(srcdir, f) return f if not SCons.Util.is_List(source): source = [source] source = list(map(prependDirIfRelative, source)) del kw['srcdir'] if self.overrides: env_kw = self.overrides.copy() env_kw.update(kw) else: env_kw = kw else: env_kw = self.overrides env = env.Override(env_kw) return self._execute(env, target, source, OverrideWarner(kw), ekw) def adjust_suffix(self, suff): if suff and not suff[0] in [ '.', '_', '$' ]: return '.' + suff return suff def get_prefix(self, env, sources=[]): prefix = self.prefix if callable(prefix): prefix = prefix(env, sources) return env.subst(prefix) def set_suffix(self, suffix): if not callable(suffix): suffix = self.adjust_suffix(suffix) self.suffix = suffix def get_suffix(self, env, sources=[]): suffix = self.suffix if callable(suffix): suffix = suffix(env, sources) return env.subst(suffix) def set_src_suffix(self, src_suffix): if not src_suffix: src_suffix = [] elif not SCons.Util.is_List(src_suffix): src_suffix = [ src_suffix ] self.src_suffix = [callable(suf) and suf or self.adjust_suffix(suf) for suf in src_suffix] def get_src_suffix(self, env): """Get the first src_suffix in the list of src_suffixes.""" ret = self.src_suffixes(env) if not ret: return '' return ret[0] def add_emitter(self, suffix, emitter): """Add a suffix-emitter mapping to this Builder. This assumes that emitter has been initialized with an appropriate dictionary type, and will throw a TypeError if not, so the caller is responsible for knowing that this is an appropriate method to call for the Builder in question. """ self.emitter[suffix] = emitter def add_src_builder(self, builder): """ Add a new Builder to the list of src_builders. This requires wiping out cached values so that the computed lists of source suffixes get re-calculated. """ self._memo = {} self.src_builder.append(builder) def _get_sdict(self, env): """ Returns a dictionary mapping all of the source suffixes of all src_builders of this Builder to the underlying Builder that should be called first. This dictionary is used for each target specified, so we save a lot of extra computation by memoizing it for each construction environment. Note that this is re-computed each time, not cached, because there might be changes to one of our source Builders (or one of their source Builders, and so on, and so on...) that we can't "see." The underlying methods we call cache their computed values, though, so we hope repeatedly aggregating them into a dictionary like this won't be too big a hit. We may need to look for a better way to do this if performance data show this has turned into a significant bottleneck. """ sdict = {} for bld in self.get_src_builders(env): for suf in bld.src_suffixes(env): sdict[suf] = bld return sdict def src_builder_sources(self, env, source, overwarn={}): sdict = self._get_sdict(env) src_suffixes = self.src_suffixes(env) lengths = list(set(map(len, src_suffixes))) def match_src_suffix(name, src_suffixes=src_suffixes, lengths=lengths): node_suffixes = [name[-l:] for l in lengths] for suf in src_suffixes: if suf in node_suffixes: return suf return None result = [] for s in SCons.Util.flatten(source): if SCons.Util.is_String(s): match_suffix = match_src_suffix(env.subst(s)) if not match_suffix and not '.' in s: src_suf = self.get_src_suffix(env) s = self._adjustixes(s, None, src_suf)[0] else: match_suffix = match_src_suffix(s.name) if match_suffix: try: bld = sdict[match_suffix] except KeyError: result.append(s) else: tlist = bld._execute(env, None, [s], overwarn) # If the subsidiary Builder returned more than one # target, then filter out any sources that this # Builder isn't capable of building. if len(tlist) > 1: tlist = [t for t in tlist if match_src_suffix(t.name)] result.extend(tlist) else: result.append(s) source_factory = env.get_factory(self.source_factory) return env.arg2nodes(result, source_factory) def _get_src_builders_key(self, env): return id(env) memoizer_counters.append(SCons.Memoize.CountDict('get_src_builders', _get_src_builders_key)) def get_src_builders(self, env): """ Returns the list of source Builders for this Builder. This exists mainly to look up Builders referenced as strings in the 'BUILDER' variable of the construction environment and cache the result. """ memo_key = id(env) try: memo_dict = self._memo['get_src_builders'] except KeyError: memo_dict = {} self._memo['get_src_builders'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass builders = [] for bld in self.src_builder: if SCons.Util.is_String(bld): try: bld = env['BUILDERS'][bld] except KeyError: continue builders.append(bld) memo_dict[memo_key] = builders return builders def _subst_src_suffixes_key(self, env): return id(env) memoizer_counters.append(SCons.Memoize.CountDict('subst_src_suffixes', _subst_src_suffixes_key)) def subst_src_suffixes(self, env): """ The suffix list may contain construction variable expansions, so we have to evaluate the individual strings. To avoid doing this over and over, we memoize the results for each construction environment. """ memo_key = id(env) try: memo_dict = self._memo['subst_src_suffixes'] except KeyError: memo_dict = {} self._memo['subst_src_suffixes'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass suffixes = [env.subst(x) for x in self.src_suffix] memo_dict[memo_key] = suffixes return suffixes def src_suffixes(self, env): """ Returns the list of source suffixes for all src_builders of this Builder. This is essentially a recursive descent of the src_builder "tree." (This value isn't cached because there may be changes in a src_builder many levels deep that we can't see.) """ sdict = {} suffixes = self.subst_src_suffixes(env) for s in suffixes: sdict[s] = 1 for builder in self.get_src_builders(env): for s in builder.src_suffixes(env): if s not in sdict: sdict[s] = 1 suffixes.append(s) return suffixes class CompositeBuilder(SCons.Util.Proxy): """A Builder Proxy whose main purpose is to always have a DictCmdGenerator as its action, and to provide access to the DictCmdGenerator's add_action() method. """ def __init__(self, builder, cmdgen): if __debug__: logInstanceCreation(self, 'Builder.CompositeBuilder') SCons.Util.Proxy.__init__(self, builder) # cmdgen should always be an instance of DictCmdGenerator. self.cmdgen = cmdgen self.builder = builder __call__ = SCons.Util.Delegate('__call__') def add_action(self, suffix, action): self.cmdgen.add_action(suffix, action) self.set_src_suffix(self.cmdgen.src_suffixes()) def is_a_Builder(obj): """"Returns True iff the specified obj is one of our Builder classes. The test is complicated a bit by the fact that CompositeBuilder is a proxy, not a subclass of BuilderBase. """ return (isinstance(obj, BuilderBase) or isinstance(obj, CompositeBuilder) or callable(obj)) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Environment Base class for 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 """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Environment.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import copy import os import sys import re import shlex from collections import UserDict import SCons.Action import SCons.Builder from SCons.Debug import logInstanceCreation import SCons.Defaults import SCons.Errors import SCons.Memoize import SCons.Node import SCons.Node.Alias import SCons.Node.FS import SCons.Node.Python import SCons.Platform import SCons.SConf import SCons.SConsign import SCons.Subst import SCons.Tool import SCons.Util import SCons.Warnings class _Null(object): pass _null = _Null _warn_copy_deprecated = True _warn_source_signatures_deprecated = True _warn_target_signatures_deprecated = True CleanTargets = {} CalculatorArgs = {} semi_deepcopy = SCons.Util.semi_deepcopy semi_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.UserError def alias_builder(env, target, source): pass AliasBuilder = 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') def apply_tools(env, tools, toolpath): # Store the toolpath in the Environment. if toolpath is not None: env['toolpath'] = toolpath if not tools: return # Filter out null tools from the list. for tool in [_f for _f in tools if _f]: if SCons.Util.is_List(tool) or isinstance(tool, tuple): toolname = tool[0] toolargs = tool[1] # should be a dict of kw args tool = 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', ] def copy_non_reserved_keywords(dict): result = semi_deepcopy(dict) for k in result.keys(): if k in reserved_construction_var_names: msg = "Ignoring attempt to set reserved variable `$%s'" SCons.Warnings.warn(SCons.Warnings.ReservedVariableWarning, msg % k) del result[k] return result def _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] = value msg = "`$%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] for k in bd.keys(): del bd[k] except KeyError: bd = BuilderDict(kwbd, env) env._dict[key] = bd for k, v in value.items(): if not SCons.Builder.is_a_Builder(v): raise SCons.Errors.UserError('%s is not a Builder.' % repr(v)) bd.update(value) def _del_SCANNERS(env, key): del env._dict[key] env.scanner_map_delete() def _set_SCANNERS(env, key, value): env._dict[key] = value env.scanner_map_delete() def _delete_duplicates(l, keep_last): """Delete duplicates from a sequence, keeping the first or last.""" seen={} result=[] if keep_last: # reverse in & out, then keep first l.reverse() for i in l: try: if i not in seen: result.append(i) seen[i]=1 except TypeError: # probably unhashable. Just keep it. result.append(i) if keep_last: result.reverse() return result # 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. class MethodWrapper(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): if name is None: name = method.__name__ self.object = object self.method = method self.name = name setattr(self.object, name, self) def __call__(self, *args, **kwargs): nargs = (self.object,) + args return self.method(*nargs, **kwargs) def clone(self, new_object): """ Returns an object that re-binds the underlying "method" to the specified new object. """ return self.__class__(new_object, self.method, self.name) class BuilderWrapper(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): if source is _null: source = target target = None if target is not None and not SCons.Util.is_List(target): target = [target] if source is not None and not SCons.Util.is_List(source): source = [source] return MethodWrapper.__call__(self, target, source, *args, **kw) def __repr__(self): return '<BuilderWrapper %s>' % repr(self.name) def __str__(self): return self.__repr__() def __getattr__(self, name): if name == 'env': return self.object elif name == 'builder': return self.method else: raise AttributeError(name) def __setattr__(self, name, value): if name == 'env': self.object = value elif name == 'builder': self.method = value else: 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) class BuilderDict(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 = env UserDict.__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 builder raise TypeError( 'cannot semi_deepcopy a BuilderDict' ) def __setitem__(self, item, val): try: method = getattr(self.env, item).method except AttributeError: pass else: 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) def update(self, dict): for i, v in dict.items(): self.__setitem__(i, v) _is_valid_var = re.compile(r'[_a-zA-Z]\w*$') def is_valid_construction_var(varstr): """Return if the specified string is a legitimate construction variable. """ return _is_valid_var.match(varstr) class SubstitutionEnvironment(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.) """ if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass def __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_ans self.lookup_list = SCons.Node.arg2nodes_lookups self._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_SCANNERS self._special_set = {} for key in reserved_construction_var_names: self._special_set[key] = _set_reserved for key in future_reserved_construction_var_names: self._special_set[key] = _set_future_reserved self._special_set['BUILDERS'] = _set_BUILDERS self._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): return cmp(self._dict, other._dict) def __delitem__(self, key): special = self._special_del.get(key) if special: special(self, key) else: del self._dict[key] def __getitem__(self, key): return self._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). if key in self._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. if key not in self._dict \ and not _is_valid_var.match(key): raise SCons.Errors.UserError("Illegal construction variable `%s'" % key) self._dict[key] = value def get(self, key, default=None): """Emulates the get() method of dictionaries.""" return self._dict.get(key, default) def has_key(self, key): return key in self._dict def __contains__(self, key): return self._dict.__contains__(key) def items(self): return list(self._dict.items()) def arg2nodes(self, args, node_factory=_null, lookup_list=_null, **kw): if node_factory is _null: node_factory = self.fs.File if lookup_list is _null: lookup_list = self.lookup_list if not args: return [] args = SCons.Util.flatten(args) nodes = [] for v in args: if SCons.Util.is_String(v): n = None for l in lookup_list: n = l(v) if n is not None: break if n is not None: if SCons.Util.is_String(n): # n = self.subst(n, raw=1, **kw) kw['raw'] = 1 n = self.subst(n, **kw) if node_factory: n = node_factory(n) if SCons.Util.is_List(n): nodes.extend(n) else: nodes.append(n) elif node_factory: # v = node_factory(self.subst(v, raw=1, **kw)) kw['raw'] = 1 v = node_factory(self.subst(v, **kw)) if SCons.Util.is_List(v): nodes.extend(v) else: nodes.append(v) else: nodes.append(v) return nodes def gvars(self): return self._dict def lvars(self): return {} def subst(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__'] = self if executor: lvars.update(executor.get_lvars()) return SCons.Subst.scons_subst(string, self, raw, target, source, gvars, lvars, conv) def subst_kw(self, kw, raw=0, target=None, source=None): nkw = {} for k, v in kw.items(): k = self.subst(k, raw, target, source) if SCons.Util.is_String(v): v = self.subst(v, raw, target, source) nkw[k] = v return nkw def subst_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__'] = self if executor: lvars.update(executor.get_lvars()) return SCons.Subst.scons_subst_list(string, self, raw, target, source, gvars, lvars, conv) def subst_path(self, path, target=None, source=None): """Substitute a path list, turning EntryProxies into Nodes and leaving Nodes (and other objects) as-is.""" if not SCons.Util.is_List(path): path = [path] def s(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.get except AttributeError: obj = SCons.Util.to_String_for_subst(obj) else: obj = get() return obj r = [] for p in path: if SCons.Util.is_String(p): p = self.subst(p, target=target, source=source, conv=s) if SCons.Util.is_List(p): if len(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) return r subst_target_source = subst def backtick(self, command): import subprocess # common arguments kw = { '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 shell if not SCons.Util.is_List(command): kw['shell'] = True # run constructed command p = SCons.Action._subproc(self, command, **kw) out,err = p.communicate() status = p.wait() if err: sys.stderr.write(unicode(err)) if status: raise OSError("'%s' exited %d" % (command, status)) return out def AddMethod(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) def RemoveMethod(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 = [dm for dm in self.added_methods if not dm.method is function] def Override(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. """ if not overrides: return self o = copy_non_reserved_keywords(overrides) if not o: return self overrides = {} merges = None for key, value in o.items(): if key == 'parse_flags': merges = value else: overrides[key] = SCons.Subst.scons_subst_once(value, self, key) env = OverrideEnvironment(self, overrides) if merges: env.MergeFlags(merges) return env def ParseFlags(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' : [], } def do_parse(arg): # if arg is a sequence, recurse with each element if not arg: return if not SCons.Util.is_String(arg): for t in arg: do_parse(t) return # if arg is a command, execute it if arg[0] == '!': arg = self.backtick(arg[1:]) # utility function to deal with -D option def append_define(name, dict = dict): t = name.split('=') if len(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=foo params = shlex.split(arg) append_next_arg_to = None # for multi-word args for arg in params: if append_next_arg_to: if append_next_arg_to == 'CPPDEFINES': append_define(arg) elif append_next_arg_to == '-include': t = ('-include', self.fs.File(arg)) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-isysroot': t = ('-isysroot', arg) dict['CCFLAGS'].append(t) dict['LINKFLAGS'].append(t) elif append_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 = None elif not arg[0] in ['-', '+']: dict['LIBS'].append(self.fs.File(arg)) elif arg == '-dylib_file': dict['LINKFLAGS'].append(arg) append_next_arg_to = 'LINKFLAGS' elif arg[:2] == '-L': if arg[2:]: dict['LIBPATH'].append(arg[2:]) else: append_next_arg_to = 'LIBPATH' elif arg[:2] == '-l': if arg[2:]: dict['LIBS'].append(arg[2:]) else: append_next_arg_to = 'LIBS' elif arg[:2] == '-I': if arg[2:]: dict['CPPPATH'].append(arg[2:]) else: append_next_arg_to = 'CPPPATH' elif arg[:4] == '-Wa,': dict['ASFLAGS'].append(arg[4:]) dict['CCFLAGS'].append(arg) elif arg[:4] == '-Wl,': if arg[:11] == '-Wl,-rpath=': dict['RPATH'].append(arg[11:]) elif arg[:7] == '-Wl,-R,': dict['RPATH'].append(arg[7:]) elif arg[:6] == '-Wl,-R': dict['RPATH'].append(arg[6:]) else: dict['LINKFLAGS'].append(arg) elif arg[:4] == '-Wp,': dict['CPPFLAGS'].append(arg) elif arg[:2] == '-D': if arg[2:]: append_define(arg[2:]) else: append_next_arg_to = 'CPPDEFINES' elif arg == '-framework': append_next_arg_to = 'FRAMEWORKS' elif arg[:14] == '-frameworkdir=': dict['FRAMEWORKPATH'].append(arg[14:]) elif arg[:2] == '-F': if arg[2:]: dict['FRAMEWORKPATH'].append(arg[2:]) else: append_next_arg_to = 'FRAMEWORKPATH' elif arg in ['-mno-cygwin', '-pthread', '-openmp', '-fopenmp']: dict['CCFLAGS'].append(arg) dict['LINKFLAGS'].append(arg) elif arg == '-mwindows': dict['LINKFLAGS'].append(arg) elif arg[:5] == '-std=': if arg[5:].find('++')!=-1: key='CXXFLAGS' else: key='CFLAGS' dict[key].append(arg) elif arg[0] == '+': dict['CCFLAGS'].append(arg) dict['LINKFLAGS'].append(arg) elif arg in ['-include', '-isysroot', '-arch']: append_next_arg_to = arg else: dict['CCFLAGS'].append(arg) for arg in flags: do_parse(arg) return dict def MergeFlags(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. """ if dict is None: dict = self if not SCons.Util.is_Dict(args): args = self.ParseFlags(args) if not unique: self.Append(**args) return self for key, value in args.items(): if not value: continue try: orig = self[key] except KeyError: orig = value else: if not orig: orig = value elif value: # 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 + value except (KeyError, TypeError): try: add_to_orig = orig.append except AttributeError: value.insert(0, orig) orig = value else: add_to_orig(value) t = [] if key[-4:] == 'PATH': ### keep left-most occurence for v in orig: if v not in t: t.append(v) else: ### keep right-most occurence orig.reverse() for v in orig: if v not in t: t.insert(0, v) self[key] = t return self # 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) def default_decide_source(dependency, target, prev_ni): f = SCons.Defaults.DefaultEnvironment().decide_source return f(dependency, target, prev_ni) def default_decide_target(dependency, target, prev_ni): f = SCons.Defaults.DefaultEnvironment().decide_target return f(dependency, target, prev_ni) def default_copy_from_cache(src, dst): f = SCons.Defaults.DefaultEnvironment().copy_from_cache return f(src, dst) class Base(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_ans self.lookup_list = SCons.Node.arg2nodes_lookups self._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_target self.decide_source = default_decide_source self.copy_from_cache = default_copy_from_cache self._dict['BUILDERS'] = BuilderDict(self._dict['BUILDERS'], self) if platform is None: platform = self._dict.get('PLATFORM', None) if platform is None: platform = SCons.Platform.Platform() if SCons.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' in kw: # Backwards compatibility: they may stll be using the # old "options" keyword. variables = kw['options'] del kw['options'] self.Replace(**kw) keys = list(kw.keys()) if variables: keys = keys + list(variables.keys()) variables.Update(self) save = {} for k in keys: try: save[k] = self._dict[k] except KeyError: # No value may have been set if they tried to pass in a # reserved variable name like TARGETS. pass SCons.Tool.Initializers(self) if tools is None: tools = self._dict.get('TOOLS', None) if tools is None: 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. for key, val in save.items(): self._dict[key] = val # Finally, apply any flags to be merged in if parse_flags: self.MergeFlags(parse_flags) ####################################################################### # Utility methods that are primarily for internal use by SCons. # These begin with lower-case letters. ####################################################################### def get_builder(self, name): """Fetch the builder with the specified name from the environment. """ try: return self._dict['BUILDERS'][name] except KeyError: return None def get_CacheDir(self): try: path = self._CacheDir_path except AttributeError: path = SCons.Defaults.DefaultEnvironment()._CacheDir_path try: if path == self._last_CacheDir_path: return self._last_CacheDir except AttributeError: pass cd = SCons.CacheDir.CacheDir(path) self._last_CacheDir_path = path self._last_CacheDir = cd return cd def get_factory(self, factory, default='File'): """Return a factory function for creating Nodes for this construction environment. """ name = default try: is_node = issubclass(factory, SCons.Node.FS.Base) except TypeError: # The specified factory isn't a Node itself--it's # most likely None, or possibly a callable. pass else: if is_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__ except AttributeError: pass else: factory = None if not factory: # 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) return factory memoizer_counters.append(SCons.Memoize.CountValue('_gsm')) def _gsm(self): try: return self._memo['_gsm'] except KeyError: pass result = {} try: scanners = self._dict['SCANNERS'] except KeyError: pass else: # 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. if not SCons.Util.is_List(scanners): scanners = [scanners] else: scanners = scanners[:] # copy so reverse() doesn't mod original scanners.reverse() for scanner in scanners: for k in scanner.get_skeys(self): if k and self['PLATFORM'] == 'win32': k = k.lower() result[k] = scanner self._memo['_gsm'] = result return result def get_scanner(self, skey): """Find the appropriate scanner given a key (usually a file suffix). """ if skey and self['PLATFORM'] == 'win32': skey = skey.lower() return self._gsm().get(skey) def scanner_map_delete(self, kw=None): """Delete the cached scanner map (if we need to). """ try: del self._memo['_gsm'] except KeyError: pass def _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) def get_src_sig_type(self): try: return self.src_sig_type except AttributeError: t = SCons.Defaults.DefaultEnvironment().src_sig_type self.src_sig_type = t return t def get_tgt_sig_type(self): try: return self.tgt_sig_type except AttributeError: t = SCons.Defaults.DefaultEnvironment().tgt_sig_type self.tgt_sig_type = t return t ####################################################################### # 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. ####################################################################### def Append(self, **kw): """Append values to existing construction variables in an Environment. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.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: if key == 'CPPDEFINES' and SCons.Util.is_String(self._dict[key]): self._dict[key] = [self._dict[key]] orig = self._dict[key] except KeyError: # No existing variable in the environment, so just set # it to the new value. if key == 'CPPDEFINES' and SCons.Util.is_String(val): self._dict[key] = [val] else: self._dict[key] = val else: 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.update except AttributeError: 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 + val except (KeyError, TypeError): try: # Check if the original is a list. add_to_orig = orig.append except AttributeError: # 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. if orig: val.insert(0, orig) self._dict[key] = val else: # The original is a list, so append the new # value to it (if there's a value to append). if val: add_to_orig(val) else: # The original looks like a dictionary, so update it # based on what we think the value looks like. if SCons.Util.is_List(val): if key == 'CPPDEFINES': orig = orig.items() orig += val self._dict[key] = orig else: for v in val: orig[v] = None else: try: update_dict(val) except (AttributeError, TypeError, ValueError): if SCons.Util.is_Dict(val): for k, v in val.items(): orig[k] = v else: orig[val] = None self.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): if not SCons.Util.is_String(path): # typically a Dir path = str(path) if path and path[0] == '#': path = str(self.fs.Dir(path)) return path def AppendENVPath(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 = '' if envname in self._dict and name in self._dict[envname]: orig = self._dict[envname][name] nv = SCons.Util.AppendPath(orig, newpath, sep, delete_existing, canonicalize=self._canonicalize) if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv def AppendUnique(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) for key, val in kw.items(): if SCons.Util.is_List(val): val = _delete_duplicates(val, delete_existing) if key not in self._dict or self._dict[key] in ('', None): self._dict[key] = val elif SCons.Util.is_Dict(self._dict[key]) and \ SCons.Util.is_Dict(val): self._dict[key].update(val) elif SCons.Util.is_List(val): dk = self._dict[key] if key == 'CPPDEFINES': tmp = [] for i in val: if SCons.Util.is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif SCons.Util.is_Tuple(i): tmp.append(i) else: tmp.append((i,)) val = tmp if SCons.Util.is_Dict(dk): dk = dk.items() elif SCons.Util.is_String(dk): dk = [(dk,)] else: tmp = [] for i in dk: if SCons.Util.is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif SCons.Util.is_Tuple(i): tmp.append(i) else: tmp.append((i,)) dk = tmp else: if not SCons.Util.is_List(dk): dk = [dk] if delete_existing: dk = [x for x in dk if x not in val] else: val = [x for x in val if x not in dk] self._dict[key] = dk + val else: dk = self._dict[key] if SCons.Util.is_List(dk): if key == 'CPPDEFINES': tmp = [] for i in dk: if SCons.Util.is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif SCons.Util.is_Tuple(i): tmp.append(i) else: tmp.append((i,)) dk = tmp if SCons.Util.is_Dict(val): val = val.items() elif SCons.Util.is_String(val): val = [(val,)] if delete_existing: dk = filter(lambda x, val=val: x not in val, dk) self._dict[key] = dk + val else: dk = [x for x in dk if x not in val] self._dict[key] = dk + val else: # By elimination, val is not a list. Since dk is a # list, wrap val in a list first. if delete_existing: dk = filter(lambda x, val=val: x not in val, dk) self._dict[key] = dk + [val] else: if not val in dk: self._dict[key] = dk + [val] else: if key == 'CPPDEFINES': if SCons.Util.is_String(dk): dk = [dk] elif SCons.Util.is_Dict(dk): dk = dk.items() if SCons.Util.is_String(val): if val in dk: val = [] else: val = [val] elif SCons.Util.is_Dict(val): tmp = [] for i,j in val.iteritems(): if j is not None: tmp.append((i,j)) else: tmp.append(i) val = tmp if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = dk + val self.scanner_map_delete(kw) def Clone(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'] except KeyError: pass clone = copy.copy(self) # BUILDERS is not safe to do a simple copy clone._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 = [] for mw in self.added_methods: if mw == 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 variables kw = copy_non_reserved_keywords(kw) new = {} for key, value in kw.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 them clone.Replace(**new) # Finally, apply any flags to be merged in if parse_flags: clone.MergeFlags(parse_flags) if __debug__: logInstanceCreation(self, 'Environment.EnvironmentClone') return clone def Copy(self, *args, **kw): global _warn_copy_deprecated if _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 = False return self.Clone(*args, **kw) def _changed_build(self, dependency, target, prev_ni): if dependency.changed_state(target, prev_ni): return 1 return self.decide_source(dependency, target, prev_ni) def _changed_content(self, dependency, target, prev_ni): return dependency.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() if type == 'source': return target_env.decide_source(dependency, target, prev_ni) else: return target_env.decide_target(dependency, target, prev_ni) def _changed_timestamp_then_content(self, dependency, target, prev_ni): return dependency.changed_timestamp_then_content(target, prev_ni) def _changed_timestamp_newer(self, dependency, target, prev_ni): return dependency.changed_timestamp_newer(target, prev_ni) def _changed_timestamp_match(self, dependency, target, prev_ni): return dependency.changed_timestamp_match(target, prev_ni) def _copy_from_cache(self, src, dst): return self.fs.copy(src, dst) def _copy2_from_cache(self, src, dst): return self.fs.copy2(src, dst) def Decider(self, function): copy_function = self._copy2_from_cache if function in ('MD5', 'content'): if not SCons.Util.md5: raise UserError("MD5 signatures are not available in this version of Python.") function = self._changed_content elif function == 'MD5-timestamp': function = self._changed_timestamp_then_content elif function in ('timestamp-newer', 'make'): function = self._changed_timestamp_newer copy_function = self._copy_from_cache elif function == 'timestamp-match': function = self._changed_timestamp_match elif not callable(function): raise UserError("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 = function self.decide_source = function self.copy_from_cache = copy_function def Detect(self, progs): """Return the first available program in progs. """ if not SCons.Util.is_List(progs): progs = [ progs ] for prog in progs: path = self.WhereIs(prog) if path: return prog return None def Dictionary(self, *args): if not args: return self._dict dlist = [self._dict[x] for x in args] if len(dlist) == 1: dlist = dlist[0] return dlist def Dump(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. """ import pprint pp = pprint.PrettyPrinter(indent=2) if key: dict = self.Dictionary(key) else: dict = self.Dictionary() return pp.pformat(dict) def FindIxes(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) for path in paths: dir,name = os.path.split(str(path)) if name[:len(prefix)] == prefix and name[-len(suffix):] == suffix: return path def ParseConfig(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. """ if function is None: def parse_conf(env, cmd, unique=unique): return env.MergeFlags(cmd, unique) function = parse_conf if SCons.Util.is_List(command): command = ' '.join(command) command = self.subst(command) return function(self, self.backtick(command)) def ParseDepends(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') except IOError: if must_exist: raise return lines = SCons.Util.LogicalLines(fp).readlines() lines = [l for l in lines if l[0] != '#'] tdlist = [] for line in lines: 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. pass else: tdlist.append((target.split(), depends.split())) if only_one: targets = [] for td in tdlist: targets.extend(td[0]) if len(targets) > 1: raise SCons.Errors.UserError( "More than one dependency target found in `%s': %s" % (filename, targets)) for target, depends in tdlist: self.Depends(target, depends) def Platform(self, platform): platform = self.subst(platform) return SCons.Platform.Platform(platform)(self) def Prepend(self, **kw): """Prepend values to existing construction variables in an Environment. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.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] except KeyError: # No existing variable in the environment, so just set # it to the new value. self._dict[key] = val else: 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.update except AttributeError: 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 + orig except (KeyError, TypeError): try: # Check if the added value is a list. add_to_val = val.append except AttributeError: # 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). if val: orig.insert(0, val) else: # The added value is a list, so append # the original to it (if there's a value # to append). if orig: add_to_val(orig) self._dict[key] = val else: # The original looks like a dictionary, so update it # based on what we think the value looks like. if SCons.Util.is_List(val): for v in val: orig[v] = None else: try: update_dict(val) except (AttributeError, TypeError, ValueError): if SCons.Util.is_Dict(val): for k, v in val.items(): orig[k] = v else: orig[val] = None self.scanner_map_delete(kw) def PrependENVPath(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 = '' if envname in self._dict and name in self._dict[envname]: orig = self._dict[envname][name] nv = SCons.Util.PrependPath(orig, newpath, sep, delete_existing, canonicalize=self._canonicalize) if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv def PrependUnique(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) for key, val in kw.items(): if SCons.Util.is_List(val): val = _delete_duplicates(val, not delete_existing) if key not in self._dict or self._dict[key] in ('', None): self._dict[key] = val elif SCons.Util.is_Dict(self._dict[key]) and \ SCons.Util.is_Dict(val): self._dict[key].update(val) elif SCons.Util.is_List(val): dk = self._dict[key] if not SCons.Util.is_List(dk): dk = [dk] if delete_existing: dk = [x for x in dk if x not in val] else: val = [x for x in val if x not in dk] self._dict[key] = val + dk else: dk = self._dict[key] if SCons.Util.is_List(dk): # By elimination, val is not a list. Since dk is a # list, wrap val in a list first. if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = [val] + dk else: if not val in dk: self._dict[key] = [val] + dk else: if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = val + dk self.scanner_map_delete(kw) def Replace(self, **kw): """Replace existing construction variables in an Environment with new construction variables and/or values. """ try: kwbd = kw['BUILDERS'] except KeyError: pass else: kwbd = BuilderDict(kwbd,self) del kw['BUILDERS'] self.__setitem__('BUILDERS', kwbd) kw = copy_non_reserved_keywords(kw) self._update(semi_deepcopy(kw)) self.scanner_map_delete(kw) def ReplaceIxes(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)) if name[:len(old_prefix)] == old_prefix: name = name[len(old_prefix):] if name[-len(old_suffix):] == old_suffix: name = name[:-len(old_suffix)] return os.path.join(dir, new_prefix+name+new_suffix) def SetDefault(self, **kw): for k in kw.keys(): if k in self._dict: del kw[k] self.Replace(**kw) def _find_toolpath_dir(self, tp): return self.fs.Dir(self.subst(tp)).srcnode().abspath def Tool(self, tool, toolpath=None, **kw): if SCons.Util.is_String(tool): tool = self.subst(tool) if toolpath is None: toolpath = self.get('toolpath', []) toolpath = list(map(self._find_toolpath_dir, toolpath)) tool = SCons.Tool.Tool(tool, toolpath, **kw) tool(self) def WhereIs(self, prog, path=None, pathext=None, reject=[]): """Find prog in the path. """ if path is None: try: path = self['ENV']['PATH'] except KeyError: pass elif SCons.Util.is_String(path): path = self.subst(path) if pathext is None: try: pathext = self['ENV']['PATHEXT'] except KeyError: pass elif SCons.Util.is_String(pathext): pathext = self.subst(pathext) prog = self.subst(prog) path = SCons.Util.WhereIs(prog, path, pathext, reject) if path: return path return None ####################################################################### # 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. ####################################################################### def Action(self, *args, **kw): def subst_string(a, self=self): if SCons.Util.is_String(a): a = self.subst(a) return a nargs = list(map(subst_string, args)) nkw = self.subst_kw(kw) return SCons.Action.Action(*nargs, **nkw) def AddPreAction(self, files, action): nodes = self.arg2nodes(files, self.fs.Entry) action = SCons.Action.Action(action) uniq = {} for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 for executor in uniq.keys(): executor.add_pre_action(action) return nodes def AddPostAction(self, files, action): nodes = self.arg2nodes(files, self.fs.Entry) action = SCons.Action.Action(action) uniq = {} for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 for executor in uniq.keys(): executor.add_post_action(action) return nodes def Alias(self, target, source=[], action=None, **kw): tlist = self.arg2nodes(target, self.ans.Alias) if not SCons.Util.is_List(source): source = [source] source = [_f for _f in source if _f] if not action: if not source: # 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." return tlist # No action, but there are sources. Re-call all the target # builders to add the sources to each target. result = [] for t in tlist: bld = t.get_builder(AliasBuilder) result.extend(bld(self, t, source)) return result nkw = 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 = [] for t in tlist: # 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() if b is None or b is AliasBuilder: b = bld else: nkw['action'] = b.action + action b = SCons.Builder.Builder(**nkw) t.convert() result.extend(b(self, t, t.sources + source)) return result def AlwaysBuild(self, *targets): tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_always_build() return tlist def BuildDir(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' in kw: kw['variant_dir'] = kw['build_dir'] del kw['build_dir'] return self.VariantDir(*args, **kw) def Builder(self, **kw): nkw = self.subst_kw(kw) return SCons.Builder.Builder(**nkw) def CacheDir(self, path): import SCons.CacheDir if path is not None: path = self.subst(path) self._CacheDir_path = path def Clean(self, targets, files): global CleanTargets tlist = self.arg2nodes(targets, self.fs.Entry) flist = self.arg2nodes(files, self.fs.Entry) for t in tlist: try: CleanTargets[t].extend(flist) except KeyError: CleanTargets[t] = flist def Configure(self, *args, **kw): nargs = [self] if args: nargs = nargs + self.subst_list(args)[0] nkw = self.subst_kw(kw) nkw['_depth'] = kw.get('_depth', 0) + 1 try: nkw['custom_tests'] = self.subst_kw(nkw['custom_tests']) except KeyError: pass return SCons.SConf.SConf(*nargs, **nkw) def Command(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'] except KeyError: pass else: del kw['source_scanner'] bld = SCons.Builder.Builder(**bkw) return bld(self, target, source, **kw) def Depends(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) for t in tlist: t.add_dependency(dlist) return tlist def Dir(self, name, *args, **kw): """ """ s = self.subst(name) if SCons.Util.is_Sequence(s): result=[] for e in s: result.append(self.fs.Dir(e, *args, **kw)) return result return self.fs.Dir(s, *args, **kw) def NoClean(self, *targets): """Tags a target so that it will not be cleaned by -c""" tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_noclean() return tlist def NoCache(self, *targets): """Tags a target so that it will not be cached""" tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_nocache() return tlist def Entry(self, name, *args, **kw): """ """ s = self.subst(name) if SCons.Util.is_Sequence(s): result=[] for e in s: result.append(self.fs.Entry(e, *args, **kw)) return result return self.fs.Entry(s, *args, **kw) def Environment(self, **kw): return SCons.Environment.Environment(**self.subst_kw(kw)) def Execute(self, action, *args, **kw): """Directly execute an action through an Environment """ action = self.Action(action, *args, **kw) result = action([], [], self) if isinstance(result, SCons.Errors.BuildError): errstr = result.errstr if result.filename: errstr = result.filename + ': ' + errstr sys.stderr.write("scons: *** %s\n" % errstr) return result.status else: return result def File(self, name, *args, **kw): """ """ s = self.subst(name) if SCons.Util.is_Sequence(s): result=[] for e in s: result.append(self.fs.File(e, *args, **kw)) return result return self.fs.File(s, *args, **kw) def FindFile(self, file, dirs): file = self.subst(file) nodes = self.arg2nodes(dirs, self.fs.Dir) return SCons.Node.FS.find_file(file, tuple(nodes)) def Flatten(self, sequence): return SCons.Util.flatten(sequence) def GetBuildPath(self, files): result = list(map(str, self.arg2nodes(files, self.fs.Entry))) if SCons.Util.is_List(files): return result else: return result[0] def Glob(self, pattern, ondisk=True, source=False, strings=False): return self.fs.Glob(self.subst(pattern), ondisk, source, strings) def Ignore(self, target, dependency): """Ignore a dependency.""" tlist = self.arg2nodes(target, self.fs.Entry) dlist = self.arg2nodes(dependency, self.fs.Entry) for t in tlist: t.add_ignore(dlist) return tlist def Literal(self, string): return SCons.Subst.Literal(string) def Local(self, *targets): ret = [] for targ in targets: if isinstance(targ, SCons.Node.Node): targ.set_local() ret.append(targ) else: for t in self.arg2nodes(targ, self.fs.Entry): t.set_local() ret.append(t) return ret def Precious(self, *targets): tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_precious() return tlist def Repository(self, *dirs, **kw): dirs = self.arg2nodes(list(dirs), self.fs.Dir) self.fs.Repository(*dirs, **kw) def Requires(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) for t in tlist: t.add_prerequisite(plist) return tlist def Scanner(self, *args, **kw): nargs = [] for arg in args: if SCons.Util.is_String(arg): arg = self.subst(arg) nargs.append(arg) nkw = self.subst_kw(kw) return SCons.Scanner.Base(*nargs, **nkw) def SConsignFile(self, name=".sconsign", dbm_module=None): if name is not None: name = self.subst(name) if not os.path.isabs(name): name = os.path.join(str(self.fs.SConstruct_dir), name) if name: name = os.path.normpath(name) sconsign_dir = os.path.dirname(name) if sconsign_dir and not os.path.exists(sconsign_dir): self.Execute(SCons.Defaults.Mkdir(sconsign_dir)) SCons.SConsign.File(name, dbm_module) def SideEffect(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) for side_effect in side_effects: if side_effect.multiple_side_effect_has_builder(): raise SCons.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 = 1 self.Precious(side_effect) for target in targets: target.side_effects.append(side_effect) return side_effects def SourceCode(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) for entry in entries: entry.set_src_builder(builder) return entries def SourceSignatures(self, type): global _warn_source_signatures_deprecated if _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 = False type = self.subst(type) self.src_sig_type = type if type == 'MD5': if not SCons.Util.md5: raise UserError("MD5 signatures are not available in this version of Python.") self.decide_source = self._changed_content elif type == 'timestamp': self.decide_source = self._changed_timestamp_match else: raise UserError("Unknown source signature type '%s'" % type) def Split(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.""" if SCons.Util.is_List(arg): return list(map(self.subst, arg)) elif SCons.Util.is_String(arg): return self.subst(arg).split() else: return [self.subst(arg)] def TargetSignatures(self, type): global _warn_target_signatures_deprecated if _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 = False type = self.subst(type) self.tgt_sig_type = type if type in ('MD5', 'content'): if not SCons.Util.md5: raise UserError("MD5 signatures are not available in this version of Python.") self.decide_target = self._changed_content elif type == 'timestamp': self.decide_target = self._changed_timestamp_match elif type == 'build': self.decide_target = self._changed_build elif type == 'source': self.decide_target = self._changed_source else: raise UserError("Unknown target signature type '%s'"%type) def Value(self, value, built_value=None): """ """ return SCons.Node.Python.Value(value, built_value) def VariantDir(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) def FindSourceFiles(self, node='.'): """ returns a list of all source files. """ node = self.arg2nodes(node, self.fs.Entry)[0] sources = [] def build_source(ss): for s in ss: if isinstance(s, SCons.Node.FS.Dir): build_source(s.all_children()) elif s.has_builder(): build_source(s.sources) elif isinstance(s.disambiguate(), SCons.Node.FS.File): sources.append(s) build_source(node.all_children()) def final_source(node): while (node != node.srcnode()): node = node.srcnode() return node sources = map( final_source, sources ); # remove duplicates return list(set(sources)) def FindInstalledFiles(self): """ returns the list of all targets of the Install and InstallAs Builder. """ from SCons.Tool import install if install._UNIQUE_INSTALLED_FILES is None: install._UNIQUE_INSTALLED_FILES = SCons.Util.uniquer_hashables(install._INSTALLED_FILES) return install._UNIQUE_INSTALLED_FILES class OverrideEnvironment(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'] = subject self.__dict__['overrides'] = overrides # Methods that make this class act like a proxy. def __getattr__(self, name): return getattr(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: return self.__dict__['overrides'][key] except KeyError: return self.__dict__['__subject'].__getitem__(key) def __setitem__(self, key, value): if not is_valid_construction_var(key): raise SCons.Errors.UserError("Illegal construction variable `%s'" % key) self.__dict__['overrides'][key] = value def __delitem__(self, key): try: del self.__dict__['overrides'][key] except KeyError: deleted = 0 else: deleted = 1 try: result = self.__dict__['__subject'].__delitem__(key) except KeyError: if not deleted: raise result = None return result def get(self, key, default=None): """Emulates the get() method of dictionaries.""" try: return self.__dict__['overrides'][key] except KeyError: return self.__dict__['__subject'].get(key, default) def has_key(self, key): try: self.__dict__['overrides'][key] return 1 except KeyError: return key in self.__dict__['__subject'] def __contains__(self, key): if self.__dict__['overrides'].__contains__(key): return 1 return self.__dict__['__subject'].__contains__(key) def Dictionary(self): """Emulates the items() method of dictionaries.""" d = self.__dict__['__subject'].Dictionary().copy() d.update(self.__dict__['overrides']) return d def items(self): """Emulates the items() method of dictionaries.""" return list(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) def gvars(self): return self.__dict__['__subject'].gvars() def lvars(self): lvars = self.__dict__['__subject'].lvars() lvars.update(self.__dict__['overrides']) return lvars # Overridden public construction environment methods. def Replace(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. def NoSubstitutionProxy(subject): class _NoSubstitutionProxy(Environment): def __init__(self, subject): self.__dict__['__subject'] = subject def __getattr__(self, name): return getattr(self.__dict__['__subject'], name) def __setattr__(self, name, value): return setattr(self.__dict__['__subject'], name, value) def executor_to_lvars(self, kwdict): if kwdict.has_key('executor'): kwdict['lvars'] = kwdict['executor'].get_lvars() del kwdict['executor'] else: kwdict['lvars'] = {} def raw_to_mode(self, dict): try: raw = dict['raw'] except KeyError: pass else: del dict['raw'] dict['mode'] = raw def subst(self, string, *args, **kwargs): return string def subst_kw(self, kw, *args, **kwargs): return kw def subst_list(self, string, *args, **kwargs): nargs = (string, self,) + args nkw = kwargs.copy() nkw['gvars'] = {} self.executor_to_lvars(nkw) self.raw_to_mode(nkw) return SCons.Subst.scons_subst_list(*nargs, **nkw) def subst_target_source(self, string, *args, **kwargs): nargs = (string, self,) + args nkw = kwargs.copy() nkw['gvars'] = {} self.executor_to_lvars(nkw) self.raw_to_mode(nkw) return SCons.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:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/engine/SCons/Memoize.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Memoizer A metaclass implementation to count hits and misses of the computed values that various methods cache in memory. Use of this modules assumes that wrapped methods be coded to cache their values in a consistent way. Here is an example of wrapping a method that returns a computed value, with no input parameters: memoizer_counters = [] # Memoization memoizer_counters.append(SCons.Memoize.CountValue('foo')) # Memoization def foo(self): try: # Memoization return self._memo['foo'] # Memoization except KeyError: # Memoization pass # Memoization result = self.compute_foo_value() self._memo['foo'] = result # Memoization return result Here is an example of wrapping a method that will return different values based on one or more input arguments: def _bar_key(self, argument): # Memoization return argument # Memoization memoizer_counters.append(SCons.Memoize.CountDict('bar', _bar_key)) # Memoization def bar(self, argument): memo_key = argument # Memoization try: # Memoization memo_dict = self._memo['bar'] # Memoization except KeyError: # Memoization memo_dict = {} # Memoization self._memo['dict'] = memo_dict # Memoization else: # Memoization try: # Memoization return memo_dict[memo_key] # Memoization except KeyError: # Memoization pass # Memoization result = self.compute_bar_value(argument) memo_dict[memo_key] = result # Memoization return result At one point we avoided replicating this sort of logic in all the methods by putting it right into this module, but we've moved away from that at present (see the "Historical Note," below.). Deciding what to cache is tricky, because different configurations can have radically different performance tradeoffs, and because the tradeoffs involved are often so non-obvious. Consequently, deciding whether or not to cache a given method will likely be more of an art than a science, but should still be based on available data from this module. Here are some VERY GENERAL guidelines about deciding whether or not to cache return values from a method that's being called a lot: -- The first question to ask is, "Can we change the calling code so this method isn't called so often?" Sometimes this can be done by changing the algorithm. Sometimes the *caller* should be memoized, not the method you're looking at. -- The memoized function should be timed with multiple configurations to make sure it doesn't inadvertently slow down some other configuration. -- When memoizing values based on a dictionary key composed of input arguments, you don't need to use all of the arguments if some of them don't affect the return values. Historical Note: The initial Memoizer implementation actually handled the caching of values for the wrapped methods, based on a set of generic algorithms for computing hashable values based on the method's arguments. This collected caching logic nicely, but had two drawbacks: Running arguments through a generic key-conversion mechanism is slower (and less flexible) than just coding these things directly. Since the methods that need memoized values are generally performance-critical, slowing them down in order to collect the logic isn't the right tradeoff. Use of the memoizer really obscured what was being called, because all the memoized methods were wrapped with re-used generic methods. This made it more difficult, for example, to use the Python profiler to figure out how to optimize the underlying methods. """ import types # A flag controlling whether or not we actually use memoization. use_memoizer = None CounterList = [] class Counter(object): """ Base class for counting memoization hits and misses. We expect that the metaclass initialization will have filled in the .name attribute that represents the name of the function being counted. """ def __init__(self, method_name): """ """ self.method_name = method_name self.hit = 0 self.miss = 0 CounterList.append(self) def display(self): fmt = " %7d hits %7d misses %s()" print fmt % (self.hit, self.miss, self.name) def __cmp__(self, other): try: return cmp(self.name, other.name) except AttributeError: return 0 class CountValue(Counter): """ A counter class for simple, atomic memoized values. A CountValue object should be instantiated in a class for each of the class's methods that memoizes its return value by simply storing the return value in its _memo dictionary. We expect that the metaclass initialization will fill in the .underlying_method attribute with the method that we're wrapping. We then call the underlying_method method after counting whether its memoized value has already been set (a hit) or not (a miss). """ def __call__(self, *args, **kw): obj = args[0] if self.method_name in obj._memo: self.hit = self.hit + 1 else: self.miss = self.miss + 1 return self.underlying_method(*args, **kw) class CountDict(Counter): """ A counter class for memoized values stored in a dictionary, with keys based on the method's input arguments. A CountDict object is instantiated in a class for each of the class's methods that memoizes its return value in a dictionary, indexed by some key that can be computed from one or more of its input arguments. We expect that the metaclass initialization will fill in the .underlying_method attribute with the method that we're wrapping. We then call the underlying_method method after counting whether the computed key value is already present in the memoization dictionary (a hit) or not (a miss). """ def __init__(self, method_name, keymaker): """ """ Counter.__init__(self, method_name) self.keymaker = keymaker def __call__(self, *args, **kw): obj = args[0] try: memo_dict = obj._memo[self.method_name] except KeyError: self.miss = self.miss + 1 else: key = self.keymaker(*args, **kw) if key in memo_dict: self.hit = self.hit + 1 else: self.miss = self.miss + 1 return self.underlying_method(*args, **kw) class Memoizer(object): """Object which performs caching of method calls for its 'primary' instance.""" def __init__(self): pass def Dump(title=None): if title: print title CounterList.sort() for counter in CounterList: counter.display() class Memoized_Metaclass(type): def __init__(cls, name, bases, cls_dict): super(Memoized_Metaclass, cls).__init__(name, bases, cls_dict) for counter in cls_dict.get('memoizer_counters', []): method_name = counter.method_name counter.name = cls.__name__ + '.' + method_name counter.underlying_method = cls_dict[method_name] replacement_method = types.MethodType(counter, None, cls) setattr(cls, method_name, replacement_method) def EnableMemoization(): global use_memoizer use_memoizer = 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
#! /usr/bin/env python # # SCons - a Software Constructor # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # 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__ = "src/script/scons.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __version__ = "2.2.0" __build__ = "issue-2856:2676:d23b7a2f45e8[MODIFIED]" __buildsys__ = "oberbrunner-dev" __date__ = "2012/08/05 15:38:28" __developer__ = "garyo" import os import sys ############################################################################## # BEGIN STANDARD SCons SCRIPT HEADER # # This is the cut-and-paste logic so that a self-contained script can # interoperate correctly with different SCons versions and installation # locations for the engine. If you modify anything in this section, you # should also change other scripts that use this same header. ############################################################################## # Strip the script directory from sys.path() so on case-insensitive # (WIN32) systems Python doesn't think that the "scons" script is the # "SCons" package. Replace it with our own library directories # (version-specific first, in case they installed by hand there, # followed by generic) so we pick up the right version of the build # engine modules if they're in either directory. # Check to see if the python version is > 3.0 which is currently unsupported # If so exit with error message try: if sys.version_info >= (3,0,0): msg = "scons: *** SCons version %s does not run under Python version %s.\n\ Python 3.0 and later are not yet supported.\n" sys.stderr.write(msg % (__version__, sys.version.split()[0])) sys.exit(1) except AttributeError: # Pre-1.6 Python has no sys.version_info # No need to check version as we then know the version is < 3.0.0 and supported pass script_dir = sys.path[0] if script_dir in sys.path: sys.path.remove(script_dir) libs = [] if "SCONS_LIB_DIR" in os.environ: libs.append(os.environ["SCONS_LIB_DIR"]) local_version = 'scons-local-' + __version__ local = 'scons-local' if script_dir: local_version = os.path.join(script_dir, local_version) local = os.path.join(script_dir, local) libs.append(os.path.abspath(local_version)) libs.append(os.path.abspath(local)) scons_version = 'scons-%s' % __version__ # preferred order of scons lookup paths prefs = [] try: import pkg_resources except ImportError: pass else: # when running from an egg add the egg's directory try: d = pkg_resources.get_distribution('scons') except pkg_resources.DistributionNotFound: pass else: prefs.append(d.location) if sys.platform == 'win32': # sys.prefix is (likely) C:\Python*; # check only C:\Python*. prefs.append(sys.prefix) prefs.append(os.path.join(sys.prefix, 'Lib', 'site-packages')) else: # On other (POSIX) platforms, things are more complicated due to # the variety of path names and library locations. Try to be smart # about it. if script_dir == 'bin': # script_dir is `pwd`/bin; # check `pwd`/lib/scons*. prefs.append(os.getcwd()) else: if script_dir == '.' or script_dir == '': script_dir = os.getcwd() head, tail = os.path.split(script_dir) if tail == "bin": # script_dir is /foo/bin; # check /foo/lib/scons*. prefs.append(head) head, tail = os.path.split(sys.prefix) if tail == "usr": # sys.prefix is /foo/usr; # check /foo/usr/lib/scons* first, # then /foo/usr/local/lib/scons*. prefs.append(sys.prefix) prefs.append(os.path.join(sys.prefix, "local")) elif tail == "local": h, t = os.path.split(head) if t == "usr": # sys.prefix is /foo/usr/local; # check /foo/usr/local/lib/scons* first, # then /foo/usr/lib/scons*. prefs.append(sys.prefix) prefs.append(head) else: # sys.prefix is /foo/local; # check only /foo/local/lib/scons*. prefs.append(sys.prefix) else: # sys.prefix is /foo (ends in neither /usr or /local); # check only /foo/lib/scons*. prefs.append(sys.prefix) temp = [os.path.join(x, 'lib') for x in prefs] temp.extend([os.path.join(x, 'lib', 'python' + sys.version[:3], 'site-packages') for x in prefs]) prefs = temp # Add the parent directory of the current python's library to the # preferences. On SuSE-91/AMD64, for example, this is /usr/lib64, # not /usr/lib. try: libpath = os.__file__ except AttributeError: pass else: # Split /usr/libfoo/python*/os.py to /usr/libfoo/python*. libpath, tail = os.path.split(libpath) # Split /usr/libfoo/python* to /usr/libfoo libpath, tail = os.path.split(libpath) # Check /usr/libfoo/scons*. prefs.append(libpath) # Look first for 'scons-__version__' in all of our preference libs, # then for 'scons'. libs.extend([os.path.join(x, scons_version) for x in prefs]) libs.extend([os.path.join(x, 'scons') for x in prefs]) sys.path = libs + sys.path ############################################################################## # END STANDARD SCons SCRIPT HEADER ############################################################################## if __name__ == "__main__": import SCons.Script # this does all the work, and calls sys.exit # with the proper exit status when done. SCons.Script.main() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
################################################################################## ## ## Photivo ## ## Copyright (C) 2013 Jos De Laender <jos@de-laender.be> ## ## This file is part of Photivo. ## ## Photivo is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License version 3 ## as published by the Free Software Foundation. ## ## Photivo is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Photivo. If not, see <http://www.gnu.org/licenses/>. ## ################################################################################ # This is a file that should be in python syntax and drives the build # of photivo. # Make a copy (f.i. MyBuild.py) if you want to tweak settings and then # use that copy for driving the build by issuing on the toplevel : # ./scons.py -Q -ptBuildConfFile=BuildConfs/MyBuild.py # Put here whatever name you want to give your build. # It's only used to create a different VariantDir in the Build directory. # And for the base name of the log file. # PT_BUILD_CONF_NAME = 'Default' # If you would want an alternative log file name. # # PT_LOGFILE_NAME = 'SomeName.log' # Where the result will be installed. # (used to be 'PREFIX' in qmake based approach) # PT_INSTALL_PATH = '/usr/local' # Whether omp is enabled. Default is True anyway. # PT_OMP = True # Whether this is a release type build. # Set False for a debug type build. # PT_RELEASE = True # Whether in windows a console should be kept when running photivo. # PT_WITH_CONSOLE = False # Whether the file manager should be built-in. # PT_WITH_FILEMGR = True # Whether to use the System CIMG (TODO , just found in the .pro files) # PT_WITH_SYSTEMCIMG = False # XXX JDLA TODO Now just coming from the linux build page. # When True, the presence of gimp-2.0 dev package is checked, but nothing else. # I guess this has to see with WithGimp but still TODO # PT_WITH_GIMPPLUGIN = False # Where to find the QT4 installation if it is not default. # Note that when uncommenting f.i. next line, qmake is expected to be at : # /usr/local/Trolltech/Qt-4.7.0/bin/qmake # This is consistent with the way Qt is built if you build it yourself. # # QT4DIR = '/usr/local/Trolltech/Qt-4.7.0' # Comment out if you want to define an 'alternative' gcc/g++ to be used. # System default otherwise. # # CC = '/opt/gcc-4.7.0/bin/gcc-4.7.0' # CXX = '/opt/gcc-4.7.0/bin/g++-4.7.0' # Future. If we want to play with install modes. # PT_INSTALL_MODE = 'Original' # Add or extend the PKG_CONFIG_PATH. Likely not needed. # # PGK_CONFIG_PATH = '/some/path' ############################################################################### # # Below this line is probably only of interest for cross compilations. # ############################################################################### # Host platform. If not automatically detected. # 'win32' or 'posix' # # PT_HOST_PLATFORM = 'posix' # Target platform. If not automatically detected. # 'win32' or 'posix' # # PT_TARGET_PLATFORM = 'posix' # Prefix used for cross-compiling tools. # # PT_CROSS = 'i686-pc-mingw32-' # Where to find the gcc/g++ and bin tools. # # PT_TOOLS_DIR = '/home/jos/SoftwareUnderDevelopment/mxe/usr/bin'
Python
################################################################################ ## ## photivo ## ## Copyright (C) 2013 Jos De Laender <jos@de-laender.be> ## ## This file is part of photivo. ## ## photivo is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License version 3 ## as published by the Free Software Foundation. ## ## photivo is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with photivo. If not, see <http://www.gnu.org/licenses/>. ## ################################################################################ import os.path Import('ptQtEnv') ptLocalEnv = ptQtEnv.Clone() ptLocalEnv.EnableQt4Modules(['QtGui','QtCore','QtNetwork']) ptForms = Glob('*.ui') ptForms += Glob('*/*.ui') ptForms += Glob('*/*/*.ui') ptLocalEnv.Uic4(ptForms) ptLocalEnv.Append(CPPPATH = ['.']) ################################################################################ # rpath addition in case qt or tools is non default. # XXX JDLA CHECKME if ptLocalEnv['PT_TARGET_PLATFORM'] == 'posix' : ptQtBin = os.path.join(str(ptLocalEnv['QT4DIR']),'bin') if not ptQtBin in ptLocalEnv['PT_DEFAULT_PATH']: ptLocalEnv.Append(LINKFLAGS = ['-Wl,-rpath',ptLocalEnv['QT4_LIBPATH']]) if not ptLocalEnv['PT_TOOLS_DIR'] in ptLocalEnv['PT_DEFAULT_PATH']: # TODO Currently roughly ok for linux. The libname needs 'variation' ptCommand = ptLocalEnv['CC'] + ' --print-file-name=libstdc++.so' ptLibStdc = os.path.normpath(os.popen(ptCommand).read().rstrip()) ptLibStdcPath = os.path.dirname(ptLibStdc) ptLocalEnv.Append(LINKFLAGS = ['-Wl,-rpath',ptLibStdcPath]) ################################################################################ # Summary ptLogFile = ptLocalEnv['PT_LOGFILE'] ptVerboseConfig = ptLocalEnv['PT_VERBOSECONFIG'] ptDoPrint = False if ptVerboseConfig: ptDoPrint = True ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta,'Summary for Sources/SConscript') ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'QT4_BINPATH : ' + str(ptLocalEnv['QT4_BINPATH'])) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'QT4_LIBPATH : ' + str(ptLocalEnv['QT4_LIBPATH'])) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'QT4_MOC : ' + str(ptLocalEnv['QT4_MOC'])) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'QT4_UIC : ' + str(ptLocalEnv['QT4_UIC'])) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'QT4_RCC : ' + str(ptLocalEnv['QT4_RCC'])) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'CPPFLAGS : ' + str(ptLocalEnv.get('CPPFLAGS'))) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'CPPPATH : ' + str(ptLocalEnv.get('CPPPATH'))) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'CPPDEFINES : ' + str(ptLocalEnv.get('CPPDEFINES'))) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'CCFLAGS : ' + str(ptLocalEnv.get('CCFLAGS'))) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'CXXFLAGS : ' + str(ptLocalEnv.get('CXXFLAGS'))) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'LINKFLAGS : ' + str(ptLocalEnv.get('LINKFLAGS'))) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'LIBS : ' + str(ptLocalEnv.get('LIBS'))) ptPrintLog(ptDoPrint,ptLogFile,ptBoldMagenta, 'LIBPATH : ' + str(ptLocalEnv.get('LIBPATH'))) ################################################################################ # Fixed, not generated sources. # Currently this is cut/paste from photivoProject.pro. # Alternatively it can be generated from it (if some IDE would generate). # Or some intelligent Globbing can be done, in case not to many noise files # are in. # Check with Mike. Not 'standalone' but included I believe : # ptSources += ['dcb/dcb_demosaicing.c'] # ptSources += ['perfectraw/lmmse_interpolate.c'] # ptSources += ['rawtherapee/amaze_interpolate.c'] # ptSources += ['rawtherapee/ca_correct.c'] # ptSources += ['rawtherapee/cfa_line_dn.c'] # ptSources += ['rawtherapee/green_equil.c'] # ptSources += ['vcd/ahd_interpolate_mod.c'] # ptSources += ['vcd/ahd_partial_interpolate.c'] # ptSources += ['vcd/es_median_filter.c'] # ptSources += ['vcd/median_filter_new.c'] # ptSources += ['vcd/refinement.c'] # ptSources += ['vcd/vcd_interpolate.c'] # ptSources += ['qtsingleapplication/qtlockedfile.cpp'] # ptSources += ['qtsingleapplication/qtlockedfile_unix.cpp'] # ptSources += ['qtsingleapplication/qtlockedfile_win.cpp'] ptSources = [] ptSources += ['filemgmt/ptColumnGridThumbnailLayouter.cpp'] ptSources += ['filemgmt/ptFileMgrDM.cpp'] ptSources += ['filemgmt/ptFileMgrWindow.cpp'] ptSources += ['filemgmt/ptGraphicsSceneEmitter.cpp'] ptSources += ['filemgmt/ptGraphicsThumbGroup.cpp'] ptSources += ['filemgmt/ptGridThumbnailLayouter.cpp'] ptSources += ['filemgmt/ptImageView.cpp'] ptSources += ['filemgmt/ptPathBar.cpp'] ptSources += ['filemgmt/ptRowGridThumbnailLayouter.cpp'] ptSources += ['filemgmt/ptSingleDirModel.cpp'] ptSources += ['filemgmt/ptTagList.cpp'] ptSources += ['filemgmt/ptTagModel.cpp'] ptSources += ['filemgmt/ptThumbnailCache.cpp'] ptSources += ['filemgmt/ptThumbnailer.cpp'] ptSources += ['filters/ptCfgItem.cpp'] ptSources += ['filters/ptFilter_ABCurves.cpp'] ptSources += ['filters/ptFilter_ColorContrast.cpp'] ptSources += ['filters/ptFilter_DetailCurve.cpp'] ptSources += ['filters/ptFilter_GammaTool.cpp'] ptSources += ['filters/ptFilter_Highlights.cpp'] ptSources += ['filters/ptFilter_LumaDenoiseCurve.cpp'] ptSources += ['filters/ptFilter_LumaSatAdjust.cpp'] ptSources += ['filters/ptFilter_Outline.cpp'] ptSources += ['filters/ptFilter_SatCurve.cpp'] ptSources += ['filters/ptFilter_ShadowsHighlights.cpp'] ptSources += ['filters/ptFilter_SigContrast.cpp'] ptSources += ['filters/ptFilter_StdCurve.cpp'] ptSources += ['filters/ptFilter_ToneAdjust.cpp'] ptSources += ['filters/ptFilter_Wiener.cpp'] ptSources += ['filters/ptFilterBase.cpp'] ptSources += ['filters/ptFilterConfig.cpp'] ptSources += ['filters/ptFilterDM.cpp'] ptSources += ['filters/ptFilterFactory.cpp'] ptSources += ['ptCalloc.cpp'] ptSources += ['ptChannelMixer.cpp'] ptSources += ['ptCheck.cpp'] ptSources += ['ptChoice.cpp'] ptSources += ['ptCimg.cpp'] ptSources += ['ptConfirmRequest.cpp'] ptSources += ['ptCurve.cpp'] ptSources += ['ptCurveWindow.cpp'] ptSources += ['ptDcRaw.cpp'] ptSources += ['ptError.cpp'] ptSources += ['ptFastBilateral.cpp'] ptSources += ['ptGridInteraction.cpp'] ptSources += ['ptGroupBox.cpp'] ptSources += ['ptGuiOptions.cpp'] ptSources += ['ptHistogramWindow.cpp'] ptSources += ['ptImage.cpp'] ptSources += ['ptImage_Cimg.cpp'] ptSources += ['ptImage_DRC.cpp'] ptSources += ['ptImage_EAW.cpp'] ptSources += ['ptImage_GM.cpp'] ptSources += ['ptImage_GMC.cpp'] ptSources += ['ptImage_Lensfun.cpp'] ptSources += ['ptImage_Lqr.cpp'] ptSources += ['ptImage_Pyramid.cpp'] ptSources += ['ptImage8.cpp'] ptSources += ['ptAbstractInteraction.cpp'] ptSources += ['ptImageHelper.cpp'] ptSources += ['ptInfo.cpp'] ptSources += ['ptInput.cpp'] ptSources += ['ptKernel.cpp'] ptSources += ['ptLensfun.cpp'] ptSources += ['ptLineInteraction.cpp'] ptSources += ['ptMain.cpp'] ptSources += ['ptMainWindow.cpp'] ptSources += ['ptMessageBox.cpp'] ptSources += ['ptParseCli.cpp'] ptSources += ['ptProcessor.cpp'] ptSources += ['ptReportOverlay.cpp'] ptSources += ['ptResizeFilters.cpp'] ptSources += ['ptRGBTemperature.cpp'] ptSources += ['ptRichRectInteraction.cpp'] ptSources += ['ptSettings.cpp'] ptSources += ['ptSimpleRectInteraction.cpp'] ptSources += ['ptSlider.cpp'] ptSources += ['ptTempFilterBase.cpp'] ptSources += ['ptTheme.cpp'] ptSources += ['ptToolBox.cpp'] ptSources += ['ptViewWindow.cpp'] ptSources += ['ptVisibleToolsView.cpp'] ptSources += ['ptWhiteBalances.cpp'] ptSources += ['ptWidget.cpp'] ptSources += ['ptWiener.cpp'] ptSources += ['qtsingleapplication/qtlocalpeer.cpp'] ptSources += ['qtsingleapplication/qtsingleapplication.cpp'] ptSources += ['filters/imagespot/ptFilter_SpotTuning.cpp'] ptSources += ['filters/imagespot/ptImageSpot.cpp'] ptSources += ['filters/imagespot/ptImageSpotEditor.cpp'] ptSources += ['filters/imagespot/ptImageSpotItemDelegate.cpp'] ptSources += ['filters/imagespot/ptImageSpotModel.cpp'] ptSources += ['filters/imagespot/ptTuningSpot.cpp'] #ptSources += ['filters/imagespot/ptRepairInteraction.cpp'] #ptSources += ['filters/imagespot/ptRepairSpot.cpp'] ptSources += ['filters/imagespot/ptSpotInteraction.cpp'] ptSources += ['filters/imagespot/ptSpotListWidget.cpp'] ptSources += ['ptTempFile.cpp'] ptSources += ['filters/imagespot/ptImageSpotList.cpp'] ptSources += ['filters/ptFilter_ColorIntensity.cpp'] ptSources += ['filters/ptFilter_Brightness.cpp'] ptSources += ['filters/ptFilter_ReinhardBrighten.cpp'] ptSources += ['filters/ptFilter_Normalization.cpp'] ptSources += ['filters/ptFilter_ColorEnhancement.cpp'] ptSources += ['filters/ptFilter_Levels.cpp'] ptSources += ['filters/ptFilter_LMHRecovery.cpp'] ptSources += ['filters/ptFilter_Drc.cpp'] ptSources += ['filters/ptFilter_LabTransform.cpp'] ptSources += ['filters/ptFilter_Saturation.cpp'] ptSources += ['filters/ptFilter_ColorBoost.cpp'] ptSources += ['filters/ptFilter_Tone.cpp'] ptSources += ['batch/ptJobListItem.cpp'] ptSources += ['batch/ptBatchWindow.cpp'] ptSources += ['batch/ptJobListModel.cpp'] if ptLocalEnv['PT_TARGET_PLATFORM'] in ['win32'] : ptSources += ['ptEcWin7.cpp'] ptSources += ['ptWinApi.cpp'] # TODO Check me. This is now outside build dir. # Maybe some copy action first or so ... ptSources += [ptLocalEnv.GetLaunchDir() + '/qrc/photivo.qrc'] ################################################################################ ptClear = ptLocalEnv.Program('ptClear',['ptClear.cpp']) ptObj = [ptLocalEnv.Object(i) for i in [ptSources]] ptPhotivo = ptLocalEnv.Program('photivo',ptObj) # Dependency via ptEmu.qrc and that is not scanned. XXX TODO REFINE # TODO Depends(photivo,Glob('Icons/*')) ptLocalEnv.Install(ptLocalEnv.GetLaunchDir(),[ptPhotivo,ptClear]) ################################################################################
Python
#! /usr/bin/env python import os from os.path import exists import shutil #name of photivo directory photivo_dir='photivo-s' home_dir = os.getenv("HOME") source_dir=home_dir +'/'+photivo_dir target_dir = home_dir +'/'+photivo_dir + "/Photivo.app/Contents" AppBundle= home_dir + '/' + photivo_dir + "/Photivo.app" os.makedirs(target_dir) shutil.copy(source_dir+'/Info.plist', target_dir) os.chdir( target_dir ) dir_tree = 'Frameworks/MacOS/Resources' tree_group = dir_tree.split("/") for item in tree_group: # Removes any empty strings from the list if item == "": tree_group.remove(item) #os.mkdir(item) if item=='MacOS': os.mkdir(item) for elm in ['Curves','LensfunDatabase','ChannelMixers','Presets','Profiles','Themes','photivo']: if os.path.isdir(source_dir + '/' + elm) == True: print elm + ' dir copied' shutil.copytree(source_dir + '/' + elm, item + '/' + elm) #distutils.dir_util.copy_tree else: print elm + ' file copied' shutil.copy(source_dir + '/' + elm, item) elif item=='Resources': os.mkdir(item) shutil.copy(source_dir+'/photivo-appicon.icns', item) else: os.mkdir(item) #print AppBundle from subprocess import call if call('/usr/bin/macdeployqt ' + AppBundle , shell=True)==0: print 'Bundle building finished!' else: print 'There was a problem building the bundle'
Python
################################################################################ ## ## Photivo ## ## Copyright (C) 2013 Jos De Laender <jos@de-laender.be> ## ## This file is part of Photivo. ## ## Photivo is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License version 3 ## as published by the Free Software Foundation. ## ## Photivo is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Photivo. If not, see <http://www.gnu.org/licenses/>. ## ################################################################################ import tempfile import subprocess import shutil ################################################################################ # Constants. ptNoAttrs = '' ptBold = '' ptNegative = '' ptBlack = '' ptRed = '' ptGreen = '' ptYellow = '' ptBlue = '' ptMagenta = '' ptCyan = '' ptWhite = '' ptBoldRed = '' ptBoldGreen = '' ptBoldYellow = '' ptBoldBlue = '' ptBoldMagenta= '' ptBoldCyan = '' ptBoldWhite = '' # Do we have colors in win32 ? ptHaveColors = True if sys.platform in ['win32'] : ptHaveColors = False try: from colorama import init init() ptHaveColors = True except : print '\nTIP : Installing colorama would give you coloured output.\n' pass if ptHaveColors and sys.stdout.isatty() : ptNoAttrs = '\033[0m' ptBold = '\033[1m' ptNegative = '\033[7m' ptBlack = '\033[30m' ptRed = '\033[31m' ptGreen = '\033[32m' ptYellow = '\033[33m' ptBlue = '\033[34m' ptMagenta = '\033[35m' ptCyan = '\033[36m' ptWhite = '\033[37m' ptBoldRed = '\033[1;31m' ptBoldGreen = '\033[1;32m' ptBoldYellow = '\033[1;33m' ptBoldBlue = '\033[1;34m' ptBoldMagenta= '\033[1;35m' ptBoldCyan = '\033[1;36m' ptBoldWhite = '\033[1;37m' ################################################################################ # Prints to screen and to log. With color to screen. def ptPrintLog(DoPrint,LogFile,Color,Message): if DoPrint : MyMessage = Color + Message + ptNoAttrs print MyMessage LogFile.write(Message + '\n') return None ################################################################################ # Check for sufficient GCC. Simply returns true if OK. def ptCheckGCCVersion(BuildEnv,MinVersion): ptPrintLog(True,BuildEnv['PT_LOGFILE'], ptBoldBlue, 'Checking for GCC >= ' + MinVersion + ' ... ') # Make sure we work with correct and minimum os.environ. Save previous. ptSavedEnviron = dict(os.environ) os.environ.clear() for Key in BuildEnv['ENV'].keys(): os.environ[Key] = BuildEnv['ENV'][Key] ptCC = BuildEnv['CC'] ptCXX = BuildEnv['CXX'] ptCCVersion = os.popen(ptCC + ' -dumpversion').read().rstrip().split('.') ptCXXVersion = os.popen(ptCXX + ' -dumpversion').read().rstrip().split('.') # Restpre env os.environ.clear() os.environ.update(ptSavedEnviron) ptMinVersion = MinVersion.split('.') if (ptCCVersion[0] > ptMinVersion[0] and ptCXXVersion[0] > ptMinVersion[0]): return True; if (ptCCVersion[0] < ptMinVersion[0] or ptCXXVersion[0] < ptMinVersion[0]): return False; if (ptCCVersion[1] > ptMinVersion[1] and ptCXXVersion[1] > ptMinVersion[1]): return True; if (ptCCVersion[1] < ptMinVersion[1] or ptCXXVersion[1] < ptMinVersion[1]): return False; # Some report 4.7 for 4.7.2 try: if (ptCCVersion[2] > ptMinVersion[2] and ptCXXVersion[2] > ptMinVersion[2]): return True; if (ptCCVersion[2] < ptMinVersion[2] or ptCXXVersion[2] < ptMinVersion[2]): return False; except IndexError: pass return True; ################################################################################ # Get GCC/CXX version def ptGetGCCVersion(BuildEnv) : # Make sure we work with correct and minimum os.environ. Save previous. ptSavedEnviron = dict(os.environ) os.environ.clear() for Key in BuildEnv['ENV'].keys(): os.environ[Key] = BuildEnv['ENV'][Key] ptCC = BuildEnv.WhereIs(BuildEnv['CC']) ptCXX = BuildEnv.WhereIs(BuildEnv['CXX']) ptCCVersion = os.popen(ptCC + ' -dumpversion').read().rstrip() ptCXXVersion = os.popen(ptCXX + ' -dumpversion').read().rstrip() # Restore env os.environ.clear() os.environ.update(ptSavedEnviron) return[ptCCVersion,ptCXXVersion] ################################################################################ # Check hg def ptCheckHg(Context): ptPrintLog(True,Context.env['PT_LOGFILE'], ptBoldBlue, 'Checking for hg ... ') Ret=Context.TryAction('hg')[0] Context.Result(Ret) return Ret ################################################################################ # Get AppVersion def ptGetAppVersion(): ptHgRev = os.popen('hg identify').read()[:11] ptChanged = os.popen('hg identify').read()[12] ptAppVer = os.popen( 'hg log --rev ' + ptHgRev + \ ' --template "{date|shortdate} (rev {node|short})"').read() return ptAppVer + ptChanged ################################################################################ # Get the package version and flags for packages handled by pkg-config def ptGetPKGOutput(Context,Name): # Make sure we work with correct and minimum os.environ. Save previous. ptSavedEnviron = dict(os.environ) os.environ.clear() for Key in Context.env['ENV'].keys(): os.environ[Key] = Context.env['ENV'][Key] ptPkgConfig = Context.env['PT_CROSS'] + 'pkg-config' ptVersion = os.popen(ptPkgConfig + ' --modversion ' + Name).read().rstrip() ptFlags = os.popen(ptPkgConfig + ' --cflags --libs ' + Name).read().rstrip() # Restore env os.environ.clear() os.environ.update(ptSavedEnviron) return [ptVersion,ptFlags] ################################################################################ def ptCheckPKGConfig(Context,MinVersion): ptPkgConfig = Context.env['PT_CROSS'] + 'pkg-config' ptPrintLog(True,Context.env['PT_LOGFILE'], ptBoldBlue, 'Checking for ' + ptPkgConfig + ' ... ') Ret=Context.TryAction( ptPkgConfig + ' --atleast-pkgconfig-version=' + MinVersion)[0] Context.Result(Ret) return Ret ################################################################################ def ptCheckPKG(Context,Name): ptPrintLog(True,Context.env['PT_LOGFILE'], ptBoldBlue, 'Checking for ' + Name + '... ') ptPkgConfig = Context.env['PT_CROSS'] + 'pkg-config' if sys.platform in ['win32'] : ptCommand = ptPkgConfig + ' --exists %s' % Name # WIN32 shell escape of > ptCommand = ptCommand.replace(">","^>") else : ptCommand = ptPkgConfig + ' --exists \'%s\'' % Name Ret = Context.TryAction(ptCommand)[0] Context.Result(Ret) return Ret ################################################################################ def ptCheckLibWithHeader(Context,Lib,Header,Language): ptPrintLog(True,Context.env['PT_LOGFILE'], ptBoldBlue, 'Checking for ' + Lib + ' (' + Header + ')... ') Ret = Context.sconf.CheckLibWithHeader(Lib,Header,Language) Context.Result(Ret) return Ret ################################################################################ # custom check on libjpeg version def ptCheckLibJpeg(Context,MinVersion,MaxVersion): ptPrintLog(True,Context.env['PT_LOGFILE'], ptBoldBlue, 'Checking for libjpeg between ' + str(MinVersion) + ' and ' + str(MaxVersion) + '... ') ptProgram = """ #include <stdlib.h> #include <stdio.h> #define JPEG_LIB_VERSION 0 #include <jpeglib.h> int main() { printf("%d",JPEG_LIB_VERSION); return 0; } """ Ret = Context.TryCompile(ptProgram, '.c') if Ret == 0: ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, 'Failing test. Cannot compile test program:') ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed,ptProgram) ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed,'Giving up.') Exit(1) Ret = Context.TryRun(ptProgram, '.c') if Ret[0] == 0: ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, 'Failing test. Cannot run test program:') ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed,ptProgram) ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed,'Giving up.') Exit(1) ptVersion = int(Ret[1]) OK = not (ptVersion < MinVersion or ptVersion > MaxVersion) if not OK: ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, 'libjpeg version : ' + str(Ret[1]) + ' should be between ' + str(MinVersion) + ' and ' + str(MaxVersion)) Context.Result(OK) return OK ################################################################################ def ptCheckQt(Context,MinVersion): ptPrintLog(True,Context.env['PT_LOGFILE'], ptBoldBlue, 'Checking for Qt >= ' + MinVersion + '... ') # Make sure we work with correct and minimum os.environ. Save previous. ptSavedEnviron = dict(os.environ) os.environ.clear() for Key in Context.env['ENV'].keys(): os.environ[Key] = Context.env['ENV'][Key] # Locate qmake. Taking QT4DIR into account. qmake_1 = Context.env['QT4DIR'] + os.sep + 'bin' + os.sep + 'qmake' qmake_2 = Context.env['QT4DIR'] + os.sep + 'bin' + os.sep + 'qmake.exe' qmake_3 = Context.env['QT4DIR'] + os.sep + 'bin' + os.sep + 'qmake-qt4' qmake_4 = Context.env['QT4DIR'] + os.sep + 'bin' + os.sep + 'qmake-qt4.exe' qmakes = [qmake_1,qmake_2,qmake_3,qmake_4] qmake = '' for qm in qmakes : if os.path.exists(qm) : qmake = qm break if not qmake: ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, 'Cannot locate qmake.') ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed,'Giving up.') Exit(1) # Locate make make = Context.env.WhereIs('make') if not make: ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, 'Cannot locate make.') ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed,'Giving up.') Exit(1) # Check version ptQtVersion = \ os.popen(qmake + ' -query QT_VERSION').read().rstrip().split('.') ptQtMinVersion = MinVersion.split('.') if ptQtVersion[0] < ptQtMinVersion[0] : Context.Result(False) return False if ptQtVersion[0] > ptQtMinVersion[0] : Context.Result(True) return True if ptQtVersion[1] < ptQtMinVersion[1] : Context.Result(False) return False if ptQtVersion[1] > ptQtMinVersion[1] : Context.Result(True) return True if ptQtVersion[2] < ptQtMinVersion[2] : Context.Result(False) return False if ptQtVersion[2] > ptQtMinVersion[2] : Context.Result(True) return True Context.Result(True) return True ################################################################################ # Determine Qt Compile and Link parameters via a qmake run on test program. def ptGetQtOutput(Context): # Make sure we work with correct and minimum os.environ. Save previous. ptSavedEnviron = dict(os.environ) os.environ.clear() for Key in Context.env['ENV'].keys(): os.environ[Key] = Context.env['ENV'][Key] # Locate qmake. Taking QT4DIR into account. qmake_1 = Context.env['QT4DIR'] + os.sep + 'bin' + os.sep + 'qmake' qmake_2 = Context.env['QT4DIR'] + os.sep + 'bin' + os.sep + 'qmake.exe' qmake_3 = Context.env['QT4DIR'] + os.sep + 'bin' + os.sep + 'qmake-qt4' qmake_4 = Context.env['QT4DIR'] + os.sep + 'bin' + os.sep + 'qmake-qt4.exe' qmakes = [qmake_1,qmake_2,qmake_3,qmake_4] qmake = '' for qm in qmakes : if os.path.exists(qm) : qmake = qm break if not qmake: ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, 'Cannot locate qmake.') ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed,'Giving up.') Exit(1) # Locate make make = Context.env.WhereIs('make') if not make: ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, 'Cannot locate make.') ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed,'Giving up.') Exit(1) # Version ptQtVersion = os.popen(qmake + ' -query QT_VERSION').read().rstrip() # Analyze output of qmake/make combo ptCurDir = os.getcwd() ptTmpDir = tempfile.mkdtemp() ptProgram = """ int main() { return 0; } """ with open(ptTmpDir + os.sep + 'FooTest.cpp','w') as f : f.write(ptProgram) with open(ptTmpDir + os.sep + 'FooTest.pro','w') as f : f.write('CONFIG -= DEBUG\n') f.write('CONFIG -= RELEASE\n') if Context.env['PT_RELEASE'] : f.write('CONFIG += RELEASE\n') else : f.write('CONFIG += DEBUG\n') f.write('QT += core\n') f.write('QT += gui\n') f.write('QT += network\n') f.write('SOURCES = FooTest.cpp\n') os.chdir(ptTmpDir) os.popen(qmake) ptMakeOutput = os.popen(make).read().rstrip().split('\n') # Analyze output to determine flags. ptCompileFlags = '' ptLinkFlags = '' for Line in ptMakeOutput: if 'FooTest.cpp' in Line : # Assuming compile step. #ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, # '\nFoo compile line : ' + Line + '\n') ptLocalEnv = Environment() ptParsedFlags = ptLocalEnv.ParseFlags(Line) for ptFlag in ptParsedFlags['CPPDEFINES'] : ptCompileFlags += ' ' + '-D' + ptFlag for ptFlag in ptParsedFlags['CCFLAGS'] : if ptFlag.startswith('-f') or ptFlag.startswith('-m'): ptCompileFlags += ' ' + ptFlag for ptPath in ptParsedFlags['CPPPATH'] : if ptPath in ['.','debug','release'] : continue ptCompileFlags += ' -I' + os.path.abspath(ptPath).replace("\\","/") #ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, # '\nptParsedFlags : ' + str(ptParsedFlags) + '\n') #ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, # '\nptCompileFlags : ' + ptCompileFlags + '\n') elif 'FooTest' in Line : # Assuming link step. #ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, # '\nFoo link line : ' + Line + '\n') ptLocalEnv = Environment() ptParsedFlags = ptLocalEnv.ParseFlags(Line) for ptFlag in ptParsedFlags['LINKFLAGS'] : ptLinkFlags += ' ' + ptFlag for ptFlag in ptParsedFlags['CCFLAGS'] : if ptFlag.startswith('-f') or ptFlag.startswith('-m'): ptLinkFlags += ' ' + ptFlag for ptPath in ptParsedFlags['LIBPATH'] : ptLinkFlags += ' -L' + os.path.abspath(ptPath).replace("\\","/") for ptLib in ptParsedFlags['LIBS'] : try: ptLinkFlags += ' -l' + ptLib except TypeError: # foo.exe,foo.o references. pass #ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, # '\nptParsedFlags : ' + str(ptParsedFlags) + '\n') #ptPrintLog(True,Context.env['PT_LOGFILE'],ptBoldRed, # '\nptLinkFlags : ' + ptLinkFlags + '\n') # Back to dir we were. os.chdir(ptCurDir) # Remove our temp dir. shutil.rmtree(ptTmpDir) # Restore env os.environ.clear() os.environ.update(ptSavedEnviron) return [ptQtVersion,ptCompileFlags + ' ' + ptLinkFlags] ################################################################################ # Boilerplate to log commands nicely to screen and completely to log file. def ptPrintCmdLine(s, target, src, env): # Always to a log file. (and with an extra linefeed to 'see' commands) LogFile = env['PT_LOGFILE'] LogFile.write('\n' + s + '\n') ShortText = 'Building object' # 'Recognized' commands ? if 'DSCONS_CXX' in s: ShortText = ptGreen + 'Building CXX object' elif 'DSCONS_CC' in s: ShortText = ptGreen + 'Building C object' elif 'DSCONS_LINK' in s: ShortText = ptBoldMagenta + 'Linking' elif 'DSCONS_UIC' in s: ShortText = ptBoldBlue + 'Generating UIC object' elif 'DSCONS_MOC' in s: ShortText = ptBoldBlue + 'Generating MOC object' elif 'DSCONS_RCC' in s: ShortText = ptBoldBlue + 'Generating RCC object' elif 'DSCONS_WINDRES' in s: ShortText = ptBoldBlue + 'Generating Windows resource' elif s.endswith('.lnk') : ShortText = ptBoldMagenta + 'Linking' elif s.startswith('Creating'): ShortText = ptBoldBlue + 'Creating' else: # Install is a kind of exception. Also it points to a func. # We *assume* fallthrough is install. But that's a very shaky one. # XXX TODO #print 'DEBUG FOO : ' + s ShortText = ptBoldMagenta + 'Creating' MyMessage = '' if not env['PT_VERBOSE']: MyMessage = ShortText + ' ' + ' and '.join([str(x) for x in target]) else: MyMessage = s MyMessage += ptNoAttrs print MyMessage return None ################################################################################ # Exit function ensures color reset. def ptLastCalledAtExit(): print ptBoldYellow + \ 'Bye from the scons build program for Photivo' + \ ptNoAttrs return None ################################################################################ # AtExit that joins the stderr collected in stderr.log into the logfile. def ptAtExit(LogFile): try: LogFile.write('\nThe stderr output is :\n') sys.stderr.flush() # Make sure the stderr is complete. StdErrFile = open('stderr.log','r') LogFile.write(StdErrFile.read()) StdErrFile.close() except: pass return None ################################################################################ # Basically from Scons wiki : Spawn which echos stdout/stderr from the child. # ptFoo is mine. def ptEchoSpawn( sh, escape, cmd, args, env ): ptFoo = ' '.join(args) # convert env from unicode strings asciienv = {} for key, value in env.iteritems(): asciienv[key] = str(value) p = subprocess.Popen( #args, ptFoo, env=asciienv, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True) (stdout, stderr) = p.communicate() # Does this screw up the relative order of the two? sys.stdout.write(stdout) sys.stderr.write(stderr) return p.returncode ################################################################################ # Local (changed) copy of TempFileMunge class ptTempFileMunge(object): """A callable class. You can set an Environment variable to this, then call it with a string argument, then it will perform temporary file substitution on it. This is used to circumvent the long command line limitation. Example usage: env["TEMPFILE"] = TempFileMunge env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}" By default, the name of the temporary file used begins with a prefix of '@'. This may be configred for other tool chains by setting '$TEMPFILEPREFIX'. env["TEMPFILEPREFIX"] = '-@' # diab compiler env["TEMPFILEPREFIX"] = '-via' # arm tool chain """ def __init__(self, cmd): self.cmd = cmd def __call__(self, target, source, env, for_signature): if for_signature: # If we're being called for signature calculation, it's # because we're being called by the string expansion in # Subst.py, which has the logic to strip any $( $) that # may be in the command line we squirreled away. So we # just return the raw command line and let the upper # string substitution layers do their thing. return self.cmd # Now we're actually being called because someone is actually # going to try to execute the command, so we have to do our # own expansion. cmd = env.subst_list(self.cmd, SCons.Subst.SUBST_CMD, target, source)[0] try: maxline = int(env.subst('$MAXLINELENGTH')) except ValueError: maxline = 2048 length = 0 for c in cmd: length += len(c) if length <= maxline: return self.cmd # We do a normpath because mktemp() has what appears to be # a bug in Windows that will use a forward slash as a path # delimiter. Windows's link mistakes that for a command line # switch and barfs. # # We use the .lnk suffix for the benefit of the Phar Lap # linkloc linker, which likes to append an .lnk suffix if # none is given. (fd, tmp) = tempfile.mkstemp('.lnk', text=True) native_tmp = SCons.Util.get_native_path(os.path.normpath(tmp)) if env['SHELL'] and env['SHELL'] == 'sh': # The sh shell will try to escape the backslashes in the # path, so unescape them. native_tmp = native_tmp.replace('\\', r'\\\\') # In Cygwin, we want to use rm to delete the temporary # file, because del does not exist in the sh shell. rm = env.Detect('rm') or 'del' else: # Don't use 'rm' if the shell is not sh, because rm won't # work with the Windows shells (cmd.exe or command.com) or # Windows path names. rm = 'del' prefix = env.subst('$TEMPFILEPREFIX') if not prefix: prefix = '@' # JDLA , Another round of escapes for win32, which is in msys in our case. if sys.platform in ['win32'] : for i,ptCmd in enumerate(cmd) : cmd[i] = ptCmd.replace('\\','\\\\') args = list(map(SCons.Subst.quote_spaces, cmd[1:])) os.write(fd, " ".join(args) + "\n") os.close(fd) # XXX Using the SCons.Action.print_actions value directly # like this is bogus, but expedient. This class should # really be rewritten as an Action that defines the # __call__() and strfunction() methods and lets the # normal action-execution logic handle whether or not to # print/execute the action. The problem, though, is all # of that is decided before we execute this method as # part of expanding the $TEMPFILE construction variable. # Consequently, refactoring this will have to wait until # we get more flexible with allowing Actions to exist # independently and get strung together arbitrarily like # Ant tasks. In the meantime, it's going to be more # user-friendly to not let obsession with architectural # purity get in the way of just being helpful, so we'll # reach into SCons.Action directly. #if SCons.Action.print_actions: if False : print("Using tempfile "+native_tmp+" for command line:\n"+ str(cmd[0]) + " " + " ".join(args)) return [ cmd[0], prefix + native_tmp + '\n' + rm, native_tmp ] ################################################################################
Python
"""SCons.Tool.qt4 Tool-specific initialization for Qt4. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001-7,2010 The SCons Foundation # # 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. # # Additionally in Photivo : # Changes done in/for Photivo are largely traceable due to the # use of pt-Prefixes. ################################################################################ ## ## Photivo ## ## Copyright (C) 2013 Jos De Laender <jos@de-laender.be> ## ## This file is part of Photivo. ## ## Photivo is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License version 3 ## as published by the Free Software Foundation. ## ## Photivo is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Photivo. If not, see <http://www.gnu.org/licenses/>. ## ################################################################################ import os.path import re import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Scanner import SCons.Tool import SCons.Util import sys class ToolQt4Warning(SCons.Warnings.Warning): pass class GeneratedMocFileNotIncluded(ToolQt4Warning): pass class QtdirNotFound(ToolQt4Warning): pass SCons.Warnings.enableWarningClass(ToolQt4Warning) try: sorted except NameError: # Pre-2.4 Python has no sorted() function. # # The pre-2.4 Python list.sort() method does not support # list.sort(key=) nor list.sort(reverse=) keyword arguments, so # we must implement the functionality of those keyword arguments # by hand instead of passing them to list.sort(). def sorted(iterable, cmp=None, key=None, reverse=0): if key is not None: result = [(key(x), x) for x in iterable] else: result = iterable[:] if cmp is None: # Pre-2.3 Python does not support list.sort(None). result.sort() else: result.sort(cmp) if key is not None: result = [t1 for t0,t1 in result] if reverse: result.reverse() return result qrcinclude_re = re.compile(r'<file[^>]*>([^<]*)</file>', re.M) def transformToWinePath(path) : return os.popen('winepath -w "%s"'%path).read().strip().replace('\\','/') header_extensions = [".h", ".hxx", ".hpp", ".hh"] if SCons.Util.case_sensitive_suffixes('.h', '.H'): header_extensions.append('.H') # TODO: The following two lines will work when integrated back to SCons # TODO: Meanwhile the third line will do the work #cplusplus = __import__('c++', globals(), locals(), []) #cxx_suffixes = cplusplus.CXXSuffixes cxx_suffixes = [".c", ".cxx", ".cpp", ".cc"] def checkMocIncluded(target, source, env): moc = target[0] cpp = source[0] # looks like cpp.includes is cleared before the build stage :-( # not really sure about the path transformations (moc.cwd? cpp.cwd?) :-/ path = SCons.Defaults.CScan.path_function(env, moc.cwd) includes = SCons.Defaults.CScan(cpp, env, path) if not moc in includes: SCons.Warnings.warn( GeneratedMocFileNotIncluded, "Generated moc file '%s' is not included by '%s'" % (str(moc), str(cpp))) def find_file(filename, paths, node_factory): for dir in paths: node = node_factory(filename, dir) if node.rexists(): return node return None class _Automoc: """ Callable class, which works as an emitter for Programs, SharedLibraries and StaticLibraries. """ def __init__(self, objBuilderName): self.objBuilderName = objBuilderName # some regular expressions: # Q_OBJECT detection self.qo_search = re.compile(r'[^A-Za-z0-9]Q_OBJECT[^A-Za-z0-9]') # cxx and c comment 'eater' self.ccomment = re.compile(r'/\*(.*?)\*/',re.S) self.cxxcomment = re.compile(r'//.*$',re.M) # we also allow Q_OBJECT in a literal string self.literal_qobject = re.compile(r'"[^\n]*Q_OBJECT[^\n]*"') def create_automoc_options(self, env): """ Create a dictionary with variables related to Automocing, based on the current environment. Is executed once in the __call__ routine. """ moc_options = {'auto_scan' : True, 'auto_scan_strategy' : 0, 'gobble_comments' : 0, 'debug' : 0, 'auto_cpppath' : True, 'cpppaths' : []} try: if int(env.subst('$QT4_AUTOSCAN')) == 0: moc_options['auto_scan'] = False except ValueError: pass try: moc_options['auto_scan_strategy'] = int(env.subst('$QT4_AUTOSCAN_STRATEGY')) except ValueError: pass try: moc_options['gobble_comments'] = int(env.subst('$QT4_GOBBLECOMMENTS')) except ValueError: pass try: moc_options['debug'] = int(env.subst('$QT4_DEBUG')) except ValueError: pass try: if int(env.subst('$QT4_AUTOMOC_SCANCPPPATH')) == 0: moc_options['auto_cpppath'] = False except ValueError: pass if moc_options['auto_cpppath']: paths = env.get('QT4_AUTOMOC_CPPPATH', []) if not paths: paths = env.get('CPPPATH', []) moc_options['cpppaths'].extend(paths) return moc_options def __automoc_strategy_simple(self, env, moc_options, cpp, cpp_contents, out_sources): """ Default Automoc strategy (Q_OBJECT driven): detect a header file (alongside the current cpp/cxx) that contains a Q_OBJECT macro...and MOC it. If a Q_OBJECT macro is also found in the cpp/cxx itself, it gets MOCed too. """ h=None for h_ext in header_extensions: # try to find the header file in the corresponding source # directory hname = self.splitext(cpp.name)[0] + h_ext h = find_file(hname, [cpp.get_dir()]+moc_options['cpppaths'], env.File) if h: if moc_options['debug']: print "scons: qt4: Scanning '%s' (header of '%s')" % (str(h), str(cpp)) h_contents = h.get_contents() if moc_options['gobble_comments']: h_contents = self.ccomment.sub('', h_contents) h_contents = self.cxxcomment.sub('', h_contents) h_contents = self.literal_qobject.sub('""', h_contents) break if not h and moc_options['debug']: print "scons: qt4: no header for '%s'." % (str(cpp)) if h and self.qo_search.search(h_contents): # h file with the Q_OBJECT macro found -> add moc_cpp moc_cpp = env.Moc4(h) moc_o = self.objBuilder(moc_cpp) out_sources.extend(moc_o) if moc_options['debug']: print "scons: qt4: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(moc_cpp)) if cpp and self.qo_search.search(cpp_contents): # cpp file with Q_OBJECT macro found -> add moc # (to be included in cpp) moc = env.Moc4(cpp) env.Ignore(moc, moc) if moc_options['debug']: print "scons: qt4: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc)) def __automoc_strategy_include_driven(self, env, moc_options, cpp, cpp_contents, out_sources): """ Automoc strategy #1 (include driven): searches for "include" statements of MOCed files in the current cpp/cxx file. This strategy tries to add support for the compilation of the qtsolutions... """ if self.splitext(str(cpp))[1] in cxx_suffixes: added = False h_moc = "%s%s%s" % (env.subst('$QT4_XMOCHPREFIX'), self.splitext(cpp.name)[0], env.subst('$QT4_XMOCHSUFFIX')) cxx_moc = "%s%s%s" % (env.subst('$QT4_XMOCCXXPREFIX'), self.splitext(cpp.name)[0], env.subst('$QT4_XMOCCXXSUFFIX')) inc_h_moc = r'#include\s+"%s"' % h_moc inc_cxx_moc = r'#include\s+"%s"' % cxx_moc # Search for special includes in qtsolutions style if cpp and re.search(inc_h_moc, cpp_contents): # cpp file with #include directive for a MOCed header found -> add moc # Try to find header file h=None hname="" for h_ext in header_extensions: # Try to find the header file in the # corresponding source directory hname = self.splitext(cpp.name)[0] + h_ext h = find_file(hname, [cpp.get_dir()]+moc_options['cpppaths'], env.File) if h: if moc_options['debug']: print "scons: qt4: Scanning '%s' (header of '%s')" % (str(h), str(cpp)) h_contents = h.get_contents() if moc_options['gobble_comments']: h_contents = self.ccomment.sub('', h_contents) h_contents = self.cxxcomment.sub('', h_contents) h_contents = self.literal_qobject.sub('""', h_contents) break if not h and moc_options['debug']: print "scons: qt4: no header for '%s'." % (str(cpp)) if h and self.qo_search.search(h_contents): # h file with the Q_OBJECT macro found -> add moc_cpp moc_cpp = env.XMoc4(h) env.Ignore(moc_cpp, moc_cpp) added = True # Removing file from list of sources, because it is not to be # compiled but simply included by the cpp/cxx file. for idx, s in enumerate(out_sources): if hasattr(s, "sources") and len(s.sources) > 0: if str(s.sources[0]) == h_moc: out_sources.pop(idx) break if moc_options['debug']: print "scons: qt4: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(h_moc)) else: if moc_options['debug']: print "scons: qt4: found no Q_OBJECT macro in '%s', but a moc'ed version '%s' gets included in '%s'" % (str(h), inc_h_moc, cpp.name) if cpp and re.search(inc_cxx_moc, cpp_contents): # cpp file with #include directive for a MOCed cxx file found -> add moc if self.qo_search.search(cpp_contents): moc = env.XMoc4(target=cxx_moc, source=cpp) env.Ignore(moc, moc) added = True if moc_options['debug']: print "scons: qt4: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc)) else: if moc_options['debug']: print "scons: qt4: found no Q_OBJECT macro in '%s', although a moc'ed version '%s' of itself gets included" % (cpp.name, inc_cxx_moc) if not added: # Fallback to default Automoc strategy (Q_OBJECT driven) self.__automoc_strategy_simple(env, moc_options, cpp, cpp_contents, out_sources) def __call__(self, target, source, env): """ Smart autoscan function. Gets the list of objects for the Program or Lib. Adds objects and builders for the special qt4 files. """ moc_options = self.create_automoc_options(env) # some shortcuts used in the scanner self.splitext = SCons.Util.splitext self.objBuilder = getattr(env, self.objBuilderName) # The following is kind of hacky to get builders working properly (FIXME) objBuilderEnv = self.objBuilder.env self.objBuilder.env = env mocBuilderEnv = env.Moc4.env env.Moc4.env = env xMocBuilderEnv = env.XMoc4.env env.XMoc4.env = env # make a deep copy for the result; MocH objects will be appended out_sources = source[:] for obj in source: if not moc_options['auto_scan']: break if isinstance(obj,basestring): # big kludge! print "scons: qt4: '%s' MAYBE USING AN OLD SCONS VERSION AND NOT CONVERTED TO 'File'. Discarded." % str(obj) continue if not obj.has_builder(): # binary obj file provided if moc_options['debug']: print "scons: qt4: '%s' seems to be a binary. Discarded." % str(obj) continue cpp = obj.sources[0] if not self.splitext(str(cpp))[1] in cxx_suffixes: if moc_options['debug']: print "scons: qt4: '%s' is no cxx file. Discarded." % str(cpp) # c or fortran source continue try: cpp_contents = cpp.get_contents() if moc_options['gobble_comments']: cpp_contents = self.ccomment.sub('', cpp_contents) cpp_contents = self.cxxcomment.sub('', cpp_contents) cpp_contents = self.literal_qobject.sub('""', cpp_contents) except: continue # may be an still not generated source if moc_options['auto_scan_strategy'] == 0: # Default Automoc strategy (Q_OBJECT driven) self.__automoc_strategy_simple(env, moc_options, cpp, cpp_contents, out_sources) else: # Automoc strategy #1 (include driven) self.__automoc_strategy_include_driven(env, moc_options, cpp, cpp_contents, out_sources) # restore the original env attributes (FIXME) self.objBuilder.env = objBuilderEnv env.Moc4.env = mocBuilderEnv env.XMoc4.env = xMocBuilderEnv # We return the set of source entries as sorted sequence, else # the order might accidentally change from one build to another # and trigger unwanted rebuilds. For proper sorting, a key function # has to be specified...FS.Entry (and Base nodes in general) do not # provide a __cmp__, for performance reasons. return (target, sorted(set(out_sources), key=lambda entry : str(entry))) AutomocShared = _Automoc('SharedObject') AutomocStatic = _Automoc('StaticObject') def _detect(env): """Not really safe, but fast method to detect the Qt4 library""" # TODO: check output of "moc -v" for correct version >= 4.0.0 try: return env['QT4DIR'] except KeyError: pass try: return env['QTDIR'] except KeyError: pass try: return os.environ['QT4DIR'] except KeyError: pass try: return os.environ['QTDIR'] except KeyError: pass moc = env.WhereIs('moc-qt4') or env.WhereIs('moc4') or env.WhereIs('moc') if moc: QT4DIR = os.path.dirname(os.path.dirname(moc)) SCons.Warnings.warn( QtdirNotFound, "QT4DIR variable is not defined, using moc executable as a hint (QT4DIR=%s)" % QT4DIR) return QT4DIR raise SCons.Errors.StopError( QtdirNotFound, "Could not detect Qt 4 installation") return None def __scanResources(node, env, path, arg): # Helper function for scanning .qrc resource files # I've been careful on providing names relative to the qrc file # If that was not needed this code could be simplified a lot def recursiveFiles(basepath, path) : result = [] for item in os.listdir(os.path.join(basepath, path)) : itemPath = os.path.join(path, item) if os.path.isdir(os.path.join(basepath, itemPath)) : result += recursiveFiles(basepath, itemPath) else: result.append(itemPath) return result contents = node.get_contents() includes = qrcinclude_re.findall(contents) qrcpath = os.path.dirname(node.path) dirs = [included for included in includes if os.path.isdir(os.path.join(qrcpath,included))] # dirs need to include files recursively for dir in dirs : includes.remove(dir) includes+=recursiveFiles(qrcpath,dir) return includes # # Scanners # __qrcscanner = SCons.Scanner.Scanner(name = 'qrcfile', function = __scanResources, argument = None, skeys = ['.qrc']) # # Emitters # def __qrc_path(head, prefix, tail, suffix): if head: if tail: return os.path.join(head, "%s%s%s" % (prefix, tail, suffix)) else: return "%s%s%s" % (prefix, head, suffix) else: return "%s%s%s" % (prefix, tail, suffix) def __qrc_emitter(target, source, env): sourceBase, sourceExt = os.path.splitext(SCons.Util.to_String(source[0])) sHead = None sTail = sourceBase if sourceBase: sHead, sTail = os.path.split(sourceBase) t = __qrc_path(sHead, env.subst('$QT4_QRCCXXPREFIX'), sTail, env.subst('$QT4_QRCCXXSUFFIX')) return t, source # # Action generators # def __moc_generator_from_h(source, target, env, for_signature): pass_defines = False try: if int(env.subst('$QT4_CPPDEFINES_PASSTOMOC')) == 1: pass_defines = True except ValueError: pass if pass_defines: return '$QT4_MOC $QT4_MOCDEFINES $QT4_MOCFROMHFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE' else: return '$QT4_MOC $QT4_MOCFROMHFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE' def __moc_generator_from_cxx(source, target, env, for_signature): pass_defines = False try: if int(env.subst('$QT4_CPPDEFINES_PASSTOMOC')) == 1: pass_defines = True except ValueError: pass if pass_defines: return ['$QT4_MOC $QT4_MOCDEFINES $QT4_MOCFROMCXXFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE', SCons.Action.Action(checkMocIncluded,None)] else: return ['$QT4_MOC $QT4_MOCFROMCXXFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE', SCons.Action.Action(checkMocIncluded,None)] def __mocx_generator_from_h(source, target, env, for_signature): pass_defines = False try: if int(env.subst('$QT4_CPPDEFINES_PASSTOMOC')) == 1: pass_defines = True except ValueError: pass if pass_defines: return '$QT4_MOC $QT4_MOCDEFINES $QT4_MOCFROMHFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE' else: return '$QT4_MOC $QT4_MOCFROMHFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE' def __mocx_generator_from_cxx(source, target, env, for_signature): pass_defines = False try: if int(env.subst('$QT4_CPPDEFINES_PASSTOMOC')) == 1: pass_defines = True except ValueError: pass if pass_defines: return ['$QT4_MOC $QT4_MOCDEFINES $QT4_MOCFROMCXXFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE', SCons.Action.Action(checkMocIncluded,None)] else: return ['$QT4_MOC $QT4_MOCFROMCXXFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE', SCons.Action.Action(checkMocIncluded,None)] def __qrc_generator(source, target, env, for_signature): name_defined = False try: if env.subst('$QT4_QRCFLAGS').find('-name') >= 0: name_defined = True except ValueError: pass if name_defined: return '$QT4_RCC $QT4_QRCFLAGS $SOURCE -o $TARGET' else: qrc_suffix = env.subst('$QT4_QRCSUFFIX') src = str(source[0]) head, tail = os.path.split(src) if tail: src = tail qrc_suffix = env.subst('$QT4_QRCSUFFIX') if src.endswith(qrc_suffix): qrc_stem = src[:-len(qrc_suffix)] else: qrc_stem = src return '$QT4_RCC $QT4_QRCFLAGS -name %s $SOURCE -o $TARGET' % qrc_stem # # Builders # __ts_builder = SCons.Builder.Builder( action = SCons.Action.Action('$QT4_LUPDATECOM','$QT4_LUPDATECOMSTR'), suffix = '.ts', source_factory = SCons.Node.FS.Entry) __qm_builder = SCons.Builder.Builder( action = SCons.Action.Action('$QT4_LRELEASECOM','$QT4_LRELEASECOMSTR'), src_suffix = '.ts', suffix = '.qm') __qrc_builder = SCons.Builder.Builder( action = SCons.Action.CommandGeneratorAction(__qrc_generator, {"cmdstr":"QT4_QRCCOMSTR"}), source_scanner = __qrcscanner, src_suffix = '$QT4_QRCSUFFIX', suffix = '$QT4_QRCCXXSUFFIX', prefix = '$QT4_QRCCXXPREFIX', single_source = 1) __ex_moc_builder = SCons.Builder.Builder( action = SCons.Action.CommandGeneratorAction(__moc_generator_from_h, {"cmdstr":"$QT4_MOCFROMHCOMSTR"})) __ex_uic_builder = SCons.Builder.Builder( action = SCons.Action.Action('$QT4_UICCOM', '$QT4_UICCOMSTR'), src_suffix = '.ui') # # Wrappers (pseudo-Builders) # def Ts4(env, target, source=None, *args, **kw): """ A pseudo-Builder wrapper around the LUPDATE executable of Qt4. lupdate [options] [source-file|path]... -ts ts-files """ if not SCons.Util.is_List(target): target = [target] if not source: source = target[:] if not SCons.Util.is_List(source): source = [source] # Check QT4_CLEAN_TS and use NoClean() function clean_ts = False try: if int(env.subst('$QT4_CLEAN_TS')) == 1: clean_ts = True except ValueError: pass result = [] for t in target: obj = __ts_builder.__call__(env, t, source, **kw) # Prevent deletion of the .ts file, unless explicitly specified if not clean_ts: env.NoClean(obj) # Always make our target "precious", such that it is not deleted # prior to a rebuild env.Precious(obj) # Add to resulting target list result.extend(obj) return result def Qm4(env, target, source=None, *args, **kw): """ A pseudo-Builder wrapper around the LRELEASE executable of Qt4. lrelease [options] ts-files [-qm qm-file] """ if not SCons.Util.is_List(target): target = [target] if not source: source = target[:] if not SCons.Util.is_List(source): source = [source] result = [] for t in target: result.extend(__qm_builder.__call__(env, t, source, **kw)) return result def Qrc4(env, target, source=None, *args, **kw): """ A pseudo-Builder wrapper around the RCC executable of Qt4. rcc [options] qrc-files -o out-file """ if not SCons.Util.is_List(target): target = [target] if not source: source = target[:] if not SCons.Util.is_List(source): source = [source] result = [] for t, s in zip(target, source): result.extend(__qrc_builder.__call__(env, t, s, **kw)) return result def ExplicitMoc4(env, target, source, *args, **kw): """ A pseudo-Builder wrapper around the MOC executable of Qt4. moc [options] <header-file> """ if not SCons.Util.is_List(target): target = [target] if not SCons.Util.is_List(source): source = [source] result = [] for t in target: # Is it a header or a cxx file? result.extend(__ex_moc_builder.__call__(env, t, source, **kw)) return result def ExplicitUic4(env, target, source, *args, **kw): """ A pseudo-Builder wrapper around the UIC executable of Qt4. uic [options] <uifile> """ if not SCons.Util.is_List(target): target = [target] if not SCons.Util.is_List(source): source = [source] result = [] for t in target: result.extend(__ex_uic_builder.__call__(env, t, source, **kw)) return result def generate(env): """Add Builders and construction variables for qt4 to an Environment.""" def locateQt4Command(env, command, qtdir) : # Take cross into account. ptCrossCommand = env['PT_CROSS'] + command # Decorations (linux and msys/mingw/cygwin accept. env in linux) # We issue something like 'ID=DSCONS_UIC /path/to/uic' # This is just for recognizing at command print time. ptDecoration = '' if command == 'moc': ptDecoration = 'ID=DSCONS_MOC' elif command == 'uic' : ptDecoration = 'ID=DSCONS_UIC' elif command == 'rcc' : ptDecoration = 'ID=DSCONS_RCC' elif command == 'lupdate' : ptDecoration = 'ID=DSCONS_LUPDATE' elif command == 'lrelease' : ptDecoration = 'ID=DSCONS_LRELEASE' if sys.platform.startswith('win') : ptDecoration = '' suffixes = [ '-qt4', '-qt4.exe', '4', '4.exe', '', '.exe', ] triedPaths = [] for suffix in suffixes : fullpath = os.path.join(qtdir,'bin',ptCrossCommand + suffix) if os.access(fullpath, os.X_OK) : return ptDecoration + ' ' + fullpath triedPaths.append(fullpath) fullpath = env.Detect([ptCrossCommand+'-qt4', ptCrossCommand+'4', ptCrossCommand]) if not (fullpath is None) : return ptDecoration + ' ' + fullpath if command in ('lupdate','lrelease'): print 'Qt4 could not locate \'' + \ ptCrossCommand + '\' ' + \ '(This might be acceptable)' return None raise Exception("Qt4 command '" + command + "' not found. Tried: " + ', '.join(triedPaths)) CLVar = SCons.Util.CLVar Action = SCons.Action.Action Builder = SCons.Builder.Builder env['QT4DIR'] = _detect(env) # TODO: 'Replace' should be 'SetDefault' # env.SetDefault( env.Replace( QT4DIR = _detect(env), QT4_BINPATH = os.path.join('$QT4DIR', 'bin'), QT4_LIBPATH = os.path.join('$QT4DIR', 'lib'), # TODO: This is not reliable to QT4DIR value changes but needed in order to support '-qt4' variants QT4_MOC = locateQt4Command(env,'moc', env['QT4DIR']), QT4_UIC = locateQt4Command(env,'uic', env['QT4DIR']), QT4_RCC = locateQt4Command(env,'rcc', env['QT4DIR']), QT4_LUPDATE = locateQt4Command(env,'lupdate', env['QT4DIR']), QT4_LRELEASE = locateQt4Command(env,'lrelease', env['QT4DIR']), QT4_AUTOSCAN = 1, # Should the qt4 tool try to figure out, which sources are to be moc'ed? QT4_AUTOSCAN_STRATEGY = 0, # While scanning for files to moc, should we search for includes in qtsolutions style? QT4_GOBBLECOMMENTS = 0, # If set to 1, comments are removed before scanning cxx/h files. QT4_CPPDEFINES_PASSTOMOC = 1, # If set to 1, all CPPDEFINES get passed to the moc executable. QT4_CLEAN_TS = 0, # If set to 1, translation files (.ts) get cleaned on 'scons -c' QT4_AUTOMOC_SCANCPPPATH = 1, # If set to 1, the CPPPATHs (or QT4_AUTOMOC_CPPPATH) get scanned for moc'able files QT4_AUTOMOC_CPPPATH = [], # Alternative paths that get scanned for moc files # Some Qt4 specific flags. I don't expect someone wants to # manipulate those ... QT4_UICFLAGS = CLVar(''), QT4_MOCFROMHFLAGS = CLVar(''), QT4_MOCFROMCXXFLAGS = CLVar('-i'), QT4_QRCFLAGS = '', QT4_LUPDATEFLAGS = '', QT4_LRELEASEFLAGS = '', # suffixes/prefixes for the headers / sources to generate QT4_UISUFFIX = '.ui', QT4_UICDECLPREFIX = 'ui_', QT4_UICDECLSUFFIX = '.h', QT4_MOCINCPREFIX = '-I', QT4_MOCHPREFIX = 'moc_', QT4_MOCHSUFFIX = '$CXXFILESUFFIX', QT4_MOCCXXPREFIX = '', QT4_MOCCXXSUFFIX = '.moc', QT4_QRCSUFFIX = '.qrc', QT4_QRCCXXSUFFIX = '$CXXFILESUFFIX', QT4_QRCCXXPREFIX = 'qrc_', QT4_MOCDEFPREFIX = '-D', QT4_MOCDEFSUFFIX = '', QT4_MOCDEFINES = '${_defines(QT4_MOCDEFPREFIX, CPPDEFINES, QT4_MOCDEFSUFFIX, __env__)}', QT4_MOCCPPPATH = [], QT4_MOCINCFLAGS = '$( ${_concat(QT4_MOCINCPREFIX, QT4_MOCCPPPATH, INCSUFFIX, __env__, RDirs)} $)', # Commands for the qt4 support ... QT4_UICCOM = '$QT4_UIC $QT4_UICFLAGS -o $TARGET $SOURCE', QT4_LUPDATECOM = '$QT4_LUPDATE $QT4_LUPDATEFLAGS $SOURCES -ts $TARGET', QT4_LRELEASECOM = '$QT4_LRELEASE $QT4_LRELEASEFLAGS -qm $TARGET $SOURCES', # Specialized variables for the Extended Automoc support # (Strategy #1 for qtsolutions) QT4_XMOCHPREFIX = 'moc_', QT4_XMOCHSUFFIX = '.cpp', QT4_XMOCCXXPREFIX = '', QT4_XMOCCXXSUFFIX = '.moc', ) try: env.AddMethod(Ts4, "Ts4") env.AddMethod(Qm4, "Qm4") env.AddMethod(Qrc4, "Qrc4") env.AddMethod(ExplicitMoc4, "ExplicitMoc4") env.AddMethod(ExplicitUic4, "ExplicitUic4") except AttributeError: # Looks like we use a pre-0.98 version of SCons... from SCons.Script.SConscript import SConsEnvironment SConsEnvironment.Ts4 = Ts4 SConsEnvironment.Qm4 = Qm4 SConsEnvironment.Qrc4 = Qrc4 SConsEnvironment.ExplicitMoc4 = ExplicitMoc4 SConsEnvironment.ExplicitUic4 = ExplicitUic4 # Interface builder uic4builder = Builder( action = SCons.Action.Action('$QT4_UICCOM', '$QT4_UICCOMSTR'), src_suffix='$QT4_UISUFFIX', suffix='$QT4_UICDECLSUFFIX', prefix='$QT4_UICDECLPREFIX', single_source = True #TODO: Consider the uiscanner on new scons version ) env['BUILDERS']['Uic4'] = uic4builder # Metaobject builder mocBld = Builder(action={}, prefix={}, suffix={}) for h in header_extensions: act = SCons.Action.CommandGeneratorAction(__moc_generator_from_h, {"cmdstr":"$QT4_MOCFROMHCOMSTR"}) mocBld.add_action(h, act) mocBld.prefix[h] = '$QT4_MOCHPREFIX' mocBld.suffix[h] = '$QT4_MOCHSUFFIX' for cxx in cxx_suffixes: act = SCons.Action.CommandGeneratorAction(__moc_generator_from_cxx, {"cmdstr":"$QT4_MOCFROMCXXCOMSTR"}) mocBld.add_action(cxx, act) mocBld.prefix[cxx] = '$QT4_MOCCXXPREFIX' mocBld.suffix[cxx] = '$QT4_MOCCXXSUFFIX' env['BUILDERS']['Moc4'] = mocBld # Metaobject builder for the extended auto scan feature # (Strategy #1 for qtsolutions) xMocBld = Builder(action={}, prefix={}, suffix={}) for h in header_extensions: act = SCons.Action.CommandGeneratorAction(__mocx_generator_from_h, {"cmdstr":"$QT4_MOCFROMHCOMSTR"}) xMocBld.add_action(h, act) xMocBld.prefix[h] = '$QT4_XMOCHPREFIX' xMocBld.suffix[h] = '$QT4_XMOCHSUFFIX' for cxx in cxx_suffixes: act = SCons.Action.CommandGeneratorAction(__mocx_generator_from_cxx, {"cmdstr":"$QT4_MOCFROMCXXCOMSTR"}) xMocBld.add_action(cxx, act) xMocBld.prefix[cxx] = '$QT4_XMOCCXXPREFIX' xMocBld.suffix[cxx] = '$QT4_XMOCCXXSUFFIX' env['BUILDERS']['XMoc4'] = xMocBld # Add the Qrc4 action to the CXX file builder (registers the # *.qrc extension with the Environment) cfile_builder, cxxfile_builder = SCons.Tool.createCFileBuilders(env) qrc_act = SCons.Action.CommandGeneratorAction(__qrc_generator, {"cmdstr":"$QT4_QRCCOMSTR"}) cxxfile_builder.add_action('$QT4_QRCSUFFIX', qrc_act) cxxfile_builder.add_emitter('$QT4_QRCSUFFIX', __qrc_emitter) # We use the emitters of Program / StaticLibrary / SharedLibrary # to scan for moc'able files # We can't refer to the builders directly, we have to fetch them # as Environment attributes because that sets them up to be called # correctly later by our emitter. env.AppendUnique(PROGEMITTER =[AutomocStatic], SHLIBEMITTER=[AutomocShared], LIBEMITTER =[AutomocStatic], ) # TODO: Does dbusxml2cpp need an adapter try: env.AddMethod(enable_modules, "EnableQt4Modules") except AttributeError: # Looks like we use a pre-0.98 version of SCons... from SCons.Script.SConscript import SConsEnvironment SConsEnvironment.EnableQt4Modules = enable_modules def enable_modules(self, modules, debug=False) : import sys validModules = [ 'QtCore', 'QtGui', 'QtOpenGL', 'Qt3Support', 'QtAssistant', # deprecated 'QtAssistantClient', 'QtScript', 'QtDBus', 'QtSql', 'QtSvg', # The next modules have not been tested yet so, please # maybe they require additional work on non Linux platforms 'QtNetwork', 'QtTest', 'QtXml', 'QtXmlPatterns', 'QtUiTools', 'QtDesigner', 'QtDesignerComponents', 'QtWebKit', 'QtHelp', 'QtScript', 'QtScriptTools', 'QtMultimedia', ] pclessModules = [ # in qt <= 4.3 designer and designerComponents are pcless, on qt4.4 they are not, so removed. # 'QtDesigner', # 'QtDesignerComponents', ] staticModules = [ 'QtUiTools', ] invalidModules=[] for module in modules: if module not in validModules : invalidModules.append(module) if invalidModules : raise Exception("Modules %s are not Qt4 modules. Valid Qt4 modules are: %s"% ( str(invalidModules),str(validModules))) moduleDefines = { 'QtScript' : ['QT_SCRIPT_LIB'], 'QtSvg' : ['QT_SVG_LIB'], 'Qt3Support' : ['QT_QT3SUPPORT_LIB','QT3_SUPPORT'], 'QtSql' : ['QT_SQL_LIB'], 'QtXml' : ['QT_XML_LIB'], 'QtOpenGL' : ['QT_OPENGL_LIB'], 'QtGui' : ['QT_GUI_LIB'], 'QtNetwork' : ['QT_NETWORK_LIB'], 'QtCore' : ['QT_CORE_LIB'], } for module in modules : try : self.AppendUnique(CPPDEFINES=moduleDefines[module]) except: pass debugSuffix = '' if sys.platform in ["darwin", "linux2", "win32"] : if debug : if sys.platform in ["win32"] : debugSuffix = 'd' else : debugSuffix = '_debug' for module in modules : if module not in pclessModules : continue self.AppendUnique(LIBS=[module+debugSuffix]) self.AppendUnique(LIBPATH=[os.path.join("$QT4DIR","lib")]) self.AppendUnique(CPPPATH=[os.path.join("$QT4DIR","include","qt4")]) self.AppendUnique(CPPPATH=[os.path.join("$QT4DIR","include","qt4",module)]) pcmodules = [module+debugSuffix for module in modules if module not in pclessModules ] if 'QtDBus' in pcmodules: self.AppendUnique(CPPPATH=[os.path.join("$QT4DIR","include","qt4","QtDBus")]) if "QtAssistant" in pcmodules: self.AppendUnique(CPPPATH=[os.path.join("$QT4DIR","include","qt4","QtAssistant")]) self["QT4_MOCCPPPATH"] = self["CPPPATH"] return else : print "CHECK ME. SHOULDN'T" Exit(1) def exists(env): return _detect(env)
Python
#!/usr/bin/env python #coding: utf-8 # # scdd.py daemon process # # author: observer # email: jingchaohu@gmail.com # blog: http://obmem.com # last edit @ 2009.12.19 import os,sys,time import re from daemon import Daemon import sqlite3 import fetchvc from download import httpfetch from Queue import Queue from threading import Thread class MyDaemon(Daemon): def __init__(self,path,pid): self.path = path self.q = Queue() Daemon.__init__(self,pid) def thread_fetch(self): conn = sqlite3.connect(self.path+'/verycd.sqlite3.db') conn.text_factory = str while True: topic = self.q.get() try: fetchvc.fetch(topic,conn) except: pass self.q.task_done() def run(self): for i in range(8): t = Thread(target=self.thread_fetch) t.setDaemon(True) t.start() conn = sqlite3.connect(self.path+'/verycd.sqlite3.db') conn.text_factory = str while True: try: #check searchqueue every 10 secs taskqueue = open(self.path+'/searchqueue','r').readlines() print taskqueue,time.mktime(time.gmtime()),time.mktime(time.gmtime())%900 open(self.path+'/searchqueue','w').write('') for task in taskqueue: url = 'http://www.verycd.com/search/folders/'+task print 'fetching', url, '...' res = httpfetch(url) print '...fetching completed' topics = re.compile(r'/topics/(\d+)',re.DOTALL).findall(res) topics = set(topics) for topic in topics: self.q.put(topic) if taskqueue == []: time.sleep(10) # read feed every 900 secs if time.mktime(time.gmtime())%800<10: url = 'http://www.verycd.com/sto/feed' print 'fetching feed ...' feeds = httpfetch(url) topics = re.compile(r'/topics/(\d+)',re.DOTALL).findall(feeds) topics = set(topics) print topics now = time.mktime(time.gmtime()) for topic in topics: self.q.put(topic) # read hot everyday at gmt 19:00 timeofday = time.mktime(time.gmtime())%86400 if timeofday>68400 and timeofday < 68410: url = 'http://www.verycd.com/' print 'fetching homepage ...' home = httpfetch(url) hotzone = re.compile(r'热门资源.*?</dl>',re.DOTALL).search(home).group() hot = re.compile(r'<a href="/topics/(\d+)/"[^>]*>(《.*?》)[^<]*</a>',re.DOTALL).findall(hotzone) html = '<h2 style="color:red">每日热门资源</h2>\n' for topic in hot: print 'fetching hot topic',topic[0],'...' self.q.put(topic[0]) html += '&nbsp;<a target="_parent" href="/?id=%s">%s</a>&nbsp;\n' % topic open(self.path+'/static/hot.html','w').write(html) # update 20 whole pages at gmt 19:10 if timeofday>69000 and timeofday < 69010: urlbase = 'http://www.verycd.com/sto/~all/page' for i in range(1,20): print 'fetching list',i,'...' url = urlbase+str(i) res = httpfetch(url) res2 = re.compile(r'"topic-list"(.*?)"pnav"',re.DOTALL).findall(res) if res2: res2 = res2[0] else: continue topics = re.compile(r'/topics/(\d+)',re.DOTALL).findall(res2) topics = set(topics) print topics for topic in topics: q.put(topic) except: time.sleep(10) continue if __name__ == "__main__": path = os.path.dirname(os.path.realpath(sys.argv[0])) daemon = MyDaemon(path=path,pid='/tmp/simplevc.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'run' == sys.argv[1]: daemon.run() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2)
Python
#!/usr/bin/env python import sys, os, time, atexit from signal import SIGTERM class Daemon: """ A generic daemon class. Usage: subclass the Daemon class and override the run() method """ def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile def daemonize(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError, e: sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() si = file(self.stdin, 'r') so = file(self.stdout, 'a+') se = file(self.stderr, 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write("%s\n" % pid) def delpid(self): os.remove(self.pidfile) def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message = "pidfile %s already exist. Daemon already running?\n" sys.stderr.write(message % self.pidfile) sys.exit(1) # Start the daemon self.daemonize() self.run() def stop(self): """ Stop the daemon """ # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = "pidfile %s does not exist. Daemon not running?\n" sys.stderr.write(message % self.pidfile) return # not an error in a restart # Try killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if err.find("No such process") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print str(err) sys.exit(1) def restart(self): """ Restart the daemon """ self.stop() self.start() def run(self): """ You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # fetchvc.py fetch resources from verycd # # author: observer # email: jingchaohu@gmail.com # blog: http://obmem.com # last edit @ 2009.12.16 import urllib import re import sqlite3 import time import os,sys from threading import Thread from Queue import Queue from download import httpfetch path = os.path.dirname(os.path.realpath(sys.argv[0])) conn = sqlite3.connect(path+'/verycd.sqlite3.db') conn.text_factory = str q = Queue() MAXC = 8 def thread_fetch(): conn = sqlite3.connect(path+'/verycd.sqlite3.db') conn.text_factory = str while True: topic = q.get() fetch(topic,conn) q.task_done() def search(keyword,full=True): '''search verycd, fetch search results''' url = 'http://www.verycd.com/search/folders/'+keyword print 'fetching search results ...' res = httpfetch(url) topics = re.compile(r'/topics/(\d+)',re.DOTALL).findall(res) topics = set(topics) links = [] if full: links = re.compile(r'/search/folders/(.*?\?start=\d+)',re.DOTALL).findall(res) print links print topics if topics: for topic in topics: q.put(topic) if full and links: for key in links: search(key,full=False) def hot(): ''' read verycd hot res and keep update very day ''' url = 'http://www.verycd.com/' print 'fetching homepage ...' home = httpfetch(url) hotzone = re.compile(r'热门资源.*?</dl>',re.DOTALL).search(home).group() hot = re.compile(r'<a href="/topics/(\d+)/"[^>]*>(《.*?》)[^<]*</a>',re.DOTALL).findall(hotzone) html = '<h2 style="color:red">每日热门资源</h2>\n' for topic in hot: print 'fetching hot topic',topic[0],'...' q.put(topic[0]) html += '&nbsp;<a target="_parent" href="/?id=%s">%s</a>&nbsp;\n' % topic open(path+'/static/hot.html','w').write(html) def feed(): ''' read verycd feed and keep update very 30 min ''' url = 'http://www.verycd.com/sto/feed' print 'fetching feed ...' feeds = httpfetch(url) ids = re.compile(r'/topics/(\d+)',re.DOTALL).findall(feeds) ids = set(ids) print ids now = time.mktime(time.gmtime()) for id in ids: q.put(id) #updtime = fetch(id) #updtime = time.mktime(time.strptime(updtime,'%Y/%m/%d %H:%M:%S'))-8*3600 #gmt+8->gmt #diff = now - updtime #print '%10s secs since update' % (diff) #if diff > 1900: # only need recent 30min updates # break def update(num=10): urlbase = 'http://www.verycd.com/sto/~all/page' for i in range(1,num+1): print 'fetching list',i,'...' url = urlbase+str(i) res = httpfetch(url) res2 = re.compile(r'"topic-list"(.*?)"pnav"',re.DOTALL).findall(res) if res2: res2 = res2[0] else: continue topics = re.compile(r'/topics/(\d+)',re.DOTALL).findall(res2) topics = set(topics) print topics for topic in topics: q.put(topic) def fetchall(ran='1-max',debug=False): urlbase = 'http://www.verycd.com/archives/' if ran == '1-max': m1 = 1 res = urllib.urlopen(urlbase).read() m2 = int(re.compile(r'archives/(\d+)').search(res).group(1)) else: m = ran.split('-') m1 = int(m[0]) m2 = int(m[1]) print 'fetching list from',m1,'to',m2,'...' for i in range(m1,m2+1): url = urlbase + '%05d'%i + '.html' print 'fetching from',url,'...' res = httpfetch(url) ids = re.compile(r'topics/(\d+)/',re.DOTALL).findall(res) print ids for id in ids: q.put(id) def fetch(id,conn=conn,debug=False): print 'fetching topic',id,'...' urlbase = 'http://www.verycd.com/topics/' url = urlbase + str(id) res = '' for _ in range(3): try: res = httpfetch(url,report=True) break except: continue abstract = re.compile(r'<h1>.*?visit',re.DOTALL).findall(res) if not abstract: print res if res == '' or '很抱歉' in res: print 'resource does not exist' return else: print 'fetching',id,'again...' return fetch(id,conn) abstract = abstract[0] title = re.compile(r'<h1>(.*?)</h1>',re.DOTALL).findall(abstract)[0] status = re.compile(r'"requestWords">(.*?)<',re.DOTALL).search(abstract).group(1) brief = re.compile(r'"font-weight:normal"><span>(.*?)</td>',re.DOTALL).search(abstract).group(1) brief = re.compile(r'<.*?>',re.DOTALL).sub('',brief).strip() pubtime = re.compile(r'"date-time">(.*?)</span>.*?"date-time">(.*?)</span>',re.DOTALL).findall(abstract)[0] category1 = re.compile(r'分类.*?<td>(.*?)&nbsp;&nbsp;(.*?)&nbsp;&nbsp;',re.DOTALL).findall(abstract)[0] category = ['',''] category[0] = re.compile(r'<.*?>',re.DOTALL).sub('',category1[0]).strip() category[1] = re.compile(r'<.*?>',re.DOTALL).sub('',category1[1]).strip() res2 = re.compile(r'iptcomED2K"><!--eMule.*?<!--eMule end-->',re.DOTALL).findall(res)[0] ed2k = re.compile(r'ed2k="([^"]*)" subtitle_[^=]*="([^"]*)">([^<]*)</a>',re.DOTALL).findall(res2) ed2k.extend( re.compile(r'ed2k="([^"]*)">([^<]*)</a>',re.DOTALL).findall(res2) ) content = re.compile(r'<!--eMule end-->(.*?)<!--Wrap-tail end-->',re.DOTALL).findall(res) if content: content = content[0] content = re.compile(r'<br />',re.DOTALL).sub('\n',content) content = re.compile(r'<.*?>',re.DOTALL).sub('',content) content = re.compile(r'&.*?;',re.DOTALL).sub(' ',content) content = re.compile(r'\n\s+',re.DOTALL).sub('\n',content) content = content.strip() else: content='' if debug: print title print status print brief print pubtime[0],pubtime[1] print category[0],category[1] for x in ed2k: print x print content ed2kstr = '' for x in ed2k: ed2kstr += '`'.join(x)+'`' if not dbfind(id,conn): dbinsert(id,title,status,brief,pubtime,category,ed2kstr,content,conn) else: dbupdate(id,title,status,brief,pubtime,category,ed2kstr,content,conn) return pubtime[1] def dbcreate(): c = conn.cursor() c.execute('''create table verycd( verycdid integer primary key, title text, status text, brief text, pubtime text, updtime text, category1 text, category2 text, ed2k text, content text )''') conn.commit() c.close() def dbinsert(id,title,status,brief,pubtime,category,ed2k,content,conn): c = conn.cursor() c.execute('insert into verycd values(?,?,?,?,?,?,?,?,?,?)',\ (id,title,status,brief,pubtime[0],pubtime[1],category[0],category[1],\ ed2k,content)) conn.commit() c.close() def dbupdate(id,title,status,brief,pubtime,category,ed2k,content,conn): c = conn.cursor() c.execute('update verycd set verycdid=?,title=?,status=?,brief=?,pubtime=?,\ updtime=?,category1=?,category2=?,ed2k=?,content=? where verycdid=?',\ (id,title,status,brief,pubtime[0],pubtime[1],category[0],category[1],\ ed2k,content,id)) conn.commit() c.close() def dbfind(id,conn): c = conn.cursor() c.execute('select 1 from verycd where verycdid=?',(id,)) c.close() for x in c: if 1 in x: return True else: return False def dblist(): c = conn.cursor() c.execute('select * from verycd') for x in c: for y in x: print y def usage(): print '''Usage: python fetchvc.py createdb python fetchvc.py fetchall python fetchvc.py fetch 1-1611 #fetch archive list python fetchvc.py fetch 5633~5684 #fetch topics python fetchvc.py fetch 5633 #fetch a topic python fetchvc.py fetch q=keyword python fetchvc.py list #list the database python fetchvc.py feed #run every 30 min to keep up-to-date python fetchvc.py hot python fetchvc.py update #update first 20 pages, run on a daily basis''' if __name__=='__main__': #initialize thread pool for i in range(MAXC): t = Thread(target=thread_fetch) t.setDaemon(True) t.start() if len(sys.argv) == 1: usage() elif len(sys.argv) == 2: if sys.argv[1] == 'createdb': dbcreate() elif sys.argv[1] == 'fetchall': fetchall() elif sys.argv[1] == 'update': update(20) elif sys.argv[1] == 'update1': update(1) elif sys.argv[1] == 'feed': feed() elif sys.argv[1] == 'hot': hot() elif sys.argv[1] == 'list': dblist() elif len(sys.argv) == 3: if sys.argv[1] != 'fetch': usage() elif '-' in sys.argv[2]: fetchall(sys.argv[2]) elif '~' in sys.argv[2]: m = sys.argv[2].split('~') for i in range(int(m[0]),int(m[1])+1): q.put(i) elif sys.argv[2].startswith("q="): search(sys.argv[2][2:]) else: fetch(int(sys.argv[2]),debug=True) # wait all threads done q.join()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # download.py: download with report # # author: observer # email: jingchaohu@gmail.com # blog: http://obmem.com # last edit @ 2009.12.16 import os,sys import urllib2 from time import time,sleep path = os.path.dirname(os.path.realpath(sys.argv[0])) #proxies = {'http':'http://proxyaddress:port'} #proxy_support = urllib2.ProxyHandler(proxies) #opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) #urllib2.install_opener(opener) #functions def report(blocknum, bs, size, t): if t == 0: t = 1 if size == -1: print '%10s' % (str(blocknum*bs)) + ' downloaded | Speed =' + '%5.2f' % (bs/t/1024) + 'KB/s' else: percent = int(blocknum*bs*100/size) print '%10s' % (str(blocknum*bs)) + '/' + str(size) + 'downloaded | ' + str(percent) + '% Speed =' + '%5.2f'%(bs/t/1024) + 'KB/s' def httpfetch(url, headers={}, reporthook=report, postData=None, report=True): ok = False for _ in range(10): try: reqObj = urllib2.Request(url, postData, headers) fp = urllib2.urlopen(reqObj) headers = fp.info() ok = True break except: sleep(1) continue if not ok: open(path+'/errors','a').write(url+'\n') return '' rawdata = '' bs = 1024*8 size = -1 read = 0 blocknum = 0 if reporthook and report: if "content-length" in headers: size = int(headers["Content-Length"]) reporthook(blocknum, bs, size, 1) t0 = time() while 1: block = '' try: block = fp.read(bs) except: open(path+'/errors','a').write(url+'\n') return '' if block == "": break rawdata += block read += len(block) blocknum += 1 if reporthook and report: reporthook(blocknum, bs, size, time()-t0) t0 = time() # raise exception if actual size does not match content-length header if size >= 0 and read < size: raise ContentTooShortError("retrieval incomplete: got only %i out " "of %i bytes" % (read, size), result) return rawdata if __name__ == '__main__': url = 'http://www.verycd.com' #test it data = httpfetch(url) open('down','w').write(data)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # code.py: based on web.py # # author: observer # email: jingchaohu@gmail.com # blog: http://obmem.com # last edit @ 2009.12.16 import web import sqlite3 web.config.debug = False db = web.database(dbn='sqlite', db='verycd.sqlite3.db') urls = ( '/', 'index', ) render = web.template.render('templates/') app = web.application(urls, globals()) class index: def GET(self): i = web.input(id=None,page='1',q=None,download=None) if i.id: myvar = dict(id=i.id) rec = db.select('verycd',vars=myvar,where="verycdid=$id") for r in rec: fl = None if i.download: links = r['ed2k'].split('`') links = [ x for x in links if 'ed2k:' in x ] fl = '<br>\n'.join(links) return render.id([r,fl,str(r['verycdid'])]) return render.error(404) else: if not i.q: vc = db.select('verycd',order='updtime DESC',limit=20,offset=20*(int(i.page)-1)) num = db.select('verycd',what="count(*) as count")[0].count arg = '/?page' else: qs = i.q.split(' ') qs = [ 'title like \'%'+x+'%\'' for x in qs ] where = ' and '.join(qs) vc = db.select('verycd',order='updtime DESC',limit=20,\ offset=20*(int(i.page)-1),where=where) num = db.select('verycd',what="count(*) as count",where=where)[0].count arg = '/?q='+i.q+'&page' prev = int(i.page)-1 == 0 and '1' or str(int(i.page)-1) next = int(i.page)+1 <= (num-1)/20+1 and str(int(i.page)+1) or i.page end = str((num-1)/20+1) pages = [prev,next,end] left = min(4,int(i.page)-1) right = min(4,int(end)-int(i.page)) if left < 4: right = min(8-left,int(end)-int(i.page)) if right < 4: left = min(8-right,int(i.page)-1) while left > 0: pages.append(str(int(i.page)-left)) left -= 1 j = 0 while j <= right: pages.append(str(int(i.page)+j)) j += 1 return render.index([vc,pages,arg,i.q,num]) if __name__ == "__main__": web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) app.run()
Python
#! /usr/bin/env python # encoding: utf-8 # waf 1.6.2 VERSION='0.3.3' import sys APPNAME='p2t' top = '.' out = 'build' CPP_SOURCES = ['poly2tri/common/shapes.cc', 'poly2tri/sweep/cdt.cc', 'poly2tri/sweep/advancing_front.cc', 'poly2tri/sweep/sweep_context.cc', 'poly2tri/sweep/sweep.cc', 'testbed/main.cc'] from waflib.Tools.compiler_cxx import cxx_compiler cxx_compiler['win32'] = ['g++'] #Platform specific libs if sys.platform == 'win32': # MS Windows sys_libs = ['glfw', 'opengl32'] elif sys.platform == 'darwin': # Apple OSX sys_libs = ['glfw', 'OpenGL'] else: # GNU/Linux, BSD, etc sys_libs = ['glfw', 'GL'] def options(opt): print(' set_options') opt.load('compiler_cxx') def configure(conf): print(' calling the configuration') conf.load('compiler_cxx') conf.env.CXXFLAGS = ['-O3', '-ffast-math'] conf.env.DEFINES_P2T = ['P2T'] conf.env.LIB_P2T = sys_libs def build(bld): print(' building') bld.program(features = 'cxx cxxprogram', source=CPP_SOURCES, target = 'p2t', uselib = 'P2T')
Python
__version__ = '0.1' __all__ = ['util']
Python
import os def walk_dir(rootdir): newdirs = [] filelist = [] newdirs.append(rootdir) # BFS while len(newdirs): for dir in newdirs: newdirs.remove(dir) files = os.listdir(dir) for file in files: if os.path.isdir('file'): newdirs.append(os.path.join(dir, file)) continue filelist.append(os.path.join(dir, file)) return filelist def read_file(path): buf = None if not os.path.isdir(path): f = open(path, 'r') buf = f.read() f.close() else: raise IOError, 'isdir' return buf def write_file(path, content): if not os.path.isdir(path): f = open(path, 'w') f.write(content) f.close() else: raise IOError, 'isdir'
Python
import random, struct class SecureRandom(random.Random): def __init__(self, paranoid=False): self._file = None self._paranoid = paranoid self.seed() def seed(self): if self._file: try: close(self._file) except: pass if self._paranoid: fname = '/dev/random' else: fname = '/dev/urandom' self._file = open(fname, 'r') def rand(self): return abs(struct.unpack('l', self._file.read(4))[0])/(0.+((1<<31))) def randint(self): return struct.unpack('l', self._file.read(4))[0] _SecRandom = SecureRandom() def rand(): global _SecRandom return _SecRandom.rand() def randint(): global _SecRandom return _SecRandom.randint() def main(): print rand() print randint() if __name__ == '__main__': main()
Python
################################################## # the module contains some util function for # operating url ################################################## # version 0.1 2010 Mar 13 import urllib import urllib2 # the file name can not cantian:\,/,:,,*,?,",<,>,| # the url can not contains:',;,1=1,|,<,> # the chars that url can, but file name can not is: \,/,:,*,?," # the chars that file name can, but url can not is: ' def url2filename(url): url = url.replace("\\", "'") url = url.replace("/", "'") url = url.replace(";", "'") url = url.replace("*", "'") url = url.replace("?", "'") url = url.replace('"', "'") return url def quote(url): url = del_duplicate_header('http://', url) header = 'http://' p = url.find(header) if p != -1: u = url[p + len(header):len(url)] else: u = url u = urllib.quote(u) return 'http://%s' % u def get_page_content(url): user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = { 'User-Agent' : user_agent } req = urllib2.Request(url, '', headers) response = urllib2.urlopen(req) return response.read() def del_duplicate_header(header, url): if url[0: len(header)] == header: url = url[len(header): len(url)] return url if __name__ == '__main__': url = """http://\\www.baidu.com;*?\"""" print url2filename(url) url = 'http://www.dianping.com/search/keyword/2/10_\xe6\x9c\x8b\xe5\x8f\x8b\xe8\x81\x9a\xe9\xa4\x90' print quote(url) url = 'http://http://www.baidu.com' url = del_duplicate_header('http://', url) print url
Python
import logging def logger(name, level): logger = logging.getLogger(name) logger.setLevel(level) filename = '%s.log' % (name) fH = logging.FileHandler(filename) fH.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")) cH = logging.StreamHandler() cH.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")) logger.addHandler(cH) logger.addHandler(fH) return logger
Python
__all__ = ['truerandom', 'url', 'file', 'logger']
Python
#!/usr/bin/python import os import sys def init(project_name): DIRS = {} DIRS['root_dir'] = './%s' % (project_name) DIRS['build_dir'] = '%s/build' % (DIRS['root_dir']) DIRS['src_dir'] = '%s/src' % (DIRS['root_dir']) DIRS['main_dir'] = '%s/main' % (DIRS['src_dir']) DIRS['include_dir'] = '%s/include' % (DIRS['src_dir']) DIRS['common_dir'] = '%s/common' % (DIRS['src_dir']) return DIRS def make_dir(DIRS, project_name): if os.path.exists(DIRS['root_dir']): print 'project: "%s" is exist' % (project_name) return False else: os.makedirs(DIRS['root_dir']) os.makedirs(DIRS['build_dir']) os.makedirs(DIRS['src_dir']) os.makedirs(DIRS['main_dir']) os.makedirs(DIRS['include_dir']) os.makedirs(DIRS['common_dir']) print 'step 1: create dir ok' return True def make_file(DIRS, project_name, project_type): if not os.path.exists(DIRS['root_dir']): return False else: Makefile_path = '%s/Makefile' % (DIRS['build_dir']) write_file(Makefile_path, make_build_mk_string(project_name)) Templatefile_path = '%s/template.mk' % (DIRS['root_dir']) write_file(Templatefile_path, template_mk_string()) Main_C_path = '%s/main.%s' % (DIRS['main_dir'], project_type) write_file(Main_C_path, main_c_file_string()) print 'step 2: make file ok' return True def write_file(path, content): file = open(path, 'w') file.write(content) file.close() def make_build_mk_string(project_name='', project_type='c'): return """ ######################################################################## # Compiler Flags ######################################################################## CFLAGS = -Wall -g -O0 #-pg CPPFLAGS = -Wall -g -O0 #-pg ######################################################################## # Project Configure ######################################################################## ROOT_DIR = .. VPATH = $(ROOT_DIR)/src/ : $(ROOT_DIR)/src/include : $(ROOT_DIR)/src/common : $(ROOT_DIR)/src/main C_SRCS = main.%s CPP_SRCS = INCS = -I$(ROOT_DIR)/src -I$(ROOT_DIR)/src/include -I$(ROOT_DIR)/src/common -I$(ROOT_DIR)/src/main EXE = %s LIBS = -lpthread include $(ROOT_DIR)/template.mk""" % (project_type, project_name) def template_mk_string(): return """ ######################################################################## # Default Targets ######################################################################## .PHONY: all exe dirs clean all : exe dirs exe : $(EXE) dirs: $(DIRS) ######################################################################## # Compilers ######################################################################## CC = gcc CPP = g++ ######################################################################## # Executable Program Rules ######################################################################## $(EXE) : $(CPP_SRCS:.cpp=.o) $(C_SRCS:.c=.o) \t$(CPP) $(CPPFLAGS) $(LIBS) -o $@ $^ ######################################################################## # Subdirectories ######################################################################## dirs: $(DIRS) ifdef DIRS .PHONY: $(DIRS) $(DIRS): \t@if [ -e $@/Makefile ] ; then $(MAKE) -C $@ $(MAKECMDGOALS) ; fi endif ######################################################################## # Implicit Rules ######################################################################## %.o: %.c \t$(CC) $(CFLAGS) $(INCS) -c $< %.o: %.cc \t$(CPP) $(CPPFLAGS) $(INCS) -c $< %.d: %.c \t@set -e; rm -f $@; \ $(CC) -MM $(CFLAGS) $(INCS) $< > $@.$$$$; \ sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ rm -f $@.$$$$ %.d: %.cc \t@set -e; rm -f $@; \ $(CPP) -MM $(CPPFLAGS) $(INCS) $< > $@.$$$$; \ sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ rm -f $@.$$$$ ######################################################################## # Cleanup Rules ######################################################################## clean: $(DIRS) \trm -f *.o *.d *.d.* $(EXE) ######################################################################## # Dependencies ######################################################################## -include $(CPP_SRCS:.cc=.d) $(C_SRCS:.c=.d)""" def main_c_file_string(): return""" #include <stdlib.h> #include <stdio.h> int main(void) { printf("project test\\n"); return 0; } """ def print_usage(): print '#############################################' print '### Thank you for using pjmaker' print '#############################################' print 'usage: pjmaker <project_name> <project_type>' print 'C project:\tpjmaker test c' print 'C++ project:\tpjmaker test cpp' def main(): if len(sys.argv) < 3: print_usage() return project_name = sys.argv[1] project_type = sys.argv[2] DIRS = init(project_name) if not make_dir(DIRS, project_name): return make_file(DIRS, project_name, project_type) if __name__ == '__main__': main()
Python
#!/usr/bin/python import sys import os def main(): if len(sys.argv) < 3: usage() return for i in range(2, len(sys.argv)): get_files(sys.argv[1], sys.argv[i]) def get_files(rule, file): if os.path.isdir(file): return (name, ext) = os.path.splitext(file) os.rename(file, name + rule) def usage(): print 'example: batchrenamef .cpp file.txt' print 'result : file.txt become file.cpp' if __name__ == '__main__': main()
Python
#!/usr/bin/env python import os import sys import subprocess import shutil CMAKE = '@CMAKE_COMMAND@' TMPDIR = '@TEMPDIR@' SRCDIR = '@SRCDIR@' GFLAGS_DIR = '@gflags_BINARY_DIR@' if __name__ == "__main__": if len(sys.argv) != 2: sys.stderr.write(' '.join(['usage:', sys.argv[0], '<test_name>\n'])) sys.exit(1) test_name = sys.argv[1] bindir = os.path.join(TMPDIR, '_'.join(['nc', test_name])) if TMPDIR == '': sys.stderr.write('Temporary directory not set!\n') sys.exit(1) # create build directory if os.path.isdir(bindir): shutil.rmtree(bindir) os.makedirs(bindir) # configure the build tree if subprocess.call([CMAKE, '-Dgflags_DIR:PATH='+GFLAGS_DIR, '-DTEST_NAME:STRING='+test_name, SRCDIR], cwd=bindir) != 0: sys.stderr.write('Failed to configure the build tree!\n') sys.exit(1) # try build, which is supposed to fail (except in case of the sanity check) if subprocess.call([CMAKE, '--build', bindir], cwd=bindir) == 0 and test_name != 'sanity': sys.stderr.write('Build expected to fail, but it succeeded!\n') sys.exit(1) sys.exit(0)
Python
''' Created on 11/07/2010 @author: Rondon ''' class Cordinator(object): ''' classdocs ''' passive = 0 active = 1 _stateList = () _mode = passive def __init__(self): ''' Constructor ''' def setActive(self): _mode = self.active def setPassive(self): _mode = self.passive def heartbeat(self): pass def _messageToState(self, message): pass
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, socket class State(object): def __init__(self, acumul): self.acumul = acumul class Message: def __init__(self, seqNum, msgType, clientID, data): self.data self.seqNum self.msgType self.clientID if __name__ == '__main__': try: addr = '225.0.0.1' port = 1905 #state = State(32) buff = sys.argv[1] except IndexError: print 'Use: %s + <valor>' % sys.argv[0] sys.exit(1) fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.sendto(buff, (addr, port)) #for i in range(100): #fd.sendto(str(i), (addr, port)) ''' try: portACK = 1906 fd.bind(('', portACK)) except socket.error, err: print "Couldn't be a udp server on port %d : %s" % (port, err) raise SystemExit fd.sendto('1', (addr, port)) #datagram = fd.recv(MAX_TO_READ) datagram = fd.recvfrom(portACK) print "ACK " + str(datagram) fd.sendto('3', (addr, port)) #datagram = fd.recv(MAX_TO_READ) datagram = fd.recvfrom(portACK) print "ACK " + str(datagram) fd.sendto('2', (addr, port)) #datagram = fd.recv(MAX_TO_READ) datagram = fd.recvfrom(portACK) print "ACK " + str(datagram) ''' fd.close()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, socket class State(object): def __init__(self, acumul): self.acumul = acumul class Message: def __init__(self, seqNum, msgType, clientID, data): self.data self.seqNum self.msgType self.clientID if __name__ == '__main__': try: addr = '225.0.0.1' port = 1905 #state = State(32) buff = sys.argv[1] except IndexError: print 'Use: %s + <valor>' % sys.argv[0] sys.exit(1) fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.sendto(buff, (addr, port)) #for i in range(100): #fd.sendto(str(i), (addr, port)) ''' try: portACK = 1906 fd.bind(('', portACK)) except socket.error, err: print "Couldn't be a udp server on port %d : %s" % (port, err) raise SystemExit fd.sendto('1', (addr, port)) #datagram = fd.recv(MAX_TO_READ) datagram = fd.recvfrom(portACK) print "ACK " + str(datagram) fd.sendto('3', (addr, port)) #datagram = fd.recv(MAX_TO_READ) datagram = fd.recvfrom(portACK) print "ACK " + str(datagram) fd.sendto('2', (addr, port)) #datagram = fd.recv(MAX_TO_READ) datagram = fd.recvfrom(portACK) print "ACK " + str(datagram) ''' fd.close()
Python
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' import sys, socket, struct from message import Message from state import State import exceptions from consts import Consts from threading import Timer from threading import Lock class Messenger(object): ''' Classe estática É a entidade que faz interface com o programador da aplicação. Ele envia as mensagens com o send e receive, e por baixo dos panos, o Messenger conversa com o Coordinator para saber o que fazer. Quando o programa da aplicação envia uma mensagem (que é uma String) através do send, o Messenger precisa adicionar o header de tolerância a falhas na mensagem, criando um objeto do tipo Message. Isso é feito através do método _insertHeader. A operação inversa (transformar um Message em String) é feita pelo _removeHeader. Além disso, para preencher essas informações, o Messenger precisa se comunicar com o Coordinator para poder obter a última sequencia recebida de um cliente. ''' port = 1905 timeout = 20 #timeout em segundos next_sequence = 0 resendList = [] #lista de mensagens a serem reenviadas send_mutex = Lock() resendList_mutex = Lock() def stringToMessage(self, string): """ Campos da mensagem: Type Sender Receiver Sequence Data """ fields = string.split() data = '' for i in range(4,len(fields)-1): data += fields[i] + ' ' data += fields[len(fields)-1] #print 'data = ' + str(data) return Message(sender=fields[1], \ receiver=fields[2], \ sequence=int(fields[3]), \ msg_type=int(fields[0]), \ data=data) def messageToString(self, message): return str(message) def getNextSeq(self, id): for state in self.coordinator.stateList: if state.message.sender == id: return state.message.sequence + 1 return 0 def stringToState(self, string): """ Campos do state: Message Data """ fields = string.split() if len(fields) != 6: raise Exception('Impossivel converter para State: ' + string) state = State() #print 'foi passado: ' + string msg = Message(sender=fields[1], \ receiver=fields[2], \ sequence=int(fields[3]), \ msg_type=int(fields[0]), \ data=fields[4]) state.message = msg state.data = fields[5] return state def resend(self, msg): print 'Reenviando mensagem' multicast = Consts.GROUPS[msg.receiver] if multicast == None: raise Exception('Destino desconhecido: ' + str(msg.receiver)) self.send_mutex.acquire() fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.sendto(str(msg), (multicast, self.port)) fd.close() self.send_mutex.release() def send(self, destination, message, type=Message.NORMAL_MESSAGE): if destination != None and message != None: #print 'para:' + destination + ' msg: ' + message msg = Message(sender=self.coordinator.id, \ receiver=destination,\ sequence=self.next_sequence, \ msg_type=type, \ data=message) #print 'Msg resultante:' + str(msg) if type == Message.NORMAL_MESSAGE: #o reenvio eh somente para msgs normais self.resendList_mutex.acquire() self.resendList.append(msg) self.resendList_mutex.release() multicast = Consts.GROUPS[destination] if multicast == None: raise Exception('Destino desconhecido: ' + str(destination)) self.send_mutex.acquire() fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.sendto(str(msg), (multicast, self.port)) fd.close() self.send_mutex.release() else: raise Exception('destino ou mensagem são nulos') def receiveAck(self): fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) fd.settimeout(self.timeout) multicast = Consts.GROUPS[self.coordinator.id] if multicast == None: raise Exception('ID da maquina nao pertence a nenhum grupo multicast: ' + str(self.coordinator.id)) # bind udp port fd.bind((multicast, self.port)) mreq = struct.pack('4sl', socket.inet_aton(multicast), socket.INADDR_ANY) fd.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) try: data, addr = fd.recvfrom(4096) #print 'Dados recebidos: ' + data except Exception as inst: return self.receiveAck() finally: fd.close() msg_rec = self.stringToMessage(data) if not msg_rec.msg_type == Message.STATE_MESSAGE: return self.receiveAck() else: return #sai do receiveAck def receive(self, useTimeout=False): ''' Retorna (mensagem, origem) quando a mensagem chega dentro do timeout E retornar um erro quando o timeout chega ao fim ''' fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if useTimeout: fd.settimeout(self.timeout) multicast = Consts.GROUPS[self.coordinator.id] if multicast == None: raise Exception('ID da maquina nao pertence a nenhum grupo multicast: ' + str(self.coordinator.id)) # bind udp port fd.bind((multicast, self.port)) mreq = struct.pack('4sl', socket.inet_aton(multicast), socket.INADDR_ANY) fd.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) try: data, addr = fd.recvfrom(4096) #print 'Dados recebidos: ' + data except Exception as inst: if useTimeout: #timeout implica reenvio self.resendList_mutex.acquire() msg = self.resendList[0] #pega o primeiro da "fila" self.resendList_mutex.release() fd.close() self.resend(msg) #parar depois de N tentativas (falta implementar) return self.receive(useTimeout) else: #saiu uma excessão e não estavamos no modo timetou raise inst #sobe a excessão finally: fd.close() if useTimeout: #timeout implica reenvio self.resendList_mutex.acquire() self.resendList.pop() #recebeu com sucesso, remove da lista self.resendList_mutex.release() msg_rec = self.stringToMessage(data) #print 'Msg a ser processada: ' + str(msg_rec) #return msg_rec.data, msg_rec.sender return self.coordinator.processMessage(msg_rec) def prepare(self): self.next_sequence += 1 #print 'NextSequence = ' + str(self.next_sequence)
Python
''' Created on 11/07/2010 @author: Rondon ''' class State(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.lastSequence = 0 self.id = ""
Python
''' Created on 11/07/2010 @author: Rondon ''' class ConcreteState(State): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.accumulated_value = 0
Python
''' Created on 11/07/2010 @author: Rondon ''' import fenixserver class Message(object): ''' classdocs ''' PEDIDO = 0 RESPOSTA = 1 def __init__(self, sender, receiver, sequence, message_type, data): ''' Constructor ''' self.sender = sender self.receiver = receiver self.sequence = sequence self.msg_type = message_type self.data = data
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # # ESSA CLASSE VAI SAIR, SOH ESTA AQUI PARA USARMOS AS COISAS DELA! # # JAH COPIEI AS COISAS DELA PARA O COORDINATOR # import sys, struct, socket #from copy import copy class State(object): def __init__(self, acumul): self.acumul = acumul def saveState(state): fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.sendto(state, (addr, port)) def mcast_server(addr, port): acumul = 0 fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind udp port fd.bind(('', port)) # set mcast group mreq = struct.pack('4sl', socket.inet_aton(addr), socket.INADDR_ANY) fd.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) try: acumulOld = -1 portACK = 1906 while 1: data, addr = fd.recvfrom(1024) #print 'Recebido %s bytes de %s - mensagem: %s' % (len(data), addr, data) print 'Recebido: ' + str(data) acumul += int(data) if acumulOld >= acumul: print 'acumulOld = ' + str(acumulOld) print 'ERRO DE SEQ' acumulOld = acumul #state = State(acumul) #saveState(acumul) print 'Acumulador = ' + str(acumul) #if isinstance(data, State): #print 'Salvando estado...' #serverState = data #else: #print 'Mensagem desconhecida: ' + str(data) #ACK #fd.sendto(str(acumul), (addr, portACK)) print '' except KeyboardInterrupt: print 'done' sys.exit(0) if __name__ == '__main__': try: addr = sys.argv[1] port = int(sys.argv[2]) except IndexError: addr = '225.0.0.1' port = 1905 finally: print 'Servidor rodando em %s:%d\n' % (addr, port) mcast_server(addr, port)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # # ESSA CLASSE VAI SAIR, SOH ESTA AQUI PARA USARMOS AS COISAS DELA! # # JAH COPIEI AS COISAS DELA PARA O COORDINATOR # import sys, struct, socket #from copy import copy class State(object): def __init__(self, acumul): self.acumul = acumul def saveState(state): fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.sendto(state, (addr, port)) def mcast_server(addr, port): acumul = 0 fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind udp port fd.bind(('', port)) # set mcast group mreq = struct.pack('4sl', socket.inet_aton(addr), socket.INADDR_ANY) fd.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) try: acumulOld = -1 portACK = 1906 while 1: data, addr = fd.recvfrom(1024) #print 'Recebido %s bytes de %s - mensagem: %s' % (len(data), addr, data) print 'Recebido: ' + str(data) acumul += int(data) if acumulOld >= acumul: print 'acumulOld = ' + str(acumulOld) print 'ERRO DE SEQ' acumulOld = acumul #state = State(acumul) #saveState(acumul) print 'Acumulador = ' + str(acumul) #if isinstance(data, State): #print 'Salvando estado...' #serverState = data #else: #print 'Mensagem desconhecida: ' + str(data) #ACK #fd.sendto(str(acumul), (addr, portACK)) print '' except KeyboardInterrupt: print 'done' sys.exit(0) if __name__ == '__main__': try: addr = sys.argv[1] port = int(sys.argv[2]) except IndexError: addr = '225.0.0.1' port = 1905 finally: print 'Servidor rodando em %s:%d\n' % (addr, port) mcast_server(addr, port)
Python
''' Created on 11/07/2010 @author: Rondon ''' import sys, struct, socket class Coordinator(object): ''' classdocs ''' passive = 0 active = 1 _stateList = () _mode = passive def __init__(self): ''' Constructor ''' def setActive(self): _mode = self.active def setPassive(self): _mode = self.passive def heartbeat(self): pass def _messageToState(self, message): pass def main(addr, port): acumul = 0 fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind udp port fd.bind(('', port)) # set mcast group mreq = struct.pack('4sl', socket.inet_aton(addr), socket.INADDR_ANY) fd.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) try: acumulOld = -1 portACK = 1906 while 1: data, addr = fd.recvfrom(1024) #print 'Recebido %s bytes de %s - mensagem: %s' % (len(data), addr, data) print 'Recebido: ' + str(data) acumul += int(data) if acumulOld >= acumul: print 'acumulOld = ' + str(acumulOld) print 'ERRO DE SEQ' acumulOld = acumul #state = State(acumul) #saveState(acumul) print 'Acumulador = ' + str(acumul) #if isinstance(data, State): #print 'Salvando estado...' #serverState = data #else: #print 'Mensagem desconhecida: ' + str(data) #ACK #fd.sendto(str(acumul), (addr, portACK)) print '' except KeyboardInterrupt: print 'done' sys.exit(0) if __name__ == '__main__': try: addr = sys.argv[1] port = int(sys.argv[2]) except IndexError: addr = '225.0.0.1' port = 1905 finally: print 'Servidor rodando em %s:%d\n' % (addr, port) main(addr, port)
Python