code
stringlengths
1
1.72M
language
stringclasses
1 value
"""gettext tool """ # 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/gettext.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" ############################################################################# def generate(env,**kw): import SCons.Tool from SCons.Tool.GettextCommon \ import _translate, tool_list for t in tool_list(env['PLATFORM'], env): env.Tool(t) env.AddMethod(_translate, 'Translate') ############################################################################# ############################################################################# def exists(env): from SCons.Tool.GettextCommon \ import _xgettext_exists, _msginit_exists, \ _msgmerge_exists, _msgfmt_exists return _xgettext_exists(env) and _msginit_exists(env) \ and _msgmerge_exists(env) and _msgfmt_exists(env) #############################################################################
Python
""" xgettext tool Tool specific initialization of `xgettext` tool. """ # 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/xgettext.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" ############################################################################# class _CmdRunner(object): """ Callabe object, which runs shell command storing its stdout and stderr to variables. It also provides `strfunction()` method, which shall be used by scons Action objects to print command string. """ def __init__( self, command, commandstr = None): self.out = None self.err = None self.status = None self.command = command self.commandstr = commandstr def __call__(self, target, source, env): import SCons.Action import subprocess import os import sys kw = { 'stdin' : 'devnull', 'stdout' : subprocess.PIPE, 'stderr' : subprocess.PIPE, 'universal_newlines' : True, 'shell' : True } command = env.subst(self.command, target = target, source = source) proc = SCons.Action._subproc(env, command, **kw) self.out, self.err = proc.communicate() self.status = proc.wait() if self.err: sys.stderr.write(unicode(self.err)) return self.status def strfunction(self, target, source, env): import os comstr = self.commandstr if env.subst(comstr, target = target, source = source) == "": comstr = self.command s = env.subst(comstr, target = target, source = source) return s ############################################################################# ############################################################################# def _update_pot_file(target, source, env): """ Action function for `POTUpdate` builder """ import re import os import SCons.Action nop = lambda target, source, env : 0 # Save scons cwd and os cwd (NOTE: they may be different. After the job, we # revert ech one to its original state). save_cwd = env.fs.getcwd() save_os_cwd = os.getcwd() chdir = target[0].dir chdir_str = repr(chdir.get_abspath()) # Print chdir message (employ SCons.Action.Action for that. It knows better # than me how to to this correctly). env.Execute(SCons.Action.Action(nop, "Entering " + chdir_str)) # Go to target's directory and do our job env.fs.chdir(chdir, 1) # Go into target's directory try: cmd = _CmdRunner('$XGETTEXTCOM', '$XGETTEXTCOMSTR') action = SCons.Action.Action(cmd, strfunction=cmd.strfunction) status = action([ target[0] ], source, env) except: # Something went wrong. env.Execute(SCons.Action.Action(nop, "Leaving " + chdir_str)) # Revert working dirs to previous state and re-throw exception. env.fs.chdir(save_cwd, 0) os.chdir(save_os_cwd) raise # Print chdir message. env.Execute(SCons.Action.Action(nop, "Leaving " + chdir_str)) # Revert working dirs to previous state. env.fs.chdir(save_cwd, 0) os.chdir(save_os_cwd) # If the command was not successfull, return error code. if status: return status new_content = cmd.out if not new_content: # When xgettext finds no internationalized messages, no *.pot is created # (because we don't want to bother translators with empty POT files). needs_update = False explain = "no internationalized messages encountered" else: if target[0].exists(): # If the file already exists, it's left unaltered unless its messages # are outdated (w.r.t. to these recovered by xgettext from sources). old_content = target[0].get_text_contents() re_cdate = re.compile(r'^"POT-Creation-Date: .*"$[\r\n]?', re.M) old_content_nocdate = re.sub(re_cdate,"",old_content) new_content_nocdate = re.sub(re_cdate,"",new_content) if(old_content_nocdate == new_content_nocdate): # Messages are up-to-date needs_update = False explain = "messages in file found to be up-to-date" else: # Messages are outdated needs_update = True explain = "messages in file were outdated" else: # No POT file found, create new one needs_update = True explain = "new file" if needs_update: # Print message employing SCons.Action.Action for that. msg = "Writting " + repr(str(target[0])) + " (" + explain + ")" env.Execute(SCons.Action.Action(nop, msg)) f = open(str(target[0]),"w") f.write(new_content) f.close() return 0 else: # Print message employing SCons.Action.Action for that. msg = "Not writting " + repr(str(target[0])) + " (" + explain + ")" env.Execute(SCons.Action.Action(nop, msg)) return 0 ############################################################################# ############################################################################# from SCons.Builder import BuilderBase ############################################################################# class _POTBuilder(BuilderBase): def _execute(self, env, target, source, *args): if not target: if env.has_key('POTDOMAIN') and env['POTDOMAIN']: domain = env['POTDOMAIN'] else: domain = 'messages' target = [ domain ] return BuilderBase._execute(self, env, target, source, *args) ############################################################################# ############################################################################# def _scan_xgettext_from_files(target, source, env, files = None, path = None): """ Parses `POTFILES.in`-like file and returns list of extracted file names. """ import re import SCons.Util import SCons.Node.FS if files is None: return 0 if not SCons.Util.is_List(files): files = [ files ] if path is None: if env.has_key('XGETTEXTPATH'): path = env['XGETTEXTPATH'] else: path = [] if not SCons.Util.is_List(path): path = [ path ] path = SCons.Util.flatten(path) dirs = () for p in path: if not isinstance(p, SCons.Node.FS.Base): if SCons.Util.is_String(p): p = env.subst(p, source = source, target = target) p = env.arg2nodes(p, env.fs.Dir) dirs += tuple(p) # cwd is the default search path (when no path is defined by user) if not dirs: dirs = (env.fs.getcwd(),) # Parse 'POTFILE.in' files. re_comment = re.compile(r'^#[^\n\r]*$\r?\n?', re.M) re_emptyln = re.compile(r'^[ \t\r]*$\r?\n?', re.M) re_trailws = re.compile(r'[ \t\r]+$') for f in files: # Find files in search path $XGETTEXTPATH if isinstance(f, SCons.Node.FS.Base) and f.rexists(): contents = f.get_text_contents() contents = re_comment.sub("", contents) contents = re_emptyln.sub("", contents) contents = re_trailws.sub("", contents) depnames = contents.splitlines() for depname in depnames: depfile = SCons.Node.FS.find_file(depname, dirs) if not depfile: depfile = env.arg2nodes(depname, dirs[0].File) env.Depends(target, depfile) return 0 ############################################################################# ############################################################################# def _pot_update_emitter(target, source, env): """ Emitter function for `POTUpdate` builder """ from SCons.Tool.GettextCommon import _POTargetFactory import SCons.Util import SCons.Node.FS if env.has_key('XGETTEXTFROM'): xfrom = env['XGETTEXTFROM'] else: return target, source if not SCons.Util.is_List(xfrom): xfrom = [ xfrom ] xfrom = SCons.Util.flatten(xfrom) # Prepare list of 'POTFILE.in' files. files = [] for xf in xfrom: if not isinstance(xf, SCons.Node.FS.Base): if SCons.Util.is_String(xf): # Interpolate variables in strings xf = env.subst(xf, source = source, target = target) xf = env.arg2nodes(xf) files.extend(xf) if files: env.Depends(target, files) _scan_xgettext_from_files(target, source, env, files) return target, source ############################################################################# ############################################################################# from SCons.Environment import _null ############################################################################# def _POTUpdateBuilderWrapper(env, target=None, source=_null, **kw): return env._POTUpdateBuilder(target, source, **kw) ############################################################################# ############################################################################# def _POTUpdateBuilder(env, **kw): """ Creates `POTUpdate` builder object """ import SCons.Action from SCons.Tool.GettextCommon import _POTargetFactory kw['action'] = SCons.Action.Action(_update_pot_file, None) kw['suffix'] = '$POTSUFFIX' kw['target_factory'] = _POTargetFactory(env, alias='$POTUPDATE_ALIAS').File kw['emitter'] = _pot_update_emitter return _POTBuilder(**kw) ############################################################################# ############################################################################# def generate(env,**kw): """ Generate `xgettext` tool """ import SCons.Util from SCons.Tool.GettextCommon import RPaths, _detect_xgettext env['XGETTEXT'] = _detect_xgettext(env) # NOTE: sources="$SOURCES" would work as well. However, we use following # construction to convert absolute paths provided by scons onto paths # relative to current working dir. Note, that scons expands $SOURCE(S) to # absolute paths for sources $SOURCE(s) outside of current subtree (e.g. in # "../"). With source=$SOURCE these absolute paths would be written to the # resultant *.pot file (and its derived *.po files) as references to lines in # source code (e.g. referring lines in *.c files). Such references would be # correct (e.g. in poedit) only on machine on which *.pot was generated and # would be of no use on other hosts (having a copy of source code located # in different place in filesystem). sources = '$( ${_concat( "", SOURCES, "", __env__, XgettextRPaths, TARGET' \ + ', SOURCES)} $)' # NOTE: the output from $XGETTEXTCOM command must go to stdout, not to a file. # This is required by the POTUpdate builder's action. xgettextcom = '$XGETTEXT $XGETTEXTFLAGS $_XGETTEXTPATHFLAGS' \ + ' $_XGETTEXTFROMFLAGS -o - ' + sources xgettextpathflags = '$( ${_concat( XGETTEXTPATHPREFIX, XGETTEXTPATH' \ + ', XGETTEXTPATHSUFFIX, __env__, RDirs, TARGET, SOURCES)} $)' xgettextfromflags = '$( ${_concat( XGETTEXTFROMPREFIX, XGETTEXTFROM' \ + ', XGETTEXTFROMSUFFIX, __env__, target=TARGET, source=SOURCES)} $)' env.SetDefault( _XGETTEXTDOMAIN = '${TARGET.filebase}', XGETTEXTFLAGS = [ ], XGETTEXTCOM = xgettextcom, XGETTEXTCOMSTR = '', XGETTEXTPATH = [ ], XGETTEXTPATHPREFIX = '-D', XGETTEXTPATHSUFFIX = '', XGETTEXTFROM = None, XGETTEXTFROMPREFIX = '-f', XGETTEXTFROMSUFFIX = '', _XGETTEXTPATHFLAGS = xgettextpathflags, _XGETTEXTFROMFLAGS = xgettextfromflags, POTSUFFIX = ['.pot'], POTUPDATE_ALIAS = 'pot-update', XgettextRPaths = RPaths(env) ) env.Append( BUILDERS = { '_POTUpdateBuilder' : _POTUpdateBuilder(env) } ) env.AddMethod(_POTUpdateBuilderWrapper, 'POTUpdate') env.AlwaysBuild(env.Alias('$POTUPDATE_ALIAS')) ############################################################################# ############################################################################# def exists(env): """ Check, whether the tool exists """ from SCons.Tool.GettextCommon import _xgettext_exists return _xgettext_exists(env) ############################################################################# # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.hpcc Tool-specific initialization for HP aCC and cc. 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/hpcc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util import cc def generate(env): """Add Builders and construction variables for aCC & cc to an Environment.""" cc.generate(env) env['CXX'] = 'aCC' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS +Z') def exists(env): return env.Detect('aCC') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sunf95 Tool-specific initialization for sunf95, the Sun Studio F95 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/sunf95.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util from FortranCommon import add_all_to_env compilers = ['sunf95', 'f95'] def generate(env): """Add Builders and construction variables for sunf95 to an Environment.""" add_all_to_env(env) fcomp = env.Detect(compilers) or 'f95' env['FORTRAN'] = fcomp env['F95'] = fcomp env['SHFORTRAN'] = '$FORTRAN' env['SHF95'] = '$F95' env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC') env['SHF95FLAGS'] = SCons.Util.CLVar('$F95FLAGS -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.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.dvi Common DVI Builder definition for various other Tool modules that use it. """ # # 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/dvi.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Builder import SCons.Tool DVIBuilder = None def generate(env): try: env['BUILDERS']['DVI'] except KeyError: global DVIBuilder if DVIBuilder is None: # The suffix is hard-coded to '.dvi', not configurable via a # construction variable like $DVISUFFIX, because the output # file name is hard-coded within TeX. DVIBuilder = SCons.Builder.Builder(action = {}, source_scanner = SCons.Tool.LaTeXScanner, suffix = '.dvi', emitter = {}, source_ext_match = None) env['BUILDERS']['DVI'] = DVIBuilder def exists(env): # This only puts a skeleton Builder in place, so if someone # references this Tool directly, it's always "available." return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sunf77 Tool-specific initialization for sunf77, the Sun Studio F77 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/sunf77.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util from FortranCommon import add_all_to_env compilers = ['sunf77', 'f77'] def generate(env): """Add Builders and construction variables for sunf77 to an Environment.""" add_all_to_env(env) fcomp = env.Detect(compilers) or 'f77' env['FORTRAN'] = fcomp env['F77'] = fcomp env['SHFORTRAN'] = '$FORTRAN' env['SHF77'] = '$F77' env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC') env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS -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.jar Tool-specific initialization for jar. 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/jar.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Subst import SCons.Util def jarSources(target, source, env, for_signature): """Only include sources that are not a manifest file.""" try: env['JARCHDIR'] except KeyError: jarchdir_set = False else: jarchdir_set = True jarchdir = env.subst('$JARCHDIR', target=target, source=source) if jarchdir: jarchdir = env.fs.Dir(jarchdir) result = [] for src in source: contents = src.get_text_contents() if contents[:16] != "Manifest-Version": if jarchdir_set: _chdir = jarchdir else: try: _chdir = src.attributes.java_classdir except AttributeError: _chdir = None if _chdir: # If we are changing the dir with -C, then sources should # be relative to that directory. src = SCons.Subst.Literal(src.get_path(_chdir)) result.append('-C') result.append(_chdir) result.append(src) return result def jarManifest(target, source, env, for_signature): """Look in sources for a manifest file, if any.""" for src in source: contents = src.get_text_contents() if contents[:16] == "Manifest-Version": return src return '' def jarFlags(target, source, env, for_signature): """If we have a manifest, make sure that the 'm' flag is specified.""" jarflags = env.subst('$JARFLAGS', target=target, source=source) for src in source: contents = src.get_text_contents() if contents[:16] == "Manifest-Version": if not 'm' in jarflags: return jarflags + 'm' break return jarflags def generate(env): """Add Builders and construction variables for jar to an Environment.""" SCons.Tool.CreateJarBuilder(env) env['JAR'] = 'jar' env['JARFLAGS'] = SCons.Util.CLVar('cf') env['_JARFLAGS'] = jarFlags env['_JARMANIFEST'] = jarManifest env['_JARSOURCES'] = jarSources env['_JARCOM'] = '$JAR $_JARFLAGS $TARGET $_JARMANIFEST $_JARSOURCES' env['JARCOM'] = "${TEMPFILE('$_JARCOM')}" env['JARSUFFIX'] = '.jar' def exists(env): # As reported by Jan Nijtmans in issue #2730, the simple # return env.Detect('jar') # doesn't always work during initialization. For now, we # stop trying to detect an executable (analogous to the # javac Builder). # TODO: Come up with a proper detect() routine...and enable it. return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.ilink32 XXX """ # # 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/ilink32.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Tool import SCons.Tool.bcc32 import SCons.Util def generate(env): """Add Builders and construction variables for Borland ilink to an Environment.""" SCons.Tool.createSharedLibBuilder(env) SCons.Tool.createProgBuilder(env) env['LINK'] = '$CC' env['LINKFLAGS'] = SCons.Util.CLVar('') env['LINKCOM'] = '$LINK -q $LINKFLAGS -e$TARGET $SOURCES $LIBS' env['LIBDIRPREFIX']='' env['LIBDIRSUFFIX']='' env['LIBLINKPREFIX']='' env['LIBLINKSUFFIX']='$LIBSUFFIX' def exists(env): # Uses bcc32 to do linking as it generally knows where the standard # LIBS are and set up the linking correctly return SCons.Tool.bcc32.findIt('bcc32', env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.mwld Tool-specific initialization for the Metrowerks CodeWarrior linker. 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/mwld.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Tool def generate(env): """Add Builders and construction variables for lib to an Environment.""" SCons.Tool.createStaticLibBuilder(env) SCons.Tool.createSharedLibBuilder(env) SCons.Tool.createProgBuilder(env) env['AR'] = 'mwld' env['ARCOM'] = '$AR $ARFLAGS -library -o $TARGET $SOURCES' env['LIBDIRPREFIX'] = '-L' env['LIBDIRSUFFIX'] = '' env['LIBLINKPREFIX'] = '-l' env['LIBLINKSUFFIX'] = '.lib' env['LINK'] = 'mwld' env['LINKCOM'] = '$LINK $LINKFLAGS -o $TARGET $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' env['SHLINK'] = '$LINK' env['SHLINKFLAGS'] = '$LINKFLAGS' env['SHLINKCOM'] = shlib_action env['SHLIBEMITTER']= shlib_emitter def exists(env): import SCons.Tool.mwcc return SCons.Tool.mwcc.set_vars(env) def shlib_generator(target, source, env, for_signature): cmd = ['$SHLINK', '$SHLINKFLAGS', '-shared'] no_import_lib = env.get('no_import_lib', 0) if no_import_lib: cmd.extend('-noimplib') dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') if dll: cmd.extend(['-o', dll]) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: cmd.extend(['-implib', implib.get_string(for_signature)]) cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS']) 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'): # Append an import library to the list of targets. target.append(env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'LIBPREFIX', 'LIBSUFFIX')) return target, source shlib_action = SCons.Action.Action(shlib_generator, generator=1) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.install Tool-specific initialization for the install 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/install.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import shutil import stat import SCons.Action from SCons.Util import make_path_relative # # We keep track of *all* installed files. _INSTALLED_FILES = [] _UNIQUE_INSTALLED_FILES = None class CopytreeError(EnvironmentError): pass # This is a patched version of shutil.copytree from python 2.5. It # doesn't fail if the dir exists, which regular copytree does # (annoyingly). Note the XXX comment in the docstring. def scons_copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an CopytreeError is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) # garyo@genarts.com fix: check for dir before making dirs. if not os.path.exists(dst): os.makedirs(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): scons_copytree(srcname, dstname, symlinks) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, str(why))) # catch the CopytreeError from the recursive copytree so that we can # continue with other files except CopytreeError, err: errors.extend(err.args[0]) try: shutil.copystat(src, dst) except WindowsError: # can't copy file access times on Windows pass except OSError, why: errors.extend((src, dst, str(why))) if errors: raise CopytreeError, errors # # Functions doing the actual work of the Install Builder. # def copyFunc(dest, source, env): """Install a source file or directory into a destination by copying, (including copying permission/mode bits).""" if os.path.isdir(source): if os.path.exists(dest): if not os.path.isdir(dest): raise SCons.Errors.UserError("cannot overwrite non-directory `%s' with a directory `%s'" % (str(dest), str(source))) else: parent = os.path.split(dest)[0] if not os.path.exists(parent): os.makedirs(parent) scons_copytree(source, dest) else: shutil.copy2(source, dest) st = os.stat(source) os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE) return 0 def installFunc(target, source, env): """Install a source file into a target using the function specified as the INSTALL construction variable.""" try: install = env['INSTALL'] except KeyError: raise SCons.Errors.UserError('Missing INSTALL construction variable.') assert len(target)==len(source), \ "Installing source %s into target %s: target and source lists must have same length."%(list(map(str, source)), list(map(str, target))) for t,s in zip(target,source): if install(t.get_path(),s.get_path(),env): return 1 return 0 def stringFunc(target, source, env): installstr = env.get('INSTALLSTR') if installstr: return env.subst_target_source(installstr, 0, target, source) target = str(target[0]) source = str(source[0]) if os.path.isdir(source): type = 'directory' else: type = 'file' return 'Install %s: "%s" as "%s"' % (type, source, target) # # Emitter functions # def add_targets_to_INSTALLED_FILES(target, source, env): """ an emitter that adds all target files to the list stored in the _INSTALLED_FILES global variable. This way all installed files of one scons call will be collected. """ global _INSTALLED_FILES, _UNIQUE_INSTALLED_FILES _INSTALLED_FILES.extend(target) _UNIQUE_INSTALLED_FILES = None return (target, source) class DESTDIR_factory(object): """ a node factory, where all files will be relative to the dir supplied in the constructor. """ def __init__(self, env, dir): self.env = env self.dir = env.arg2nodes( dir, env.fs.Dir )[0] def Entry(self, name): name = make_path_relative(name) return self.dir.Entry(name) def Dir(self, name): name = make_path_relative(name) return self.dir.Dir(name) # # The Builder Definition # install_action = SCons.Action.Action(installFunc, stringFunc) installas_action = SCons.Action.Action(installFunc, stringFunc) BaseInstallBuilder = None def InstallBuilderWrapper(env, target=None, source=None, dir=None, **kw): if target and dir: import SCons.Errors raise SCons.Errors.UserError("Both target and dir defined for Install(), only one may be defined.") if not dir: dir=target import SCons.Script install_sandbox = SCons.Script.GetOption('install_sandbox') if install_sandbox: target_factory = DESTDIR_factory(env, install_sandbox) else: target_factory = env.fs try: dnodes = env.arg2nodes(dir, target_factory.Dir) except TypeError: raise SCons.Errors.UserError("Target `%s' of Install() is a file, but should be a directory. Perhaps you have the Install() arguments backwards?" % str(dir)) sources = env.arg2nodes(source, env.fs.Entry) tgt = [] for dnode in dnodes: for src in sources: # Prepend './' so the lookup doesn't interpret an initial # '#' on the file name portion as meaning the Node should # be relative to the top-level SConstruct directory. target = env.fs.Entry('.'+os.sep+src.name, dnode) #tgt.extend(BaseInstallBuilder(env, target, src, **kw)) tgt.extend(BaseInstallBuilder(env, target, src, **kw)) return tgt def InstallAsBuilderWrapper(env, target=None, source=None, **kw): result = [] for src, tgt in map(lambda x, y: (x, y), source, target): #result.extend(BaseInstallBuilder(env, tgt, src, **kw)) result.extend(BaseInstallBuilder(env, tgt, src, **kw)) return result added = None def generate(env): from SCons.Script import AddOption, GetOption global added if not added: added = 1 AddOption('--install-sandbox', dest='install_sandbox', type="string", action="store", help='A directory under which all installed files will be placed.') global BaseInstallBuilder if BaseInstallBuilder is None: install_sandbox = GetOption('install_sandbox') if install_sandbox: target_factory = DESTDIR_factory(env, install_sandbox) else: target_factory = env.fs BaseInstallBuilder = SCons.Builder.Builder( action = install_action, target_factory = target_factory.Entry, source_factory = env.fs.Entry, multi = 1, emitter = [ add_targets_to_INSTALLED_FILES, ], name = 'InstallBuilder') env['BUILDERS']['_InternalInstall'] = InstallBuilderWrapper env['BUILDERS']['_InternalInstallAs'] = InstallAsBuilderWrapper # We'd like to initialize this doing something like the following, # but there isn't yet support for a ${SOURCE.type} expansion that # will print "file" or "directory" depending on what's being # installed. For now we punt by not initializing it, and letting # the stringFunc() that we put in the action fall back to the # hand-crafted default string if it's not set. # #try: # env['INSTALLSTR'] #except KeyError: # env['INSTALLSTR'] = 'Install ${SOURCE.type}: "$SOURCES" as "$TARGETS"' try: env['INSTALL'] except KeyError: env['INSTALL'] = copyFunc 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.gas Tool-specific initialization for as, the Gnu assembler. 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/gas.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" as_module = __import__('as', globals(), locals(), []) assemblers = ['as', 'gas'] def generate(env): """Add Builders and construction variables for as to an Environment.""" as_module.generate(env) env['AS'] = env.Detect(assemblers) or 'as' def exists(env): return env.Detect(assemblers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.lex Tool-specific initialization for lex. 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/lex.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Action import SCons.Tool import SCons.Util LexAction = SCons.Action.Action("$LEXCOM", "$LEXCOMSTR") def lexEmitter(target, source, env): sourceBase, sourceExt = os.path.splitext(SCons.Util.to_String(source[0])) if sourceExt == ".lm": # If using Objective-C target = [sourceBase + ".m"] # the extension is ".m". # This emitter essentially tries to add to the target all extra # files generated by flex. # Different options that are used to trigger the creation of extra files. fileGenOptions = ["--header-file=", "--tables-file="] lexflags = env.subst("$LEXFLAGS", target=target, source=source) for option in SCons.Util.CLVar(lexflags): for fileGenOption in fileGenOptions: l = len(fileGenOption) if option[:l] == fileGenOption: # A file generating option is present, so add the # file name to the target list. fileName = option[l:].strip() target.append(fileName) return (target, source) def generate(env): """Add Builders and construction variables for lex to an Environment.""" c_file, cxx_file = SCons.Tool.createCFileBuilders(env) # C c_file.add_action(".l", LexAction) c_file.add_emitter(".l", lexEmitter) c_file.add_action(".lex", LexAction) c_file.add_emitter(".lex", lexEmitter) # Objective-C cxx_file.add_action(".lm", LexAction) cxx_file.add_emitter(".lm", lexEmitter) # C++ cxx_file.add_action(".ll", LexAction) cxx_file.add_emitter(".ll", lexEmitter) env["LEX"] = env.Detect("flex") or "lex" env["LEXFLAGS"] = SCons.Util.CLVar("") env["LEXCOM"] = "$LEX $LEXFLAGS -t $SOURCES > $TARGET" def exists(env): return env.Detect(["flex", "lex"]) # 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/Tool/mssdk.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" """engine.SCons.Tool.mssdk Tool-specific initialization for Microsoft SDKs, both Platform SDKs and Windows SDKs. 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. """ from MSCommon import mssdk_exists, \ mssdk_setup_env def generate(env): """Add construction variables for an MS SDK to an Environment.""" mssdk_setup_env(env) def exists(env): return mssdk_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.PharLapCommon This module contains common code used by all Tools for the Phar Lap ETS tool chain. Right now, this is linkloc and 386asm. """ # # 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/PharLapCommon.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Errors import SCons.Util import re def getPharLapPath(): """Reads the registry to find the installed path of the Phar Lap ETS development kit. Raises UserError if no installed version of Phar Lap can be found.""" if not SCons.Util.can_read_reg: raise SCons.Errors.InternalError("No Windows registry module was found") try: k=SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Pharlap\\ETS') val, type = SCons.Util.RegQueryValueEx(k, 'BaseDir') # The following is a hack...there is (not surprisingly) # an odd issue in the Phar Lap plug in that inserts # a bunch of junk data after the phar lap path in the # registry. We must trim it. idx=val.find('\0') if idx >= 0: val = val[:idx] return os.path.normpath(val) except SCons.Util.RegError: raise SCons.Errors.UserError("Cannot find Phar Lap ETS path in the registry. Is it installed properly?") REGEX_ETS_VER = re.compile(r'#define\s+ETS_VER\s+([0-9]+)') def getPharLapVersion(): """Returns the version of the installed ETS Tool Suite as a decimal number. This version comes from the ETS_VER #define in the embkern.h header. For example, '#define ETS_VER 1010' (which is what Phar Lap 10.1 defines) would cause this method to return 1010. Phar Lap 9.1 does not have such a #define, but this method will return 910 as a default. Raises UserError if no installed version of Phar Lap can be found.""" include_path = os.path.join(getPharLapPath(), os.path.normpath("include/embkern.h")) if not os.path.exists(include_path): raise SCons.Errors.UserError("Cannot find embkern.h in ETS include directory.\nIs Phar Lap ETS installed properly?") mo = REGEX_ETS_VER.search(open(include_path, 'r').read()) if mo: return int(mo.group(1)) # Default return for Phar Lap 9.1 return 910 def addPathIfNotExists(env_dict, key, path, sep=os.pathsep): """This function will take 'key' out of the dictionary 'env_dict', then add the path 'path' to that key if it is not already there. This treats the value of env_dict[key] as if it has a similar format to the PATH variable...a list of paths separated by tokens. The 'path' will get added to the list if it is not already there.""" try: is_list = 1 paths = env_dict[key] if not SCons.Util.is_List(env_dict[key]): paths = paths.split(sep) is_list = 0 if os.path.normcase(path) not in list(map(os.path.normcase, paths)): paths = [ path ] + paths if is_list: env_dict[key] = paths else: env_dict[key] = sep.join(paths) except KeyError: env_dict[key] = path def addPharLapPaths(env): """This function adds the path to the Phar Lap binaries, includes, and libraries, if they are not already there.""" ph_path = getPharLapPath() try: env_dict = env['ENV'] except KeyError: env_dict = {} env['ENV'] = env_dict addPathIfNotExists(env_dict, 'PATH', os.path.join(ph_path, 'bin')) addPathIfNotExists(env_dict, 'INCLUDE', os.path.join(ph_path, 'include')) addPathIfNotExists(env_dict, 'LIB', os.path.join(ph_path, 'lib')) addPathIfNotExists(env_dict, 'LIB', os.path.join(ph_path, os.path.normpath('lib/vclib'))) env['PHARLAP_PATH'] = getPharLapPath() env['PHARLAP_VERSION'] = str(getPharLapVersion()) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sgic++ Tool-specific initialization for MIPSpro C++ on SGI. 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/sgic++.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util cplusplus = __import__('c++', globals(), locals(), []) def generate(env): """Add Builders and construction variables for SGI MIPS C++ to an Environment.""" cplusplus.generate(env) env['CXX'] = 'CC' env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std') env['SHCXX'] = '$CXX' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 def exists(env): return env.Detect('CC') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.icl Tool-specific initialization for the Intel C/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/icl.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Tool.intelc # This has been completely superceded by intelc.py, which can # handle both Windows and Linux versions. def generate(*args, **kw): """Add Builders and construction variables for icl to an Environment.""" return SCons.Tool.intelc.generate(*args, **kw) def exists(*args, **kw): return SCons.Tool.intelc.exists(*args, **kw) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.ilink Tool-specific initialization for the OS/2 ilink linker. 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/ilink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util def generate(env): """Add Builders and construction variables for ilink to an Environment.""" SCons.Tool.createProgBuilder(env) env['LINK'] = 'ilink' env['LINKFLAGS'] = SCons.Util.CLVar('') env['LINKCOM'] = '$LINK $LINKFLAGS /O:$TARGET $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' env['LIBDIRPREFIX']='/LIBPATH:' env['LIBDIRSUFFIX']='' env['LIBLINKPREFIX']='' env['LIBLINKSUFFIX']='$LIBSUFFIX' def exists(env): return env.Detect('ilink') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.pdflatex Tool-specific initialization for pdflatex. Generates .pdf files from .latex or .ltx 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/pdflatex.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Util import SCons.Tool.pdf import SCons.Tool.tex PDFLaTeXAction = None def PDFLaTeXAuxFunction(target = None, source= None, env=None): result = SCons.Tool.tex.InternalLaTeXAuxAction( PDFLaTeXAction, target, source, env ) if result != 0: SCons.Tool.tex.check_file_error_message(env['PDFLATEX']) return result PDFLaTeXAuxAction = None def generate(env): """Add Builders and construction variables for pdflatex to an Environment.""" global PDFLaTeXAction if PDFLaTeXAction is None: PDFLaTeXAction = SCons.Action.Action('$PDFLATEXCOM', '$PDFLATEXCOMSTR') global PDFLaTeXAuxAction if PDFLaTeXAuxAction is None: PDFLaTeXAuxAction = SCons.Action.Action(PDFLaTeXAuxFunction, strfunction=SCons.Tool.tex.TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.ltx', PDFLaTeXAuxAction) bld.add_action('.latex', PDFLaTeXAuxAction) bld.add_emitter('.ltx', SCons.Tool.tex.tex_pdf_emitter) bld.add_emitter('.latex', SCons.Tool.tex.tex_pdf_emitter) SCons.Tool.tex.generate_common(env) def exists(env): SCons.Tool.tex.generate_darwin(env) return env.Detect('pdflatex') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.msvc Tool-specific initialization for Microsoft Visual C/C++. 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/msvc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import re import sys import SCons.Action import SCons.Builder import SCons.Errors import SCons.Platform.win32 import SCons.Tool import SCons.Tool.msvs import SCons.Util import SCons.Warnings import SCons.Scanner.RC from MSCommon import msvc_exists, msvc_setup_env_once CSuffixes = ['.c', '.C'] CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++'] def validate_vars(env): """Validate the PCH and PCHSTOP construction variables.""" if 'PCH' in env and env['PCH']: if 'PCHSTOP' not in env: raise SCons.Errors.UserError("The PCHSTOP construction must be defined if PCH is defined.") if not SCons.Util.is_String(env['PCHSTOP']): raise SCons.Errors.UserError("The PCHSTOP construction variable must be a string: %r"%env['PCHSTOP']) def pch_emitter(target, source, env): """Adds the object file target.""" validate_vars(env) pch = None obj = None for t in target: if SCons.Util.splitext(str(t))[1] == '.pch': pch = t if SCons.Util.splitext(str(t))[1] == '.obj': obj = t if not obj: obj = SCons.Util.splitext(str(pch))[0]+'.obj' target = [pch, obj] # pch must be first, and obj second for the PCHCOM to work return (target, source) def object_emitter(target, source, env, parent_emitter): """Sets up the PCH dependencies for an object file.""" validate_vars(env) parent_emitter(target, source, env) # Add a dependency, but only if the target (e.g. 'Source1.obj') # doesn't correspond to the pre-compiled header ('Source1.pch'). # If the basenames match, then this was most likely caused by # someone adding the source file to both the env.PCH() and the # env.Program() calls, and adding the explicit dependency would # cause a cycle on the .pch file itself. # # See issue #2505 for a discussion of what to do if it turns # out this assumption causes trouble in the wild: # http://scons.tigris.org/issues/show_bug.cgi?id=2505 if 'PCH' in env: pch = env['PCH'] if str(target[0]) != SCons.Util.splitext(str(pch))[0] + '.obj': env.Depends(target, pch) return (target, source) def static_object_emitter(target, source, env): return object_emitter(target, source, env, SCons.Defaults.StaticObjectEmitter) def shared_object_emitter(target, source, env): return object_emitter(target, source, env, SCons.Defaults.SharedObjectEmitter) pch_action = SCons.Action.Action('$PCHCOM', '$PCHCOMSTR') pch_builder = SCons.Builder.Builder(action=pch_action, suffix='.pch', emitter=pch_emitter, source_scanner=SCons.Tool.SourceFileScanner) # Logic to build .rc files into .res files (resource files) res_scanner = SCons.Scanner.RC.RCScan() res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR') res_builder = SCons.Builder.Builder(action=res_action, src_suffix='.rc', suffix='.res', src_builder=[], source_scanner=res_scanner) def msvc_batch_key(action, env, target, source): """ Returns a key to identify unique batches of sources for compilation. If batching is enabled (via the $MSVC_BATCH setting), then all target+source pairs that use the same action, defined by the same environment, and have the same target and source directories, will be batched. Returning None specifies that the specified target+source should not be batched with other compilations. """ # Fixing MSVC_BATCH mode. Previous if did not work when MSVC_BATCH # was set to False. This new version should work better. # Note we need to do the env.subst so $MSVC_BATCH can be a reference to # another construction variable, which is why we test for False and 0 # as strings. if not 'MSVC_BATCH' in env or env.subst('$MSVC_BATCH') in ('0', 'False', '', None): # We're not using batching; return no key. return None t = target[0] s = source[0] if os.path.splitext(t.name)[0] != os.path.splitext(s.name)[0]: # The base names are different, so this *must* be compiled # separately; return no key. return None return (id(action), id(env), t.dir, s.dir) def msvc_output_flag(target, source, env, for_signature): """ Returns the correct /Fo flag for batching. If batching is disabled or there's only one source file, then we return an /Fo string that specifies the target explicitly. Otherwise, we return an /Fo string that just specifies the first target's directory (where the Visual C/C++ compiler will put the .obj files). """ # Fixing MSVC_BATCH mode. Previous if did not work when MSVC_BATCH # was set to False. This new version should work better. Removed # len(source)==1 as batch mode can compile only one file # (and it also fixed problem with compiling only one changed file # with batch mode enabled) if not 'MSVC_BATCH' in env or env.subst('$MSVC_BATCH') in ('0', 'False', '', None): return '/Fo$TARGET' else: # The Visual C/C++ compiler requires a \ at the end of the /Fo # option to indicate an output directory. We use os.sep here so # that the test(s) for this can be run on non-Windows systems # without having a hard-coded backslash mess up command-line # argument parsing. return '/Fo${TARGET.dir}' + os.sep CAction = SCons.Action.Action("$CCCOM", "$CCCOMSTR", batch_key=msvc_batch_key, targets='$CHANGED_TARGETS') ShCAction = SCons.Action.Action("$SHCCCOM", "$SHCCCOMSTR", batch_key=msvc_batch_key, targets='$CHANGED_TARGETS') CXXAction = SCons.Action.Action("$CXXCOM", "$CXXCOMSTR", batch_key=msvc_batch_key, targets='$CHANGED_TARGETS') ShCXXAction = SCons.Action.Action("$SHCXXCOM", "$SHCXXCOMSTR", batch_key=msvc_batch_key, targets='$CHANGED_TARGETS') def generate(env): """Add Builders and construction variables for MSVC++ to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) # TODO(batch): shouldn't reach in to cmdgen this way; necessary # for now to bypass the checks in Builder.DictCmdGenerator.__call__() # and allow .cc and .cpp to be compiled in the same command line. static_obj.cmdgen.source_ext_match = False shared_obj.cmdgen.source_ext_match = False for suffix in CSuffixes: static_obj.add_action(suffix, CAction) shared_obj.add_action(suffix, ShCAction) static_obj.add_emitter(suffix, static_object_emitter) shared_obj.add_emitter(suffix, shared_object_emitter) for suffix in CXXSuffixes: static_obj.add_action(suffix, CXXAction) shared_obj.add_action(suffix, ShCXXAction) static_obj.add_emitter(suffix, static_object_emitter) shared_obj.add_emitter(suffix, shared_object_emitter) env['CCPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Z7") or ""}']) env['CCPCHFLAGS'] = SCons.Util.CLVar(['${(PCH and "/Yu%s \\\"/Fp%s\\\""%(PCHSTOP or "",File(PCH))) or ""}']) env['_MSVC_OUTPUT_FLAG'] = msvc_output_flag env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $CCPCHFLAGS $CCPDBFLAGS' env['CC'] = 'cl' env['CCFLAGS'] = SCons.Util.CLVar('/nologo') env['CFLAGS'] = SCons.Util.CLVar('') env['CCCOM'] = '${TEMPFILE("$CC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CFLAGS $CCFLAGS $_CCCOMCOM")}' env['SHCC'] = '$CC' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS') env['SHCCCOM'] = '${TEMPFILE("$SHCC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCFLAGS $SHCCFLAGS $_CCCOMCOM")}' env['CXX'] = '$CC' env['CXXFLAGS'] = SCons.Util.CLVar('$( /TP $)') env['CXXCOM'] = '${TEMPFILE("$CXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CXXFLAGS $CCFLAGS $_CCCOMCOM")}' env['SHCXX'] = '$CXX' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHCXXCOM'] = '${TEMPFILE("$SHCXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM")}' env['CPPDEFPREFIX'] = '/D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '/I' env['INCSUFFIX'] = '' # env.Append(OBJEMITTER = [static_object_emitter]) # env.Append(SHOBJEMITTER = [shared_object_emitter]) env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['RC'] = 'rc' env['RCFLAGS'] = SCons.Util.CLVar('') env['RCSUFFIXES']=['.rc','.rc2'] env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES' env['BUILDERS']['RES'] = res_builder env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' # Set-up ms tools paths msvc_setup_env_once(env) env['CFILESUFFIX'] = '.c' env['CXXFILESUFFIX'] = '.cc' env['PCHPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Yd") or ""}']) env['PCHCOM'] = '$CXX /Fo${TARGETS[1]} $CXXFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS' env['BUILDERS']['PCH'] = pch_builder if 'ENV' not in env: env['ENV'] = {} if 'SystemRoot' not in env['ENV']: # required for dlls in the winsxs folders env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root() def exists(env): return msvc_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.zip Tool-specific initialization for zip. 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/zip.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Builder import SCons.Defaults import SCons.Node.FS import SCons.Util try: import zipfile internal_zip = 1 except ImportError: internal_zip = 0 if internal_zip: zipcompression = zipfile.ZIP_DEFLATED def zip(target, source, env): compression = env.get('ZIPCOMPRESSION', 0) zf = zipfile.ZipFile(str(target[0]), 'w', compression) for s in source: if s.isdir(): for dirpath, dirnames, filenames in os.walk(str(s)): for fname in filenames: path = os.path.join(dirpath, fname) if os.path.isfile(path): zf.write(path) else: zf.write(str(s)) zf.close() else: zipcompression = 0 zip = "$ZIP $ZIPFLAGS ${TARGET.abspath} $SOURCES" zipAction = SCons.Action.Action(zip, varlist=['ZIPCOMPRESSION']) ZipBuilder = SCons.Builder.Builder(action = SCons.Action.Action('$ZIPCOM', '$ZIPCOMSTR'), source_factory = SCons.Node.FS.Entry, source_scanner = SCons.Defaults.DirScanner, suffix = '$ZIPSUFFIX', multi = 1) def generate(env): """Add Builders and construction variables for zip to an Environment.""" try: bld = env['BUILDERS']['Zip'] except KeyError: bld = ZipBuilder env['BUILDERS']['Zip'] = bld env['ZIP'] = 'zip' env['ZIPFLAGS'] = SCons.Util.CLVar('') env['ZIPCOM'] = zipAction env['ZIPCOMPRESSION'] = zipcompression env['ZIPSUFFIX'] = '.zip' def exists(env): return internal_zip or env.Detect('zip') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.javah Tool-specific initialization for javah. 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/javah.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Action import SCons.Builder import SCons.Node.FS import SCons.Tool.javac import SCons.Util def emit_java_headers(target, source, env): """Create and return lists of Java stub header files that will be created from a set of class files. """ class_suffix = env.get('JAVACLASSSUFFIX', '.class') classdir = env.get('JAVACLASSDIR') if not classdir: try: s = source[0] except IndexError: classdir = '.' else: try: classdir = s.attributes.java_classdir except AttributeError: classdir = '.' classdir = env.Dir(classdir).rdir() if str(classdir) == '.': c_ = None else: c_ = str(classdir) + os.sep slist = [] for src in source: try: classname = src.attributes.java_classname except AttributeError: classname = str(src) if c_ and classname[:len(c_)] == c_: classname = classname[len(c_):] if class_suffix and classname[-len(class_suffix):] == class_suffix: classname = classname[:-len(class_suffix)] classname = SCons.Tool.javac.classname(classname) s = src.rfile() s.attributes.java_classname = classname slist.append(s) s = source[0].rfile() if not hasattr(s.attributes, 'java_classdir'): s.attributes.java_classdir = classdir if target[0].__class__ is SCons.Node.FS.File: tlist = target else: if not isinstance(target[0], SCons.Node.FS.Dir): target[0].__class__ = SCons.Node.FS.Dir target[0]._morph() tlist = [] for s in source: fname = s.attributes.java_classname.replace('.', '_') + '.h' t = target[0].File(fname) t.attributes.java_lookupdir = target[0] tlist.append(t) return tlist, source def JavaHOutFlagGenerator(target, source, env, for_signature): try: t = target[0] except (AttributeError, IndexError, TypeError): t = target try: return '-d ' + str(t.attributes.java_lookupdir) except AttributeError: return '-o ' + str(t) def getJavaHClassPath(env,target, source, for_signature): path = "${SOURCE.attributes.java_classdir}" if 'JAVACLASSPATH' in env and env['JAVACLASSPATH']: path = SCons.Util.AppendPath(path, env['JAVACLASSPATH']) return "-classpath %s" % (path) def generate(env): """Add Builders and construction variables for javah to an Environment.""" java_javah = SCons.Tool.CreateJavaHBuilder(env) java_javah.emitter = emit_java_headers env['_JAVAHOUTFLAG'] = JavaHOutFlagGenerator env['JAVAH'] = 'javah' env['JAVAHFLAGS'] = SCons.Util.CLVar('') env['_JAVAHCLASSPATH'] = getJavaHClassPath env['JAVAHCOM'] = '$JAVAH $JAVAHFLAGS $_JAVAHOUTFLAG $_JAVAHCLASSPATH ${SOURCES.attributes.java_classname}' env['JAVACLASSSUFFIX'] = '.class' def exists(env): return env.Detect('javah') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.hpc++ Tool-specific initialization for c++ on HP/UX. 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/hpc++.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Util cplusplus = __import__('c++', globals(), locals(), []) acc = None # search for the acc compiler and linker front end try: dirs = os.listdir('/opt') except (IOError, OSError): # Not being able to read the directory because it doesn't exist # (IOError) or isn't readable (OSError) is okay. dirs = [] for dir in dirs: cc = '/opt/' + dir + '/bin/aCC' if os.path.exists(cc): acc = cc break def generate(env): """Add Builders and construction variables for g++ to an Environment.""" cplusplus.generate(env) if acc: env['CXX'] = acc or 'aCC' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS +Z') # determine version of aCC line = os.popen(acc + ' -V 2>&1').readline().rstrip() if line.find('aCC: HP ANSI C++') == 0: env['CXXVERSION'] = line.split()[-1] if env['PLATFORM'] == 'cygwin': env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') else: env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS +Z') def exists(env): return acc # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.yacc Tool-specific initialization for yacc. 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/yacc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Defaults import SCons.Tool import SCons.Util YaccAction = SCons.Action.Action("$YACCCOM", "$YACCCOMSTR") def _yaccEmitter(target, source, env, ysuf, hsuf): yaccflags = env.subst("$YACCFLAGS", target=target, source=source) flags = SCons.Util.CLVar(yaccflags) targetBase, targetExt = os.path.splitext(SCons.Util.to_String(target[0])) if '.ym' in ysuf: # If using Objective-C target = [targetBase + ".m"] # the extension is ".m". # If -d is specified on the command line, yacc will emit a .h # or .hpp file with the same name as the .c or .cpp output file. if '-d' in flags: target.append(targetBase + env.subst(hsuf, target=target, source=source)) # If -g is specified on the command line, yacc will emit a .vcg # file with the same base name as the .y, .yacc, .ym or .yy file. if "-g" in flags: base, ext = os.path.splitext(SCons.Util.to_String(source[0])) target.append(base + env.subst("$YACCVCGFILESUFFIX")) # If -v is specirfied yacc will create the output debug file # which is not really source for any process, but should # be noted and also be cleaned # Bug #2558 if "-v" in flags: env.SideEffect(targetBase+'.output',target[0]) env.Clean(target[0],targetBase+'.output') # With --defines and --graph, the name of the file is totally defined # in the options. fileGenOptions = ["--defines=", "--graph="] for option in flags: for fileGenOption in fileGenOptions: l = len(fileGenOption) if option[:l] == fileGenOption: # A file generating option is present, so add the file # name to the list of targets. fileName = option[l:].strip() target.append(fileName) return (target, source) def yEmitter(target, source, env): return _yaccEmitter(target, source, env, ['.y', '.yacc'], '$YACCHFILESUFFIX') def ymEmitter(target, source, env): return _yaccEmitter(target, source, env, ['.ym'], '$YACCHFILESUFFIX') def yyEmitter(target, source, env): return _yaccEmitter(target, source, env, ['.yy'], '$YACCHXXFILESUFFIX') def generate(env): """Add Builders and construction variables for yacc to an Environment.""" c_file, cxx_file = SCons.Tool.createCFileBuilders(env) # C c_file.add_action('.y', YaccAction) c_file.add_emitter('.y', yEmitter) c_file.add_action('.yacc', YaccAction) c_file.add_emitter('.yacc', yEmitter) # Objective-C c_file.add_action('.ym', YaccAction) c_file.add_emitter('.ym', ymEmitter) # C++ cxx_file.add_action('.yy', YaccAction) cxx_file.add_emitter('.yy', yyEmitter) env['YACC'] = env.Detect('bison') or 'yacc' env['YACCFLAGS'] = SCons.Util.CLVar('') env['YACCCOM'] = '$YACC $YACCFLAGS -o $TARGET $SOURCES' env['YACCHFILESUFFIX'] = '.h' # Apparently, OS X now creates file.hpp like everybody else # I have no idea when it changed; it was fixed in 10.4 #if env['PLATFORM'] == 'darwin': # # Bison on Mac OS X just appends ".h" to the generated target .cc # # or .cpp file name. Hooray for delayed expansion of variables. # env['YACCHXXFILESUFFIX'] = '${TARGET.suffix}.h' #else: # env['YACCHXXFILESUFFIX'] = '.hpp' env['YACCHXXFILESUFFIX'] = '.hpp' env['YACCVCGFILESUFFIX'] = '.vcg' def exists(env): return env.Detect(['bison', 'yacc']) # 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.bcc32 XXX """ # # 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/bcc32.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Defaults import SCons.Tool import SCons.Util def findIt(program, env): # First search in the SCons path and then the OS path: borwin = env.WhereIs(program) or SCons.Util.WhereIs(program) if borwin: dir = os.path.dirname(borwin) env.PrependENVPath('PATH', dir) return borwin def generate(env): findIt('bcc32', env) """Add Builders and construction variables for bcc to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ['.c', '.cpp']: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix, SCons.Defaults.ShCAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) env['CC'] = 'bcc32' env['CCFLAGS'] = SCons.Util.CLVar('') env['CFLAGS'] = SCons.Util.CLVar('') env['CCCOM'] = '$CC -q $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES' env['SHCC'] = '$CC' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS') env['SHCCCOM'] = '$SHCC -WD $SHCFLAGS $SHCCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES' env['CPPDEFPREFIX'] = '-D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '-I' env['INCSUFFIX'] = '' env['SHOBJSUFFIX'] = '.dll' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0 env['CFILESUFFIX'] = '.cpp' def exists(env): return findIt('bcc32', env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.ar Tool-specific initialization for ar (library archive). 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/ar.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util def generate(env): """Add Builders and construction variables for ar to an Environment.""" SCons.Tool.createStaticLibBuilder(env) env['AR'] = 'ar' env['ARFLAGS'] = SCons.Util.CLVar('rc') env['ARCOM'] = '$AR $ARFLAGS $TARGET $SOURCES' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' if env.Detect('ranlib'): env['RANLIB'] = 'ranlib' env['RANLIBFLAGS'] = SCons.Util.CLVar('') env['RANLIBCOM'] = '$RANLIB $RANLIBFLAGS $TARGET' def exists(env): return env.Detect('ar') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool SCons tool selection. This looks for modules that define a callable object that can modify a construction environment as appropriate for a given tool (or tool chain). Note that because this subsystem just *selects* a callable that can modify a construction environment, it's possible for people to define their own "tool specification" in an arbitrary callable function. No one needs to use or tie in to this subsystem in order to roll their own tool 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/Tool/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import imp import sys import SCons.Builder import SCons.Errors import SCons.Node.FS import SCons.Scanner import SCons.Scanner.C import SCons.Scanner.D import SCons.Scanner.LaTeX import SCons.Scanner.Prog DefaultToolpath=[] CScanner = SCons.Scanner.C.CScanner() DScanner = SCons.Scanner.D.DScanner() LaTeXScanner = SCons.Scanner.LaTeX.LaTeXScanner() PDFLaTeXScanner = SCons.Scanner.LaTeX.PDFLaTeXScanner() ProgramScanner = SCons.Scanner.Prog.ProgramScanner() SourceFileScanner = SCons.Scanner.Base({}, name='SourceFileScanner') CSuffixes = [".c", ".C", ".cxx", ".cpp", ".c++", ".cc", ".h", ".H", ".hxx", ".hpp", ".hh", ".F", ".fpp", ".FPP", ".m", ".mm", ".S", ".spp", ".SPP", ".sx"] DSuffixes = ['.d'] IDLSuffixes = [".idl", ".IDL"] LaTeXSuffixes = [".tex", ".ltx", ".latex"] for suffix in CSuffixes: SourceFileScanner.add_scanner(suffix, CScanner) for suffix in DSuffixes: SourceFileScanner.add_scanner(suffix, DScanner) # FIXME: what should be done here? Two scanners scan the same extensions, # but look for different files, e.g., "picture.eps" vs. "picture.pdf". # The builders for DVI and PDF explicitly reference their scanners # I think that means this is not needed??? for suffix in LaTeXSuffixes: SourceFileScanner.add_scanner(suffix, LaTeXScanner) SourceFileScanner.add_scanner(suffix, PDFLaTeXScanner) class Tool(object): def __init__(self, name, toolpath=[], **kw): self.name = name self.toolpath = toolpath + DefaultToolpath # remember these so we can merge them into the call self.init_kw = kw module = self._tool_module() self.generate = module.generate self.exists = module.exists if hasattr(module, 'options'): self.options = module.options def _tool_module(self): # TODO: Interchange zipimport with normal initilization for better error reporting oldpythonpath = sys.path sys.path = self.toolpath + sys.path try: try: file, path, desc = imp.find_module(self.name, self.toolpath) try: return imp.load_module(self.name, file, path, desc) finally: if file: file.close() except ImportError, e: if str(e)!="No module named %s"%self.name: raise SCons.Errors.EnvironmentError(e) try: import zipimport except ImportError: pass else: for aPath in self.toolpath: try: importer = zipimport.zipimporter(aPath) return importer.load_module(self.name) except ImportError, e: pass finally: sys.path = oldpythonpath full_name = 'SCons.Tool.' + self.name try: return sys.modules[full_name] except KeyError: try: smpath = sys.modules['SCons.Tool'].__path__ try: file, path, desc = imp.find_module(self.name, smpath) module = imp.load_module(full_name, file, path, desc) setattr(SCons.Tool, self.name, module) if file: file.close() return module except ImportError, e: if str(e)!="No module named %s"%self.name: raise SCons.Errors.EnvironmentError(e) try: import zipimport importer = zipimport.zipimporter( sys.modules['SCons.Tool'].__path__[0] ) module = importer.load_module(full_name) setattr(SCons.Tool, self.name, module) return module except ImportError, e: m = "No tool named '%s': %s" % (self.name, e) raise SCons.Errors.EnvironmentError(m) except ImportError, e: m = "No tool named '%s': %s" % (self.name, e) raise SCons.Errors.EnvironmentError(m) def __call__(self, env, *args, **kw): if self.init_kw is not None: # Merge call kws into init kws; # but don't bash self.init_kw. if kw is not None: call_kw = kw kw = self.init_kw.copy() kw.update(call_kw) else: kw = self.init_kw env.Append(TOOLS = [ self.name ]) if hasattr(self, 'options'): import SCons.Variables if 'options' not in env: from SCons.Script import ARGUMENTS env['options']=SCons.Variables.Variables(args=ARGUMENTS) opts=env['options'] self.options(opts) opts.Update(env) self.generate(env, *args, **kw) def __str__(self): return self.name ########################################################################## # Create common executable program / library / object builders def createProgBuilder(env): """This is a utility function that creates the Program Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: program = env['BUILDERS']['Program'] except KeyError: import SCons.Defaults program = SCons.Builder.Builder(action = SCons.Defaults.LinkAction, emitter = '$PROGEMITTER', prefix = '$PROGPREFIX', suffix = '$PROGSUFFIX', src_suffix = '$OBJSUFFIX', src_builder = 'Object', target_scanner = ProgramScanner) env['BUILDERS']['Program'] = program return program def createStaticLibBuilder(env): """This is a utility function that creates the StaticLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: static_lib = env['BUILDERS']['StaticLibrary'] except KeyError: action_list = [ SCons.Action.Action("$ARCOM", "$ARCOMSTR") ] if env.Detect('ranlib'): ranlib_action = SCons.Action.Action("$RANLIBCOM", "$RANLIBCOMSTR") action_list.append(ranlib_action) static_lib = SCons.Builder.Builder(action = action_list, emitter = '$LIBEMITTER', prefix = '$LIBPREFIX', suffix = '$LIBSUFFIX', src_suffix = '$OBJSUFFIX', src_builder = 'StaticObject') env['BUILDERS']['StaticLibrary'] = static_lib env['BUILDERS']['Library'] = static_lib return static_lib def createSharedLibBuilder(env): """This is a utility function that creates the SharedLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: shared_lib = env['BUILDERS']['SharedLibrary'] except KeyError: import SCons.Defaults action_list = [ SCons.Defaults.SharedCheck, SCons.Defaults.ShLinkAction ] shared_lib = SCons.Builder.Builder(action = action_list, emitter = "$SHLIBEMITTER", prefix = '$SHLIBPREFIX', suffix = '$SHLIBSUFFIX', target_scanner = ProgramScanner, src_suffix = '$SHOBJSUFFIX', src_builder = 'SharedObject') env['BUILDERS']['SharedLibrary'] = shared_lib return shared_lib def createLoadableModuleBuilder(env): """This is a utility function that creates the LoadableModule Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: ld_module = env['BUILDERS']['LoadableModule'] except KeyError: import SCons.Defaults action_list = [ SCons.Defaults.SharedCheck, SCons.Defaults.LdModuleLinkAction ] ld_module = SCons.Builder.Builder(action = action_list, emitter = "$LDMODULEEMITTER", prefix = '$LDMODULEPREFIX', suffix = '$LDMODULESUFFIX', target_scanner = ProgramScanner, src_suffix = '$SHOBJSUFFIX', src_builder = 'SharedObject') env['BUILDERS']['LoadableModule'] = ld_module return ld_module def createObjBuilders(env): """This is a utility function that creates the StaticObject and SharedObject Builders in an Environment if they are not there already. If they are there already, we return the existing ones. This is a separate function because soooo many Tools use this functionality. The return is a 2-tuple of (StaticObject, SharedObject) """ try: static_obj = env['BUILDERS']['StaticObject'] except KeyError: static_obj = SCons.Builder.Builder(action = {}, emitter = {}, prefix = '$OBJPREFIX', suffix = '$OBJSUFFIX', src_builder = ['CFile', 'CXXFile'], source_scanner = SourceFileScanner, single_source = 1) env['BUILDERS']['StaticObject'] = static_obj env['BUILDERS']['Object'] = static_obj try: shared_obj = env['BUILDERS']['SharedObject'] except KeyError: shared_obj = SCons.Builder.Builder(action = {}, emitter = {}, prefix = '$SHOBJPREFIX', suffix = '$SHOBJSUFFIX', src_builder = ['CFile', 'CXXFile'], source_scanner = SourceFileScanner, single_source = 1) env['BUILDERS']['SharedObject'] = shared_obj return (static_obj, shared_obj) def createCFileBuilders(env): """This is a utility function that creates the CFile/CXXFile Builders in an Environment if they are not there already. If they are there already, we return the existing ones. This is a separate function because soooo many Tools use this functionality. The return is a 2-tuple of (CFile, CXXFile) """ try: c_file = env['BUILDERS']['CFile'] except KeyError: c_file = SCons.Builder.Builder(action = {}, emitter = {}, suffix = {None:'$CFILESUFFIX'}) env['BUILDERS']['CFile'] = c_file env.SetDefault(CFILESUFFIX = '.c') try: cxx_file = env['BUILDERS']['CXXFile'] except KeyError: cxx_file = SCons.Builder.Builder(action = {}, emitter = {}, suffix = {None:'$CXXFILESUFFIX'}) env['BUILDERS']['CXXFile'] = cxx_file env.SetDefault(CXXFILESUFFIX = '.cc') return (c_file, cxx_file) ########################################################################## # Create common Java builders def CreateJarBuilder(env): try: java_jar = env['BUILDERS']['Jar'] except KeyError: fs = SCons.Node.FS.get_default_fs() jar_com = SCons.Action.Action('$JARCOM', '$JARCOMSTR') java_jar = SCons.Builder.Builder(action = jar_com, suffix = '$JARSUFFIX', src_suffix = '$JAVACLASSSUFIX', src_builder = 'JavaClassFile', source_factory = fs.Entry) env['BUILDERS']['Jar'] = java_jar return java_jar def CreateJavaHBuilder(env): try: java_javah = env['BUILDERS']['JavaH'] except KeyError: fs = SCons.Node.FS.get_default_fs() java_javah_com = SCons.Action.Action('$JAVAHCOM', '$JAVAHCOMSTR') java_javah = SCons.Builder.Builder(action = java_javah_com, src_suffix = '$JAVACLASSSUFFIX', target_factory = fs.Entry, source_factory = fs.File, src_builder = 'JavaClassFile') env['BUILDERS']['JavaH'] = java_javah return java_javah def CreateJavaClassFileBuilder(env): try: java_class_file = env['BUILDERS']['JavaClassFile'] except KeyError: fs = SCons.Node.FS.get_default_fs() javac_com = SCons.Action.Action('$JAVACCOM', '$JAVACCOMSTR') java_class_file = SCons.Builder.Builder(action = javac_com, emitter = {}, #suffix = '$JAVACLASSSUFFIX', src_suffix = '$JAVASUFFIX', src_builder = ['JavaFile'], target_factory = fs.Entry, source_factory = fs.File) env['BUILDERS']['JavaClassFile'] = java_class_file return java_class_file def CreateJavaClassDirBuilder(env): try: java_class_dir = env['BUILDERS']['JavaClassDir'] except KeyError: fs = SCons.Node.FS.get_default_fs() javac_com = SCons.Action.Action('$JAVACCOM', '$JAVACCOMSTR') java_class_dir = SCons.Builder.Builder(action = javac_com, emitter = {}, target_factory = fs.Dir, source_factory = fs.Dir) env['BUILDERS']['JavaClassDir'] = java_class_dir return java_class_dir def CreateJavaFileBuilder(env): try: java_file = env['BUILDERS']['JavaFile'] except KeyError: java_file = SCons.Builder.Builder(action = {}, emitter = {}, suffix = {None:'$JAVASUFFIX'}) env['BUILDERS']['JavaFile'] = java_file env['JAVASUFFIX'] = '.java' return java_file class ToolInitializerMethod(object): """ This is added to a construction environment in place of a method(s) normally called for a Builder (env.Object, env.StaticObject, etc.). When called, it has its associated ToolInitializer object search the specified list of tools and apply the first one that exists to the construction environment. It then calls whatever builder was (presumably) added to the construction environment in place of this particular instance. """ def __init__(self, name, initializer): """ Note: we store the tool name as __name__ so it can be used by the class that attaches this to a construction environment. """ self.__name__ = name self.initializer = initializer def get_builder(self, env): """ Returns the appropriate real Builder for this method name after having the associated ToolInitializer object apply the appropriate Tool module. """ builder = getattr(env, self.__name__) self.initializer.apply_tools(env) builder = getattr(env, self.__name__) if builder is self: # There was no Builder added, which means no valid Tool # for this name was found (or possibly there's a mismatch # between the name we were called by and the Builder name # added by the Tool module). return None self.initializer.remove_methods(env) return builder def __call__(self, env, *args, **kw): """ """ builder = self.get_builder(env) if builder is None: return [], [] return builder(*args, **kw) class ToolInitializer(object): """ A class for delayed initialization of Tools modules. Instances of this class associate a list of Tool modules with a list of Builder method names that will be added by those Tool modules. As part of instantiating this object for a particular construction environment, we also add the appropriate ToolInitializerMethod objects for the various Builder methods that we want to use to delay Tool searches until necessary. """ def __init__(self, env, tools, names): if not SCons.Util.is_List(tools): tools = [tools] if not SCons.Util.is_List(names): names = [names] self.env = env self.tools = tools self.names = names self.methods = {} for name in names: method = ToolInitializerMethod(name, self) self.methods[name] = method env.AddMethod(method) def remove_methods(self, env): """ Removes the methods that were added by the tool initialization so we no longer copy and re-bind them when the construction environment gets cloned. """ for method in self.methods.values(): env.RemoveMethod(method) def apply_tools(self, env): """ Searches the list of associated Tool modules for one that exists, and applies that to the construction environment. """ for t in self.tools: tool = SCons.Tool.Tool(t) if tool.exists(env): env.Tool(tool) return # If we fall through here, there was no tool module found. # This is where we can put an informative error message # about the inability to find the tool. We'll start doing # this as we cut over more pre-defined Builder+Tools to use # the ToolInitializer class. def Initializers(env): ToolInitializer(env, ['install'], ['_InternalInstall', '_InternalInstallAs']) def Install(self, *args, **kw): return self._InternalInstall(*args, **kw) def InstallAs(self, *args, **kw): return self._InternalInstallAs(*args, **kw) env.AddMethod(Install) env.AddMethod(InstallAs) def FindTool(tools, env): for tool in tools: t = Tool(tool) if t.exists(env): return tool return None def FindAllTools(tools, env): def ToolExists(tool, env=env): return Tool(tool).exists(env) return list(filter (ToolExists, tools)) def tool_list(platform, env): other_plat_tools=[] # XXX this logic about what tool to prefer on which platform # should be moved into either the platform files or # the tool files themselves. # The search orders here are described in the man page. If you # change these search orders, update the man page as well. if str(platform) == 'win32': "prefer Microsoft tools on Windows" linkers = ['mslink', 'gnulink', 'ilink', 'linkloc', 'ilink32' ] c_compilers = ['msvc', 'mingw', 'gcc', 'intelc', 'icl', 'icc', 'cc', 'bcc32' ] cxx_compilers = ['msvc', 'intelc', 'icc', 'g++', 'c++', 'bcc32' ] assemblers = ['masm', 'nasm', 'gas', '386asm' ] fortran_compilers = ['gfortran', 'g77', 'ifl', 'cvf', 'f95', 'f90', 'fortran'] ars = ['mslib', 'ar', 'tlib'] other_plat_tools=['msvs','midl'] elif str(platform) == 'os2': "prefer IBM tools on OS/2" linkers = ['ilink', 'gnulink', ]#'mslink'] c_compilers = ['icc', 'gcc',]# 'msvc', 'cc'] cxx_compilers = ['icc', 'g++',]# 'msvc', 'c++'] assemblers = ['nasm',]# 'masm', 'gas'] fortran_compilers = ['ifl', 'g77'] ars = ['ar',]# 'mslib'] elif str(platform) == 'irix': "prefer MIPSPro on IRIX" linkers = ['sgilink', 'gnulink'] c_compilers = ['sgicc', 'gcc', 'cc'] cxx_compilers = ['sgic++', 'g++', 'c++'] assemblers = ['as', 'gas'] fortran_compilers = ['f95', 'f90', 'f77', 'g77', 'fortran'] ars = ['sgiar'] elif str(platform) == 'sunos': "prefer Forte tools on SunOS" linkers = ['sunlink', 'gnulink'] c_compilers = ['suncc', 'gcc', 'cc'] cxx_compilers = ['sunc++', 'g++', 'c++'] assemblers = ['as', 'gas'] fortran_compilers = ['sunf95', 'sunf90', 'sunf77', 'f95', 'f90', 'f77', 'gfortran', 'g77', 'fortran'] ars = ['sunar'] elif str(platform) == 'hpux': "prefer aCC tools on HP-UX" linkers = ['hplink', 'gnulink'] c_compilers = ['hpcc', 'gcc', 'cc'] cxx_compilers = ['hpc++', 'g++', 'c++'] assemblers = ['as', 'gas'] fortran_compilers = ['f95', 'f90', 'f77', 'g77', 'fortran'] ars = ['ar'] elif str(platform) == 'aix': "prefer AIX Visual Age tools on AIX" linkers = ['aixlink', 'gnulink'] c_compilers = ['aixcc', 'gcc', 'cc'] cxx_compilers = ['aixc++', 'g++', 'c++'] assemblers = ['as', 'gas'] fortran_compilers = ['f95', 'f90', 'aixf77', 'g77', 'fortran'] ars = ['ar'] elif str(platform) == 'darwin': "prefer GNU tools on Mac OS X, except for some linkers and IBM tools" linkers = ['applelink', 'gnulink'] c_compilers = ['gcc', 'cc'] cxx_compilers = ['g++', 'c++'] assemblers = ['as'] fortran_compilers = ['gfortran', 'f95', 'f90', 'g77'] ars = ['ar'] else: "prefer GNU tools on all other platforms" linkers = ['gnulink', 'mslink', 'ilink'] c_compilers = ['gcc', 'msvc', 'intelc', 'icc', 'cc'] cxx_compilers = ['g++', 'msvc', 'intelc', 'icc', 'c++'] assemblers = ['gas', 'nasm', 'masm'] fortran_compilers = ['gfortran', 'g77', 'ifort', 'ifl', 'f95', 'f90', 'f77'] ars = ['ar', 'mslib'] c_compiler = FindTool(c_compilers, env) or c_compilers[0] # XXX this logic about what tool provides what should somehow be # moved into the tool files themselves. if c_compiler and c_compiler == 'mingw': # MinGW contains a linker, C compiler, C++ compiler, # Fortran compiler, archiver and assembler: cxx_compiler = None linker = None assembler = None fortran_compiler = None ar = None else: # Don't use g++ if the C compiler has built-in C++ support: if c_compiler in ('msvc', 'intelc', 'icc'): cxx_compiler = None else: cxx_compiler = FindTool(cxx_compilers, env) or cxx_compilers[0] linker = FindTool(linkers, env) or linkers[0] assembler = FindTool(assemblers, env) or assemblers[0] fortran_compiler = FindTool(fortran_compilers, env) or fortran_compilers[0] ar = FindTool(ars, env) or ars[0] other_tools = FindAllTools(other_plat_tools + [ 'dmd', #TODO: merge 'install' into 'filesystem' and # make 'filesystem' the default 'filesystem', 'm4', 'wix', #'midl', 'msvs', # Parser generators 'lex', 'yacc', # Foreign function interface 'rpcgen', 'swig', # Java 'jar', 'javac', 'javah', 'rmic', # TeX 'dvipdf', 'dvips', 'gs', 'tex', 'latex', 'pdflatex', 'pdftex', # Archivers 'tar', 'zip', 'rpm', # SourceCode factories 'BitKeeper', 'CVS', 'Perforce', 'RCS', 'SCCS', # 'Subversion', ], env) tools = ([linker, c_compiler, cxx_compiler, fortran_compiler, assembler, ar] + other_tools) return [x for x in tools if x] # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.gnulink Tool-specific initialization for the gnu linker. 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/gnulink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util import link linkers = ['g++', 'gcc'] def generate(env): """Add Builders and construction variables for gnulink to an Environment.""" link.generate(env) if env['PLATFORM'] == 'hpux': env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared -fPIC') # __RPATH is set to $_RPATH in the platform specification if that # platform supports it. env['RPATHPREFIX'] = '-Wl,-rpath=' env['RPATHSUFFIX'] = '' env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}' def exists(env): return env.Detect(linkers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.tlib XXX """ # # 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/tlib.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Tool import SCons.Tool.bcc32 import SCons.Util def generate(env): SCons.Tool.bcc32.findIt('tlib', env) """Add Builders and construction variables for ar to an Environment.""" SCons.Tool.createStaticLibBuilder(env) env['AR'] = 'tlib' env['ARFLAGS'] = SCons.Util.CLVar('') env['ARCOM'] = '$AR $TARGET $ARFLAGS /a $SOURCES' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' def exists(env): return SCons.Tool.bcc32.findIt('tlib', env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.link Tool-specific initialization for the generic Posix linker. 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/link.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util import SCons.Warnings from SCons.Tool.FortranCommon import isfortran cplusplus = __import__('c++', globals(), locals(), []) issued_mixed_link_warning = False def smart_link(source, target, env, for_signature): has_cplusplus = cplusplus.iscplusplus(source) has_fortran = isfortran(env, source) if has_cplusplus and has_fortran: global issued_mixed_link_warning if not issued_mixed_link_warning: msg = "Using $CXX to link Fortran and C++ code together.\n\t" + \ "This may generate a buggy executable if the '%s'\n\t" + \ "compiler does not know how to deal with Fortran runtimes." SCons.Warnings.warn(SCons.Warnings.FortranCxxMixWarning, msg % env.subst('$CXX')) issued_mixed_link_warning = True return '$CXX' elif has_fortran: return '$FORTRAN' elif has_cplusplus: return '$CXX' return '$CC' def shlib_emitter(target, source, env): for tgt in target: tgt.attributes.shared = 1 return (target, source) def generate(env): """Add Builders and construction variables for gnulink to an Environment.""" SCons.Tool.createSharedLibBuilder(env) SCons.Tool.createProgBuilder(env) env['SHLINK'] = '$LINK' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = '$SHLINK -o $TARGET $SHLINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' # don't set up the emitter, cause AppendUnique will generate a list # starting with None :-( env.Append(SHLIBEMITTER = [shlib_emitter]) env['SMARTLINK'] = smart_link env['LINK'] = "$SMARTLINK" env['LINKFLAGS'] = SCons.Util.CLVar('') # __RPATH is only set to something ($_RPATH typically) on platforms that support it. env['LINKCOM'] = '$LINK -o $TARGET $LINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' env['LIBDIRPREFIX']='-L' env['LIBDIRSUFFIX']='' env['_LIBFLAGS']='${_stripixes(LIBLINKPREFIX, LIBS, LIBLINKSUFFIX, LIBPREFIXES, LIBSUFFIXES, __env__)}' env['LIBLINKPREFIX']='-l' env['LIBLINKSUFFIX']='' if env['PLATFORM'] == 'hpux': env['SHLIBSUFFIX'] = '.sl' elif env['PLATFORM'] == 'aix': env['SHLIBSUFFIX'] = '.a' # For most platforms, a loadable module is the same as a shared # library. Platforms which are different can override these, but # setting them the same means that LoadableModule works everywhere. SCons.Tool.createLoadableModuleBuilder(env) env['LDMODULE'] = '$SHLINK' # don't set up the emitter, cause AppendUnique will generate a list # starting with None :-( env.Append(LDMODULEEMITTER='$SHLIBEMITTER') env['LDMODULEPREFIX'] = '$SHLIBPREFIX' env['LDMODULESUFFIX'] = '$SHLIBSUFFIX' env['LDMODULEFLAGS'] = '$SHLINKFLAGS' env['LDMODULECOM'] = '$LDMODULE -o $TARGET $LDMODULEFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' def exists(env): # This module isn't really a Tool on its own, it's common logic for # other linkers. return None # 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
"""SCons.Tool.icl Tool-specific initialization for the Intel C/C++ compiler. Supports Linux and Windows compilers, v7 and up. 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. from __future__ import division __revision__ = "src/engine/SCons/Tool/intelc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import math, sys, os.path, glob, string, re is_windows = sys.platform == 'win32' is_win64 = is_windows and (os.environ['PROCESSOR_ARCHITECTURE'] == 'AMD64' or ('PROCESSOR_ARCHITEW6432' in os.environ and os.environ['PROCESSOR_ARCHITEW6432'] == 'AMD64')) is_linux = sys.platform.startswith('linux') is_mac = sys.platform == 'darwin' if is_windows: import SCons.Tool.msvc elif is_linux: import SCons.Tool.gcc elif is_mac: import SCons.Tool.gcc import SCons.Util import SCons.Warnings # Exceptions for this tool class IntelCError(SCons.Errors.InternalError): pass class MissingRegistryError(IntelCError): # missing registry entry pass class MissingDirError(IntelCError): # dir not found pass class NoRegistryModuleError(IntelCError): # can't read registry at all pass def uniquify(s): """Return a sequence containing only one copy of each unique element from input sequence s. Does not preserve order. Input sequence must be hashable (i.e. must be usable as a dictionary key).""" u = {} for x in s: u[x] = 1 return list(u.keys()) def linux_ver_normalize(vstr): """Normalize a Linux compiler version number. Intel changed from "80" to "9.0" in 2005, so we assume if the number is greater than 60 it's an old-style number and otherwise new-style. Always returns an old-style float like 80 or 90 for compatibility with Windows. Shades of Y2K!""" # Check for version number like 9.1.026: return 91.026 m = re.match(r'([0-9]+)\.([0-9]+)\.([0-9]+)', vstr) if m: vmaj,vmin,build = m.groups() return float(vmaj) * 10. + float(vmin) + float(build) / 1000.; else: f = float(vstr) if is_windows: return f else: if f < 60: return f * 10.0 else: return f def check_abi(abi): """Check for valid ABI (application binary interface) name, and map into canonical one""" if not abi: return None abi = abi.lower() # valid_abis maps input name to canonical name if is_windows: valid_abis = {'ia32' : 'ia32', 'x86' : 'ia32', 'ia64' : 'ia64', 'em64t' : 'em64t', 'amd64' : 'em64t'} if is_linux: valid_abis = {'ia32' : 'ia32', 'x86' : 'ia32', 'x86_64' : 'x86_64', 'em64t' : 'x86_64', 'amd64' : 'x86_64'} if is_mac: valid_abis = {'ia32' : 'ia32', 'x86' : 'ia32', 'x86_64' : 'x86_64', 'em64t' : 'x86_64'} try: abi = valid_abis[abi] except KeyError: raise SCons.Errors.UserError("Intel compiler: Invalid ABI %s, valid values are %s"% \ (abi, list(valid_abis.keys()))) return abi def vercmp(a, b): """Compare strings as floats, but Intel changed Linux naming convention at 9.0""" return cmp(linux_ver_normalize(b), linux_ver_normalize(a)) def get_version_from_list(v, vlist): """See if we can match v (string) in vlist (list of strings) Linux has to match in a fuzzy way.""" if is_windows: # Simple case, just find it in the list if v in vlist: return v else: return None else: # Fuzzy match: normalize version number first, but still return # original non-normalized form. fuzz = 0.001 for vi in vlist: if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz: return vi # Not found return None def get_intel_registry_value(valuename, version=None, abi=None): """ Return a value from the Intel compiler registry tree. (Windows only) """ # Open the key: if is_win64: K = 'Software\\Wow6432Node\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper() else: K = 'Software\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper() try: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, K) except SCons.Util.RegError: raise MissingRegistryError("%s was not found in the registry, for Intel compiler version %s, abi='%s'"%(K, version,abi)) # Get the value: try: v = SCons.Util.RegQueryValueEx(k, valuename)[0] return v # or v.encode('iso-8859-1', 'replace') to remove unicode? except SCons.Util.RegError: raise MissingRegistryError("%s\\%s was not found in the registry."%(K, valuename)) def get_all_compiler_versions(): """Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first. """ versions=[] if is_windows: if is_win64: keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++' else: keyname = 'Software\\Intel\\Compilers\\C++' try: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, keyname) except WindowsError: return [] i = 0 versions = [] try: while i < 100: subkey = SCons.Util.RegEnumKey(k, i) # raises EnvironmentError # Check that this refers to an existing dir. # This is not 100% perfect but should catch common # installation issues like when the compiler was installed # and then the install directory deleted or moved (rather # than uninstalling properly), so the registry values # are still there. ok = False for try_abi in ('IA32', 'IA32e', 'IA64', 'EM64T'): try: d = get_intel_registry_value('ProductDir', subkey, try_abi) except MissingRegistryError: continue # not found in reg, keep going if os.path.exists(d): ok = True if ok: versions.append(subkey) else: try: # Registry points to nonexistent dir. Ignore this # version. value = get_intel_registry_value('ProductDir', subkey, 'IA32') except MissingRegistryError, e: # Registry key is left dangling (potentially # after uninstalling). print \ "scons: *** Ignoring the registry key for the Intel compiler version %s.\n" \ "scons: *** It seems that the compiler was uninstalled and that the registry\n" \ "scons: *** was not cleaned up properly.\n" % subkey else: print "scons: *** Ignoring "+str(value) i = i + 1 except EnvironmentError: # no more subkeys pass elif is_linux: for d in glob.glob('/opt/intel_cc_*'): # Typical dir here is /opt/intel_cc_80. m = re.search(r'cc_(.*)$', d) if m: versions.append(m.group(1)) for d in glob.glob('/opt/intel/cc*/*'): # Typical dir here is /opt/intel/cc/9.0 for IA32, # /opt/intel/cce/9.0 for EMT64 (AMD64) m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) for d in glob.glob('/opt/intel/Compiler/*'): # Typical dir here is /opt/intel/Compiler/11.1 m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) elif is_mac: for d in glob.glob('/opt/intel/cc*/*'): # Typical dir here is /opt/intel/cc/9.0 for IA32, # /opt/intel/cce/9.0 for EMT64 (AMD64) m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) def keyfunc(str): """Given a dot-separated version string, return a tuple of ints representing it.""" return [int(x) for x in str.split('.')] # split into ints, sort, then remove dups return sorted(uniquify(versions), key=keyfunc, reverse=True) def get_intel_compiler_top(version, abi): """ Return the main path to the top-level dir of the Intel compiler, using the given version. The compiler will be in <top>/bin/icl.exe (icc on linux), the include dir is <top>/include, etc. """ if is_windows: if not SCons.Util.can_read_reg: raise NoRegistryModuleError("No Windows registry module was found") top = get_intel_registry_value('ProductDir', version, abi) # pre-11, icl was in Bin. 11 and later, it's in Bin/<abi> apparently. if not os.path.exists(os.path.join(top, "Bin", "icl.exe")) \ and not os.path.exists(os.path.join(top, "Bin", abi, "icl.exe")): raise MissingDirError("Can't find Intel compiler in %s"%(top)) elif is_mac or is_linux: def find_in_2008style_dir(version): # first dir is new (>=9.0) style, second is old (8.0) style. dirs=('/opt/intel/cc/%s', '/opt/intel_cc_%s') if abi == 'x86_64': dirs=('/opt/intel/cce/%s',) # 'e' stands for 'em64t', aka x86_64 aka amd64 top=None for d in dirs: if os.path.exists(os.path.join(d%version, "bin", "icc")): top = d%version break return top def find_in_2010style_dir(version): dirs=('/opt/intel/Compiler/%s/*'%version) # typically /opt/intel/Compiler/11.1/064 (then bin/intel64/icc) dirs=glob.glob(dirs) # find highest sub-version number by reverse sorting and picking first existing one. dirs.sort() dirs.reverse() top=None for d in dirs: if (os.path.exists(os.path.join(d, "bin", "ia32", "icc")) or os.path.exists(os.path.join(d, "bin", "intel64", "icc"))): top = d break return top top = find_in_2010style_dir(version) or find_in_2008style_dir(version) print "INTELC: top=",top if not top: raise MissingDirError("Can't find version %s Intel compiler in %s (abi='%s')"%(version,top, abi)) return top def generate(env, version=None, abi=None, topdir=None, verbose=0): """Add Builders and construction variables for Intel C/C++ compiler to an Environment. args: version: (string) compiler version to use, like "80" abi: (string) 'win32' or whatever Itanium version wants topdir: (string) compiler top dir, like "c:\Program Files\Intel\Compiler70" If topdir is used, version and abi are ignored. verbose: (int) if >0, prints compiler version used. """ if not (is_mac or is_linux or is_windows): # can't handle this platform return if is_windows: SCons.Tool.msvc.generate(env) elif is_linux: SCons.Tool.gcc.generate(env) elif is_mac: SCons.Tool.gcc.generate(env) # if version is unspecified, use latest vlist = get_all_compiler_versions() if not version: if vlist: version = vlist[0] else: # User may have specified '90' but we need to get actual dirname '9.0'. # get_version_from_list does that mapping. v = get_version_from_list(version, vlist) if not v: raise SCons.Errors.UserError("Invalid Intel compiler version %s: "%version + \ "installed versions are %s"%(', '.join(vlist))) version = v # if abi is unspecified, use ia32 # alternatives are ia64 for Itanium, or amd64 or em64t or x86_64 (all synonyms here) abi = check_abi(abi) if abi is None: if is_mac or is_linux: # Check if we are on 64-bit linux, default to 64 then. uname_m = os.uname()[4] if uname_m == 'x86_64': abi = 'x86_64' else: abi = 'ia32' else: if is_win64: abi = 'em64t' else: abi = 'ia32' if version and not topdir: try: topdir = get_intel_compiler_top(version, abi) except (SCons.Util.RegError, IntelCError): topdir = None if not topdir: # Normally this is an error, but it might not be if the compiler is # on $PATH and the user is importing their env. class ICLTopDirWarning(SCons.Warnings.Warning): pass if (is_mac or is_linux) and not env.Detect('icc') or \ is_windows and not env.Detect('icl'): SCons.Warnings.enableWarningClass(ICLTopDirWarning) SCons.Warnings.warn(ICLTopDirWarning, "Failed to find Intel compiler for version='%s', abi='%s'"% (str(version), str(abi))) else: # should be cleaned up to say what this other version is # since in this case we have some other Intel compiler installed SCons.Warnings.enableWarningClass(ICLTopDirWarning) SCons.Warnings.warn(ICLTopDirWarning, "Can't find Intel compiler top dir for version='%s', abi='%s'"% (str(version), str(abi))) if topdir: archdir={'x86_64': 'intel64', 'amd64' : 'intel64', 'em64t' : 'intel64', 'x86' : 'ia32', 'i386' : 'ia32', 'ia32' : 'ia32' }[abi] # for v11 and greater if os.path.exists(os.path.join(topdir, 'bin', archdir)): bindir="bin/%s"%archdir libdir="lib/%s"%archdir else: bindir="bin" libdir="lib" if verbose: print "Intel C compiler: using version %s (%g), abi %s, in '%s/%s'"%\ (repr(version), linux_ver_normalize(version),abi,topdir,bindir) if is_linux: # Show the actual compiler version by running the compiler. os.system('%s/%s/icc --version'%(topdir,bindir)) if is_mac: # Show the actual compiler version by running the compiler. os.system('%s/%s/icc --version'%(topdir,bindir)) env['INTEL_C_COMPILER_TOP'] = topdir if is_linux: paths={'INCLUDE' : 'include', 'LIB' : libdir, 'PATH' : bindir, 'LD_LIBRARY_PATH' : libdir} for p in paths.keys(): env.PrependENVPath(p, os.path.join(topdir, paths[p])) if is_mac: paths={'INCLUDE' : 'include', 'LIB' : libdir, 'PATH' : bindir, 'LD_LIBRARY_PATH' : libdir} for p in paths.keys(): env.PrependENVPath(p, os.path.join(topdir, paths[p])) if is_windows: # env key reg valname default subdir of top paths=(('INCLUDE', 'IncludeDir', 'Include'), ('LIB' , 'LibDir', 'Lib'), ('PATH' , 'BinDir', 'Bin')) # We are supposed to ignore version if topdir is set, so set # it to the emptry string if it's not already set. if version is None: version = '' # Each path has a registry entry, use that or default to subdir for p in paths: try: path=get_intel_registry_value(p[1], version, abi) # These paths may have $(ICInstallDir) # which needs to be substituted with the topdir. path=path.replace('$(ICInstallDir)', topdir + os.sep) except IntelCError: # Couldn't get it from registry: use default subdir of topdir env.PrependENVPath(p[0], os.path.join(topdir, p[2])) else: env.PrependENVPath(p[0], path.split(os.pathsep)) # print "ICL %s: %s, final=%s"%(p[0], path, str(env['ENV'][p[0]])) if is_windows: env['CC'] = 'icl' env['CXX'] = 'icl' env['LINK'] = 'xilink' else: env['CC'] = 'icc' env['CXX'] = 'icpc' # Don't reset LINK here; # use smart_link which should already be here from link.py. #env['LINK'] = '$CC' env['AR'] = 'xiar' env['LD'] = 'xild' # not used by default # This is not the exact (detailed) compiler version, # just the major version as determined above or specified # by the user. It is a float like 80 or 90, in normalized form for Linux # (i.e. even for Linux 9.0 compiler, still returns 90 rather than 9.0) if version: env['INTEL_C_COMPILER_VERSION']=linux_ver_normalize(version) if is_windows: # Look for license file dir # in system environment, registry, and default location. envlicdir = os.environ.get("INTEL_LICENSE_FILE", '') K = ('SOFTWARE\Intel\Licenses') try: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, K) reglicdir = SCons.Util.RegQueryValueEx(k, "w_cpp")[0] except (AttributeError, SCons.Util.RegError): reglicdir = "" defaultlicdir = r'C:\Program Files\Common Files\Intel\Licenses' licdir = None for ld in [envlicdir, reglicdir]: # If the string contains an '@', then assume it's a network # license (port@system) and good by definition. if ld and (ld.find('@') != -1 or os.path.exists(ld)): licdir = ld break if not licdir: licdir = defaultlicdir if not os.path.exists(licdir): class ICLLicenseDirWarning(SCons.Warnings.Warning): pass SCons.Warnings.enableWarningClass(ICLLicenseDirWarning) SCons.Warnings.warn(ICLLicenseDirWarning, "Intel license dir was not found." " Tried using the INTEL_LICENSE_FILE environment variable (%s), the registry (%s) and the default path (%s)." " Using the default path as a last resort." % (envlicdir, reglicdir, defaultlicdir)) env['ENV']['INTEL_LICENSE_FILE'] = licdir def exists(env): if not (is_mac or is_linux or is_windows): # can't handle this platform return 0 try: versions = get_all_compiler_versions() except (SCons.Util.RegError, IntelCError): versions = None detected = versions is not None and len(versions) > 0 if not detected: # try env.Detect, maybe that will work if is_windows: return env.Detect('icl') elif is_linux: return env.Detect('icc') elif is_mac: return env.Detect('icc') return detected # end of file # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.fortran Tool-specific initialization for a generic Posix f77/f90 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/fortran.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import re import SCons.Action import SCons.Defaults import SCons.Scanner.Fortran import SCons.Tool import SCons.Util from SCons.Tool.FortranCommon import add_all_to_env, add_fortran_to_env compilers = ['f95', 'f90', 'f77'] def generate(env): add_all_to_env(env) add_fortran_to_env(env) fc = env.Detect(compilers) or 'f77' env['SHFORTRAN'] = fc env['FORTRAN'] = fc 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.pdftex Tool-specific initialization for pdftex. Generates .pdf 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/pdftex.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import SCons.Action import SCons.Util import SCons.Tool.tex PDFTeXAction = None # This action might be needed more than once if we are dealing with # labels and bibtex. PDFLaTeXAction = None def PDFLaTeXAuxAction(target = None, source= None, env=None): result = SCons.Tool.tex.InternalLaTeXAuxAction( PDFLaTeXAction, target, source, env ) return result def PDFTeXLaTeXFunction(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.""" basedir = os.path.split(str(source[0]))[0] abspath = os.path.abspath(basedir) if SCons.Tool.tex.is_LaTeX(source,env,abspath): result = PDFLaTeXAuxAction(target,source,env) if result != 0: SCons.Tool.tex.check_file_error_message(env['PDFLATEX']) else: result = PDFTeXAction(target,source,env) if result != 0: SCons.Tool.tex.check_file_error_message(env['PDFTEX']) return result PDFTeXLaTeXAction = None def generate(env): """Add Builders and construction variables for pdftex to an Environment.""" global PDFTeXAction if PDFTeXAction is None: PDFTeXAction = SCons.Action.Action('$PDFTEXCOM', '$PDFTEXCOMSTR') global PDFLaTeXAction if PDFLaTeXAction is None: PDFLaTeXAction = SCons.Action.Action("$PDFLATEXCOM", "$PDFLATEXCOMSTR") global PDFTeXLaTeXAction if PDFTeXLaTeXAction is None: PDFTeXLaTeXAction = SCons.Action.Action(PDFTeXLaTeXFunction, strfunction=SCons.Tool.tex.TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.tex', PDFTeXLaTeXAction) bld.add_emitter('.tex', SCons.Tool.tex.tex_pdf_emitter) # Add the epstopdf builder after the pdftex builder # so pdftex is the default for no source suffix pdf.generate2(env) SCons.Tool.tex.generate_common(env) def exists(env): SCons.Tool.tex.generate_darwin(env) return env.Detect('pdftex') # 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.as Tool-specific initialization for as, the generic Posix assembler. 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/as.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util assemblers = ['as'] ASSuffixes = ['.s', '.asm', '.ASM'] ASPPSuffixes = ['.spp', '.SPP', '.sx'] if SCons.Util.case_sensitive_suffixes('.s', '.S'): ASPPSuffixes.extend(['.S']) else: ASSuffixes.extend(['.S']) def generate(env): """Add Builders and construction variables for as to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) shared_obj.add_action(suffix, SCons.Defaults.ASAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) for suffix in ASPPSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASPPAction) shared_obj.add_action(suffix, SCons.Defaults.ASPPAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) env['AS'] = env.Detect(assemblers) or 'as' env['ASFLAGS'] = SCons.Util.CLVar('') env['ASCOM'] = '$AS $ASFLAGS -o $TARGET $SOURCES' env['ASPPFLAGS'] = '$ASFLAGS' env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES' def exists(env): return env.Detect(assemblers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging.ipk """ # # 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/packaging/ipk.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Builder import SCons.Node.FS import os from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION, SUMMARY, X_IPK_PRIORITY, X_IPK_SECTION, SOURCE_URL, X_IPK_MAINTAINER, X_IPK_DEPENDS, **kw): """ this function prepares the packageroot directory for packaging with the ipkg builder. """ SCons.Tool.Tool('ipkg').generate(env) # setup the Ipkg builder bld = env['BUILDERS']['Ipkg'] target, source = stripinstallbuilder(target, source, env) target, source = putintopackageroot(target, source, env, PACKAGEROOT) # This should be overridable from the construction environment, # which it is by using ARCHITECTURE=. # Guessing based on what os.uname() returns at least allows it # to work for both i386 and x86_64 Linux systems. archmap = { 'i686' : 'i386', 'i586' : 'i386', 'i486' : 'i386', } buildarchitecture = os.uname()[4] buildarchitecture = archmap.get(buildarchitecture, buildarchitecture) if 'ARCHITECTURE' in kw: buildarchitecture = kw['ARCHITECTURE'] # setup the kw to contain the mandatory arguments to this fucntion. # do this before calling any builder or setup function loc=locals() del loc['kw'] kw.update(loc) del kw['source'], kw['target'], kw['env'] # generate the specfile specfile = gen_ipk_dir(PACKAGEROOT, source, env, kw) # override the default target. if str(target[0])=="%s-%s"%(NAME, VERSION): target=[ "%s_%s_%s.ipk"%(NAME, VERSION, buildarchitecture) ] # now apply the Ipkg builder return bld(env, target, specfile, **kw) def gen_ipk_dir(proot, source, env, kw): # make sure the packageroot is a Dir object. if SCons.Util.is_String(proot): proot=env.Dir(proot) # create the specfile builder s_bld=SCons.Builder.Builder( action = build_specfiles, ) # create the specfile targets spec_target=[] control=proot.Dir('CONTROL') spec_target.append(control.File('control')) spec_target.append(control.File('conffiles')) spec_target.append(control.File('postrm')) spec_target.append(control.File('prerm')) spec_target.append(control.File('postinst')) spec_target.append(control.File('preinst')) # apply the builder to the specfile targets s_bld(env, spec_target, source, **kw) # the packageroot directory does now contain the specfiles. return proot def build_specfiles(source, target, env): """ filter the targets for the needed files and use the variables in env to create the specfile. """ # # At first we care for the CONTROL/control file, which is the main file for ipk. # # For this we need to open multiple files in random order, so we store into # a dict so they can be easily accessed. # # opened_files={} def open_file(needle, haystack): try: return opened_files[needle] except KeyError: file=filter(lambda x: x.get_path().rfind(needle)!=-1, haystack)[0] opened_files[needle]=open(file.abspath, 'w') return opened_files[needle] control_file=open_file('control', target) if 'X_IPK_DESCRIPTION' not in env: env['X_IPK_DESCRIPTION']="%s\n %s"%(env['SUMMARY'], env['DESCRIPTION'].replace('\n', '\n ')) content = """ Package: $NAME Version: $VERSION Priority: $X_IPK_PRIORITY Section: $X_IPK_SECTION Source: $SOURCE_URL Architecture: $ARCHITECTURE Maintainer: $X_IPK_MAINTAINER Depends: $X_IPK_DEPENDS Description: $X_IPK_DESCRIPTION """ control_file.write(env.subst(content)) # # now handle the various other files, which purpose it is to set post-, # pre-scripts and mark files as config files. # # We do so by filtering the source files for files which are marked with # the "config" tag and afterwards we do the same for x_ipk_postrm, # x_ipk_prerm, x_ipk_postinst and x_ipk_preinst tags. # # The first one will write the name of the file into the file # CONTROL/configfiles, the latter add the content of the x_ipk_* variable # into the same named file. # for f in [x for x in source if 'PACKAGING_CONFIG' in dir(x)]: config=open_file('conffiles') config.write(f.PACKAGING_INSTALL_LOCATION) config.write('\n') for str in 'POSTRM PRERM POSTINST PREINST'.split(): name="PACKAGING_X_IPK_%s"%str for f in [x for x in source if name in dir(x)]: file=open_file(name) file.write(env[str]) # # close all opened files for f in opened_files.values(): f.close() # call a user specified function if 'CHANGE_SPECFILE' in env: content += env['CHANGE_SPECFILE'](target) return 0 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging.targz The targz SRC packager. """ # # 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/packaging/src_targz.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Tool.packaging import putintopackageroot def package(env, target, source, PACKAGEROOT, **kw): bld = env['BUILDERS']['Tar'] bld.set_suffix('.tar.gz') target, source = putintopackageroot(target, source, env, PACKAGEROOT, honor_install_location=0) return bld(env, target, source, TARFLAGS='-zc') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging.targz The targz SRC packager. """ # # 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/packaging/targz.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot def package(env, target, source, PACKAGEROOT, **kw): bld = env['BUILDERS']['Tar'] bld.set_suffix('.tar.gz') target, source = stripinstallbuilder(target, source, env) target, source = putintopackageroot(target, source, env, PACKAGEROOT) return bld(env, target, source, TARFLAGS='-zc') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging.zip The zip SRC packager. """ # # 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/packaging/src_zip.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Tool.packaging import putintopackageroot def package(env, target, source, PACKAGEROOT, **kw): bld = env['BUILDERS']['Zip'] bld.set_suffix('.zip') target, source = putintopackageroot(target, source, env, PACKAGEROOT, honor_install_location=0) return bld(env, target, source) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging.rpm The rpm packager. """ # # 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/packaging/rpm.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import SCons.Builder from SCons.Environment import OverrideEnvironment from SCons.Tool.packaging import stripinstallbuilder, src_targz from SCons.Errors import UserError def package(env, target, source, PACKAGEROOT, NAME, VERSION, PACKAGEVERSION, DESCRIPTION, SUMMARY, X_RPM_GROUP, LICENSE, **kw): # initialize the rpm tool SCons.Tool.Tool('rpm').generate(env) bld = env['BUILDERS']['Rpm'] # Generate a UserError whenever the target name has been set explicitly, # since rpm does not allow for controlling it. This is detected by # checking if the target has been set to the default by the Package() # Environment function. if str(target[0])!="%s-%s"%(NAME, VERSION): raise UserError( "Setting target is not supported for rpm." ) else: # This should be overridable from the construction environment, # which it is by using ARCHITECTURE=. # Guessing based on what os.uname() returns at least allows it # to work for both i386 and x86_64 Linux systems. archmap = { 'i686' : 'i386', 'i586' : 'i386', 'i486' : 'i386', } buildarchitecture = os.uname()[4] buildarchitecture = archmap.get(buildarchitecture, buildarchitecture) if 'ARCHITECTURE' in kw: buildarchitecture = kw['ARCHITECTURE'] fmt = '%s-%s-%s.%s.rpm' srcrpm = fmt % (NAME, VERSION, PACKAGEVERSION, 'src') binrpm = fmt % (NAME, VERSION, PACKAGEVERSION, buildarchitecture) target = [ srcrpm, binrpm ] # get the correct arguments into the kw hash loc=locals() del loc['kw'] kw.update(loc) del kw['source'], kw['target'], kw['env'] # if no "SOURCE_URL" tag is given add a default one. if 'SOURCE_URL' not in kw: #kw['SOURCE_URL']=(str(target[0])+".tar.gz").replace('.rpm', '') kw['SOURCE_URL']=(str(target[0])+".tar.gz").replace('.rpm', '') # mangle the source and target list for the rpmbuild env = OverrideEnvironment(env, kw) target, source = stripinstallbuilder(target, source, env) target, source = addspecfile(target, source, env) target, source = collectintargz(target, source, env) # now call the rpm builder to actually build the packet. return bld(env, target, source, **kw) def collectintargz(target, source, env): """ Puts all source files into a tar.gz file. """ # the rpm tool depends on a source package, until this is chagned # this hack needs to be here that tries to pack all sources in. sources = env.FindSourceFiles() # filter out the target we are building the source list for. #sources = [s for s in sources if not (s in target)] sources = [s for s in sources if s not in target] # find the .spec file for rpm and add it since it is not necessarily found # by the FindSourceFiles function. #sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] ) spec_file = lambda s: str(s).rfind('.spec') != -1 sources.extend( list(filter(spec_file, source)) ) # as the source contains the url of the source package this rpm package # is built from, we extract the target name #tarball = (str(target[0])+".tar.gz").replace('.rpm', '') tarball = (str(target[0])+".tar.gz").replace('.rpm', '') try: #tarball = env['SOURCE_URL'].split('/')[-1] tarball = env['SOURCE_URL'].split('/')[-1] except KeyError, e: raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] ) tarball = src_targz.package(env, source=sources, target=tarball, PACKAGEROOT=env['PACKAGEROOT'], ) return (target, tarball) def addspecfile(target, source, env): specfile = "%s-%s" % (env['NAME'], env['VERSION']) bld = SCons.Builder.Builder(action = build_specfile, suffix = '.spec', target_factory = SCons.Node.FS.File) source.extend(bld(env, specfile, source)) return (target,source) def build_specfile(target, source, env): """ Builds a RPM specfile from a dictionary with string metadata and by analyzing a tree of nodes. """ file = open(target[0].abspath, 'w') str = "" try: file.write( build_specfile_header(env) ) file.write( build_specfile_sections(env) ) file.write( build_specfile_filesection(env, source) ) file.close() # call a user specified function if 'CHANGE_SPECFILE' in env: env['CHANGE_SPECFILE'](target, source) except KeyError, e: raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] ) # # mandatory and optional package tag section # def build_specfile_sections(spec): """ Builds the sections of a rpm specfile. """ str = "" mandatory_sections = { 'DESCRIPTION' : '\n%%description\n%s\n\n', } str = str + SimpleTagCompiler(mandatory_sections).compile( spec ) optional_sections = { 'DESCRIPTION_' : '%%description -l %s\n%s\n\n', 'CHANGELOG' : '%%changelog\n%s\n\n', 'X_RPM_PREINSTALL' : '%%pre\n%s\n\n', 'X_RPM_POSTINSTALL' : '%%post\n%s\n\n', 'X_RPM_PREUNINSTALL' : '%%preun\n%s\n\n', 'X_RPM_POSTUNINSTALL' : '%%postun\n%s\n\n', 'X_RPM_VERIFY' : '%%verify\n%s\n\n', # These are for internal use but could possibly be overriden 'X_RPM_PREP' : '%%prep\n%s\n\n', 'X_RPM_BUILD' : '%%build\n%s\n\n', 'X_RPM_INSTALL' : '%%install\n%s\n\n', 'X_RPM_CLEAN' : '%%clean\n%s\n\n', } # Default prep, build, install and clean rules # TODO: optimize those build steps, to not compile the project a second time if 'X_RPM_PREP' not in spec: spec['X_RPM_PREP'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' + '\n%setup -q' if 'X_RPM_BUILD' not in spec: spec['X_RPM_BUILD'] = 'mkdir "$RPM_BUILD_ROOT"' if 'X_RPM_INSTALL' not in spec: spec['X_RPM_INSTALL'] = 'scons --install-sandbox="$RPM_BUILD_ROOT" "$RPM_BUILD_ROOT"' if 'X_RPM_CLEAN' not in spec: spec['X_RPM_CLEAN'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' str = str + SimpleTagCompiler(optional_sections, mandatory=0).compile( spec ) return str def build_specfile_header(spec): """ Builds all section but the %file of a rpm specfile """ str = "" # first the mandatory sections mandatory_header_fields = { 'NAME' : '%%define name %s\nName: %%{name}\n', 'VERSION' : '%%define version %s\nVersion: %%{version}\n', 'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n', 'X_RPM_GROUP' : 'Group: %s\n', 'SUMMARY' : 'Summary: %s\n', 'LICENSE' : 'License: %s\n', } str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec ) # now the optional tags optional_header_fields = { 'VENDOR' : 'Vendor: %s\n', 'X_RPM_URL' : 'Url: %s\n', 'SOURCE_URL' : 'Source: %s\n', 'SUMMARY_' : 'Summary(%s): %s\n', 'X_RPM_DISTRIBUTION' : 'Distribution: %s\n', 'X_RPM_ICON' : 'Icon: %s\n', 'X_RPM_PACKAGER' : 'Packager: %s\n', 'X_RPM_GROUP_' : 'Group(%s): %s\n', 'X_RPM_REQUIRES' : 'Requires: %s\n', 'X_RPM_PROVIDES' : 'Provides: %s\n', 'X_RPM_CONFLICTS' : 'Conflicts: %s\n', 'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n', 'X_RPM_SERIAL' : 'Serial: %s\n', 'X_RPM_EPOCH' : 'Epoch: %s\n', 'X_RPM_AUTOREQPROV' : 'AutoReqProv: %s\n', 'X_RPM_EXCLUDEARCH' : 'ExcludeArch: %s\n', 'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n', 'X_RPM_PREFIX' : 'Prefix: %s\n', 'X_RPM_CONFLICTS' : 'Conflicts: %s\n', # internal use 'X_RPM_BUILDROOT' : 'BuildRoot: %s\n', } # fill in default values: # Adding a BuildRequires renders the .rpm unbuildable under System, which # are not managed by rpm, since the database to resolve this dependency is # missing (take Gentoo as an example) # if not s.has_key('x_rpm_BuildRequires'): # s['x_rpm_BuildRequires'] = 'scons' if 'X_RPM_BUILDROOT' not in spec: spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}' str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec ) return str # # mandatory and optional file tags # def build_specfile_filesection(spec, files): """ builds the %file section of the specfile """ str = '%files\n' if 'X_RPM_DEFATTR' not in spec: spec['X_RPM_DEFATTR'] = '(-,root,root)' str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR'] supported_tags = { 'PACKAGING_CONFIG' : '%%config %s', 'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s', 'PACKAGING_DOC' : '%%doc %s', 'PACKAGING_UNIX_ATTR' : '%%attr %s', 'PACKAGING_LANG_' : '%%lang(%s) %s', 'PACKAGING_X_RPM_VERIFY' : '%%verify %s', 'PACKAGING_X_RPM_DIR' : '%%dir %s', 'PACKAGING_X_RPM_DOCDIR' : '%%docdir %s', 'PACKAGING_X_RPM_GHOST' : '%%ghost %s', } for file in files: # build the tagset tags = {} for k in supported_tags.keys(): try: tags[k]=getattr(file, k) except AttributeError: pass # compile the tagset str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags ) str = str + ' ' str = str + file.PACKAGING_INSTALL_LOCATION str = str + '\n\n' return str class SimpleTagCompiler(object): """ This class is a simple string substition utility: the replacement specfication is stored in the tagset dictionary, something like: { "abc" : "cdef %s ", "abc_" : "cdef %s %s" } the compile function gets a value dictionary, which may look like: { "abc" : "ghij", "abc_gh" : "ij" } The resulting string will be: "cdef ghij cdef gh ij" """ def __init__(self, tagset, mandatory=1): self.tagset = tagset self.mandatory = mandatory def compile(self, values): """ compiles the tagset and returns a str containing the result """ def is_international(tag): #return tag.endswith('_') return tag[-1:] == '_' def get_country_code(tag): return tag[-2:] def strip_country_code(tag): return tag[:-2] replacements = list(self.tagset.items()) str = "" #domestic = [ (k,v) for k,v in replacements if not is_international(k) ] domestic = [t for t in replacements if not is_international(t[0])] for key, replacement in domestic: try: str = str + replacement % values[key] except KeyError, e: if self.mandatory: raise e #international = [ (k,v) for k,v in replacements if is_international(k) ] international = [t for t in replacements if is_international(t[0])] for key, replacement in international: try: #int_values_for_key = [ (get_country_code(k),v) for k,v in values.items() if strip_country_code(k) == key ] x = [t for t in values.items() if strip_country_code(t[0]) == key] int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x] for v in int_values_for_key: str = str + replacement % v except KeyError, e: if self.mandatory: raise e return str # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.packaging.msi The msi packager. """ # # 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/packaging/msi.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import SCons from SCons.Action import Action from SCons.Builder import Builder from xml.dom.minidom import * from xml.sax.saxutils import escape from SCons.Tool.packaging import stripinstallbuilder # # Utility functions # def convert_to_id(s, id_set): """ Some parts of .wxs need an Id attribute (for example: The File and Directory directives. The charset is limited to A-Z, a-z, digits, underscores, periods. Each Id must begin with a letter or with a underscore. Google for "CNDL0015" for information about this. Requirements: * the string created must only contain chars from the target charset. * the string created must have a minimal editing distance from the original string. * the string created must be unique for the whole .wxs file. Observation: * There are 62 chars in the charset. Idea: * filter out forbidden characters. Check for a collision with the help of the id_set. Add the number of the number of the collision at the end of the created string. Furthermore care for a correct start of the string. """ charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.' if s[0] in '0123456789.': s += '_'+s id = [c for c in s if c in charset] # did we already generate an id for this file? try: return id_set[id][s] except KeyError: # no we did not so initialize with the id if id not in id_set: id_set[id] = { s : id } # there is a collision, generate an id which is unique by appending # the collision number else: id_set[id][s] = id + str(len(id_set[id])) return id_set[id][s] def is_dos_short_file_name(file): """ examine if the given file is in the 8.3 form. """ fname, ext = os.path.splitext(file) proper_ext = len(ext) == 0 or (2 <= len(ext) <= 4) # the ext contains the dot proper_fname = file.isupper() and len(fname) <= 8 return proper_ext and proper_fname def gen_dos_short_file_name(file, filename_set): """ see http://support.microsoft.com/default.aspx?scid=kb;en-us;Q142982 These are no complete 8.3 dos short names. The ~ char is missing and replaced with one character from the filename. WiX warns about such filenames, since a collision might occur. Google for "CNDL1014" for more information. """ # guard this to not confuse the generation if is_dos_short_file_name(file): return file fname, ext = os.path.splitext(file) # ext contains the dot # first try if it suffices to convert to upper file = file.upper() if is_dos_short_file_name(file): return file # strip forbidden characters. forbidden = '."/[]:;=, ' fname = [c for c in fname if c not in forbidden] # check if we already generated a filename with the same number: # thisis1.txt, thisis2.txt etc. duplicate, num = not None, 1 while duplicate: shortname = "%s%s" % (fname[:8-len(str(num))].upper(),\ str(num)) if len(ext) >= 2: shortname = "%s%s" % (shortname, ext[:4].upper()) duplicate, num = shortname in filename_set, num+1 assert( is_dos_short_file_name(shortname) ), 'shortname is %s, longname is %s' % (shortname, file) filename_set.append(shortname) return shortname def create_feature_dict(files): """ X_MSI_FEATURE and doc FileTag's can be used to collect files in a hierarchy. This function collects the files into this hierarchy. """ dict = {} def add_to_dict( feature, file ): if not SCons.Util.is_List( feature ): feature = [ feature ] for f in feature: if f not in dict: dict[ f ] = [ file ] else: dict[ f ].append( file ) for file in files: if hasattr( file, 'PACKAGING_X_MSI_FEATURE' ): add_to_dict(file.PACKAGING_X_MSI_FEATURE, file) elif hasattr( file, 'PACKAGING_DOC' ): add_to_dict( 'PACKAGING_DOC', file ) else: add_to_dict( 'default', file ) return dict def generate_guids(root): """ generates globally unique identifiers for parts of the xml which need them. Component tags have a special requirement. Their UUID is only allowed to change if the list of their contained resources has changed. This allows for clean removal and proper updates. To handle this requirement, the uuid is generated with an md5 hashing the whole subtree of a xml node. """ from hashlib import md5 # specify which tags need a guid and in which attribute this should be stored. needs_id = { 'Product' : 'Id', 'Package' : 'Id', 'Component' : 'Guid', } # find all XMl nodes matching the key, retrieve their attribute, hash their # subtree, convert hash to string and add as a attribute to the xml node. for (key,value) in needs_id.items(): node_list = root.getElementsByTagName(key) attribute = value for node in node_list: hash = md5(node.toxml()).hexdigest() hash_str = '%s-%s-%s-%s-%s' % ( hash[:8], hash[8:12], hash[12:16], hash[16:20], hash[20:] ) node.attributes[attribute] = hash_str def string_wxsfile(target, source, env): return "building WiX file %s"%( target[0].path ) def build_wxsfile(target, source, env): """ compiles a .wxs file from the keywords given in env['msi_spec'] and by analyzing the tree of source nodes and their tags. """ file = open(target[0].abspath, 'w') try: # Create a document with the Wix root tag doc = Document() root = doc.createElement( 'Wix' ) root.attributes['xmlns']='http://schemas.microsoft.com/wix/2003/01/wi' doc.appendChild( root ) filename_set = [] # this is to circumvent duplicates in the shortnames id_set = {} # this is to circumvent duplicates in the ids # Create the content build_wxsfile_header_section(root, env) build_wxsfile_file_section(root, source, env['NAME'], env['VERSION'], env['VENDOR'], filename_set, id_set) generate_guids(root) build_wxsfile_features_section(root, source, env['NAME'], env['VERSION'], env['SUMMARY'], id_set) build_wxsfile_default_gui(root) build_license_file(target[0].get_dir(), env) # write the xml to a file file.write( doc.toprettyxml() ) # call a user specified function if 'CHANGE_SPECFILE' in env: env['CHANGE_SPECFILE'](target, source) except KeyError, e: raise SCons.Errors.UserError( '"%s" package field for MSI is missing.' % e.args[0] ) # # setup function # def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set): """ Create the wix default target directory layout and return the innermost directory. We assume that the XML tree delivered in the root argument already contains the Product tag. Everything is put under the PFiles directory property defined by WiX. After that a directory with the 'VENDOR' tag is placed and then a directory with the name of the project and its VERSION. This leads to the following TARGET Directory Layout: C:\<PFiles>\<Vendor>\<Projectname-Version>\ Example: C:\Programme\Company\Product-1.2\ """ doc = Document() d1 = doc.createElement( 'Directory' ) d1.attributes['Id'] = 'TARGETDIR' d1.attributes['Name'] = 'SourceDir' d2 = doc.createElement( 'Directory' ) d2.attributes['Id'] = 'ProgramFilesFolder' d2.attributes['Name'] = 'PFiles' d3 = doc.createElement( 'Directory' ) d3.attributes['Id'] = 'VENDOR_folder' d3.attributes['Name'] = escape( gen_dos_short_file_name( VENDOR, filename_set ) ) d3.attributes['LongName'] = escape( VENDOR ) d4 = doc.createElement( 'Directory' ) project_folder = "%s-%s" % ( NAME, VERSION ) d4.attributes['Id'] = 'MY_DEFAULT_FOLDER' d4.attributes['Name'] = escape( gen_dos_short_file_name( project_folder, filename_set ) ) d4.attributes['LongName'] = escape( project_folder ) d1.childNodes.append( d2 ) d2.childNodes.append( d3 ) d3.childNodes.append( d4 ) root.getElementsByTagName('Product')[0].childNodes.append( d1 ) return d4 # # mandatory and optional file tags # def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set): """ builds the Component sections of the wxs file with their included files. Files need to be specified in 8.3 format and in the long name format, long filenames will be converted automatically. Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag. """ root = create_default_directory_layout( root, NAME, VERSION, VENDOR, filename_set ) components = create_feature_dict( files ) factory = Document() def get_directory( node, dir ): """ returns the node under the given node representing the directory. Returns the component node if dir is None or empty. """ if dir == '' or not dir: return node Directory = node dir_parts = dir.split(os.path.sep) # to make sure that our directory ids are unique, the parent folders are # consecutively added to upper_dir upper_dir = '' # walk down the xml tree finding parts of the directory dir_parts = [d for d in dir_parts if d != ''] for d in dir_parts[:]: already_created = [c for c in Directory.childNodes if c.nodeName == 'Directory' and c.attributes['LongName'].value == escape(d)] if already_created != []: Directory = already_created[0] dir_parts.remove(d) upper_dir += d else: break for d in dir_parts: nDirectory = factory.createElement( 'Directory' ) nDirectory.attributes['LongName'] = escape( d ) nDirectory.attributes['Name'] = escape( gen_dos_short_file_name( d, filename_set ) ) upper_dir += d nDirectory.attributes['Id'] = convert_to_id( upper_dir, id_set ) Directory.childNodes.append( nDirectory ) Directory = nDirectory return Directory for file in files: drive, path = os.path.splitdrive( file.PACKAGING_INSTALL_LOCATION ) filename = os.path.basename( path ) dirname = os.path.dirname( path ) h = { # tagname : default value 'PACKAGING_X_MSI_VITAL' : 'yes', 'PACKAGING_X_MSI_FILEID' : convert_to_id(filename, id_set), 'PACKAGING_X_MSI_LONGNAME' : filename, 'PACKAGING_X_MSI_SHORTNAME' : gen_dos_short_file_name(filename, filename_set), 'PACKAGING_X_MSI_SOURCE' : file.get_path(), } # fill in the default tags given above. for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]: setattr( file, k, v ) File = factory.createElement( 'File' ) File.attributes['LongName'] = escape( file.PACKAGING_X_MSI_LONGNAME ) File.attributes['Name'] = escape( file.PACKAGING_X_MSI_SHORTNAME ) File.attributes['Source'] = escape( file.PACKAGING_X_MSI_SOURCE ) File.attributes['Id'] = escape( file.PACKAGING_X_MSI_FILEID ) File.attributes['Vital'] = escape( file.PACKAGING_X_MSI_VITAL ) # create the <Component> Tag under which this file should appear Component = factory.createElement('Component') Component.attributes['DiskId'] = '1' Component.attributes['Id'] = convert_to_id( filename, id_set ) # hang the component node under the root node and the file node # under the component node. Directory = get_directory( root, dirname ) Directory.childNodes.append( Component ) Component.childNodes.append( File ) # # additional functions # def build_wxsfile_features_section(root, files, NAME, VERSION, SUMMARY, id_set): """ This function creates the <features> tag based on the supplied xml tree. This is achieved by finding all <component>s and adding them to a default target. It should be called after the tree has been built completly. We assume that a MY_DEFAULT_FOLDER Property is defined in the wxs file tree. Furthermore a top-level with the name and VERSION of the software will be created. An PACKAGING_X_MSI_FEATURE can either be a string, where the feature DESCRIPTION will be the same as its title or a Tuple, where the first part will be its title and the second its DESCRIPTION. """ factory = Document() Feature = factory.createElement('Feature') Feature.attributes['Id'] = 'complete' Feature.attributes['ConfigurableDirectory'] = 'MY_DEFAULT_FOLDER' Feature.attributes['Level'] = '1' Feature.attributes['Title'] = escape( '%s %s' % (NAME, VERSION) ) Feature.attributes['Description'] = escape( SUMMARY ) Feature.attributes['Display'] = 'expand' for (feature, files) in create_feature_dict(files).items(): SubFeature = factory.createElement('Feature') SubFeature.attributes['Level'] = '1' if SCons.Util.is_Tuple(feature): SubFeature.attributes['Id'] = convert_to_id( feature[0], id_set ) SubFeature.attributes['Title'] = escape(feature[0]) SubFeature.attributes['Description'] = escape(feature[1]) else: SubFeature.attributes['Id'] = convert_to_id( feature, id_set ) if feature=='default': SubFeature.attributes['Description'] = 'Main Part' SubFeature.attributes['Title'] = 'Main Part' elif feature=='PACKAGING_DOC': SubFeature.attributes['Description'] = 'Documentation' SubFeature.attributes['Title'] = 'Documentation' else: SubFeature.attributes['Description'] = escape(feature) SubFeature.attributes['Title'] = escape(feature) # build the componentrefs. As one of the design decision is that every # file is also a component we walk the list of files and create a # reference. for f in files: ComponentRef = factory.createElement('ComponentRef') ComponentRef.attributes['Id'] = convert_to_id( os.path.basename(f.get_path()), id_set ) SubFeature.childNodes.append(ComponentRef) Feature.childNodes.append(SubFeature) root.getElementsByTagName('Product')[0].childNodes.append(Feature) def build_wxsfile_default_gui(root): """ this function adds a default GUI to the wxs file """ factory = Document() Product = root.getElementsByTagName('Product')[0] UIRef = factory.createElement('UIRef') UIRef.attributes['Id'] = 'WixUI_Mondo' Product.childNodes.append(UIRef) UIRef = factory.createElement('UIRef') UIRef.attributes['Id'] = 'WixUI_ErrorProgressText' Product.childNodes.append(UIRef) def build_license_file(directory, spec): """ creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT" in the given directory """ name, text = '', '' try: name = spec['LICENSE'] text = spec['X_MSI_LICENSE_TEXT'] except KeyError: pass # ignore this as X_MSI_LICENSE_TEXT is optional if name!='' or text!='': file = open( os.path.join(directory.get_path(), 'License.rtf'), 'w' ) file.write('{\\rtf') if text!='': file.write(text.replace('\n', '\\par ')) else: file.write(name+'\\par\\par') file.write('}') file.close() # # mandatory and optional package tags # def build_wxsfile_header_section(root, spec): """ Adds the xml file node which define the package meta-data. """ # Create the needed DOM nodes and add them at the correct position in the tree. factory = Document() Product = factory.createElement( 'Product' ) Package = factory.createElement( 'Package' ) root.childNodes.append( Product ) Product.childNodes.append( Package ) # set "mandatory" default values if 'X_MSI_LANGUAGE' not in spec: spec['X_MSI_LANGUAGE'] = '1033' # select english # mandatory sections, will throw a KeyError if the tag is not available Product.attributes['Name'] = escape( spec['NAME'] ) Product.attributes['Version'] = escape( spec['VERSION'] ) Product.attributes['Manufacturer'] = escape( spec['VENDOR'] ) Product.attributes['Language'] = escape( spec['X_MSI_LANGUAGE'] ) Package.attributes['Description'] = escape( spec['SUMMARY'] ) # now the optional tags, for which we avoid the KeyErrror exception if 'DESCRIPTION' in spec: Package.attributes['Comments'] = escape( spec['DESCRIPTION'] ) if 'X_MSI_UPGRADE_CODE' in spec: Package.attributes['X_MSI_UPGRADE_CODE'] = escape( spec['X_MSI_UPGRADE_CODE'] ) # We hardcode the media tag as our current model cannot handle it. Media = factory.createElement('Media') Media.attributes['Id'] = '1' Media.attributes['Cabinet'] = 'default.cab' Media.attributes['EmbedCab'] = 'yes' root.getElementsByTagName('Product')[0].childNodes.append(Media) # this builder is the entry-point for .wxs file compiler. wxs_builder = Builder( action = Action( build_wxsfile, string_wxsfile ), ensure_suffix = '.wxs' ) def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION, SUMMARY, VENDOR, X_MSI_LANGUAGE, **kw): # make sure that the Wix Builder is in the environment SCons.Tool.Tool('wix').generate(env) # get put the keywords for the specfile compiler. These are the arguments # given to the package function and all optional ones stored in kw, minus # the the source, target and env one. loc = locals() del loc['kw'] kw.update(loc) del kw['source'], kw['target'], kw['env'] # strip the install builder from the source files target, source = stripinstallbuilder(target, source, env) # put the arguments into the env and call the specfile builder. env['msi_spec'] = kw specfile = wxs_builder(* [env, target, source], **kw) # now call the WiX Tool with the built specfile added as a source. msifile = env.WiX(target, specfile) # return the target and source tuple. return (msifile, source+[specfile]) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging.zip The zip SRC packager. """ # # 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/packaging/zip.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot def package(env, target, source, PACKAGEROOT, **kw): bld = env['BUILDERS']['Zip'] bld.set_suffix('.zip') target, source = stripinstallbuilder(target, source, env) target, source = putintopackageroot(target, source, env, PACKAGEROOT) return bld(env, target, source) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging SCons Packaging Tool. """ # # 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/packaging/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Environment from SCons.Variables import * from SCons.Errors import * from SCons.Util import is_List, make_path_relative from SCons.Warnings import warn, Warning import os, imp import SCons.Defaults __all__ = [ 'src_targz', 'src_tarbz2', 'src_zip', 'tarbz2', 'targz', 'zip', 'rpm', 'msi', 'ipk' ] # # Utility and Builder function # def Tag(env, target, source, *more_tags, **kw_tags): """ Tag a file with the given arguments, just sets the accordingly named attribute on the file object. TODO: FIXME """ if not target: target=source first_tag=None else: first_tag=source if first_tag: kw_tags[first_tag[0]] = '' if len(kw_tags) == 0 and len(more_tags) == 0: raise UserError("No tags given.") # XXX: sanity checks for x in more_tags: kw_tags[x] = '' if not SCons.Util.is_List(target): target=[target] else: # hmm, sometimes the target list, is a list of a list # make sure it is flattened prior to processing. # TODO: perhaps some bug ?!? target=env.Flatten(target) for t in target: for (k,v) in kw_tags.items(): # all file tags have to start with PACKAGING_, so we can later # differentiate between "normal" object attributes and the # packaging attributes. As the user should not be bothered with # that, the prefix will be added here if missing. #if not k.startswith('PACKAGING_'): if k[:10] != 'PACKAGING_': k='PACKAGING_'+k setattr(t, k, v) def Package(env, target=None, source=None, **kw): """ Entry point for the package tool. """ # check if we need to find the source files ourself if not source: source = env.FindInstalledFiles() if len(source)==0: raise UserError("No source for Package() given") # decide which types of packages shall be built. Can be defined through # four mechanisms: command line argument, keyword argument, # environment argument and default selection( zip or tar.gz ) in that # order. try: kw['PACKAGETYPE']=env['PACKAGETYPE'] except KeyError: pass if not kw.get('PACKAGETYPE'): from SCons.Script import GetOption kw['PACKAGETYPE'] = GetOption('package_type') if kw['PACKAGETYPE'] == None: if 'Tar' in env['BUILDERS']: kw['PACKAGETYPE']='targz' elif 'Zip' in env['BUILDERS']: kw['PACKAGETYPE']='zip' else: raise UserError("No type for Package() given") PACKAGETYPE=kw['PACKAGETYPE'] if not is_List(PACKAGETYPE): PACKAGETYPE=PACKAGETYPE.split(',') # load the needed packagers. def load_packager(type): try: file,path,desc=imp.find_module(type, __path__) return imp.load_module(type, file, path, desc) except ImportError, e: raise EnvironmentError("packager %s not available: %s"%(type,str(e))) packagers=list(map(load_packager, PACKAGETYPE)) # set up targets and the PACKAGEROOT try: # fill up the target list with a default target name until the PACKAGETYPE # list is of the same size as the target list. if not target: target = [] size_diff = len(PACKAGETYPE)-len(target) default_name = "%(NAME)s-%(VERSION)s" if size_diff>0: default_target = default_name%kw target.extend( [default_target]*size_diff ) if 'PACKAGEROOT' not in kw: kw['PACKAGEROOT'] = default_name%kw except KeyError, e: raise SCons.Errors.UserError( "Missing Packagetag '%s'"%e.args[0] ) # setup the source files source=env.arg2nodes(source, env.fs.Entry) # call the packager to setup the dependencies. targets=[] try: for packager in packagers: t=[target.pop(0)] t=packager.package(env,t,source, **kw) targets.extend(t) assert( len(target) == 0 ) except KeyError, e: raise SCons.Errors.UserError( "Missing Packagetag '%s' for %s packager"\ % (e.args[0],packager.__name__) ) except TypeError, e: # this exception means that a needed argument for the packager is # missing. As our packagers get their "tags" as named function # arguments we need to find out which one is missing. from inspect import getargspec args,varargs,varkw,defaults=getargspec(packager.package) if defaults!=None: args=args[:-len(defaults)] # throw away arguments with default values args.remove('env') args.remove('target') args.remove('source') # now remove any args for which we have a value in kw. args=[x for x in args if x not in kw] if len(args)==0: raise # must be a different error, so reraise elif len(args)==1: raise SCons.Errors.UserError( "Missing Packagetag '%s' for %s packager"\ % (args[0],packager.__name__) ) else: raise SCons.Errors.UserError( "Missing Packagetags '%s' for %s packager"\ % (", ".join(args),packager.__name__) ) target=env.arg2nodes(target, env.fs.Entry) targets.extend(env.Alias( 'package', targets )) return targets # # SCons tool initialization functions # added = None def generate(env): from SCons.Script import AddOption global added if not added: added = 1 AddOption('--package-type', dest='package_type', default=None, type="string", action="store", help='The type of package to create.') try: env['BUILDERS']['Package'] env['BUILDERS']['Tag'] except KeyError: env['BUILDERS']['Package'] = Package env['BUILDERS']['Tag'] = Tag def exists(env): return 1 # XXX def options(opts): opts.AddVariables( EnumVariable( 'PACKAGETYPE', 'the type of package to create.', None, allowed_values=list(map( str, __all__ )), ignorecase=2 ) ) # # Internal utility functions # def copy_attr(f1, f2): """ copies the special packaging file attributes from f1 to f2. """ #pattrs = [x for x in dir(f1) if not hasattr(f2, x) and\ # x.startswith('PACKAGING_')] copyit = lambda x: not hasattr(f2, x) and x[:10] == 'PACKAGING_' pattrs = list(filter(copyit, dir(f1))) for attr in pattrs: setattr(f2, attr, getattr(f1, attr)) def putintopackageroot(target, source, env, pkgroot, honor_install_location=1): """ Uses the CopyAs builder to copy all source files to the directory given in pkgroot. If honor_install_location is set and the copied source file has an PACKAGING_INSTALL_LOCATION attribute, the PACKAGING_INSTALL_LOCATION is used as the new name of the source file under pkgroot. The source file will not be copied if it is already under the the pkgroot directory. All attributes of the source file will be copied to the new file. """ # make sure the packageroot is a Dir object. if SCons.Util.is_String(pkgroot): pkgroot=env.Dir(pkgroot) if not SCons.Util.is_List(source): source=[source] new_source = [] for file in source: if SCons.Util.is_String(file): file = env.File(file) if file.is_under(pkgroot): new_source.append(file) else: if hasattr(file, 'PACKAGING_INSTALL_LOCATION') and\ honor_install_location: new_name=make_path_relative(file.PACKAGING_INSTALL_LOCATION) else: new_name=make_path_relative(file.get_path()) new_file=pkgroot.File(new_name) new_file=env.CopyAs(new_file, file)[0] copy_attr(file, new_file) new_source.append(new_file) return (target, new_source) def stripinstallbuilder(target, source, env): """ strips the install builder action from the source list and stores the final installation location as the "PACKAGING_INSTALL_LOCATION" of the source of the source file. This effectively removes the final installed files from the source list while remembering the installation location. It also warns about files which have no install builder attached. """ def has_no_install_location(file): return not (file.has_builder() and\ hasattr(file.builder, 'name') and\ (file.builder.name=="InstallBuilder" or\ file.builder.name=="InstallAsBuilder")) if len(list(filter(has_no_install_location, source))): warn(Warning, "there are files to package which have no\ InstallBuilder attached, this might lead to irreproducible packages") n_source=[] for s in source: if has_no_install_location(s): n_source.append(s) else: for ss in s.sources: n_source.append(ss) copy_attr(s, ss) setattr(ss, 'PACKAGING_INSTALL_LOCATION', s.get_path()) return (target, n_source) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging.tarbz2 The tarbz2 SRC packager. """ # # 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/packaging/src_tarbz2.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Tool.packaging import putintopackageroot def package(env, target, source, PACKAGEROOT, **kw): bld = env['BUILDERS']['Tar'] bld.set_suffix('.tar.bz2') target, source = putintopackageroot(target, source, env, PACKAGEROOT, honor_install_location=0) return bld(env, target, source, TARFLAGS='-jc') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Packaging.tarbz2 The tarbz2 SRC packager. """ # # 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/packaging/tarbz2.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot def package(env, target, source, PACKAGEROOT, **kw): bld = env['BUILDERS']['Tar'] bld.set_suffix('.tar.gz') target, source = putintopackageroot(target, source, env, PACKAGEROOT) target, source = stripinstallbuilder(target, source, env) return bld(env, target, source, TARFLAGS='-jc') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.BitKeeper.py Tool-specific initialization for the BitKeeper source code control 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/BitKeeper.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Util def generate(env): """Add a Builder factory function and construction variables for BitKeeper to an Environment.""" def BitKeeperFactory(env=env): """ """ import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The BitKeeper() factory is deprecated and there is no replacement.""") act = SCons.Action.Action("$BITKEEPERCOM", "$BITKEEPERCOMSTR") return SCons.Builder.Builder(action = act, env = env) #setattr(env, 'BitKeeper', BitKeeperFactory) env.BitKeeper = BitKeeperFactory env['BITKEEPER'] = 'bk' env['BITKEEPERGET'] = '$BITKEEPER get' env['BITKEEPERGETFLAGS'] = SCons.Util.CLVar('') env['BITKEEPERCOM'] = '$BITKEEPERGET $BITKEEPERGETFLAGS $TARGET' def exists(env): return env.Detect('bk') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.cc Tool-specific initialization for generic Posix C compilers. 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/cc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Tool import SCons.Defaults import SCons.Util CSuffixes = ['.c', '.m'] if not SCons.Util.case_sensitive_suffixes('.c', '.C'): CSuffixes.append('.C') def add_common_cc_variables(env): """ Add underlying common "C compiler" variables that are used by multiple tools (specifically, c++). """ if '_CCCOMCOM' not in env: env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS' # It's a hack to test for darwin here, but the alternative # of creating an applecc.py to contain this seems overkill. # Maybe someday the Apple platform will require more setup and # this logic will be moved. env['FRAMEWORKS'] = SCons.Util.CLVar('') env['FRAMEWORKPATH'] = SCons.Util.CLVar('') if env['PLATFORM'] == 'darwin': env['_CCCOMCOM'] = env['_CCCOMCOM'] + ' $_FRAMEWORKPATH' if 'CCFLAGS' not in env: env['CCFLAGS'] = SCons.Util.CLVar('') if 'SHCCFLAGS' not in env: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') def generate(env): """ Add Builders and construction variables for C compilers to an Environment. """ static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CSuffixes: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix, SCons.Defaults.ShCAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) add_common_cc_variables(env) env['CC'] = 'cc' env['CFLAGS'] = SCons.Util.CLVar('') env['CCCOM'] = '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES' env['SHCC'] = '$CC' env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS') env['SHCCCOM'] = '$SHCC -o $TARGET -c $SHCFLAGS $SHCCFLAGS $_CCCOMCOM $SOURCES' env['CPPDEFPREFIX'] = '-D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '-I' env['INCSUFFIX'] = '' env['SHOBJSUFFIX'] = '.os' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0 env['CFILESUFFIX'] = '.c' def exists(env): return env.Detect('cc') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.dvipdf Tool-specific initialization for dvipdf. 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/dvipdf.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Defaults import SCons.Tool.pdf import SCons.Tool.tex import SCons.Util _null = SCons.Scanner.LaTeX._null def DviPdfPsFunction(XXXDviAction, target = None, source= None, env=None): """A builder for DVI files that sets the TEXPICTS environment variable before running dvi2ps or dvipdf.""" try: abspath = source[0].attributes.path except AttributeError : abspath = '' saved_env = SCons.Scanner.LaTeX.modify_env_var(env, 'TEXPICTS', abspath) result = XXXDviAction(target, source, env) if saved_env is _null: try: del env['ENV']['TEXPICTS'] except KeyError: pass # was never set else: env['ENV']['TEXPICTS'] = saved_env return result def DviPdfFunction(target = None, source= None, env=None): result = DviPdfPsFunction(PDFAction,target,source,env) return result def DviPdfStrFunction(target = None, source= None, env=None): """A strfunction for dvipdf that returns the appropriate command string for the no_exec options.""" if env.GetOption("no_exec"): result = env.subst('$DVIPDFCOM',0,target,source) else: result = '' return result PDFAction = None DVIPDFAction = None def PDFEmitter(target, source, env): """Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file. """ def strip_suffixes(n): return not SCons.Util.splitext(str(n))[1] in ['.aux', '.log'] source = list(filter(strip_suffixes, source)) return (target, source) def generate(env): """Add Builders and construction variables for dvipdf to an Environment.""" global PDFAction if PDFAction is None: PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR') global DVIPDFAction if DVIPDFAction is None: DVIPDFAction = SCons.Action.Action(DviPdfFunction, strfunction = DviPdfStrFunction) import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.dvi', DVIPDFAction) bld.add_emitter('.dvi', PDFEmitter) env['DVIPDF'] = 'dvipdf' env['DVIPDFFLAGS'] = SCons.Util.CLVar('') env['DVIPDFCOM'] = 'cd ${TARGET.dir} && $DVIPDF $DVIPDFFLAGS ${SOURCE.file} ${TARGET.file}' # Deprecated synonym. env['PDFCOM'] = ['$DVIPDFCOM'] def exists(env): SCons.Tool.tex.generate_darwin(env) return env.Detect('dvipdf') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.f77 Tool-specific initialization for the generic Posix f77 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/f77.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Scanner.Fortran import SCons.Tool import SCons.Util from SCons.Tool.FortranCommon import add_all_to_env, add_f77_to_env compilers = ['f77'] def generate(env): add_all_to_env(env) add_f77_to_env(env) fcomp = env.Detect(compilers) or 'f77' env['F77'] = fcomp env['SHF77'] = 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.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.ipkg Tool-specific initialization for ipkg. 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. The ipkg tool calls the ipkg-build. Its only argument should be the packages fake_root. """ # # 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/ipkg.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import SCons.Builder def generate(env): """Add Builders and construction variables for ipkg to an Environment.""" try: bld = env['BUILDERS']['Ipkg'] except KeyError: bld = SCons.Builder.Builder( action = '$IPKGCOM', suffix = '$IPKGSUFFIX', source_scanner = None, target_scanner = None) env['BUILDERS']['Ipkg'] = bld env['IPKG'] = 'ipkg-build' env['IPKGCOM'] = '$IPKG $IPKGFLAGS ${SOURCE}' env['IPKGUSER'] = os.popen('id -un').read().strip() env['IPKGGROUP'] = os.popen('id -gn').read().strip() env['IPKGFLAGS'] = SCons.Util.CLVar('-o $IPKGUSER -g $IPKGGROUP') env['IPKGSUFFIX'] = '.ipk' def exists(env): return env.Detect('ipkg-build') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.suncc Tool-specific initialization for Sun Solaris (Forte) CC and cc. 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/suncc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util import cc def generate(env): """ Add Builders and construction variables for Forte C and C++ compilers to an Environment. """ cc.generate(env) env['CXX'] = 'CC' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -KPIC') env['SHOBJPREFIX'] = 'so_' env['SHOBJSUFFIX'] = '.o' def exists(env): return env.Detect('CC') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.gfortran Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran 2003 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/gfortran.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util import fortran def generate(env): """Add Builders and construction variables for gfortran to an Environment.""" fortran.generate(env) for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03']: env['%s' % dialect] = 'gfortran' env['SH%s' % dialect] = '$%s' % dialect if env['PLATFORM'] in ['cygwin', 'win32']: env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect) else: env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect) env['INC%sPREFIX' % dialect] = "-I" env['INC%sSUFFIX' % dialect] = "" def exists(env): return env.Detect('gfortran') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sgilink Tool-specific initialization for the SGI MIPSPro linker on SGI. 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/sgilink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util import link linkers = ['CC', 'cc'] def generate(env): """Add Builders and construction variables for MIPSPro to an Environment.""" link.generate(env) env['LINK'] = env.Detect(linkers) or 'cc' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') # __RPATH is set to $_RPATH in the platform specification if that # platform supports it. env['RPATHPREFIX'] = '-rpath ' env['RPATHSUFFIX'] = '' env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}' def exists(env): return env.Detect(linkers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.mwcc Tool-specific initialization for the Metrowerks CodeWarrior 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/mwcc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Util def set_vars(env): """Set MWCW_VERSION, MWCW_VERSIONS, and some codewarrior environment vars MWCW_VERSIONS is set to a list of objects representing installed versions MWCW_VERSION is set to the version object that will be used for building. MWCW_VERSION can be set to a string during Environment construction to influence which version is chosen, otherwise the latest one from MWCW_VERSIONS is used. Returns true if at least one version is found, false otherwise """ desired = env.get('MWCW_VERSION', '') # return right away if the variables are already set if isinstance(desired, MWVersion): return 1 elif desired is None: return 0 versions = find_versions() version = None if desired: for v in versions: if str(v) == desired: version = v elif versions: version = versions[-1] env['MWCW_VERSIONS'] = versions env['MWCW_VERSION'] = version if version is None: return 0 env.PrependENVPath('PATH', version.clpath) env.PrependENVPath('PATH', version.dllpath) ENV = env['ENV'] ENV['CWFolder'] = version.path ENV['LM_LICENSE_FILE'] = version.license plus = lambda x: '+%s' % x ENV['MWCIncludes'] = os.pathsep.join(map(plus, version.includes)) ENV['MWLibraries'] = os.pathsep.join(map(plus, version.libs)) return 1 def find_versions(): """Return a list of MWVersion objects representing installed versions""" versions = [] ### This function finds CodeWarrior by reading from the registry on ### Windows. Some other method needs to be implemented for other ### platforms, maybe something that calls env.WhereIs('mwcc') if SCons.Util.can_read_reg: try: HLM = SCons.Util.HKEY_LOCAL_MACHINE product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions' product_key = SCons.Util.RegOpenKeyEx(HLM, product) i = 0 while True: name = product + '\\' + SCons.Util.RegEnumKey(product_key, i) name_key = SCons.Util.RegOpenKeyEx(HLM, name) try: version = SCons.Util.RegQueryValueEx(name_key, 'VERSION') path = SCons.Util.RegQueryValueEx(name_key, 'PATH') mwv = MWVersion(version[0], path[0], 'Win32-X86') versions.append(mwv) except SCons.Util.RegError: pass i = i + 1 except SCons.Util.RegError: pass return versions class MWVersion(object): def __init__(self, version, path, platform): self.version = version self.path = path self.platform = platform self.clpath = os.path.join(path, 'Other Metrowerks Tools', 'Command Line Tools') self.dllpath = os.path.join(path, 'Bin') # The Metrowerks tools don't store any configuration data so they # are totally dumb when it comes to locating standard headers, # libraries, and other files, expecting all the information # to be handed to them in environment variables. The members set # below control what information scons injects into the environment ### The paths below give a normal build environment in CodeWarrior for ### Windows, other versions of CodeWarrior might need different paths. msl = os.path.join(path, 'MSL') support = os.path.join(path, '%s Support' % platform) self.license = os.path.join(path, 'license.dat') self.includes = [msl, support] self.libs = [msl, support] def __str__(self): return self.version CSuffixes = ['.c', '.C'] CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++'] def generate(env): """Add Builders and construction variables for the mwcc to an Environment.""" import SCons.Defaults import SCons.Tool set_vars(env) static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CSuffixes: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix, SCons.Defaults.ShCAction) for suffix in CXXSuffixes: static_obj.add_action(suffix, SCons.Defaults.CXXAction) shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction) env['CCCOMFLAGS'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -nolink -o $TARGET $SOURCES' env['CC'] = 'mwcc' env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CCCOMFLAGS' env['CXX'] = 'mwcc' env['CXXCOM'] = '$CXX $CXXFLAGS $CCCOMFLAGS' env['SHCC'] = '$CC' env['SHCCFLAGS'] = '$CCFLAGS' env['SHCFLAGS'] = '$CFLAGS' env['SHCCCOM'] = '$SHCC $SHCFLAGS $SHCCFLAGS $CCCOMFLAGS' env['SHCXX'] = '$CXX' env['SHCXXFLAGS'] = '$CXXFLAGS' env['SHCXXCOM'] = '$SHCXX $SHCXXFLAGS $CCCOMFLAGS' env['CFILESUFFIX'] = '.c' env['CXXFILESUFFIX'] = '.cpp' env['CPPDEFPREFIX'] = '-D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '-I' env['INCSUFFIX'] = '' #env['PCH'] = ? #env['PCHSTOP'] = ? def exists(env): return set_vars(env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.aixlink Tool-specific initialization for the IBM Visual Age linker. 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/aixlink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Util import aixcc import link cplusplus = __import__('c++', globals(), locals(), []) def smart_linkflags(source, target, env, for_signature): if cplusplus.iscplusplus(source): build_dir = env.subst('$BUILDDIR', target=target, source=source) if build_dir: return '-qtempinc=' + os.path.join(build_dir, 'tempinc') return '' def generate(env): """ Add Builders and construction variables for Visual Age linker to an Environment. """ link.generate(env) env['SMARTLINKFLAGS'] = smart_linkflags env['LINKFLAGS'] = SCons.Util.CLVar('$SMARTLINKFLAGS') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -qmkshrobj -qsuppress=1501-218') env['SHLIBSUFFIX'] = '.a' def exists(env): path, _cc, _shcc, version = aixcc.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.msvs Tool-specific initialization for Microsoft Visual Studio project 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/msvs.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import base64 import hashlib import ntpath import os # compat layer imports "cPickle" for us if it's available. import pickle import re import sys import SCons.Builder import SCons.Node.FS import SCons.Platform.win32 import SCons.Script.SConscript import SCons.PathList import SCons.Util import SCons.Warnings from MSCommon import msvc_exists, msvc_setup_env_once from SCons.Defaults import processDefines ############################################################################## # Below here are the classes and functions for generation of # DSP/DSW/SLN/VCPROJ files. ############################################################################## def xmlify(s): s = s.replace("&", "&amp;") # do this first s = s.replace("'", "&apos;") s = s.replace('"', "&quot;") return s # Process a CPPPATH list in includes, given the env, target and source. # Returns a tuple of nodes. def processIncludes(includes, env, target, source): return SCons.PathList.PathList(includes).subst_path(env, target, source) external_makefile_guid = '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}' def _generateGUID(slnfile, name): """This generates a dummy GUID for the sln file to use. It is based on the MD5 signatures of the sln filename plus the name of the project. It basically just needs to be unique, and not change with each invocation.""" m = hashlib.md5() # Normalize the slnfile path to a Windows path (\ separators) so # the generated file has a consistent GUID even if we generate # it on a non-Windows platform. m.update(ntpath.normpath(str(slnfile)) + str(name)) solution = m.hexdigest().upper() # convert most of the signature to GUID form (discard the rest) solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}" return solution version_re = re.compile(r'(\d+\.\d+)(.*)') def msvs_parse_version(s): """ Split a Visual Studio version, which may in fact be something like '7.0Exp', into is version number (returned as a float) and trailing "suite" portion. """ num, suite = version_re.match(s).groups() return float(num), suite # os.path.relpath has been introduced in Python 2.6 # We define it locally for earlier versions of Python def relpath(path, start=os.path.curdir): """Return a relative version of a path""" import sys if not path: raise ValueError("no path specified") start_list = os.path.abspath(start).split(os.sep) path_list = os.path.abspath(path).split(os.sep) if 'posix' in sys.builtin_module_names: # Work out how much of the filepath is shared by start and path. i = len(os.path.commonprefix([start_list, path_list])) else: if start_list[0].lower() != path_list[0].lower(): unc_path, rest = os.path.splitunc(path) unc_start, rest = os.path.splitunc(start) if bool(unc_path) ^ bool(unc_start): raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_list[0], start_list[0])) # Work out how much of the filepath is shared by start and path. for i in range(min(len(start_list), len(path_list))): if start_list[i].lower() != path_list[i].lower(): break else: i += 1 rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return os.path.curdir return os.path.join(*rel_list) if not "relpath" in os.path.__all__: os.path.relpath = relpath # This is how we re-invoke SCons from inside MSVS Project files. # The problem is that we might have been invoked as either scons.bat # or scons.py. If we were invoked directly as scons.py, then we could # use sys.argv[0] to find the SCons "executable," but that doesn't work # if we were invoked as scons.bat, which uses "python -c" to execute # things and ends up with "-c" as sys.argv[0]. Consequently, we have # the MSVS Project file invoke SCons the same way that scons.bat does, # which works regardless of how we were invoked. def getExecScriptMain(env, xml=None): scons_home = env.get('SCONS_HOME') if not scons_home and 'SCONS_LIB_DIR' in os.environ: scons_home = os.environ['SCONS_LIB_DIR'] if scons_home: exec_script_main = "from os.path import join; import sys; sys.path = [ r'%s' ] + sys.path; import SCons.Script; SCons.Script.main()" % scons_home else: version = SCons.__version__ exec_script_main = "from os.path import join; import sys; sys.path = [ join(sys.prefix, 'Lib', 'site-packages', 'scons-%(version)s'), join(sys.prefix, 'scons-%(version)s'), join(sys.prefix, 'Lib', 'site-packages', 'scons'), join(sys.prefix, 'scons') ] + sys.path; import SCons.Script; SCons.Script.main()" % locals() if xml: exec_script_main = xmlify(exec_script_main) return exec_script_main # The string for the Python executable we tell the Project file to use # is either sys.executable or, if an external PYTHON_ROOT environment # variable exists, $(PYTHON)ROOT\\python.exe (generalized a little to # pluck the actual executable name from sys.executable). try: python_root = os.environ['PYTHON_ROOT'] except KeyError: python_executable = sys.executable else: python_executable = os.path.join('$$(PYTHON_ROOT)', os.path.split(sys.executable)[1]) class Config(object): pass def splitFully(path): dir, base = os.path.split(path) if dir and dir != '' and dir != path: return splitFully(dir)+[base] if base == '': return [] return [base] def makeHierarchy(sources): '''Break a list of files into a hierarchy; for each value, if it is a string, then it is a file. If it is a dictionary, it is a folder. The string is the original path of the file.''' hierarchy = {} for file in sources: path = splitFully(file) if len(path): dict = hierarchy for part in path[:-1]: if part not in dict: dict[part] = {} dict = dict[part] dict[path[-1]] = file #else: # print 'Warning: failed to decompose path for '+str(file) return hierarchy class _DSPGenerator(object): """ Base class for DSP generators """ srcargs = [ 'srcs', 'incs', 'localincs', 'resources', 'misc'] def __init__(self, dspfile, source, env): self.dspfile = str(dspfile) try: get_abspath = dspfile.get_abspath except AttributeError: self.dspabs = os.path.abspath(dspfile) else: self.dspabs = get_abspath() if 'variant' not in env: raise SCons.Errors.InternalError("You must specify a 'variant' argument (i.e. 'Debug' or " +\ "'Release') to create an MSVSProject.") elif SCons.Util.is_String(env['variant']): variants = [env['variant']] elif SCons.Util.is_List(env['variant']): variants = env['variant'] if 'buildtarget' not in env or env['buildtarget'] == None: buildtarget = [''] elif SCons.Util.is_String(env['buildtarget']): buildtarget = [env['buildtarget']] elif SCons.Util.is_List(env['buildtarget']): if len(env['buildtarget']) != len(variants): raise SCons.Errors.InternalError("Sizes of 'buildtarget' and 'variant' lists must be the same.") buildtarget = [] for bt in env['buildtarget']: if SCons.Util.is_String(bt): buildtarget.append(bt) else: buildtarget.append(bt.get_abspath()) else: buildtarget = [env['buildtarget'].get_abspath()] if len(buildtarget) == 1: bt = buildtarget[0] buildtarget = [] for _ in variants: buildtarget.append(bt) if 'outdir' not in env or env['outdir'] == None: outdir = [''] elif SCons.Util.is_String(env['outdir']): outdir = [env['outdir']] elif SCons.Util.is_List(env['outdir']): if len(env['outdir']) != len(variants): raise SCons.Errors.InternalError("Sizes of 'outdir' and 'variant' lists must be the same.") outdir = [] for s in env['outdir']: if SCons.Util.is_String(s): outdir.append(s) else: outdir.append(s.get_abspath()) else: outdir = [env['outdir'].get_abspath()] if len(outdir) == 1: s = outdir[0] outdir = [] for v in variants: outdir.append(s) if 'runfile' not in env or env['runfile'] == None: runfile = buildtarget[-1:] elif SCons.Util.is_String(env['runfile']): runfile = [env['runfile']] elif SCons.Util.is_List(env['runfile']): if len(env['runfile']) != len(variants): raise SCons.Errors.InternalError("Sizes of 'runfile' and 'variant' lists must be the same.") runfile = [] for s in env['runfile']: if SCons.Util.is_String(s): runfile.append(s) else: runfile.append(s.get_abspath()) else: runfile = [env['runfile'].get_abspath()] if len(runfile) == 1: s = runfile[0] runfile = [] for v in variants: runfile.append(s) self.sconscript = env['MSVSSCONSCRIPT'] cmdargs = env.get('cmdargs', '') self.env = env if 'name' in self.env: self.name = self.env['name'] else: self.name = os.path.basename(SCons.Util.splitext(self.dspfile)[0]) self.name = self.env.subst(self.name) sourcenames = [ 'Source Files', 'Header Files', 'Local Headers', 'Resource Files', 'Other Files'] self.sources = {} for n in sourcenames: self.sources[n] = [] self.configs = {} self.nokeep = 0 if 'nokeep' in env and env['variant'] != 0: self.nokeep = 1 if self.nokeep == 0 and os.path.exists(self.dspabs): self.Parse() for t in zip(sourcenames,self.srcargs): if t[1] in self.env: if SCons.Util.is_List(self.env[t[1]]): for i in self.env[t[1]]: if not i in self.sources[t[0]]: self.sources[t[0]].append(i) else: if not self.env[t[1]] in self.sources[t[0]]: self.sources[t[0]].append(self.env[t[1]]) for n in sourcenames: #TODO 2.4: compat layer supports sorted(key=) but not sort(key=) #TODO 2.4: self.sources[n].sort(key=lambda a: a.lower()) self.sources[n] = sorted(self.sources[n], key=lambda a: a.lower()) def AddConfig(self, variant, buildtarget, outdir, runfile, cmdargs, dspfile=dspfile): config = Config() config.buildtarget = buildtarget config.outdir = outdir config.cmdargs = cmdargs config.runfile = runfile match = re.match('(.*)\|(.*)', variant) if match: config.variant = match.group(1) config.platform = match.group(2) else: config.variant = variant config.platform = 'Win32' self.configs[variant] = config print "Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dspfile) + "'" for i in range(len(variants)): AddConfig(self, variants[i], buildtarget[i], outdir[i], runfile[i], cmdargs) self.platforms = [] for key in self.configs.keys(): platform = self.configs[key].platform if not platform in self.platforms: self.platforms.append(platform) def Build(self): pass V6DSPHeader = """\ # Microsoft Developer Studio Project File - Name="%(name)s" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) External Target" 0x0106 CFG=%(name)s - Win32 %(confkey)s !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "%(name)s.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "%(name)s.mak" CFG="%(name)s - Win32 %(confkey)s" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE """ class _GenerateV6DSP(_DSPGenerator): """Generates a Project file for MSVS 6.0""" def PrintHeader(self): # pick a default config confkeys = sorted(self.configs.keys()) name = self.name confkey = confkeys[0] self.file.write(V6DSPHeader % locals()) for kind in confkeys: self.file.write('!MESSAGE "%s - Win32 %s" (based on "Win32 (x86) External Target")\n' % (name, kind)) self.file.write('!MESSAGE \n\n') def PrintProject(self): name = self.name self.file.write('# Begin Project\n' '# PROP AllowPerConfigDependencies 0\n' '# PROP Scc_ProjName ""\n' '# PROP Scc_LocalPath ""\n\n') first = 1 confkeys = sorted(self.configs.keys()) for kind in confkeys: outdir = self.configs[kind].outdir buildtarget = self.configs[kind].buildtarget if first == 1: self.file.write('!IF "$(CFG)" == "%s - Win32 %s"\n\n' % (name, kind)) first = 0 else: self.file.write('\n!ELSEIF "$(CFG)" == "%s - Win32 %s"\n\n' % (name, kind)) env_has_buildtarget = 'MSVSBUILDTARGET' in self.env if not env_has_buildtarget: self.env['MSVSBUILDTARGET'] = buildtarget # have to write this twice, once with the BASE settings, and once without for base in ("BASE ",""): self.file.write('# PROP %sUse_MFC 0\n' '# PROP %sUse_Debug_Libraries ' % (base, base)) if kind.lower().find('debug') < 0: self.file.write('0\n') else: self.file.write('1\n') self.file.write('# PROP %sOutput_Dir "%s"\n' '# PROP %sIntermediate_Dir "%s"\n' % (base,outdir,base,outdir)) cmd = 'echo Starting SCons && ' + self.env.subst('$MSVSBUILDCOM', 1) self.file.write('# PROP %sCmd_Line "%s"\n' '# PROP %sRebuild_Opt "-c && %s"\n' '# PROP %sTarget_File "%s"\n' '# PROP %sBsc_Name ""\n' '# PROP %sTarget_Dir ""\n'\ %(base,cmd,base,cmd,base,buildtarget,base,base)) if not env_has_buildtarget: del self.env['MSVSBUILDTARGET'] self.file.write('\n!ENDIF\n\n' '# Begin Target\n\n') for kind in confkeys: self.file.write('# Name "%s - Win32 %s"\n' % (name,kind)) self.file.write('\n') first = 0 for kind in confkeys: if first == 0: self.file.write('!IF "$(CFG)" == "%s - Win32 %s"\n\n' % (name,kind)) first = 1 else: self.file.write('!ELSEIF "$(CFG)" == "%s - Win32 %s"\n\n' % (name,kind)) self.file.write('!ENDIF \n\n') self.PrintSourceFiles() self.file.write('# End Target\n' '# End Project\n') if self.nokeep == 0: # now we pickle some data and add it to the file -- MSDEV will ignore it. pdata = pickle.dumps(self.configs,1) pdata = base64.encodestring(pdata) self.file.write(pdata + '\n') pdata = pickle.dumps(self.sources,1) pdata = base64.encodestring(pdata) self.file.write(pdata + '\n') def PrintSourceFiles(self): categories = {'Source Files': 'cpp|c|cxx|l|y|def|odl|idl|hpj|bat', 'Header Files': 'h|hpp|hxx|hm|inl', 'Local Headers': 'h|hpp|hxx|hm|inl', 'Resource Files': 'r|rc|ico|cur|bmp|dlg|rc2|rct|bin|cnt|rtf|gif|jpg|jpeg|jpe', 'Other Files': ''} for kind in sorted(categories.keys(), key=lambda a: a.lower()): if not self.sources[kind]: continue # skip empty groups self.file.write('# Begin Group "' + kind + '"\n\n') typelist = categories[kind].replace('|', ';') self.file.write('# PROP Default_Filter "' + typelist + '"\n') for file in self.sources[kind]: file = os.path.normpath(file) self.file.write('# Begin Source File\n\n' 'SOURCE="' + file + '"\n' '# End Source File\n') self.file.write('# End Group\n') # add the SConscript file outside of the groups self.file.write('# Begin Source File\n\n' 'SOURCE="' + str(self.sconscript) + '"\n' '# End Source File\n') def Parse(self): try: dspfile = open(self.dspabs,'r') except IOError: return # doesn't exist yet, so can't add anything to configs. line = dspfile.readline() while line: if line.find("# End Project") > -1: break line = dspfile.readline() line = dspfile.readline() datas = line while line and line != '\n': line = dspfile.readline() datas = datas + line # OK, we've found our little pickled cache of data. try: datas = base64.decodestring(datas) data = pickle.loads(datas) except KeyboardInterrupt: raise except: return # unable to unpickle any data for some reason self.configs.update(data) data = None line = dspfile.readline() datas = line while line and line != '\n': line = dspfile.readline() datas = datas + line # OK, we've found our little pickled cache of data. # it has a "# " in front of it, so we strip that. try: datas = base64.decodestring(datas) data = pickle.loads(datas) except KeyboardInterrupt: raise except: return # unable to unpickle any data for some reason self.sources.update(data) def Build(self): try: self.file = open(self.dspabs,'w') except IOError, detail: raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail)) else: self.PrintHeader() self.PrintProject() self.file.close() V7DSPHeader = """\ <?xml version="1.0" encoding="%(encoding)s"?> <VisualStudioProject \tProjectType="Visual C++" \tVersion="%(versionstr)s" \tName="%(name)s" \tProjectGUID="%(project_guid)s" %(scc_attrs)s \tKeyword="MakeFileProj"> """ V7DSPConfiguration = """\ \t\t<Configuration \t\t\tName="%(variant)s|%(platform)s" \t\t\tOutputDirectory="%(outdir)s" \t\t\tIntermediateDirectory="%(outdir)s" \t\t\tConfigurationType="0" \t\t\tUseOfMFC="0" \t\t\tATLMinimizesCRunTimeLibraryUsage="FALSE"> \t\t\t<Tool \t\t\t\tName="VCNMakeTool" \t\t\t\tBuildCommandLine="%(buildcmd)s" \t\t\t\tReBuildCommandLine="%(rebuildcmd)s" \t\t\t\tCleanCommandLine="%(cleancmd)s" \t\t\t\tOutput="%(runfile)s"/> \t\t</Configuration> """ V8DSPHeader = """\ <?xml version="1.0" encoding="%(encoding)s"?> <VisualStudioProject \tProjectType="Visual C++" \tVersion="%(versionstr)s" \tName="%(name)s" \tProjectGUID="%(project_guid)s" \tRootNamespace="%(name)s" %(scc_attrs)s \tKeyword="MakeFileProj"> """ V8DSPConfiguration = """\ \t\t<Configuration \t\t\tName="%(variant)s|%(platform)s" \t\t\tConfigurationType="0" \t\t\tUseOfMFC="0" \t\t\tATLMinimizesCRunTimeLibraryUsage="false" \t\t\t> \t\t\t<Tool \t\t\t\tName="VCNMakeTool" \t\t\t\tBuildCommandLine="%(buildcmd)s" \t\t\t\tReBuildCommandLine="%(rebuildcmd)s" \t\t\t\tCleanCommandLine="%(cleancmd)s" \t\t\t\tOutput="%(runfile)s" \t\t\t\tPreprocessorDefinitions="%(preprocdefs)s" \t\t\t\tIncludeSearchPath="%(includepath)s" \t\t\t\tForcedIncludes="" \t\t\t\tAssemblySearchPath="" \t\t\t\tForcedUsingAssemblies="" \t\t\t\tCompileAsManaged="" \t\t\t/> \t\t</Configuration> """ class _GenerateV7DSP(_DSPGenerator): """Generates a Project file for MSVS .NET""" def __init__(self, dspfile, source, env): _DSPGenerator.__init__(self, dspfile, source, env) self.version = env['MSVS_VERSION'] self.version_num, self.suite = msvs_parse_version(self.version) if self.version_num >= 9.0: self.versionstr = '9.00' self.dspheader = V8DSPHeader self.dspconfiguration = V8DSPConfiguration elif self.version_num >= 8.0: self.versionstr = '8.00' self.dspheader = V8DSPHeader self.dspconfiguration = V8DSPConfiguration else: if self.version_num >= 7.1: self.versionstr = '7.10' else: self.versionstr = '7.00' self.dspheader = V7DSPHeader self.dspconfiguration = V7DSPConfiguration self.file = None def PrintHeader(self): env = self.env versionstr = self.versionstr name = self.name encoding = self.env.subst('$MSVSENCODING') scc_provider = env.get('MSVS_SCC_PROVIDER', '') scc_project_name = env.get('MSVS_SCC_PROJECT_NAME', '') scc_aux_path = env.get('MSVS_SCC_AUX_PATH', '') # MSVS_SCC_LOCAL_PATH is kept for backwards compatibility purpose and should # be deprecated as soon as possible. scc_local_path_legacy = env.get('MSVS_SCC_LOCAL_PATH', '') scc_connection_root = env.get('MSVS_SCC_CONNECTION_ROOT', os.curdir) scc_local_path = os.path.relpath(scc_connection_root, os.path.dirname(self.dspabs)) project_guid = env.get('MSVS_PROJECT_GUID', '') if not project_guid: project_guid = _generateGUID(self.dspfile, '') if scc_provider != '': scc_attrs = '\tSccProjectName="%s"\n' % scc_project_name if scc_aux_path != '': scc_attrs += '\tSccAuxPath="%s"\n' % scc_aux_path scc_attrs += ('\tSccLocalPath="%s"\n' '\tSccProvider="%s"' % (scc_local_path, scc_provider)) elif scc_local_path_legacy != '': # This case is kept for backwards compatibility purpose and should # be deprecated as soon as possible. scc_attrs = ('\tSccProjectName="%s"\n' '\tSccLocalPath="%s"' % (scc_project_name, scc_local_path_legacy)) else: self.dspheader = self.dspheader.replace('%(scc_attrs)s\n', '') self.file.write(self.dspheader % locals()) self.file.write('\t<Platforms>\n') for platform in self.platforms: self.file.write( '\t\t<Platform\n' '\t\t\tName="%s"/>\n' % platform) self.file.write('\t</Platforms>\n') if self.version_num >= 8.0: self.file.write('\t<ToolFiles>\n' '\t</ToolFiles>\n') def PrintProject(self): self.file.write('\t<Configurations>\n') confkeys = sorted(self.configs.keys()) for kind in confkeys: variant = self.configs[kind].variant platform = self.configs[kind].platform outdir = self.configs[kind].outdir buildtarget = self.configs[kind].buildtarget runfile = self.configs[kind].runfile cmdargs = self.configs[kind].cmdargs env_has_buildtarget = 'MSVSBUILDTARGET' in self.env if not env_has_buildtarget: self.env['MSVSBUILDTARGET'] = buildtarget starting = 'echo Starting SCons && ' if cmdargs: cmdargs = ' ' + cmdargs else: cmdargs = '' buildcmd = xmlify(starting + self.env.subst('$MSVSBUILDCOM', 1) + cmdargs) rebuildcmd = xmlify(starting + self.env.subst('$MSVSREBUILDCOM', 1) + cmdargs) cleancmd = xmlify(starting + self.env.subst('$MSVSCLEANCOM', 1) + cmdargs) # This isn't perfect; CPPDEFINES and CPPPATH can contain $TARGET and $SOURCE, # so they could vary depending on the command being generated. This code # assumes they don't. preprocdefs = xmlify(';'.join(processDefines(self.env.get('CPPDEFINES', [])))) includepath_Dirs = processIncludes(self.env.get('CPPPATH', []), self.env, None, None) includepath = xmlify(';'.join([str(x) for x in includepath_Dirs])) if not env_has_buildtarget: del self.env['MSVSBUILDTARGET'] self.file.write(self.dspconfiguration % locals()) self.file.write('\t</Configurations>\n') if self.version_num >= 7.1: self.file.write('\t<References>\n' '\t</References>\n') self.PrintSourceFiles() self.file.write('</VisualStudioProject>\n') if self.nokeep == 0: # now we pickle some data and add it to the file -- MSDEV will ignore it. pdata = pickle.dumps(self.configs,1) pdata = base64.encodestring(pdata) self.file.write('<!-- SCons Data:\n' + pdata + '\n') pdata = pickle.dumps(self.sources,1) pdata = base64.encodestring(pdata) self.file.write(pdata + '-->\n') def printSources(self, hierarchy, commonprefix): sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower()) # First folders, then files for key, value in sorteditems: if SCons.Util.is_Dict(value): self.file.write('\t\t\t<Filter\n' '\t\t\t\tName="%s"\n' '\t\t\t\tFilter="">\n' % (key)) self.printSources(value, commonprefix) self.file.write('\t\t\t</Filter>\n') for key, value in sorteditems: if SCons.Util.is_String(value): file = value if commonprefix: file = os.path.join(commonprefix, value) file = os.path.normpath(file) self.file.write('\t\t\t<File\n' '\t\t\t\tRelativePath="%s">\n' '\t\t\t</File>\n' % (file)) def PrintSourceFiles(self): categories = {'Source Files': 'cpp;c;cxx;l;y;def;odl;idl;hpj;bat', 'Header Files': 'h;hpp;hxx;hm;inl', 'Local Headers': 'h;hpp;hxx;hm;inl', 'Resource Files': 'r;rc;ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe', 'Other Files': ''} self.file.write('\t<Files>\n') cats = sorted([k for k in categories.keys() if self.sources[k]], key=lambda a: a.lower()) for kind in cats: if len(cats) > 1: self.file.write('\t\t<Filter\n' '\t\t\tName="%s"\n' '\t\t\tFilter="%s">\n' % (kind, categories[kind])) sources = self.sources[kind] # First remove any common prefix commonprefix = None s = list(map(os.path.normpath, sources)) # take the dirname because the prefix may include parts # of the filenames (e.g. if you have 'dir\abcd' and # 'dir\acde' then the cp will be 'dir\a' ) cp = os.path.dirname( os.path.commonprefix(s) ) if cp and s[0][len(cp)] == os.sep: # +1 because the filename starts after the separator sources = [s[len(cp)+1:] for s in sources] commonprefix = cp hierarchy = makeHierarchy(sources) self.printSources(hierarchy, commonprefix=commonprefix) if len(cats)>1: self.file.write('\t\t</Filter>\n') # add the SConscript file outside of the groups self.file.write('\t\t<File\n' '\t\t\tRelativePath="%s">\n' '\t\t</File>\n' % str(self.sconscript)) self.file.write('\t</Files>\n' '\t<Globals>\n' '\t</Globals>\n') def Parse(self): try: dspfile = open(self.dspabs,'r') except IOError: return # doesn't exist yet, so can't add anything to configs. line = dspfile.readline() while line: if line.find('<!-- SCons Data:') > -1: break line = dspfile.readline() line = dspfile.readline() datas = line while line and line != '\n': line = dspfile.readline() datas = datas + line # OK, we've found our little pickled cache of data. try: datas = base64.decodestring(datas) data = pickle.loads(datas) except KeyboardInterrupt: raise except: return # unable to unpickle any data for some reason self.configs.update(data) data = None line = dspfile.readline() datas = line while line and line != '\n': line = dspfile.readline() datas = datas + line # OK, we've found our little pickled cache of data. try: datas = base64.decodestring(datas) data = pickle.loads(datas) except KeyboardInterrupt: raise except: return # unable to unpickle any data for some reason self.sources.update(data) def Build(self): try: self.file = open(self.dspabs,'w') except IOError, detail: raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail)) else: self.PrintHeader() self.PrintProject() self.file.close() V10DSPHeader = """\ <?xml version="1.0" encoding="%(encoding)s"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> """ V10DSPProjectConfiguration = """\ \t\t<ProjectConfiguration Include="%(variant)s|%(platform)s"> \t\t\t<Configuration>%(variant)s</Configuration> \t\t\t<Platform>%(platform)s</Platform> \t\t</ProjectConfiguration> """ V10DSPGlobals = """\ \t<PropertyGroup Label="Globals"> \t\t<ProjectGuid>%(project_guid)s</ProjectGuid> %(scc_attrs)s\t\t<RootNamespace>%(name)s</RootNamespace> \t\t<Keyword>MakeFileProj</Keyword> \t</PropertyGroup> """ V10DSPPropertyGroupCondition = """\ \t<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'" Label="Configuration"> \t\t<ConfigurationType>Makefile</ConfigurationType> \t\t<UseOfMfc>false</UseOfMfc> \t</PropertyGroup> """ V10DSPImportGroupCondition = """\ \t<ImportGroup Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'" Label="PropertySheets"> \t\t<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> \t</ImportGroup> """ V10DSPCommandLine = """\ \t\t<NMakeBuildCommandLine Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(buildcmd)s</NMakeBuildCommandLine> \t\t<NMakeReBuildCommandLine Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(rebuildcmd)s</NMakeReBuildCommandLine> \t\t<NMakeCleanCommandLine Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(cleancmd)s</NMakeCleanCommandLine> \t\t<NMakeOutput Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(runfile)s</NMakeOutput> \t\t<NMakePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(preprocdefs)s</NMakePreprocessorDefinitions> \t\t<NMakeIncludeSearchPath Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">%(includepath)s</NMakeIncludeSearchPath> \t\t<NMakeForcedIncludes Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">$(NMakeForcedIncludes)</NMakeForcedIncludes> \t\t<NMakeAssemblySearchPath Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">$(NMakeAssemblySearchPath)</NMakeAssemblySearchPath> \t\t<NMakeForcedUsingAssemblies Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'">$(NMakeForcedUsingAssemblies)</NMakeForcedUsingAssemblies> """ class _GenerateV10DSP(_DSPGenerator): """Generates a Project file for MSVS 2010""" def __init__(self, dspfile, source, env): _DSPGenerator.__init__(self, dspfile, source, env) self.dspheader = V10DSPHeader self.dspconfiguration = V10DSPProjectConfiguration self.dspglobals = V10DSPGlobals def PrintHeader(self): env = self.env name = self.name encoding = env.subst('$MSVSENCODING') project_guid = env.get('MSVS_PROJECT_GUID', '') scc_provider = env.get('MSVS_SCC_PROVIDER', '') scc_project_name = env.get('MSVS_SCC_PROJECT_NAME', '') scc_aux_path = env.get('MSVS_SCC_AUX_PATH', '') # MSVS_SCC_LOCAL_PATH is kept for backwards compatibility purpose and should # be deprecated as soon as possible. scc_local_path_legacy = env.get('MSVS_SCC_LOCAL_PATH', '') scc_connection_root = env.get('MSVS_SCC_CONNECTION_ROOT', os.curdir) scc_local_path = os.path.relpath(scc_connection_root, os.path.dirname(self.dspabs)) if not project_guid: project_guid = _generateGUID(self.dspfile, '') if scc_provider != '': scc_attrs = '\t\t<SccProjectName>%s</SccProjectName>\n' % scc_project_name if scc_aux_path != '': scc_attrs += '\t\t<SccAuxPath>%s</SccAuxPath>\n' % scc_aux_path scc_attrs += ('\t\t<SccLocalPath>%s</SccLocalPath>\n' '\t\t<SccProvider>%s</SccProvider>\n' % (scc_local_path, scc_provider)) elif scc_local_path_legacy != '': # This case is kept for backwards compatibility purpose and should # be deprecated as soon as possible. scc_attrs = ('\t\t<SccProjectName>%s</SccProjectName>\n' '\t\t<SccLocalPath>%s</SccLocalPath>\n' % (scc_project_name, scc_local_path_legacy)) else: self.dspglobals = self.dspglobals.replace('%(scc_attrs)s', '') self.file.write(self.dspheader % locals()) self.file.write('\t<ItemGroup Label="ProjectConfigurations">\n') confkeys = sorted(self.configs.keys()) for kind in confkeys: variant = self.configs[kind].variant platform = self.configs[kind].platform self.file.write(self.dspconfiguration % locals()) self.file.write('\t</ItemGroup>\n') self.file.write(self.dspglobals % locals()) def PrintProject(self): name = self.name confkeys = sorted(self.configs.keys()) self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\n') for kind in confkeys: variant = self.configs[kind].variant platform = self.configs[kind].platform self.file.write(V10DSPPropertyGroupCondition % locals()) self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\n') self.file.write('\t<ImportGroup Label="ExtensionSettings">\n') self.file.write('\t</ImportGroup>\n') for kind in confkeys: variant = self.configs[kind].variant platform = self.configs[kind].platform self.file.write(V10DSPImportGroupCondition % locals()) self.file.write('\t<PropertyGroup Label="UserMacros" />\n') self.file.write('\t<PropertyGroup>\n') self.file.write('\t<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>\n') for kind in confkeys: variant = self.configs[kind].variant platform = self.configs[kind].platform outdir = self.configs[kind].outdir buildtarget = self.configs[kind].buildtarget runfile = self.configs[kind].runfile cmdargs = self.configs[kind].cmdargs env_has_buildtarget = 'MSVSBUILDTARGET' in self.env if not env_has_buildtarget: self.env['MSVSBUILDTARGET'] = buildtarget starting = 'echo Starting SCons && ' if cmdargs: cmdargs = ' ' + cmdargs else: cmdargs = '' buildcmd = xmlify(starting + self.env.subst('$MSVSBUILDCOM', 1) + cmdargs) rebuildcmd = xmlify(starting + self.env.subst('$MSVSREBUILDCOM', 1) + cmdargs) cleancmd = xmlify(starting + self.env.subst('$MSVSCLEANCOM', 1) + cmdargs) # This isn't perfect; CPPDEFINES and CPPPATH can contain $TARGET and $SOURCE, # so they could vary depending on the command being generated. This code # assumes they don't. preprocdefs = xmlify(';'.join(processDefines(self.env.get('CPPDEFINES', [])))) includepath_Dirs = processIncludes(self.env.get('CPPPATH', []), self.env, None, None) includepath = xmlify(';'.join([str(x) for x in includepath_Dirs])) if not env_has_buildtarget: del self.env['MSVSBUILDTARGET'] self.file.write(V10DSPCommandLine % locals()) self.file.write('\t</PropertyGroup>\n') #filter settings in MSVS 2010 are stored in separate file self.filtersabs = self.dspabs + '.filters' try: self.filters_file = open(self.filtersabs, 'w') except IOError, detail: raise SCons.Errors.InternalError('Unable to open "' + self.filtersabs + '" for writing:' + str(detail)) self.filters_file.write('<?xml version="1.0" encoding="utf-8"?>\n' '<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n') self.PrintSourceFiles() self.filters_file.write('</Project>') self.filters_file.close() self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\n' '\t<ImportGroup Label="ExtensionTargets">\n' '\t</ImportGroup>\n' '</Project>\n') if self.nokeep == 0: # now we pickle some data and add it to the file -- MSDEV will ignore it. pdata = pickle.dumps(self.configs,1) pdata = base64.encodestring(pdata) self.file.write('<!-- SCons Data:\n' + pdata + '\n') pdata = pickle.dumps(self.sources,1) pdata = base64.encodestring(pdata) self.file.write(pdata + '-->\n') def printFilters(self, hierarchy, name): sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower()) for key, value in sorteditems: if SCons.Util.is_Dict(value): filter_name = name + '\\' + key self.filters_file.write('\t\t<Filter Include="%s">\n' '\t\t\t<UniqueIdentifier>%s</UniqueIdentifier>\n' '\t\t</Filter>\n' % (filter_name, _generateGUID(self.dspabs, filter_name))) self.printFilters(value, filter_name) def printSources(self, hierarchy, kind, commonprefix, filter_name): keywords = {'Source Files': 'ClCompile', 'Header Files': 'ClInclude', 'Local Headers': 'ClInclude', 'Resource Files': 'None', 'Other Files': 'None'} sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower()) # First folders, then files for key, value in sorteditems: if SCons.Util.is_Dict(value): self.printSources(value, kind, commonprefix, filter_name + '\\' + key) for key, value in sorteditems: if SCons.Util.is_String(value): file = value if commonprefix: file = os.path.join(commonprefix, value) file = os.path.normpath(file) self.file.write('\t\t<%s Include="%s" />\n' % (keywords[kind], file)) self.filters_file.write('\t\t<%s Include="%s">\n' '\t\t\t<Filter>%s</Filter>\n' '\t\t</%s>\n' % (keywords[kind], file, filter_name, keywords[kind])) def PrintSourceFiles(self): categories = {'Source Files': 'cpp;c;cxx;l;y;def;odl;idl;hpj;bat', 'Header Files': 'h;hpp;hxx;hm;inl', 'Local Headers': 'h;hpp;hxx;hm;inl', 'Resource Files': 'r;rc;ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe', 'Other Files': ''} cats = sorted([k for k in categories.keys() if self.sources[k]], key = lambda a: a.lower()) # print vcxproj.filters file first self.filters_file.write('\t<ItemGroup>\n') for kind in cats: self.filters_file.write('\t\t<Filter Include="%s">\n' '\t\t\t<UniqueIdentifier>{7b42d31d-d53c-4868-8b92-ca2bc9fc052f}</UniqueIdentifier>\n' '\t\t\t<Extensions>%s</Extensions>\n' '\t\t</Filter>\n' % (kind, categories[kind])) # First remove any common prefix sources = self.sources[kind] commonprefix = None s = list(map(os.path.normpath, sources)) # take the dirname because the prefix may include parts # of the filenames (e.g. if you have 'dir\abcd' and # 'dir\acde' then the cp will be 'dir\a' ) cp = os.path.dirname( os.path.commonprefix(s) ) if cp and s[0][len(cp)] == os.sep: # +1 because the filename starts after the separator sources = [s[len(cp)+1:] for s in sources] commonprefix = cp hierarchy = makeHierarchy(sources) self.printFilters(hierarchy, kind) self.filters_file.write('\t</ItemGroup>\n') # then print files and filters for kind in cats: self.file.write('\t<ItemGroup>\n') self.filters_file.write('\t<ItemGroup>\n') # First remove any common prefix sources = self.sources[kind] commonprefix = None s = list(map(os.path.normpath, sources)) # take the dirname because the prefix may include parts # of the filenames (e.g. if you have 'dir\abcd' and # 'dir\acde' then the cp will be 'dir\a' ) cp = os.path.dirname( os.path.commonprefix(s) ) if cp and s[0][len(cp)] == os.sep: # +1 because the filename starts after the separator sources = [s[len(cp)+1:] for s in sources] commonprefix = cp hierarchy = makeHierarchy(sources) self.printSources(hierarchy, kind, commonprefix, kind) self.file.write('\t</ItemGroup>\n') self.filters_file.write('\t</ItemGroup>\n') # add the SConscript file outside of the groups self.file.write('\t<ItemGroup>\n' '\t\t<None Include="%s" />\n' #'\t\t<None Include="SConstruct" />\n' '\t</ItemGroup>\n' % str(self.sconscript)) def Parse(self): print "_GenerateV10DSP.Parse()" def Build(self): try: self.file = open(self.dspabs, 'w') except IOError, detail: raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail)) else: self.PrintHeader() self.PrintProject() self.file.close() class _DSWGenerator(object): """ Base class for DSW generators """ def __init__(self, dswfile, source, env): self.dswfile = os.path.normpath(str(dswfile)) self.dsw_folder_path = os.path.dirname(os.path.abspath(self.dswfile)) self.env = env if 'projects' not in env: raise SCons.Errors.UserError("You must specify a 'projects' argument to create an MSVSSolution.") projects = env['projects'] if not SCons.Util.is_List(projects): raise SCons.Errors.InternalError("The 'projects' argument must be a list of nodes.") projects = SCons.Util.flatten(projects) if len(projects) < 1: raise SCons.Errors.UserError("You must specify at least one project to create an MSVSSolution.") self.dspfiles = list(map(str, projects)) if 'name' in self.env: self.name = self.env['name'] else: self.name = os.path.basename(SCons.Util.splitext(self.dswfile)[0]) self.name = self.env.subst(self.name) def Build(self): pass class _GenerateV7DSW(_DSWGenerator): """Generates a Solution file for MSVS .NET""" def __init__(self, dswfile, source, env): _DSWGenerator.__init__(self, dswfile, source, env) self.file = None self.version = self.env['MSVS_VERSION'] self.version_num, self.suite = msvs_parse_version(self.version) self.versionstr = '7.00' if self.version_num >= 11.0: self.versionstr = '12.0' elif self.version_num >= 10.0: self.versionstr = '11.00' elif self.version_num >= 9.0: self.versionstr = '10.00' elif self.version_num >= 8.0: self.versionstr = '9.00' elif self.version_num >= 7.1: self.versionstr = '8.00' if 'slnguid' in env and env['slnguid']: self.slnguid = env['slnguid'] else: self.slnguid = _generateGUID(dswfile, self.name) self.configs = {} self.nokeep = 0 if 'nokeep' in env and env['variant'] != 0: self.nokeep = 1 if self.nokeep == 0 and os.path.exists(self.dswfile): self.Parse() def AddConfig(self, variant, dswfile=dswfile): config = Config() match = re.match('(.*)\|(.*)', variant) if match: config.variant = match.group(1) config.platform = match.group(2) else: config.variant = variant config.platform = 'Win32' self.configs[variant] = config print "Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dswfile) + "'" if 'variant' not in env: raise SCons.Errors.InternalError("You must specify a 'variant' argument (i.e. 'Debug' or " +\ "'Release') to create an MSVS Solution File.") elif SCons.Util.is_String(env['variant']): AddConfig(self, env['variant']) elif SCons.Util.is_List(env['variant']): for variant in env['variant']: AddConfig(self, variant) self.platforms = [] for key in self.configs.keys(): platform = self.configs[key].platform if not platform in self.platforms: self.platforms.append(platform) def GenerateProjectFilesInfo(self): for dspfile in self.dspfiles: dsp_folder_path, name = os.path.split(dspfile) dsp_folder_path = os.path.abspath(dsp_folder_path) dsp_relative_folder_path = os.path.relpath(dsp_folder_path, self.dsw_folder_path) if dsp_relative_folder_path == os.curdir: dsp_relative_file_path = name else: dsp_relative_file_path = os.path.join(dsp_relative_folder_path, name) dspfile_info = {'NAME': name, 'GUID': _generateGUID(dspfile, ''), 'FOLDER_PATH': dsp_folder_path, 'FILE_PATH': dspfile, 'SLN_RELATIVE_FOLDER_PATH': dsp_relative_folder_path, 'SLN_RELATIVE_FILE_PATH': dsp_relative_file_path} self.dspfiles_info.append(dspfile_info) self.dspfiles_info = [] GenerateProjectFilesInfo(self) def Parse(self): try: dswfile = open(self.dswfile,'r') except IOError: return # doesn't exist yet, so can't add anything to configs. line = dswfile.readline() while line: if line[:9] == "EndGlobal": break line = dswfile.readline() line = dswfile.readline() datas = line while line: line = dswfile.readline() datas = datas + line # OK, we've found our little pickled cache of data. try: datas = base64.decodestring(datas) data = pickle.loads(datas) except KeyboardInterrupt: raise except: return # unable to unpickle any data for some reason self.configs.update(data) def PrintSolution(self): """Writes a solution file""" self.file.write('Microsoft Visual Studio Solution File, Format Version %s\n' % self.versionstr) if self.versionstr >= 11.0: self.file.write('# Visual Studio 11\n') elif self.version_num >= 10.0: self.file.write('# Visual Studio 2010\n') elif self.version_num >= 9.0: self.file.write('# Visual Studio 2008\n') elif self.version_num >= 8.0: self.file.write('# Visual Studio 2005\n') for dspinfo in self.dspfiles_info: name = dspinfo['NAME'] base, suffix = SCons.Util.splitext(name) if suffix == '.vcproj': name = base self.file.write('Project("%s") = "%s", "%s", "%s"\n' % (external_makefile_guid, name, dspinfo['SLN_RELATIVE_FILE_PATH'], dspinfo['GUID'])) if self.version_num >= 7.1 and self.version_num < 8.0: self.file.write('\tProjectSection(ProjectDependencies) = postProject\n' '\tEndProjectSection\n') self.file.write('EndProject\n') self.file.write('Global\n') env = self.env if 'MSVS_SCC_PROVIDER' in env: scc_number_of_projects = len(self.dspfiles) + 1 slnguid = self.slnguid scc_provider = env.get('MSVS_SCC_PROVIDER', '').replace(' ', r'\u0020') scc_project_name = env.get('MSVS_SCC_PROJECT_NAME', '').replace(' ', r'\u0020') scc_connection_root = env.get('MSVS_SCC_CONNECTION_ROOT', os.curdir) scc_local_path = os.path.relpath(scc_connection_root, self.dsw_folder_path).replace('\\', '\\\\') self.file.write('\tGlobalSection(SourceCodeControl) = preSolution\n' '\t\tSccNumberOfProjects = %(scc_number_of_projects)d\n' '\t\tSccProjectName0 = %(scc_project_name)s\n' '\t\tSccLocalPath0 = %(scc_local_path)s\n' '\t\tSccProvider0 = %(scc_provider)s\n' '\t\tCanCheckoutShared = true\n' % locals()) sln_relative_path_from_scc = os.path.relpath(self.dsw_folder_path, scc_connection_root) if sln_relative_path_from_scc != os.curdir: self.file.write('\t\tSccProjectFilePathRelativizedFromConnection0 = %s\\\\\n' % sln_relative_path_from_scc.replace('\\', '\\\\')) if self.version_num < 8.0: # When present, SolutionUniqueID is automatically removed by VS 2005 # TODO: check for Visual Studio versions newer than 2005 self.file.write('\t\tSolutionUniqueID = %s\n' % slnguid) for dspinfo in self.dspfiles_info: i = self.dspfiles_info.index(dspinfo) + 1 dsp_relative_file_path = dspinfo['SLN_RELATIVE_FILE_PATH'].replace('\\', '\\\\') dsp_scc_relative_folder_path = os.path.relpath(dspinfo['FOLDER_PATH'], scc_connection_root).replace('\\', '\\\\') self.file.write('\t\tSccProjectUniqueName%(i)s = %(dsp_relative_file_path)s\n' '\t\tSccLocalPath%(i)d = %(scc_local_path)s\n' '\t\tCanCheckoutShared = true\n' '\t\tSccProjectFilePathRelativizedFromConnection%(i)s = %(dsp_scc_relative_folder_path)s\\\\\n' % locals()) self.file.write('\tEndGlobalSection\n') if self.version_num >= 8.0: self.file.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n') else: self.file.write('\tGlobalSection(SolutionConfiguration) = preSolution\n') confkeys = sorted(self.configs.keys()) cnt = 0 for name in confkeys: variant = self.configs[name].variant platform = self.configs[name].platform if self.version_num >= 8.0: self.file.write('\t\t%s|%s = %s|%s\n' % (variant, platform, variant, platform)) else: self.file.write('\t\tConfigName.%d = %s\n' % (cnt, variant)) cnt = cnt + 1 self.file.write('\tEndGlobalSection\n') if self.version_num <= 7.1: self.file.write('\tGlobalSection(ProjectDependencies) = postSolution\n' '\tEndGlobalSection\n') if self.version_num >= 8.0: self.file.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n') else: self.file.write('\tGlobalSection(ProjectConfiguration) = postSolution\n') for name in confkeys: variant = self.configs[name].variant platform = self.configs[name].platform if self.version_num >= 8.0: for dspinfo in self.dspfiles_info: guid = dspinfo['GUID'] self.file.write('\t\t%s.%s|%s.ActiveCfg = %s|%s\n' '\t\t%s.%s|%s.Build.0 = %s|%s\n' % (guid,variant,platform,variant,platform,guid,variant,platform,variant,platform)) else: for dspinfo in self.dspfiles_info: guid = dspinfo['GUID'] self.file.write('\t\t%s.%s.ActiveCfg = %s|%s\n' '\t\t%s.%s.Build.0 = %s|%s\n' %(guid,variant,variant,platform,guid,variant,variant,platform)) self.file.write('\tEndGlobalSection\n') if self.version_num >= 8.0: self.file.write('\tGlobalSection(SolutionProperties) = preSolution\n' '\t\tHideSolutionNode = FALSE\n' '\tEndGlobalSection\n') else: self.file.write('\tGlobalSection(ExtensibilityGlobals) = postSolution\n' '\tEndGlobalSection\n' '\tGlobalSection(ExtensibilityAddIns) = postSolution\n' '\tEndGlobalSection\n') self.file.write('EndGlobal\n') if self.nokeep == 0: pdata = pickle.dumps(self.configs,1) pdata = base64.encodestring(pdata) self.file.write(pdata + '\n') def Build(self): try: self.file = open(self.dswfile,'w') except IOError, detail: raise SCons.Errors.InternalError('Unable to open "' + self.dswfile + '" for writing:' + str(detail)) else: self.PrintSolution() self.file.close() V6DSWHeader = """\ Microsoft Developer Studio Workspace File, Format Version 6.00 # WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! ############################################################################### Project: "%(name)s"="%(dspfile)s" - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Global: Package=<5> {{{ }}} Package=<3> {{{ }}} ############################################################################### """ class _GenerateV6DSW(_DSWGenerator): """Generates a Workspace file for MSVS 6.0""" def PrintWorkspace(self): """ writes a DSW file """ name = self.name dspfile = os.path.relpath(self.dspfiles[0], self.dsw_folder_path) self.file.write(V6DSWHeader % locals()) def Build(self): try: self.file = open(self.dswfile,'w') except IOError, detail: raise SCons.Errors.InternalError('Unable to open "' + self.dswfile + '" for writing:' + str(detail)) else: self.PrintWorkspace() self.file.close() def GenerateDSP(dspfile, source, env): """Generates a Project file based on the version of MSVS that is being used""" version_num = 6.0 if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) if version_num >= 10.0: g = _GenerateV10DSP(dspfile, source, env) g.Build() elif version_num >= 7.0: g = _GenerateV7DSP(dspfile, source, env) g.Build() else: g = _GenerateV6DSP(dspfile, source, env) g.Build() def GenerateDSW(dswfile, source, env): """Generates a Solution/Workspace file based on the version of MSVS that is being used""" version_num = 6.0 if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) if version_num >= 7.0: g = _GenerateV7DSW(dswfile, source, env) g.Build() else: g = _GenerateV6DSW(dswfile, source, env) g.Build() ############################################################################## # Above here are the classes and functions for generation of # DSP/DSW/SLN/VCPROJ files. ############################################################################## def GetMSVSProjectSuffix(target, source, env, for_signature): return env['MSVS']['PROJECTSUFFIX'] def GetMSVSSolutionSuffix(target, source, env, for_signature): return env['MSVS']['SOLUTIONSUFFIX'] def GenerateProject(target, source, env): # generate the dsp file, according to the version of MSVS. builddspfile = target[0] dspfile = builddspfile.srcnode() # this detects whether or not we're using a VariantDir if not dspfile is builddspfile: try: bdsp = open(str(builddspfile), "w+") except IOError, detail: print 'Unable to open "' + str(dspfile) + '" for writing:',detail,'\n' raise bdsp.write("This is just a placeholder file.\nThe real project file is here:\n%s\n" % dspfile.get_abspath()) GenerateDSP(dspfile, source, env) if env.get('auto_build_solution', 1): builddswfile = target[1] dswfile = builddswfile.srcnode() if not dswfile is builddswfile: try: bdsw = open(str(builddswfile), "w+") except IOError, detail: print 'Unable to open "' + str(dspfile) + '" for writing:',detail,'\n' raise bdsw.write("This is just a placeholder file.\nThe real workspace file is here:\n%s\n" % dswfile.get_abspath()) GenerateDSW(dswfile, source, env) def GenerateSolution(target, source, env): GenerateDSW(target[0], source, env) def projectEmitter(target, source, env): """Sets up the DSP dependencies.""" # todo: Not sure what sets source to what user has passed as target, # but this is what happens. When that is fixed, we also won't have # to make the user always append env['MSVSPROJECTSUFFIX'] to target. if source[0] == target[0]: source = [] # make sure the suffix is correct for the version of MSVS we're running. (base, suff) = SCons.Util.splitext(str(target[0])) suff = env.subst('$MSVSPROJECTSUFFIX') target[0] = base + suff if not source: source = 'prj_inputs:' source = source + env.subst('$MSVSSCONSCOM', 1) source = source + env.subst('$MSVSENCODING', 1) # Project file depends on CPPDEFINES and CPPPATH preprocdefs = xmlify(';'.join(processDefines(env.get('CPPDEFINES', [])))) includepath_Dirs = processIncludes(env.get('CPPPATH', []), env, None, None) includepath = xmlify(';'.join([str(x) for x in includepath_Dirs])) source = source + "; ppdefs:%s incpath:%s"%(preprocdefs, includepath) if 'buildtarget' in env and env['buildtarget'] != None: if SCons.Util.is_String(env['buildtarget']): source = source + ' "%s"' % env['buildtarget'] elif SCons.Util.is_List(env['buildtarget']): for bt in env['buildtarget']: if SCons.Util.is_String(bt): source = source + ' "%s"' % bt else: try: source = source + ' "%s"' % bt.get_abspath() except AttributeError: raise SCons.Errors.InternalError("buildtarget can be a string, a node, a list of strings or nodes, or None") else: try: source = source + ' "%s"' % env['buildtarget'].get_abspath() except AttributeError: raise SCons.Errors.InternalError("buildtarget can be a string, a node, a list of strings or nodes, or None") if 'outdir' in env and env['outdir'] != None: if SCons.Util.is_String(env['outdir']): source = source + ' "%s"' % env['outdir'] elif SCons.Util.is_List(env['outdir']): for s in env['outdir']: if SCons.Util.is_String(s): source = source + ' "%s"' % s else: try: source = source + ' "%s"' % s.get_abspath() except AttributeError: raise SCons.Errors.InternalError("outdir can be a string, a node, a list of strings or nodes, or None") else: try: source = source + ' "%s"' % env['outdir'].get_abspath() except AttributeError: raise SCons.Errors.InternalError("outdir can be a string, a node, a list of strings or nodes, or None") if 'name' in env: if SCons.Util.is_String(env['name']): source = source + ' "%s"' % env['name'] else: raise SCons.Errors.InternalError("name must be a string") if 'variant' in env: if SCons.Util.is_String(env['variant']): source = source + ' "%s"' % env['variant'] elif SCons.Util.is_List(env['variant']): for variant in env['variant']: if SCons.Util.is_String(variant): source = source + ' "%s"' % variant else: raise SCons.Errors.InternalError("name must be a string or a list of strings") else: raise SCons.Errors.InternalError("variant must be a string or a list of strings") else: raise SCons.Errors.InternalError("variant must be specified") for s in _DSPGenerator.srcargs: if s in env: if SCons.Util.is_String(env[s]): source = source + ' "%s' % env[s] elif SCons.Util.is_List(env[s]): for t in env[s]: if SCons.Util.is_String(t): source = source + ' "%s"' % t else: raise SCons.Errors.InternalError(s + " must be a string or a list of strings") else: raise SCons.Errors.InternalError(s + " must be a string or a list of strings") source = source + ' "%s"' % str(target[0]) source = [SCons.Node.Python.Value(source)] targetlist = [target[0]] sourcelist = source if env.get('auto_build_solution', 1): env['projects'] = [env.File(t).srcnode() for t in targetlist] t, s = solutionEmitter(target, target, env) targetlist = targetlist + t return (targetlist, sourcelist) def solutionEmitter(target, source, env): """Sets up the DSW dependencies.""" # todo: Not sure what sets source to what user has passed as target, # but this is what happens. When that is fixed, we also won't have # to make the user always append env['MSVSSOLUTIONSUFFIX'] to target. if source[0] == target[0]: source = [] # make sure the suffix is correct for the version of MSVS we're running. (base, suff) = SCons.Util.splitext(str(target[0])) suff = env.subst('$MSVSSOLUTIONSUFFIX') target[0] = base + suff if not source: source = 'sln_inputs:' if 'name' in env: if SCons.Util.is_String(env['name']): source = source + ' "%s"' % env['name'] else: raise SCons.Errors.InternalError("name must be a string") if 'variant' in env: if SCons.Util.is_String(env['variant']): source = source + ' "%s"' % env['variant'] elif SCons.Util.is_List(env['variant']): for variant in env['variant']: if SCons.Util.is_String(variant): source = source + ' "%s"' % variant else: raise SCons.Errors.InternalError("name must be a string or a list of strings") else: raise SCons.Errors.InternalError("variant must be a string or a list of strings") else: raise SCons.Errors.InternalError("variant must be specified") if 'slnguid' in env: if SCons.Util.is_String(env['slnguid']): source = source + ' "%s"' % env['slnguid'] else: raise SCons.Errors.InternalError("slnguid must be a string") if 'projects' in env: if SCons.Util.is_String(env['projects']): source = source + ' "%s"' % env['projects'] elif SCons.Util.is_List(env['projects']): for t in env['projects']: if SCons.Util.is_String(t): source = source + ' "%s"' % t source = source + ' "%s"' % str(target[0]) source = [SCons.Node.Python.Value(source)] return ([target[0]], source) projectAction = SCons.Action.Action(GenerateProject, None) solutionAction = SCons.Action.Action(GenerateSolution, None) projectBuilder = SCons.Builder.Builder(action = '$MSVSPROJECTCOM', suffix = '$MSVSPROJECTSUFFIX', emitter = projectEmitter) solutionBuilder = SCons.Builder.Builder(action = '$MSVSSOLUTIONCOM', suffix = '$MSVSSOLUTIONSUFFIX', emitter = solutionEmitter) default_MSVS_SConscript = None def generate(env): """Add Builders and construction variables for Microsoft Visual Studio project files to an Environment.""" try: env['BUILDERS']['MSVSProject'] except KeyError: env['BUILDERS']['MSVSProject'] = projectBuilder try: env['BUILDERS']['MSVSSolution'] except KeyError: env['BUILDERS']['MSVSSolution'] = solutionBuilder env['MSVSPROJECTCOM'] = projectAction env['MSVSSOLUTIONCOM'] = solutionAction if SCons.Script.call_stack: # XXX Need to find a way to abstract this; the build engine # shouldn't depend on anything in SCons.Script. env['MSVSSCONSCRIPT'] = SCons.Script.call_stack[0].sconscript else: global default_MSVS_SConscript if default_MSVS_SConscript is None: default_MSVS_SConscript = env.File('SConstruct') env['MSVSSCONSCRIPT'] = default_MSVS_SConscript env['MSVSSCONS'] = '"%s" -c "%s"' % (python_executable, getExecScriptMain(env)) env['MSVSSCONSFLAGS'] = '-C "${MSVSSCONSCRIPT.dir.abspath}" -f ${MSVSSCONSCRIPT.name}' env['MSVSSCONSCOM'] = '$MSVSSCONS $MSVSSCONSFLAGS' env['MSVSBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"' env['MSVSREBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"' env['MSVSCLEANCOM'] = '$MSVSSCONSCOM -c "$MSVSBUILDTARGET"' # Set-up ms tools paths for default version msvc_setup_env_once(env) if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) else: (version_num, suite) = (7.0, None) # guess at a default if 'MSVS' not in env: env['MSVS'] = {} if (version_num < 7.0): env['MSVS']['PROJECTSUFFIX'] = '.dsp' env['MSVS']['SOLUTIONSUFFIX'] = '.dsw' elif (version_num < 10.0): env['MSVS']['PROJECTSUFFIX'] = '.vcproj' env['MSVS']['SOLUTIONSUFFIX'] = '.sln' else: env['MSVS']['PROJECTSUFFIX'] = '.vcxproj' env['MSVS']['SOLUTIONSUFFIX'] = '.sln' if (version_num >= 10.0): env['MSVSENCODING'] = 'utf-8' else: env['MSVSENCODING'] = 'Windows-1252' env['GET_MSVSPROJECTSUFFIX'] = GetMSVSProjectSuffix env['GET_MSVSSOLUTIONSUFFIX'] = GetMSVSSolutionSuffix env['MSVSPROJECTSUFFIX'] = '${GET_MSVSPROJECTSUFFIX}' env['MSVSSOLUTIONSUFFIX'] = '${GET_MSVSSOLUTIONSUFFIX}' env['SCONS_HOME'] = os.environ.get('SCONS_HOME') def exists(env): return msvc_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.JavaCommon Stuff for processing Java. """ # # 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/JavaCommon.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import re java_parsing = 1 default_java_version = '1.4' if java_parsing: # Parse Java files for class names. # # This is a really cool parser from Charles Crain # that finds appropriate class names in Java source. # A regular expression that will find, in a java file: # newlines; # double-backslashes; # a single-line comment "//"; # single or double quotes preceeded by a backslash; # single quotes, double quotes, open or close braces, semi-colons, # periods, open or close parentheses; # floating-point numbers; # any alphanumeric token (keyword, class name, specifier); # any alphanumeric token surrounded by angle brackets (generics); # the multi-line comment begin and end tokens /* and */; # array declarations "[]". _reToken = re.compile(r'(\n|\\\\|//|\\[\'"]|[\'"\{\}\;\.\(\)]|' + r'\d*\.\d*|[A-Za-z_][\w\$\.]*|<[A-Za-z_]\w+>|' + r'/\*|\*/|\[\])') class OuterState(object): """The initial state for parsing a Java file for classes, interfaces, and anonymous inner classes.""" def __init__(self, version=default_java_version): if not version in ('1.1', '1.2', '1.3','1.4', '1.5', '1.6', '5', '6'): msg = "Java version %s not supported" % version raise NotImplementedError(msg) self.version = version self.listClasses = [] self.listOutputs = [] self.stackBrackets = [] self.brackets = 0 self.nextAnon = 1 self.localClasses = [] self.stackAnonClassBrackets = [] self.anonStacksStack = [[0]] self.package = None def trace(self): pass def __getClassState(self): try: return self.classState except AttributeError: ret = ClassState(self) self.classState = ret return ret def __getPackageState(self): try: return self.packageState except AttributeError: ret = PackageState(self) self.packageState = ret return ret def __getAnonClassState(self): try: return self.anonState except AttributeError: self.outer_state = self ret = SkipState(1, AnonClassState(self)) self.anonState = ret return ret def __getSkipState(self): try: return self.skipState except AttributeError: ret = SkipState(1, self) self.skipState = ret return ret def __getAnonStack(self): return self.anonStacksStack[-1] def openBracket(self): self.brackets = self.brackets + 1 def closeBracket(self): self.brackets = self.brackets - 1 if len(self.stackBrackets) and \ self.brackets == self.stackBrackets[-1]: self.listOutputs.append('$'.join(self.listClasses)) self.localClasses.pop() self.listClasses.pop() self.anonStacksStack.pop() self.stackBrackets.pop() if len(self.stackAnonClassBrackets) and \ self.brackets == self.stackAnonClassBrackets[-1]: self.__getAnonStack().pop() self.stackAnonClassBrackets.pop() def parseToken(self, token): if token[:2] == '//': return IgnoreState('\n', self) elif token == '/*': return IgnoreState('*/', self) elif token == '{': self.openBracket() elif token == '}': self.closeBracket() elif token in [ '"', "'" ]: return IgnoreState(token, self) elif token == "new": # anonymous inner class if len(self.listClasses) > 0: return self.__getAnonClassState() return self.__getSkipState() # Skip the class name elif token in ['class', 'interface', 'enum']: if len(self.listClasses) == 0: self.nextAnon = 1 self.stackBrackets.append(self.brackets) return self.__getClassState() elif token == 'package': return self.__getPackageState() elif token == '.': # Skip the attribute, it might be named "class", in which # case we don't want to treat the following token as # an inner class name... return self.__getSkipState() return self def addAnonClass(self): """Add an anonymous inner class""" if self.version in ('1.1', '1.2', '1.3', '1.4'): clazz = self.listClasses[0] self.listOutputs.append('%s$%d' % (clazz, self.nextAnon)) elif self.version in ('1.5', '1.6', '5', '6'): self.stackAnonClassBrackets.append(self.brackets) className = [] className.extend(self.listClasses) self.__getAnonStack()[-1] = self.__getAnonStack()[-1] + 1 for anon in self.__getAnonStack(): className.append(str(anon)) self.listOutputs.append('$'.join(className)) self.nextAnon = self.nextAnon + 1 self.__getAnonStack().append(0) def setPackage(self, package): self.package = package class AnonClassState(object): """A state that looks for anonymous inner classes.""" def __init__(self, old_state): # outer_state is always an instance of OuterState self.outer_state = old_state.outer_state self.old_state = old_state self.brace_level = 0 def parseToken(self, token): # This is an anonymous class if and only if the next # non-whitespace token is a bracket. Everything between # braces should be parsed as normal java code. if token[:2] == '//': return IgnoreState('\n', self) elif token == '/*': return IgnoreState('*/', self) elif token == '\n': return self elif token[0] == '<' and token[-1] == '>': return self elif token == '(': self.brace_level = self.brace_level + 1 return self if self.brace_level > 0: if token == 'new': # look further for anonymous inner class return SkipState(1, AnonClassState(self)) elif token in [ '"', "'" ]: return IgnoreState(token, self) elif token == ')': self.brace_level = self.brace_level - 1 return self if token == '{': self.outer_state.addAnonClass() return self.old_state.parseToken(token) class SkipState(object): """A state that will skip a specified number of tokens before reverting to the previous state.""" def __init__(self, tokens_to_skip, old_state): self.tokens_to_skip = tokens_to_skip self.old_state = old_state def parseToken(self, token): self.tokens_to_skip = self.tokens_to_skip - 1 if self.tokens_to_skip < 1: return self.old_state return self class ClassState(object): """A state we go into when we hit a class or interface keyword.""" def __init__(self, outer_state): # outer_state is always an instance of OuterState self.outer_state = outer_state def parseToken(self, token): # the next non-whitespace token should be the name of the class if token == '\n': return self # If that's an inner class which is declared in a method, it # requires an index prepended to the class-name, e.g. # 'Foo$1Inner' (Tigris Issue 2087) if self.outer_state.localClasses and \ self.outer_state.stackBrackets[-1] > \ self.outer_state.stackBrackets[-2]+1: locals = self.outer_state.localClasses[-1] try: idx = locals[token] locals[token] = locals[token]+1 except KeyError: locals[token] = 1 token = str(locals[token]) + token self.outer_state.localClasses.append({}) self.outer_state.listClasses.append(token) self.outer_state.anonStacksStack.append([0]) return self.outer_state class IgnoreState(object): """A state that will ignore all tokens until it gets to a specified token.""" def __init__(self, ignore_until, old_state): self.ignore_until = ignore_until self.old_state = old_state def parseToken(self, token): if self.ignore_until == token: return self.old_state return self class PackageState(object): """The state we enter when we encounter the package keyword. We assume the next token will be the package name.""" def __init__(self, outer_state): # outer_state is always an instance of OuterState self.outer_state = outer_state def parseToken(self, token): self.outer_state.setPackage(token) return self.outer_state def parse_java_file(fn, version=default_java_version): return parse_java(open(fn, 'r').read(), version) def parse_java(contents, version=default_java_version, trace=None): """Parse a .java file and return a double of package directory, plus a list of .class files that compiling that .java file will produce""" package = None initial = OuterState(version) currstate = initial for token in _reToken.findall(contents): # The regex produces a bunch of groups, but only one will # have anything in it. currstate = currstate.parseToken(token) if trace: trace(token, currstate) if initial.package: package = initial.package.replace('.', os.sep) return (package, initial.listOutputs) else: # Don't actually parse Java files for class names. # # We might make this a configurable option in the future if # Java-file parsing takes too long (although it shouldn't relative # to how long the Java compiler itself seems to take...). def parse_java_file(fn): """ "Parse" a .java file. This actually just splits the file name, so the assumption here is that the file name matches the public class name, and that the path to the file is the same as the package name. """ return os.path.split(file) # 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.dvips Tool-specific initialization for dvips. 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/dvips.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Tool.dvipdf import SCons.Util def DviPsFunction(target = None, source= None, env=None): result = SCons.Tool.dvipdf.DviPdfPsFunction(PSAction,target,source,env) return result def DviPsStrFunction(target = None, source= None, env=None): """A strfunction for dvipdf that returns the appropriate command string for the no_exec options.""" if env.GetOption("no_exec"): result = env.subst('$PSCOM',0,target,source) else: result = '' return result PSAction = None DVIPSAction = None PSBuilder = None def generate(env): """Add Builders and construction variables for dvips to an Environment.""" global PSAction if PSAction is None: PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR') global DVIPSAction if DVIPSAction is None: DVIPSAction = SCons.Action.Action(DviPsFunction, strfunction = DviPsStrFunction) global PSBuilder if PSBuilder is None: PSBuilder = SCons.Builder.Builder(action = PSAction, prefix = '$PSPREFIX', suffix = '$PSSUFFIX', src_suffix = '.dvi', src_builder = 'DVI', single_source=True) env['BUILDERS']['PostScript'] = PSBuilder env['DVIPS'] = 'dvips' env['DVIPSFLAGS'] = SCons.Util.CLVar('') # I'm not quite sure I got the directories and filenames right for variant_dir # We need to be in the correct directory for the sake of latex \includegraphics eps included files. env['PSCOM'] = 'cd ${TARGET.dir} && $DVIPS $DVIPSFLAGS -o ${TARGET.file} ${SOURCE.file}' env['PSPREFIX'] = '' env['PSSUFFIX'] = '.ps' def exists(env): SCons.Tool.tex.generate_darwin(env) return env.Detect('dvips') # 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
# 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
# # 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
"""SCons.Defaults Builders and other things for the local site. Here's where we'll duplicate the functionality of autoconf until we move it into the installation procedure or use something like qmconf. The code that reads the registry to find MSVC components was borrowed from distutils.msvccompiler. """ # # 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/Defaults.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import errno import shutil import stat import time import sys import SCons.Action import SCons.Builder import SCons.CacheDir import SCons.Environment import SCons.PathList import SCons.Subst import SCons.Tool # A placeholder for a default Environment (for fetching source files # from source code management systems and the like). This must be # initialized later, after the top-level directory is set by the calling # interface. _default_env = None # Lazily instantiate the default environment so the overhead of creating # it doesn't apply when it's not needed. def _fetch_DefaultEnvironment(*args, **kw): """ Returns the already-created default construction environment. """ global _default_env return _default_env def DefaultEnvironment(*args, **kw): """ Initial public entry point for creating the default construction Environment. After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the initialized default construction environment without checking for its existence. (This function still exists with its _default_check because someone else (*cough* Script/__init__.py *cough*) may keep a reference to this function. So we can't use the fully functional idiom of having the name originally be a something that *only* creates the construction environment and then overwrites the name.) """ global _default_env if not _default_env: import SCons.Util _default_env = SCons.Environment.Environment(*args, **kw) if SCons.Util.md5: _default_env.Decider('MD5') else: _default_env.Decider('timestamp-match') global DefaultEnvironment DefaultEnvironment = _fetch_DefaultEnvironment _default_env._CacheDir_path = None return _default_env # Emitters for setting the shared attribute on object files, # and an action for checking that all of the source files # going into a shared library are, in fact, shared. def StaticObjectEmitter(target, source, env): for tgt in target: tgt.attributes.shared = None return (target, source) def SharedObjectEmitter(target, source, env): for tgt in target: tgt.attributes.shared = 1 return (target, source) def SharedFlagChecker(source, target, env): same = env.subst('$STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME') if same == '0' or same == '' or same == 'False': for src in source: try: shared = src.attributes.shared except AttributeError: shared = None if not shared: raise SCons.Errors.UserError("Source file: %s is static and is not compatible with shared target: %s" % (src, target[0])) SharedCheck = SCons.Action.Action(SharedFlagChecker, None) # Some people were using these variable name before we made # SourceFileScanner part of the public interface. Don't break their # SConscript files until we've given them some fair warning and a # transition period. CScan = SCons.Tool.CScanner DScan = SCons.Tool.DScanner LaTeXScan = SCons.Tool.LaTeXScanner ObjSourceScan = SCons.Tool.SourceFileScanner ProgScan = SCons.Tool.ProgramScanner # These aren't really tool scanners, so they don't quite belong with # the rest of those in Tool/__init__.py, but I'm not sure where else # they should go. Leave them here for now. import SCons.Scanner.Dir DirScanner = SCons.Scanner.Dir.DirScanner() DirEntryScanner = SCons.Scanner.Dir.DirEntryScanner() # Actions for common languages. CAction = SCons.Action.Action("$CCCOM", "$CCCOMSTR") ShCAction = SCons.Action.Action("$SHCCCOM", "$SHCCCOMSTR") CXXAction = SCons.Action.Action("$CXXCOM", "$CXXCOMSTR") ShCXXAction = SCons.Action.Action("$SHCXXCOM", "$SHCXXCOMSTR") ASAction = SCons.Action.Action("$ASCOM", "$ASCOMSTR") ASPPAction = SCons.Action.Action("$ASPPCOM", "$ASPPCOMSTR") LinkAction = SCons.Action.Action("$LINKCOM", "$LINKCOMSTR") ShLinkAction = SCons.Action.Action("$SHLINKCOM", "$SHLINKCOMSTR") LdModuleLinkAction = SCons.Action.Action("$LDMODULECOM", "$LDMODULECOMSTR") # Common tasks that we allow users to perform in platform-independent # ways by creating ActionFactory instances. ActionFactory = SCons.Action.ActionFactory def get_paths_str(dest): # If dest is a list, we need to manually call str() on each element if SCons.Util.is_List(dest): elem_strs = [] for element in dest: elem_strs.append('"' + str(element) + '"') return '[' + ', '.join(elem_strs) + ']' else: return '"' + str(dest) + '"' def chmod_func(dest, mode): SCons.Node.FS.invalidate_node_memos(dest) if not SCons.Util.is_List(dest): dest = [dest] for element in dest: os.chmod(str(element), mode) def chmod_strfunc(dest, mode): return 'Chmod(%s, 0%o)' % (get_paths_str(dest), mode) Chmod = ActionFactory(chmod_func, chmod_strfunc) def copy_func(dest, src): SCons.Node.FS.invalidate_node_memos(dest) if SCons.Util.is_List(src) and os.path.isdir(dest): for file in src: shutil.copy2(file, dest) return 0 elif os.path.isfile(src): return shutil.copy2(src, dest) else: return shutil.copytree(src, dest, 1) Copy = ActionFactory(copy_func, lambda dest, src: 'Copy("%s", "%s")' % (dest, src), convert=str) def delete_func(dest, must_exist=0): SCons.Node.FS.invalidate_node_memos(dest) if not SCons.Util.is_List(dest): dest = [dest] for entry in dest: entry = str(entry) # os.path.exists returns False with broken links that exist entry_exists = os.path.exists(entry) or os.path.islink(entry) if not entry_exists and not must_exist: continue # os.path.isdir returns True when entry is a link to a dir if os.path.isdir(entry) and not os.path.islink(entry): shutil.rmtree(entry, 1) continue os.unlink(entry) def delete_strfunc(dest, must_exist=0): return 'Delete(%s)' % get_paths_str(dest) Delete = ActionFactory(delete_func, delete_strfunc) def mkdir_func(dest): SCons.Node.FS.invalidate_node_memos(dest) if not SCons.Util.is_List(dest): dest = [dest] for entry in dest: try: os.makedirs(str(entry)) except os.error, e: p = str(entry) if (e.args[0] == errno.EEXIST or (sys.platform=='win32' and e.args[0]==183)) \ and os.path.isdir(str(entry)): pass # not an error if already exists else: raise Mkdir = ActionFactory(mkdir_func, lambda dir: 'Mkdir(%s)' % get_paths_str(dir)) def move_func(dest, src): SCons.Node.FS.invalidate_node_memos(dest) SCons.Node.FS.invalidate_node_memos(src) shutil.move(src, dest) Move = ActionFactory(move_func, lambda dest, src: 'Move("%s", "%s")' % (dest, src), convert=str) def touch_func(dest): SCons.Node.FS.invalidate_node_memos(dest) if not SCons.Util.is_List(dest): dest = [dest] for file in dest: file = str(file) mtime = int(time.time()) if os.path.exists(file): atime = os.path.getatime(file) else: open(file, 'w') atime = mtime os.utime(file, (atime, mtime)) Touch = ActionFactory(touch_func, lambda file: 'Touch(%s)' % get_paths_str(file)) # Internal utility functions def _concat(prefix, list, suffix, env, f=lambda x: x, target=None, source=None): """ Creates a new list from 'list' by first interpolating each element in the list using the 'env' dictionary and then calling f on the list, and finally calling _concat_ixes to concatenate 'prefix' and 'suffix' onto each element of the list. """ if not list: return list l = f(SCons.PathList.PathList(list).subst_path(env, target, source)) if l is not None: list = l return _concat_ixes(prefix, list, suffix, env) def _concat_ixes(prefix, list, suffix, env): """ Creates a new list from 'list' by concatenating the 'prefix' and 'suffix' arguments onto each element of the list. A trailing space on 'prefix' or leading space on 'suffix' will cause them to be put into separate list elements rather than being concatenated. """ result = [] # ensure that prefix and suffix are strings prefix = str(env.subst(prefix, SCons.Subst.SUBST_RAW)) suffix = str(env.subst(suffix, SCons.Subst.SUBST_RAW)) for x in list: if isinstance(x, SCons.Node.FS.File): result.append(x) continue x = str(x) if x: if prefix: if prefix[-1] == ' ': result.append(prefix[:-1]) elif x[:len(prefix)] != prefix: x = prefix + x result.append(x) if suffix: if suffix[0] == ' ': result.append(suffix[1:]) elif x[-len(suffix):] != suffix: result[-1] = result[-1]+suffix return result def _stripixes(prefix, itms, suffix, stripprefixes, stripsuffixes, env, c=None): """ This is a wrapper around _concat()/_concat_ixes() that checks for the existence of prefixes or suffixes on list items and strips them where it finds them. This is used by tools (like the GNU linker) that need to turn something like 'libfoo.a' into '-lfoo'. """ if not itms: return itms if not callable(c): env_c = env['_concat'] if env_c != _concat and callable(env_c): # There's a custom _concat() method in the construction # environment, and we've allowed people to set that in # the past (see test/custom-concat.py), so preserve the # backwards compatibility. c = env_c else: c = _concat_ixes stripprefixes = list(map(env.subst, SCons.Util.flatten(stripprefixes))) stripsuffixes = list(map(env.subst, SCons.Util.flatten(stripsuffixes))) stripped = [] for l in SCons.PathList.PathList(itms).subst_path(env, None, None): if isinstance(l, SCons.Node.FS.File): stripped.append(l) continue if not SCons.Util.is_String(l): l = str(l) for stripprefix in stripprefixes: lsp = len(stripprefix) if l[:lsp] == stripprefix: l = l[lsp:] # Do not strip more than one prefix break for stripsuffix in stripsuffixes: lss = len(stripsuffix) if l[-lss:] == stripsuffix: l = l[:-lss] # Do not strip more than one suffix break stripped.append(l) return c(prefix, stripped, suffix, env) def processDefines(defs): """process defines, resolving strings, lists, dictionaries, into a list of strings """ if SCons.Util.is_List(defs): l = [] for d in defs: if d is None: continue elif SCons.Util.is_List(d) or isinstance(d, tuple): if len(d) >= 2: l.append(str(d[0]) + '=' + str(d[1])) else: l.append(str(d[0])) elif SCons.Util.is_Dict(d): for macro,value in d.iteritems(): if value is not None: l.append(str(macro) + '=' + str(value)) else: l.append(str(macro)) elif SCons.Util.is_String(d): l.append(str(d)) else: raise SCons.Errors.UserError("DEFINE %s is not a list, dict, string or None."%repr(d)) elif SCons.Util.is_Dict(defs): # The items in a dictionary are stored in random order, but # if the order of the command-line options changes from # invocation to invocation, then the signature of the command # line will change and we'll get random unnecessary rebuilds. # Consequently, we have to sort the keys to ensure a # consistent order... l = [] for k,v in sorted(defs.items()): if v is None: l.append(str(k)) else: l.append(str(k) + '=' + str(v)) else: l = [str(defs)] return l def _defines(prefix, defs, suffix, env, c=_concat_ixes): """A wrapper around _concat_ixes that turns a list or string into a list of C preprocessor command-line definitions. """ return c(prefix, env.subst_path(processDefines(defs)), suffix, env) class NullCmdGenerator(object): """This is a callable class that can be used in place of other command generators if you don't want them to do anything. The __call__ method for this class simply returns the thing you instantiated it with. Example usage: env["DO_NOTHING"] = NullCmdGenerator env["LINKCOM"] = "${DO_NOTHING('$LINK $SOURCES $TARGET')}" """ def __init__(self, cmd): self.cmd = cmd def __call__(self, target, source, env, for_signature=None): return self.cmd class Variable_Method_Caller(object): """A class for finding a construction variable on the stack and calling one of its methods. We use this to support "construction variables" in our string eval()s that actually stand in for methods--specifically, use of "RDirs" in call to _concat that should actually execute the "TARGET.RDirs" method. (We used to support this by creating a little "build dictionary" that mapped RDirs to the method, but this got in the way of Memoizing construction environments, because we had to create new environment objects to hold the variables.) """ def __init__(self, variable, method): self.variable = variable self.method = method def __call__(self, *args, **kw): 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 variable = self.variable while frame: if variable in frame.f_locals: v = frame.f_locals[variable] if v: method = getattr(v, self.method) return method(*args, **kw) frame = frame.f_back return None ConstructionEnvironment = { 'BUILDERS' : {}, 'SCANNERS' : [], 'CONFIGUREDIR' : '#/.sconf_temp', 'CONFIGURELOG' : '#/config.log', 'CPPSUFFIXES' : SCons.Tool.CSuffixes, 'DSUFFIXES' : SCons.Tool.DSuffixes, 'ENV' : {}, 'IDLSUFFIXES' : SCons.Tool.IDLSuffixes, # 'LATEXSUFFIXES' : SCons.Tool.LaTeXSuffixes, # moved to the TeX tools generate functions '_concat' : _concat, '_defines' : _defines, '_stripixes' : _stripixes, '_LIBFLAGS' : '${_concat(LIBLINKPREFIX, LIBS, LIBLINKSUFFIX, __env__)}', '_LIBDIRFLAGS' : '$( ${_concat(LIBDIRPREFIX, LIBPATH, LIBDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)', '_CPPINCFLAGS' : '$( ${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)', '_CPPDEFFLAGS' : '${_defines(CPPDEFPREFIX, CPPDEFINES, CPPDEFSUFFIX, __env__)}', 'TEMPFILE' : NullCmdGenerator, 'Dir' : Variable_Method_Caller('TARGET', 'Dir'), 'Dirs' : Variable_Method_Caller('TARGET', 'Dirs'), 'File' : Variable_Method_Caller('TARGET', 'File'), 'RDirs' : Variable_Method_Caller('TARGET', 'RDirs'), } # 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
# # 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.Errors This file contains the exception classes used to handle internal and user errors in SCons. """ __revision__ = "src/engine/SCons/Errors.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util import exceptions class BuildError(Exception): """ Errors occuring while building. BuildError have the following attributes: Information about the cause of the build error: ----------------------------------------------- errstr : a description of the error message status : the return code of the action that caused the build error. Must be set to a non-zero value even if the build error is not due to an action returning a non-zero returned code. exitstatus : SCons exit status due to this build error. Must be nonzero unless due to an explicit Exit() call. Not always the same as status, since actions return a status code that should be respected, but SCons typically exits with 2 irrespective of the return value of the failed action. filename : The name of the file or directory that caused the build error. Set to None if no files are associated with this error. This might be different from the target being built. For example, failure to create the directory in which the target file will appear. It can be None if the error is not due to a particular filename. exc_info : Info about exception that caused the build error. Set to (None, None, None) if this build error is not due to an exception. Information about the cause of the location of the error: --------------------------------------------------------- node : the error occured while building this target node(s) executor : the executor that caused the build to fail (might be None if the build failures is not due to the executor failing) action : the action that caused the build to fail (might be None if the build failures is not due to the an action failure) command : the command line for the action that caused the build to fail (might be None if the build failures is not due to the an action failure) """ def __init__(self, node=None, errstr="Unknown error", status=2, exitstatus=2, filename=None, executor=None, action=None, command=None, exc_info=(None, None, None)): self.errstr = errstr self.status = status self.exitstatus = exitstatus self.filename = filename self.exc_info = exc_info self.node = node self.executor = executor self.action = action self.command = command Exception.__init__(self, node, errstr, status, exitstatus, filename, executor, action, command, exc_info) def __str__(self): if self.filename: return self.filename + ': ' + self.errstr else: return self.errstr class InternalError(Exception): pass class UserError(Exception): pass class StopError(Exception): pass class EnvironmentError(Exception): pass class MSVCError(IOError): pass class ExplicitExit(Exception): def __init__(self, node=None, status=None, *args): self.node = node self.status = status self.exitstatus = status Exception.__init__(self, *args) def convert_to_BuildError(status, exc_info=None): """ Convert any return code a BuildError Exception. `status' can either be a return code or an Exception. The buildError.status we set here will normally be used as the exit status of the "scons" process. """ if not exc_info and isinstance(status, Exception): exc_info = (status.__class__, status, None) if isinstance(status, BuildError): buildError = status buildError.exitstatus = 2 # always exit with 2 on build errors elif isinstance(status, ExplicitExit): status = status.status errstr = 'Explicit exit, status %s' % status buildError = BuildError( errstr=errstr, status=status, # might be 0, OK here exitstatus=status, # might be 0, OK here exc_info=exc_info) elif isinstance(status, (StopError, UserError)): buildError = BuildError( errstr=str(status), status=2, exitstatus=2, exc_info=exc_info) elif isinstance(status, exceptions.EnvironmentError): # If an IOError/OSError happens, raise a BuildError. # Report the name of the file or directory that caused the # error, which might be different from the target being built # (for example, failure to create the directory in which the # target file will appear). try: filename = status.filename except AttributeError: filename = None buildError = BuildError( errstr=status.strerror, status=status.errno, exitstatus=2, filename=filename, exc_info=exc_info) elif isinstance(status, Exception): buildError = BuildError( errstr='%s : %s' % (status.__class__.__name__, status), status=2, exitstatus=2, exc_info=exc_info) elif SCons.Util.is_String(status): buildError = BuildError( errstr=status, status=2, exitstatus=2) else: buildError = BuildError( errstr="Error %s" % status, status=status, exitstatus=2) #import sys #sys.stderr.write("convert_to_BuildError: status %s => (errstr %s, status %s)"%(status,buildError.errstr, buildError.status)) return buildError # 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
"""SCons.Subst SCons string substitution. """ # # 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/Subst.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import collections import re import SCons.Errors from SCons.Util import is_String, is_Sequence # Indexed by the SUBST_* constants below. _strconv = [SCons.Util.to_String_for_subst, SCons.Util.to_String_for_subst, SCons.Util.to_String_for_signature] AllowableExceptions = (IndexError, NameError) def SetAllowableExceptions(*excepts): global AllowableExceptions AllowableExceptions = [_f for _f in excepts if _f] def raise_exception(exception, target, s): name = exception.__class__.__name__ msg = "%s `%s' trying to evaluate `%s'" % (name, exception, s) if target: raise SCons.Errors.BuildError(target[0], msg) else: raise SCons.Errors.UserError(msg) class Literal(object): """A wrapper for a string. If you use this object wrapped around a string, then it will be interpreted as literal. When passed to the command interpreter, all special characters will be escaped.""" def __init__(self, lstr): self.lstr = lstr def __str__(self): return self.lstr def escape(self, escape_func): return escape_func(self.lstr) def for_signature(self): return self.lstr def is_literal(self): return 1 class SpecialAttrWrapper(object): """This is a wrapper for what we call a 'Node special attribute.' This is any of the attributes of a Node that we can reference from Environment variable substitution, such as $TARGET.abspath or $SOURCES[1].filebase. We implement the same methods as Literal so we can handle special characters, plus a for_signature method, such that we can return some canonical string during signature calculation to avoid unnecessary rebuilds.""" def __init__(self, lstr, for_signature=None): """The for_signature parameter, if supplied, will be the canonical string we return from for_signature(). Else we will simply return lstr.""" self.lstr = lstr if for_signature: self.forsig = for_signature else: self.forsig = lstr def __str__(self): return self.lstr def escape(self, escape_func): return escape_func(self.lstr) def for_signature(self): return self.forsig def is_literal(self): return 1 def quote_spaces(arg): """Generic function for putting double quotes around any string that has white space in it.""" if ' ' in arg or '\t' in arg: return '"%s"' % arg else: return str(arg) class CmdStringHolder(collections.UserString): """This is a special class used to hold strings generated by scons_subst() and scons_subst_list(). It defines a special method escape(). When passed a function with an escape algorithm for a particular platform, it will return the contained string with the proper escape sequences inserted. """ def __init__(self, cmd, literal=None): collections.UserString.__init__(self, cmd) self.literal = literal def is_literal(self): return self.literal def escape(self, escape_func, quote_func=quote_spaces): """Escape the string with the supplied function. The function is expected to take an arbitrary string, then return it with all special characters escaped and ready for passing to the command interpreter. After calling this function, the next call to str() will return the escaped string. """ if self.is_literal(): return escape_func(self.data) elif ' ' in self.data or '\t' in self.data: return quote_func(self.data) else: return self.data def escape_list(mylist, escape_func): """Escape a list of arguments by running the specified escape_func on every object in the list that has an escape() method.""" def escape(obj, escape_func=escape_func): try: e = obj.escape except AttributeError: return obj else: return e(escape_func) return list(map(escape, mylist)) class NLWrapper(object): """A wrapper class that delays turning a list of sources or targets into a NodeList until it's needed. The specified function supplied when the object is initialized is responsible for turning raw nodes into proxies that implement the special attributes like .abspath, .source, etc. This way, we avoid creating those proxies just "in case" someone is going to use $TARGET or the like, and only go through the trouble if we really have to. In practice, this might be a wash performance-wise, but it's a little cleaner conceptually... """ def __init__(self, list, func): self.list = list self.func = func def _return_nodelist(self): return self.nodelist def _gen_nodelist(self): mylist = self.list if mylist is None: mylist = [] elif not is_Sequence(mylist): mylist = [mylist] # The map(self.func) call is what actually turns # a list into appropriate proxies. self.nodelist = SCons.Util.NodeList(list(map(self.func, mylist))) self._create_nodelist = self._return_nodelist return self.nodelist _create_nodelist = _gen_nodelist class Targets_or_Sources(collections.UserList): """A class that implements $TARGETS or $SOURCES expansions by in turn wrapping a NLWrapper. This class handles the different methods used to access the list, calling the NLWrapper to create proxies on demand. 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, nl): self.nl = nl def __getattr__(self, attr): nl = self.nl._create_nodelist() return getattr(nl, attr) def __getitem__(self, i): nl = self.nl._create_nodelist() return nl[i] def __getslice__(self, i, j): nl = self.nl._create_nodelist() i = max(i, 0); j = max(j, 0) return nl[i:j] def __str__(self): nl = self.nl._create_nodelist() return str(nl) def __repr__(self): nl = self.nl._create_nodelist() return repr(nl) class Target_or_Source(object): """A class that implements $TARGET or $SOURCE expansions by in turn wrapping a NLWrapper. This class handles the different methods used to access an individual proxy Node, calling the NLWrapper to create a proxy on demand. """ def __init__(self, nl): self.nl = nl def __getattr__(self, attr): nl = self.nl._create_nodelist() try: nl0 = nl[0] except IndexError: # If there is nothing in the list, then we have no attributes to # pass through, so raise AttributeError for everything. raise AttributeError("NodeList has no attribute: %s" % attr) return getattr(nl0, attr) def __str__(self): nl = self.nl._create_nodelist() if nl: return str(nl[0]) return '' def __repr__(self): nl = self.nl._create_nodelist() if nl: return repr(nl[0]) return '' class NullNodeList(SCons.Util.NullSeq): def __call__(self, *args, **kwargs): return '' def __str__(self): return '' NullNodesList = NullNodeList() def subst_dict(target, source): """Create a dictionary for substitution of special construction variables. This translates the following special arguments: target - the target (object or array of objects), used to generate the TARGET and TARGETS construction variables source - the source (object or array of objects), used to generate the SOURCES and SOURCE construction variables """ dict = {} if target: def get_tgt_subst_proxy(thing): try: subst_proxy = thing.get_subst_proxy() except AttributeError: subst_proxy = thing # probably a string, just return it return subst_proxy tnl = NLWrapper(target, get_tgt_subst_proxy) dict['TARGETS'] = Targets_or_Sources(tnl) dict['TARGET'] = Target_or_Source(tnl) # This is a total cheat, but hopefully this dictionary goes # away soon anyway. We just let these expand to $TARGETS # because that's "good enough" for the use of ToolSurrogates # (see test/ToolSurrogate.py) to generate documentation. dict['CHANGED_TARGETS'] = '$TARGETS' dict['UNCHANGED_TARGETS'] = '$TARGETS' else: dict['TARGETS'] = NullNodesList dict['TARGET'] = NullNodesList if source: def get_src_subst_proxy(node): try: rfile = node.rfile except AttributeError: pass else: node = rfile() try: return node.get_subst_proxy() except AttributeError: return node # probably a String, just return it snl = NLWrapper(source, get_src_subst_proxy) dict['SOURCES'] = Targets_or_Sources(snl) dict['SOURCE'] = Target_or_Source(snl) # This is a total cheat, but hopefully this dictionary goes # away soon anyway. We just let these expand to $TARGETS # because that's "good enough" for the use of ToolSurrogates # (see test/ToolSurrogate.py) to generate documentation. dict['CHANGED_SOURCES'] = '$SOURCES' dict['UNCHANGED_SOURCES'] = '$SOURCES' else: dict['SOURCES'] = NullNodesList dict['SOURCE'] = NullNodesList return dict # Constants for the "mode" parameter to scons_subst_list() and # scons_subst(). SUBST_RAW gives the raw command line. SUBST_CMD # gives a command line suitable for passing to a shell. SUBST_SIG # gives a command line appropriate for calculating the signature # of a command line...if this changes, we should rebuild. SUBST_CMD = 0 SUBST_RAW = 1 SUBST_SIG = 2 _rm = re.compile(r'\$[()]') _remove = re.compile(r'\$\([^\$]*(\$[^\)][^\$]*)*\$\)') # Indexed by the SUBST_* constants above. _regex_remove = [ _rm, None, _remove ] def _rm_list(list): #return [ l for l in list if not l in ('$(', '$)') ] return [l for l in list if not l in ('$(', '$)')] def _remove_list(list): result = [] do_append = result.append for l in list: if l == '$(': do_append = lambda x: None elif l == '$)': do_append = result.append else: do_append(l) return result # Indexed by the SUBST_* constants above. _list_remove = [ _rm_list, None, _remove_list ] # Regular expressions for splitting strings and handling substitutions, # for use by the scons_subst() and scons_subst_list() functions: # # The first expression compiled matches all of the $-introduced tokens # that we need to process in some way, and is used for substitutions. # The expressions it matches are: # # "$$" # "$(" # "$)" # "$variable" [must begin with alphabetic or underscore] # "${any stuff}" # # The second expression compiled is used for splitting strings into tokens # to be processed, and it matches all of the tokens listed above, plus # the following that affect how arguments do or don't get joined together: # # " " [white space] # "non-white-space" [without any dollar signs] # "$" [single dollar sign] # _dollar_exps_str = r'\$[\$\(\)]|\$[_a-zA-Z][\.\w]*|\${[^}]*}' _dollar_exps = re.compile(r'(%s)' % _dollar_exps_str) _separate_args = re.compile(r'(%s|\s+|[^\s\$]+|\$)' % _dollar_exps_str) # This regular expression is used to replace strings of multiple white # space characters in the string result from the scons_subst() function. _space_sep = re.compile(r'[\t ]+(?![^{]*})') def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None): """Expand a string or list containing construction variable substitutions. This is the work-horse function for substitutions in file names and the like. The companion scons_subst_list() function (below) handles separating command lines into lists of arguments, so see that function if that's what you're looking for. """ if isinstance(strSubst, str) and strSubst.find('$') < 0: return strSubst class StringSubber(object): """A class to construct the results of a scons_subst() call. This binds a specific construction environment, mode, target and source with two methods (substitute() and expand()) that handle the expansion. """ def __init__(self, env, mode, conv, gvars): self.env = env self.mode = mode self.conv = conv self.gvars = gvars def expand(self, s, lvars): """Expand a single "token" as necessary, returning an appropriate string containing the expansion. This handles expanding different types of things (strings, lists, callables) appropriately. It calls the wrapper substitute() method to re-expand things as necessary, so that the results of expansions of side-by-side strings still get re-evaluated separately, not smushed together. """ if is_String(s): try: s0, s1 = s[:2] except (IndexError, ValueError): return s if s0 != '$': return s if s1 == '$': return '$' elif s1 in '()': return s else: key = s[1:] if key[0] == '{' or key.find('.') >= 0: if key[0] == '{': key = key[1:-1] try: s = eval(key, self.gvars, lvars) except KeyboardInterrupt: raise except Exception, e: if e.__class__ in AllowableExceptions: return '' raise_exception(e, lvars['TARGETS'], s) else: if key in lvars: s = lvars[key] elif key in self.gvars: s = self.gvars[key] elif not NameError in AllowableExceptions: raise_exception(NameError(key), lvars['TARGETS'], s) else: return '' # Before re-expanding the result, handle # recursive expansion by copying the local # variable dictionary and overwriting a null # string for the value of the variable name # we just expanded. # # This could potentially be optimized by only # copying lvars when s contains more expansions, # but lvars is usually supposed to be pretty # small, and deeply nested variable expansions # are probably more the exception than the norm, # so it should be tolerable for now. lv = lvars.copy() var = key.split('.')[0] lv[var] = '' return self.substitute(s, lv) elif is_Sequence(s): def func(l, conv=self.conv, substitute=self.substitute, lvars=lvars): return conv(substitute(l, lvars)) return list(map(func, s)) elif callable(s): try: s = s(target=lvars['TARGETS'], source=lvars['SOURCES'], env=self.env, for_signature=(self.mode != SUBST_CMD)) except TypeError: # This probably indicates that it's a callable # object that doesn't match our calling arguments # (like an Action). if self.mode == SUBST_RAW: return s s = self.conv(s) return self.substitute(s, lvars) elif s is None: return '' else: return s def substitute(self, args, lvars): """Substitute expansions in an argument or list of arguments. This serves as a wrapper for splitting up a string into separate tokens. """ if is_String(args) and not isinstance(args, CmdStringHolder): args = str(args) # In case it's a UserString. try: def sub_match(match): return self.conv(self.expand(match.group(1), lvars)) result = _dollar_exps.sub(sub_match, args) except TypeError: # If the internal conversion routine doesn't return # strings (it could be overridden to return Nodes, for # example), then the 1.5.2 re module will throw this # exception. Back off to a slower, general-purpose # algorithm that works for all data types. args = _separate_args.findall(args) result = [] for a in args: result.append(self.conv(self.expand(a, lvars))) if len(result) == 1: result = result[0] else: result = ''.join(map(str, result)) return result else: return self.expand(args, lvars) if conv is None: conv = _strconv[mode] # Doing this every time is a bit of a waste, since the Executor # has typically already populated the OverrideEnvironment with # $TARGET/$SOURCE variables. We're keeping this (for now), though, # because it supports existing behavior that allows us to call # an Action directly with an arbitrary target+source pair, which # we use in Tool/tex.py to handle calling $BIBTEX when necessary. # If we dropped that behavior (or found another way to cover it), # we could get rid of this call completely and just rely on the # Executor setting the variables. if 'TARGET' not in lvars: d = subst_dict(target, source) if d: lvars = lvars.copy() lvars.update(d) # We're (most likely) going to eval() things. If Python doesn't # find a __builtins__ value in the global dictionary used for eval(), # it copies the current global values for you. Avoid this by # setting it explicitly and then deleting, so we don't pollute the # construction environment Dictionary(ies) that are typically used # for expansion. gvars['__builtins__'] = __builtins__ ss = StringSubber(env, mode, conv, gvars) result = ss.substitute(strSubst, lvars) try: del gvars['__builtins__'] except KeyError: pass if is_String(result): # Remove $(-$) pairs and any stuff in between, # if that's appropriate. remove = _regex_remove[mode] if remove: result = remove.sub('', result) if mode != SUBST_RAW: # Compress strings of white space characters into # a single space. result = _space_sep.sub(' ', result).strip() elif is_Sequence(result): remove = _list_remove[mode] if remove: result = remove(result) return result #Subst_List_Strings = {} def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None): """Substitute construction variables in a string (or list or other object) and separate the arguments into a command list. The companion scons_subst() function (above) handles basic substitutions within strings, so see that function instead if that's what you're looking for. """ # try: # Subst_List_Strings[strSubst] = Subst_List_Strings[strSubst] + 1 # except KeyError: # Subst_List_Strings[strSubst] = 1 # import SCons.Debug # SCons.Debug.caller_trace(1) class ListSubber(collections.UserList): """A class to construct the results of a scons_subst_list() call. Like StringSubber, this class binds a specific construction environment, mode, target and source with two methods (substitute() and expand()) that handle the expansion. In addition, however, this class is used to track the state of the result(s) we're gathering so we can do the appropriate thing whenever we have to append another word to the result--start a new line, start a new word, append to the current word, etc. We do this by setting the "append" attribute to the right method so that our wrapper methods only need ever call ListSubber.append(), and the rest of the object takes care of doing the right thing internally. """ def __init__(self, env, mode, conv, gvars): collections.UserList.__init__(self, []) self.env = env self.mode = mode self.conv = conv self.gvars = gvars if self.mode == SUBST_RAW: self.add_strip = lambda x: self.append(x) else: self.add_strip = lambda x: None self.in_strip = None self.next_line() def expand(self, s, lvars, within_list): """Expand a single "token" as necessary, appending the expansion to the current result. This handles expanding different types of things (strings, lists, callables) appropriately. It calls the wrapper substitute() method to re-expand things as necessary, so that the results of expansions of side-by-side strings still get re-evaluated separately, not smushed together. """ if is_String(s): try: s0, s1 = s[:2] except (IndexError, ValueError): self.append(s) return if s0 != '$': self.append(s) return if s1 == '$': self.append('$') elif s1 == '(': self.open_strip('$(') elif s1 == ')': self.close_strip('$)') else: key = s[1:] if key[0] == '{' or key.find('.') >= 0: if key[0] == '{': key = key[1:-1] try: s = eval(key, self.gvars, lvars) except KeyboardInterrupt: raise except Exception, e: if e.__class__ in AllowableExceptions: return raise_exception(e, lvars['TARGETS'], s) else: if key in lvars: s = lvars[key] elif key in self.gvars: s = self.gvars[key] elif not NameError in AllowableExceptions: raise_exception(NameError(), lvars['TARGETS'], s) else: return # Before re-expanding the result, handle # recursive expansion by copying the local # variable dictionary and overwriting a null # string for the value of the variable name # we just expanded. lv = lvars.copy() var = key.split('.')[0] lv[var] = '' self.substitute(s, lv, 0) self.this_word() elif is_Sequence(s): for a in s: self.substitute(a, lvars, 1) self.next_word() elif callable(s): try: s = s(target=lvars['TARGETS'], source=lvars['SOURCES'], env=self.env, for_signature=(self.mode != SUBST_CMD)) except TypeError: # This probably indicates that it's a callable # object that doesn't match our calling arguments # (like an Action). if self.mode == SUBST_RAW: self.append(s) return s = self.conv(s) self.substitute(s, lvars, within_list) elif s is None: self.this_word() else: self.append(s) def substitute(self, args, lvars, within_list): """Substitute expansions in an argument or list of arguments. This serves as a wrapper for splitting up a string into separate tokens. """ if is_String(args) and not isinstance(args, CmdStringHolder): args = str(args) # In case it's a UserString. args = _separate_args.findall(args) for a in args: if a[0] in ' \t\n\r\f\v': if '\n' in a: self.next_line() elif within_list: self.append(a) else: self.next_word() else: self.expand(a, lvars, within_list) else: self.expand(args, lvars, within_list) def next_line(self): """Arrange for the next word to start a new line. This is like starting a new word, except that we have to append another line to the result.""" collections.UserList.append(self, []) self.next_word() def this_word(self): """Arrange for the next word to append to the end of the current last word in the result.""" self.append = self.add_to_current_word def next_word(self): """Arrange for the next word to start a new word.""" self.append = self.add_new_word def add_to_current_word(self, x): """Append the string x to the end of the current last word in the result. If that is not possible, then just add it as a new word. Make sure the entire concatenated string inherits the object attributes of x (in particular, the escape function) by wrapping it as CmdStringHolder.""" if not self.in_strip or self.mode != SUBST_SIG: try: current_word = self[-1][-1] except IndexError: self.add_new_word(x) else: # All right, this is a hack and it should probably # be refactored out of existence in the future. # The issue is that we want to smoosh words together # and make one file name that gets escaped if # we're expanding something like foo$EXTENSION, # but we don't want to smoosh them together if # it's something like >$TARGET, because then we'll # treat the '>' like it's part of the file name. # So for now, just hard-code looking for the special # command-line redirection characters... try: last_char = str(current_word)[-1] except IndexError: last_char = '\0' if last_char in '<>|': self.add_new_word(x) else: y = current_word + x # We used to treat a word appended to a literal # as a literal itself, but this caused problems # with interpreting quotes around space-separated # targets on command lines. Removing this makes # none of the "substantive" end-to-end tests fail, # so we'll take this out but leave it commented # for now in case there's a problem not covered # by the test cases and we need to resurrect this. #literal1 = self.literal(self[-1][-1]) #literal2 = self.literal(x) y = self.conv(y) if is_String(y): #y = CmdStringHolder(y, literal1 or literal2) y = CmdStringHolder(y, None) self[-1][-1] = y def add_new_word(self, x): if not self.in_strip or self.mode != SUBST_SIG: literal = self.literal(x) x = self.conv(x) if is_String(x): x = CmdStringHolder(x, literal) self[-1].append(x) self.append = self.add_to_current_word def literal(self, x): try: l = x.is_literal except AttributeError: return None else: return l() def open_strip(self, x): """Handle the "open strip" $( token.""" self.add_strip(x) self.in_strip = 1 def close_strip(self, x): """Handle the "close strip" $) token.""" self.add_strip(x) self.in_strip = None if conv is None: conv = _strconv[mode] # Doing this every time is a bit of a waste, since the Executor # has typically already populated the OverrideEnvironment with # $TARGET/$SOURCE variables. We're keeping this (for now), though, # because it supports existing behavior that allows us to call # an Action directly with an arbitrary target+source pair, which # we use in Tool/tex.py to handle calling $BIBTEX when necessary. # If we dropped that behavior (or found another way to cover it), # we could get rid of this call completely and just rely on the # Executor setting the variables. if 'TARGET' not in lvars: d = subst_dict(target, source) if d: lvars = lvars.copy() lvars.update(d) # We're (most likely) going to eval() things. If Python doesn't # find a __builtins__ value in the global dictionary used for eval(), # it copies the current global values for you. Avoid this by # setting it explicitly and then deleting, so we don't pollute the # construction environment Dictionary(ies) that are typically used # for expansion. gvars['__builtins__'] = __builtins__ ls = ListSubber(env, mode, conv, gvars) ls.substitute(strSubst, lvars, 0) try: del gvars['__builtins__'] except KeyError: pass return ls.data def scons_subst_once(strSubst, env, key): """Perform single (non-recursive) substitution of a single construction variable keyword. This is used when setting a variable when copying or overriding values in an Environment. We want to capture (expand) the old value before we override it, so people can do things like: env2 = env.Clone(CCFLAGS = '$CCFLAGS -g') We do this with some straightforward, brute-force code here... """ if isinstance(strSubst, str) and strSubst.find('$') < 0: return strSubst matchlist = ['$' + key, '${' + key + '}'] val = env.get(key, '') def sub_match(match, val=val, matchlist=matchlist): a = match.group(1) if a in matchlist: a = val if is_Sequence(a): return ' '.join(map(str, a)) else: return str(a) if is_Sequence(strSubst): result = [] for arg in strSubst: if is_String(arg): if arg in matchlist: arg = val if is_Sequence(arg): result.extend(arg) else: result.append(arg) else: result.append(_dollar_exps.sub(sub_match, arg)) else: result.append(arg) return result elif is_String(strSubst): return _dollar_exps.sub(sub_match, strSubst) else: return strSubst # 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/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
"""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
"""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
# # 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/CacheDir.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """ CacheDir support """ import os.path import stat import sys import SCons.Action cache_enabled = True cache_debug = False cache_force = False cache_show = False def CacheRetrieveFunc(target, source, env): t = target[0] fs = t.fs cd = env.get_CacheDir() cachedir, cachefile = cd.cachepath(t) if not fs.exists(cachefile): cd.CacheDebug('CacheRetrieve(%s): %s not in cache\n', t, cachefile) return 1 cd.CacheDebug('CacheRetrieve(%s): retrieving from %s\n', t, cachefile) if SCons.Action.execute_actions: if fs.islink(cachefile): fs.symlink(fs.readlink(cachefile), t.path) else: env.copy_from_cache(cachefile, t.path) st = fs.stat(cachefile) fs.chmod(t.path, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE) return 0 def CacheRetrieveString(target, source, env): t = target[0] fs = t.fs cd = env.get_CacheDir() cachedir, cachefile = cd.cachepath(t) if t.fs.exists(cachefile): return "Retrieved `%s' from cache" % t.path return None CacheRetrieve = SCons.Action.Action(CacheRetrieveFunc, CacheRetrieveString) CacheRetrieveSilent = SCons.Action.Action(CacheRetrieveFunc, None) def CachePushFunc(target, source, env): t = target[0] if t.nocache: return fs = t.fs cd = env.get_CacheDir() cachedir, cachefile = cd.cachepath(t) if fs.exists(cachefile): # Don't bother copying it if it's already there. Note that # usually this "shouldn't happen" because if the file already # existed in cache, we'd have retrieved the file from there, # not built it. This can happen, though, in a race, if some # other person running the same build pushes their copy to # the cache after we decide we need to build it but before our # build completes. cd.CacheDebug('CachePush(%s): %s already exists in cache\n', t, cachefile) return cd.CacheDebug('CachePush(%s): pushing to %s\n', t, cachefile) tempfile = cachefile+'.tmp'+str(os.getpid()) errfmt = "Unable to copy %s to cache. Cache file is %s" if not fs.isdir(cachedir): try: fs.makedirs(cachedir) except EnvironmentError: # We may have received an exception because another process # has beaten us creating the directory. if not fs.isdir(cachedir): msg = errfmt % (str(target), cachefile) raise SCons.Errors.EnvironmentError(msg) try: if fs.islink(t.path): fs.symlink(fs.readlink(t.path), tempfile) else: fs.copy2(t.path, tempfile) fs.rename(tempfile, cachefile) st = fs.stat(t.path) fs.chmod(cachefile, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE) except EnvironmentError: # It's possible someone else tried writing the file at the # same time we did, or else that there was some problem like # the CacheDir being on a separate file system that's full. # In any case, inability to push a file to cache doesn't affect # the correctness of the build, so just print a warning. msg = errfmt % (str(target), cachefile) SCons.Warnings.warn(SCons.Warnings.CacheWriteErrorWarning, msg) CachePush = SCons.Action.Action(CachePushFunc, None) class CacheDir(object): def __init__(self, path): try: import hashlib except ImportError: msg = "No hashlib or MD5 module available, CacheDir() not supported" SCons.Warnings.warn(SCons.Warnings.NoMD5ModuleWarning, msg) self.path = None else: self.path = path self.current_cache_debug = None self.debugFP = None def CacheDebug(self, fmt, target, cachefile): if cache_debug != self.current_cache_debug: if cache_debug == '-': self.debugFP = sys.stdout elif cache_debug: self.debugFP = open(cache_debug, 'w') else: self.debugFP = None self.current_cache_debug = cache_debug if self.debugFP: self.debugFP.write(fmt % (target, os.path.split(cachefile)[1])) def is_enabled(self): return (cache_enabled and not self.path is None) def cachepath(self, node): """ """ if not self.is_enabled(): return None, None sig = node.get_cachedir_bsig() subdir = sig[0].upper() dir = os.path.join(self.path, subdir) return dir, os.path.join(dir, sig) def retrieve(self, node): """ This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Note that there's a special trick here with the execute flag (one that's not normally done for other actions). Basically if the user requested a no_exec (-n) build, then SCons.Action.execute_actions is set to 0 and when any action is called, it does its showing but then just returns zero instead of actually calling the action execution operation. The problem for caching is that if the file does NOT exist in cache then the CacheRetrieveString won't return anything to show for the task, but the Action.__call__ won't call CacheRetrieveFunc; instead it just returns zero, which makes the code below think that the file *was* successfully retrieved from the cache, therefore it doesn't do any subsequent building. However, the CacheRetrieveString didn't print anything because it didn't actually exist in the cache, and no more build actions will be performed, so the user just sees nothing. The fix is to tell Action.__call__ to always execute the CacheRetrieveFunc and then have the latter explicitly check SCons.Action.execute_actions itself. """ if not self.is_enabled(): return False env = node.get_build_env() if cache_show: if CacheRetrieveSilent(node, [], env, execute=1) == 0: node.build(presub=0, execute=0) return True else: if CacheRetrieve(node, [], env, execute=1) == 0: return True return False def push(self, node): if not self.is_enabled(): return return CachePush(node, [], node.get_build_env()) def push_if_forced(self, node): if cache_force: return self.push(node) # 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
"""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
"""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.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.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.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.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/PathList.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """SCons.PathList A module for handling lists of directory paths (the sort of things that get set as CPPPATH, LIBPATH, etc.) with as much caching of data and efficiency as we can while still keeping the evaluation delayed so that we Do the Right Thing (almost) regardless of how the variable is specified. """ import os import SCons.Memoize import SCons.Node import SCons.Util # # Variables to specify the different types of entries in a PathList object: # TYPE_STRING_NO_SUBST = 0 # string with no '$' TYPE_STRING_SUBST = 1 # string containing '$' TYPE_OBJECT = 2 # other object def node_conv(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: if isinstance(obj, SCons.Node.Node) or SCons.Util.is_Sequence( obj ): result = obj else: result = str(obj) else: result = get() return result class _PathList(object): """ An actual PathList object. """ def __init__(self, pathlist): """ Initializes a PathList object, canonicalizing the input and pre-processing it for quicker substitution later. The stored representation of the PathList is a list of tuples containing (type, value), where the "type" is one of the TYPE_* variables defined above. We distinguish between: strings that contain no '$' and therefore need no delayed-evaluation string substitution (we expect that there will be many of these and that we therefore get a pretty big win from avoiding string substitution) strings that contain '$' and therefore need substitution (the hard case is things like '${TARGET.dir}/include', which require re-evaluation for every target + source) other objects (which may be something like an EntryProxy that needs a method called to return a Node) Pre-identifying the type of each element in the PathList up-front and storing the type in the list of tuples is intended to reduce the amount of calculation when we actually do the substitution over and over for each target. """ if SCons.Util.is_String(pathlist): pathlist = pathlist.split(os.pathsep) elif not SCons.Util.is_Sequence(pathlist): pathlist = [pathlist] pl = [] for p in pathlist: try: index = p.find('$') except (AttributeError, TypeError): type = TYPE_OBJECT else: if index == -1: type = TYPE_STRING_NO_SUBST else: type = TYPE_STRING_SUBST pl.append((type, p)) self.pathlist = tuple(pl) def __len__(self): return len(self.pathlist) def __getitem__(self, i): return self.pathlist[i] def subst_path(self, env, target, source): """ Performs construction variable substitution on a pre-digested PathList for a specific target and source. """ result = [] for type, value in self.pathlist: if type == TYPE_STRING_SUBST: value = env.subst(value, target=target, source=source, conv=node_conv) if SCons.Util.is_Sequence(value): result.extend(value) continue elif type == TYPE_OBJECT: value = node_conv(value) if value: result.append(value) return tuple(result) class PathListCache(object): """ A class to handle caching of PathList lookups. This class gets instantiated once and then deleted from the namespace, so it's used as a Singleton (although we don't enforce that in the usual Pythonic ways). We could have just made the cache a dictionary in the module namespace, but putting it in this class allows us to use the same Memoizer pattern that we use elsewhere to count cache hits and misses, which is very valuable. Lookup keys in the cache are computed by the _PathList_key() method. Cache lookup should be quick, so we don't spend cycles canonicalizing all forms of the same lookup key. For example, 'x:y' and ['x', 'y'] logically represent the same list, but we don't bother to split string representations and treat those two equivalently. (Note, however, that we do, treat lists and tuples the same.) The main type of duplication we're trying to catch will come from looking up the same path list from two different clones of the same construction environment. That is, given env2 = env1.Clone() both env1 and env2 will have the same CPPPATH value, and we can cheaply avoid re-parsing both values of CPPPATH by using the common value from this cache. """ if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass memoizer_counters = [] def __init__(self): self._memo = {} def _PathList_key(self, pathlist): """ Returns the key for memoization of PathLists. Note that we want this to be pretty quick, so we don't completely canonicalize all forms of the same list. For example, 'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically represent the same list if you're executing from $ROOT, but we're not going to bother splitting strings into path elements, or massaging strings into Nodes, to identify that equivalence. We just want to eliminate obvious redundancy from the normal case of re-using exactly the same cloned value for a path. """ if SCons.Util.is_Sequence(pathlist): pathlist = tuple(SCons.Util.flatten(pathlist)) return pathlist memoizer_counters.append(SCons.Memoize.CountDict('PathList', _PathList_key)) def PathList(self, pathlist): """ Returns the cached _PathList object for the specified pathlist, creating and caching a new object as necessary. """ pathlist = self._PathList_key(pathlist) try: memo_dict = self._memo['PathList'] except KeyError: memo_dict = {} self._memo['PathList'] = memo_dict else: try: return memo_dict[pathlist] except KeyError: pass result = _PathList(pathlist) memo_dict[pathlist] = result return result PathList = PathListCache().PathList del PathListCache # 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
#!/usr/bin/env python ''' mm extern photivo.py Passes an image to Photivo Author: Michael Munzert (mike photivo org) Bernd Schoeler (brother.john photivo org) Version: 2011.08.28 Brother John: Adjust Photivo cli 2011.01.29 Brother John: Ask user for photivo.exe and store in gimprc 2011.01.27 Brother John: Fixed failing execution of Photivo on Windows. 2011.01.02 mike: Initial version. modelled after the trace plugin (lloyd konneker, lkk, bootch at nc.rr.com) License: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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. The GNU Public License is available at http://www.gnu.org/copyleft/gpl.html ''' from gimpfu import * from platform import system import os import subprocess import Tkinter, tkFileDialog def plugin_main(image, drawable, visible): # Copy so the save operations doesn't affect the original tempimage = pdb.gimp_image_duplicate(image) if not tempimage: raise RuntimeError # Use temp file names from gimp, it reflects the user's choices in gimp.rc tempfilename = pdb.gimp_temp_name("tif") if visible == 0: # Save in temporary. Note: empty user entered file name tempdrawable = pdb.gimp_image_get_active_drawable(tempimage) else: # Get the current visible tempdrawable = pdb.gimp_layer_new_from_visible(image, tempimage, "visible") # !!! Note no run-mode first parameter, and user entered filename is empty string pdb.gimp_progress_set_text ("Saving a copy") pdb.gimp_file_save(tempimage, tempdrawable, tempfilename, "") # cleanup gimp.delete(tempimage) # delete the temporary image # Platform dependent full command string for Photivo. if system() == "Linux": # We can assume Photivo can be called with a simple photivo. command = 'photivo --load-and-delete "%s"' % (tempfilename) elif system() == "Windows": # There is no way to call Photivo without knowing exactly where it is installed. # So we ask the user for the path to photivo.exe and store it in the user's gimprc. cmdWindows = "" try: cmdWindows = pdb.gimp_gimprc_query("photivo-executable") except RuntimeError: # Catch ExecutionError when the key is not found in gimprc pass if not os.path.exists(cmdWindows): root = Tkinter.Tk() root.withdraw() # Hide the Tkinter main window so only the file dialog shows cmdWindows = tkFileDialog.askopenfilename( parent = None, title = "Where is photivo.exe located?", filetypes = [('photivo.exe','photivo.exe')], initialdir = "C:\\" ) dummy = pdb.gimp_gimprc_set("photivo-executable", cmdWindows) command = '"%s" --load-and-delete "%s"' % (cmdWindows, tempfilename) # Invoke Photivo. pdb.gimp_progress_set_text(command) pdb.gimp_progress_pulse() if system() == "Windows": child = subprocess.Popen(command) elif system() == "Linux": child = subprocess.Popen(command, shell = True) register( "python_fu_mm_extern_photivo", "Pass the image to Photivo.", "Pass the image to Photivo.", "Michael Munzert (mike photivo org)", "Copyright 2011 Michael Munzert", "2011", "<Image>/Filters/MM-Filters/_Export to Photivo ...", "*", [ (PF_RADIO, "visible", "Layer:", 1, (("new from visible", 1),("current layer",0))) ], [], plugin_main, ) main()
Python
#!/usr/bin/python # ps-to-cmyk.py -- script to convert files from [E]PS to CMYK TIFFs # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import sys, os if len (sys.argv) != 3: print "usage: %s PS-FILE OUTPUT-FILE" % sys.argv[0] sys.exit (1) in_file = sys.argv[1] out_file = sys.argv[2] pdf_file = "/tmp/ps-to-cmyk." + str (os.getpid ()) + ".pdf" # Create a PostScript converter and use it to generate a PDF # document for our input file if not CGPSConverterCreateWithoutCallbacks ().convert ( CGDataProviderCreateWithFilename (in_file), CGDataConsumerCreateWithFilename (pdf_file)): print "Error while converting %s" % in_file sys.exit (1) # Open the PDF we just created and delete the temp. file pdf = CGPDFDocumentCreateWithProvider ( CGDataProviderCreateWithFilename (pdf_file)) os.unlink (pdf_file) # Get the bounding box of the content, create a CMYK bitmap context # of the same size with a white background, and draw the PDF into # the context r = pdf.getMediaBox (1) cs = CGColorSpaceCreateWithName (kCGColorSpaceUserCMYK) ctx = CGBitmapContextCreateWithColor ( int(r.size.width), int(r.size.height), cs, (0, 0, 0, 0, 1)) ctx.drawPDFDocument (r, pdf, 1) # Output everything to the TIFF file ctx.writeToFile (out_file, kCGImageFormatTIFF)
Python
#!/usr/bin/python # bitmap.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import math # Create an RGB bitmap context, transparent black background, 256x256 cs = CGColorSpaceCreateDeviceRGB () c = CGBitmapContextCreateWithColor (256, 256, cs, (0,0,0,0)) # Draw a yellow square with a red outline in the center c.saveGState () c.setRGBStrokeColor (1,0,0,1) # red c.setRGBFillColor (1,1,0,1) # yellow c.setLineWidth (3) c.setLineJoin (kCGLineJoinBevel) c.addRect (CGRectMake (32.5, 32.5, 191, 191)) c.drawPath (kCGPathFillStroke); c.restoreGState () # Draw some text at an angle c.saveGState () c.translateCTM (128, 128) c.rotateCTM ((-30.0 / 360) * (2 * math.pi)) c.translateCTM (-128, -128) c.setRGBStrokeColor (0,0,0,1) c.setRGBFillColor (1,1,1,1) c.selectFont ("Helvetica", 36, kCGEncodingMacRoman) c.setTextPosition (40, 118) c.setTextDrawingMode (kCGTextFillStroke) c.setShadow (CGSizeMake (0,-10), 2) c.showText ("hello, world", 12) c.restoreGState () # Write the bitmap to disk in PNG format c.writeToFile ("out.png", kCGImageFormatPNG)
Python
#!/usr/bin/python # circle.py -- Simple python example to draw a circle # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import math # for pi pageRect = CGRectMake (0, 0, 612, 792) # landscape c = CGPDFContextCreateWithFilename ("circle.pdf", pageRect) c.beginPage (pageRect) c.setRGBFillColor(1.0,0.0,0.0,1.0) c.addArc(300,300,100,0,2*math.pi,1) c.fillPath() c.endPage() c.finish()
Python
#!/usr/bin/python # wedge.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import math # For old times sake -- the PostScript cookbook wedge example in python... def inch(x): return 72*x def rad(angle): return angle*math.pi/180.0 def wedge(c): c.beginPath() c.moveToPoint(0,0) c.translateCTM(1,0) c.rotateCTM(rad(16)) c.translateCTM(0, math.sin(rad(15))) c.addArc(0,0, math.sin(rad(15)), rad(-90), rad(90), 0) c.closePath() pageRect = CGRectMake (0, 0, 612, 792) # landscape c = CGPDFContextCreateWithFilename ("wedge.pdf", pageRect) c.beginPage(pageRect) c.saveGState() c.translateCTM(inch(4.25), inch(4.25)) c.scaleCTM(inch(1.75), inch(1.75)) c.setLineWidth(.02) for i in range(1,13): c.setGrayFillColor(i/12.0,1.0) c.saveGState() wedge(c) c.fillPath() c.restoreGState() c.saveGState() c.setGrayStrokeColor(0,1) wedge(c) c.strokePath() c.restoreGState() c.rotateCTM(rad(30)) c.restoreGState() c.endPage() c.finish()
Python
#!/usr/bin/python # contactsheet.py -- create contact sheet from a list of jpg files # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys, os, getopt, string, pwd, math, time from CoreGraphics import * baseCTM = 0 totSize = 0 # Generic Graphic classes # - sourceRect defines drawing coordinate system for graphic # - xform transform between this graphic and it's drawing coordinate transform # - boundingRect: computed axis-aligned bbox result of sending sourceRect through transform class Graphic: def __init__(self, sourceRect): self.sourceRect = sourceRect self.xform = CGAffineTransformIdentity def centerPoint(self): return CGPointMake(self.sourceRect.getMidX(),self.sourceRect.getMidY()).applyAffineTransform(self.xform) # drawing transform is pre multipled with new transforms (opposite of CTM) def concat(self, xform): self.xform = self.xform.concat(xform) def scaleAboutCenter(self,sx,sy): currentCenter = self.centerPoint() self.translate(-currentCenter.x, -currentCenter.y) self.xform = self.xform.concat(CGAffineTransformMakeScale(sx,sy)) self.translate(currentCenter.x, currentCenter.y) def rotateAboutCenter(self, angle): currentCenter = self.centerPoint() self.translate(-currentCenter.x, -currentCenter.y) self.xform = self.xform.concat(CGAffineTransformMakeRotation(angle*math.pi/180.0)) self.translate(currentCenter.x, currentCenter.y) def translate(self, tx, ty): self.xform = self.xform.concat(CGAffineTransformMakeTranslation(tx,ty)) def boundingRect(self): # compute bounding rect lowerLeft = CGPointMake(self.sourceRect.origin.x, self.sourceRect.origin.y) lowerLeft = lowerLeft.applyAffineTransform(self.xform) upperRight = CGPointMake(self.sourceRect.origin.x + self.sourceRect.size.width, self.sourceRect.origin.y + self.sourceRect.size.height) upperRight = upperRight.applyAffineTransform(self.xform) return CGRectMake(lowerLeft.x, lowerLeft.y, upperRight.x - lowerLeft.x, upperRight.y - lowerLeft.y).standardize() def render(self, c): c.saveGState() c.concatCTM(self.xform) self.draw(c) c.restoreGState() def centerInRect(self, rect): cx = rect.getMidX() cy = rect.getMidY() currentCenter = self.centerPoint() self.translate(cx - currentCenter.x, cy - currentCenter.y) def fitInRect(self, rect, preserveAspectRatio): self.centerInRect(rect) bbox = self.boundingRect() if(preserveAspectRatio): scale = rect.size.width/bbox.size.width; if (scale * bbox.size.height > rect.size.height): scale = rect.size.height/bbox.size.height self.scaleAboutCenter(scale,scale) else: self.scaleAboutCenter(rect.size.width/bbox.size.width, rect.size.height/bbox.size.height) class Rectangle(Graphic): def draw(self,c): c.addRect(self.sourceRect) ## return to "base space" for consistent linewidth c.saveGState() c.concatCTM(baseCTM.concat(c.getCTM().invert())) c.setLineWidth(1) c.strokePath() c.restoreGState() class Image(Graphic): def __init__(self,imageRef): self.i = imageRef Graphic.__init__(self, CGRectMake(0,0,imageRef.getWidth(), imageRef.getHeight())) def draw(self,c): c.drawImage(self.sourceRect, self.i) class TextString(Graphic): def __init__(self, rect, string, font, size, sizeToFit): # self.html = '<html><p style="font-size:%spx; font-family:%s;"> %s/p></html>\n' % (size, font, string) self.html = '<html><p <FONT="font-size:%spx; font-family:%s;"> %s/p></html>\n' % (size, font, string) self.rtf = '{\\rtf1\\mac\\ansicpg10000\\cocoartf102{\\fonttbl\\f0\\fnil\\fcharset77 %s;}\\f0\\fs%s %s}\n' % (font, size, string) if (sizeToFit) : rect = CGContextMeasureRTFTextInRect(CGDataProviderCreateWithString (self.rtf), rect) Graphic.__init__(self, rect) def draw(self,c): # tr = c.drawHTMLTextInRect (CGDataProviderCreateWithString (self.html), self.sourceRect) tr = c.drawRTFTextInRect (CGDataProviderCreateWithString (self.rtf), self.sourceRect) # helper to create an image from a filename def ImageFromFile(filename): # special case JPG files and render directly with CG -- this keeps created PDFs smaller if (os.path.splitext(filename)[1].upper() == '.JPG') : return Image(CGImageCreateWithJPEGDataProvider(CGDataProviderCreateWithFilename (filename), [0,1,0,1,0,1], 1, kCGRenderingIntentDefault)) return Image(CGImageImport (CGDataProviderCreateWithFilename (filename))) # # Contact Sheet specific classes # # # ContactSheetCell object # class ContactSheetCell(Graphic): def __init__(self, jpgFile): global totSize str = os.path.basename(jpgFile) str += "\\\n" + time.strftime('%x', time.localtime(os.path.getmtime(jpgFile))) str += "\\\n" + ('%dK' % (os.path.getsize(jpgFile)/1024)) totSize += os.path.getsize(jpgFile) self.label = TextString(CGRectMake(0,0,100,30), str , "LucidaGrande", 12, 0) self.image = ImageFromFile(jpgFile) self.image.fitInRect(CGRectMake(0,30,100,70), 1) self.border = Rectangle(CGRectMake(0,0,100,100)) Graphic.__init__(self, CGRectMake(0,0,100,100)) def draw(self,c): self.label.render(c) self.image.render(c) self.border.render(c) class ContactSheetPage(Graphic): def __init__(self, imageFiles, rect, cellSize): # create the array of cells self.cells = [ ContactSheetCell(i) for i in imageFiles] # position each cell row,col = 0,0 for cell in self.cells: x = rect.origin.x + col*cellSize if ( x + cellSize > rect.origin.x + rect.size.width) : col = 0 x = rect.origin.x row += 1 cell.fitInRect(CGRectMake(x, rect.origin.y + rect.size.height - (row + 1)*cellSize, cellSize, cellSize), 1) col += 1 Graphic.__init__(self, rect) def draw(self,c): for cell in self.cells: cell.render(c) def LayoutContactSheets(imageFiles, pageRect): rect = pageRect.inset(36,36) # use .5 inch margins nCols = int(math.ceil(math.sqrt(len(imageFiles)*rect.size.width/rect.size.height))) step = rect.size.width/nCols while (step < 72): # constrain tiles to be at least 1 inch nCols -= 1 step = rect.size.width/nCols nRows = int(math.floor(rect.size.height/step)) cellsPerPage = nRows*nCols base = 0 pages = [] while(base < len(imageFiles)): slice = imageFiles[base:base+cellsPerPage] pages.append(ContactSheetPage(slice, rect, step)) base += cellsPerPage return pages def usage (): print ''' usage: python contactsheet.py [OPTION]... JPG-FILES... Create a pdf contact sheet of JPGs. -o, --output=FILENAME ''' def main (): global baseCTM try: opts,args = getopt.getopt (sys.argv[1:], 'o:', ['output=']) except getopt.GetoptError: usage () sys.exit (1) output_file = "" page_rect = CGRectMake (0, 0, 612, 792) for o,a in opts: if o in ('-o', '--output'): output_file = a # need at least an output file if output_file == "": print "error: missing output filename" usage () sys.exit (1) c = CGPDFContextCreateWithFilename (output_file, page_rect) print "%d image files" % len(args) pages = LayoutContactSheets(args, page_rect) for page in pages: c.beginPage (page_rect) baseCTM = c.getCTM() page.render(c) c.endPage () # serialized the constructed PDF document to its file c.finish () print "Wrote output: \'%s\', %d pages, %dK bytes" % (output_file, len(pages), os.path.getsize(output_file)/1024) if __name__ == '__main__': main ()
Python
#!/usr/bin/env python # doc2pdf.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * from fnmatch import fnmatch import os, sys, getopt def usage(): print ''' usage: python doc2pdf.py [OPTION] DOCUMENT[S] Convert any of several document types to PDF: Text: .txt .? .?? RTF: .rtf HTML: .htm .html .php Word: .doc .xml .wordml Options: -f, --font-size=SIZE ''' def drawDocument(input_file, font_size): '''Convert input file into PDF, using font_size''' text = CGDataProviderCreateWithFilename(input_file) if not text: return "Error: document '%s' not found"%(input_file) (root, ext) = os.path.splitext(input_file) output_file = root + ".pdf" pageRect = CGRectMake(0, 0, 612, 792) c = CGPDFContextCreateWithFilename(output_file, pageRect) c.beginPage(pageRect) if fnmatch(ext,".txt") or fnmatch(ext,".?") or fnmatch(ext,".??"): tr = c.drawPlainTextInRect(text, pageRect, font_size) elif fnmatch(ext,".rtf"): tr = c.drawRTFTextInRect(text, pageRect, font_size) elif fnmatch(ext,".htm*") or fnmatch(ext,".php"): tr = c.drawHTMLTextInRect(text, pageRect, font_size) elif fnmatch(ext,".doc"): tr = c.drawDocFormatTextInRect(text, pageRect, font_size) elif fnmatch(ext,"*ml"): tr = c.drawWordMLFormatTextInRect(text, pageRect, font_size) else: return "Error: unknown type '%s' for '%s'"%(ext, input_file) c.endPage() c.finish() return output_file def main(): '''Parse font_size option, then convert each argument''' try: opts,args = getopt.getopt(sys.argv[1:], 'f:', ['font-size=']) except getopt.GetoptError: usage() sys.exit(1) font_size = 12.0 for(o,a) in opts: if o in('-f', '--font-size'): font_size = float(a) if len(args) < 1: usage() exit() for arg in args: print arg, "->", drawDocument(arg, font_size) # Run as main if __name__ == '__main__': main()
Python
#!/usr/bin/python # Usage: picttopdf pict-data-file # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os import string from CoreGraphics import * # we need two arguments, the zeroth argument is the name of the executable # and the first is the data file to convert if len(sys.argv) != 2: sys.stderr.write("Usage: picttopdf pict_data_file\n") sys.stderr.write("produces pict_data_file.pdf\n") sys.stderr.write("if the file suffix is .pict or .pic then it is replaced with .pdf\n") sys.exit() inFile = sys.argv[1]; if os.path.isfile(inFile): qdPict = QDPictCreateWithFilename(inFile) else: sys.stderr.write('ERROR: "'+inFile+'"' + " is not a file\n") sys.exit() if not qdPict: sys.stderr.write('ERROR: "'+inFile+'"' + " is not a PICT file!\n") sys.exit() pictRect = qdPict.getBounds(); if pictRect.size.width <= 0 or pictRect.size.height <= 0 : sys.stderr.write("Width or height of PICT bounds is zero! Can't use this picture!\n") sys.exit() result = os.path.splitext(inFile) extension = string.upper(result[1]) if (extension == ".PICT") or (extension == ".PIC"): outFile = result[0] +".pdf" else: outFile = inFile +".pdf" ctx = CGPDFContextCreateWithFilename(outFile, pictRect); if ctx: ctx.beginPage(pictRect); success = qdPict.drawToCGContext(ctx, pictRect) ctx.endPage(); ctx.finish() else: sys.stderr.write("Couldn't create PDF context for output file " + '"' + outFile + '"\n')
Python
#!/usr/bin/python # cmyk-bitmap.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * pi = 3.1415927 # Create a CYMK bitmap context with an opaque white background cs = CGColorSpaceCreateWithName (kCGColorSpaceUserCMYK) c = CGBitmapContextCreateWithColor (256, 256, cs, (0,0,0,0,1)) # Draw a yellow square with a red outline in the center c.saveGState () c.setRGBStrokeColor (1,0,0,1) # red c.setRGBFillColor (1,1,0,1) # yellow c.setLineWidth (3) c.setLineJoin (kCGLineJoinBevel) c.addRect (CGRectMake (32.5, 32.5, 191, 191)) c.drawPath (kCGPathFillStroke); c.restoreGState () # Draw some text at an angle c.saveGState () c.translateCTM (128, 128) c.rotateCTM ((-30.0 / 360) * (2 * pi)) c.translateCTM (-128, -128) c.setRGBStrokeColor (0,0,0,1) c.setRGBFillColor (1,1,1,1) c.selectFont ("Helvetica", 36, kCGEncodingMacRoman) c.setTextPosition (40, 118) c.setTextDrawingMode (kCGTextFillStroke) c.showText ("hello, world", 12) c.restoreGState () # Write the bitmap to disk as a TIFF c.writeToFile ("out.tiff", kCGImageFormatTIFF)
Python
#!/usr/bin/python # image.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import sys if len (sys.argv) >= 2: inputFile = sys.argv[1]; else: inputFile = "out.png" outputFile = "out.pdf" i = CGImageImport (CGDataProviderCreateWithFilename (inputFile)) print "Image \'%s\' size is (%d,%d)" % (inputFile, i.getWidth(), i.getHeight()) # create an output document to draw the image into pageRect = CGRectMake (0, 0, 612, 792) c = CGPDFContextCreateWithFilename (outputFile, pageRect) c.beginPage (pageRect) c.drawImage (pageRect.inset (72, 72), i) c.endPage () c.finish () print "Output PDF file created at \'%s\' " % outputFile
Python
#!/usr/bin/python # filter-pdf.py -- apply a ColorSync Filter to each page of a pdf document # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import sys, os, math, getopt, string def usage (): print ''' usage: python filter-pdf.py FILTER INPUT-PDF OUTPUT-PDF Apply a ColorSync Filter to a PDF document. ''' def main (): page_rect = CGRectMake (0, 0, 612, 792) try: opts,args = getopt.getopt (sys.argv[1:], '', []) except getopt.GetoptError: usage () sys.exit (1) if len (args) != 3: usage () sys.exit (1) filter = CGContextFilterCreateDictionary (args[0]) if not filter: print 'Unable to create context filter' sys.exit (1) pdf = CGPDFDocumentCreateWithProvider (CGDataProviderCreateWithFilename (args[1])) if not pdf: print 'Unable to open input file' sys.exit (1) c = CGPDFContextCreateWithFilename (args[2], page_rect, filter) if not c: print 'Unable to create output context' sys.exit (1) for p in range (1, pdf.getNumberOfPages () + 1): r = pdf.getMediaBox (p) c.beginPage (r) c.drawPDFDocument (r, pdf, p) c.endPage () c.finish () if __name__ == '__main__': main ()
Python
#!/usr/bin/python # circle.py -- Simple python example to draw a circle # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import math # for pi pageRect = CGRectMake (0, 0, 612, 792) # landscape c = CGPDFContextCreateWithFilename ("circle.pdf", pageRect) c.beginPage (pageRect) c.setRGBFillColor(1.0,0.0,0.0,1.0) c.addArc(300,300,100,0,2*math.pi,1) c.fillPath() c.endPage() c.finish()
Python
#!/usr/bin/python # ps-to-cmyk.py -- script to convert files from [E]PS to CMYK TIFFs # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import sys, os if len (sys.argv) != 3: print "usage: %s PS-FILE OUTPUT-FILE" % sys.argv[0] sys.exit (1) in_file = sys.argv[1] out_file = sys.argv[2] pdf_file = "/tmp/ps-to-cmyk." + str (os.getpid ()) + ".pdf" # Create a PostScript converter and use it to generate a PDF # document for our input file if not CGPSConverterCreateWithoutCallbacks ().convert ( CGDataProviderCreateWithFilename (in_file), CGDataConsumerCreateWithFilename (pdf_file)): print "Error while converting %s" % in_file sys.exit (1) # Open the PDF we just created and delete the temp. file pdf = CGPDFDocumentCreateWithProvider ( CGDataProviderCreateWithFilename (pdf_file)) os.unlink (pdf_file) # Get the bounding box of the content, create a CMYK bitmap context # of the same size with a white background, and draw the PDF into # the context r = pdf.getMediaBox (1) cs = CGColorSpaceCreateWithName (kCGColorSpaceUserCMYK) ctx = CGBitmapContextCreateWithColor ( int(r.size.width), int(r.size.height), cs, (0, 0, 0, 0, 1)) ctx.drawPDFDocument (r, pdf, 1) # Output everything to the TIFF file ctx.writeToFile (out_file, kCGImageFormatTIFF)
Python