From 340d57481935334465037d97c0db1555b70c0eb1 Mon Sep 17 00:00:00 2001 From: Luca Falavigna Date: Tue, 15 Jun 2010 09:21:32 +0000 Subject: Imported Upstream version 2.0.0 --- engine/SCons/Action.py | 147 ++- engine/SCons/Builder.py | 111 +- engine/SCons/CacheDir.py | 9 +- engine/SCons/Conftest.py | 11 +- engine/SCons/Debug.py | 63 +- engine/SCons/Defaults.py | 49 +- engine/SCons/Environment.py | 264 ++--- engine/SCons/Errors.py | 8 +- engine/SCons/Executor.py | 65 +- engine/SCons/Job.py | 34 +- engine/SCons/Memoize.py | 106 +- engine/SCons/Node/Alias.py | 13 +- engine/SCons/Node/FS.py | 248 ++-- engine/SCons/Node/Python.py | 4 +- engine/SCons/Node/__init__.py | 87 +- engine/SCons/Options/BoolOption.py | 4 +- engine/SCons/Options/EnumOption.py | 4 +- engine/SCons/Options/ListOption.py | 4 +- engine/SCons/Options/PackageOption.py | 4 +- engine/SCons/Options/PathOption.py | 16 +- engine/SCons/Options/__init__.py | 19 +- engine/SCons/PathList.py | 11 +- engine/SCons/Platform/__init__.py | 43 +- engine/SCons/Platform/aix.py | 9 +- engine/SCons/Platform/cygwin.py | 2 +- engine/SCons/Platform/darwin.py | 2 +- engine/SCons/Platform/hpux.py | 2 +- engine/SCons/Platform/irix.py | 2 +- engine/SCons/Platform/os2.py | 4 +- engine/SCons/Platform/posix.py | 27 +- engine/SCons/Platform/sunos.py | 2 +- engine/SCons/Platform/win32.py | 37 +- engine/SCons/SConf.py | 72 +- engine/SCons/SConsign.py | 24 +- engine/SCons/Scanner/C.py | 6 +- engine/SCons/Scanner/D.py | 5 +- engine/SCons/Scanner/Dir.py | 16 +- engine/SCons/Scanner/Fortran.py | 14 +- engine/SCons/Scanner/IDL.py | 2 +- engine/SCons/Scanner/LaTeX.py | 56 +- engine/SCons/Scanner/Prog.py | 8 +- engine/SCons/Scanner/RC.py | 2 +- engine/SCons/Scanner/__init__.py | 36 +- engine/SCons/Script/Interactive.py | 22 +- engine/SCons/Script/Main.py | 132 +-- engine/SCons/Script/SConsOptions.py | 65 +- engine/SCons/Script/SConscript.py | 70 +- engine/SCons/Script/__init__.py | 16 +- engine/SCons/Sig.py | 4 +- engine/SCons/Subst.py | 103 +- engine/SCons/Taskmaster.py | 79 +- engine/SCons/Tool/386asm.py | 2 +- engine/SCons/Tool/BitKeeper.py | 4 +- engine/SCons/Tool/CVS.py | 6 +- engine/SCons/Tool/FortranCommon.py | 17 +- engine/SCons/Tool/JavaCommon.py | 23 +- engine/SCons/Tool/MSCommon/__init__.py | 2 +- engine/SCons/Tool/MSCommon/arch.py | 4 +- engine/SCons/Tool/MSCommon/common.py | 62 +- engine/SCons/Tool/MSCommon/netframework.py | 10 +- engine/SCons/Tool/MSCommon/sdk.py | 22 +- engine/SCons/Tool/MSCommon/vc.py | 182 +-- engine/SCons/Tool/MSCommon/vs.py | 36 +- engine/SCons/Tool/Perforce.py | 7 +- engine/SCons/Tool/PharLapCommon.py | 15 +- engine/SCons/Tool/RCS.py | 6 +- engine/SCons/Tool/SCCS.py | 6 +- engine/SCons/Tool/Subversion.py | 6 +- engine/SCons/Tool/__init__.py | 68 +- engine/SCons/Tool/aixc++.py | 2 +- engine/SCons/Tool/aixcc.py | 2 +- engine/SCons/Tool/aixf77.py | 2 +- engine/SCons/Tool/aixlink.py | 2 +- engine/SCons/Tool/applelink.py | 2 +- engine/SCons/Tool/ar.py | 2 +- engine/SCons/Tool/as.py | 2 +- engine/SCons/Tool/bcc32.py | 3 +- engine/SCons/Tool/c++.py | 2 +- engine/SCons/Tool/cc.py | 20 +- engine/SCons/Tool/cvf.py | 2 +- engine/SCons/Tool/default.py | 2 +- engine/SCons/Tool/dmd.py | 5 +- engine/SCons/Tool/dvi.py | 2 +- engine/SCons/Tool/dvipdf.py | 5 +- engine/SCons/Tool/dvips.py | 2 +- engine/SCons/Tool/f77.py | 2 +- engine/SCons/Tool/f90.py | 2 +- engine/SCons/Tool/f95.py | 2 +- engine/SCons/Tool/filesystem.py | 6 +- engine/SCons/Tool/fortran.py | 3 +- engine/SCons/Tool/g++.py | 2 +- engine/SCons/Tool/g77.py | 2 +- engine/SCons/Tool/gas.py | 2 +- engine/SCons/Tool/gcc.py | 2 +- engine/SCons/Tool/gfortran.py | 2 +- engine/SCons/Tool/gnulink.py | 2 +- engine/SCons/Tool/gs.py | 4 +- engine/SCons/Tool/hpc++.py | 7 +- engine/SCons/Tool/hpcc.py | 2 +- engine/SCons/Tool/hplink.py | 2 +- engine/SCons/Tool/icc.py | 2 +- engine/SCons/Tool/icl.py | 6 +- engine/SCons/Tool/ifl.py | 6 +- engine/SCons/Tool/ifort.py | 10 +- engine/SCons/Tool/ilink.py | 2 +- engine/SCons/Tool/ilink32.py | 2 +- engine/SCons/Tool/install.py | 16 +- engine/SCons/Tool/intelc.py | 42 +- engine/SCons/Tool/ipkg.py | 10 +- engine/SCons/Tool/jar.py | 2 +- engine/SCons/Tool/javac.py | 36 +- engine/SCons/Tool/javah.py | 7 +- engine/SCons/Tool/latex.py | 4 +- engine/SCons/Tool/lex.py | 6 +- engine/SCons/Tool/link.py | 2 +- engine/SCons/Tool/linkloc.py | 4 +- engine/SCons/Tool/m4.py | 2 +- engine/SCons/Tool/masm.py | 2 +- engine/SCons/Tool/midl.py | 8 +- engine/SCons/Tool/mingw.py | 5 +- engine/SCons/Tool/mslib.py | 2 +- engine/SCons/Tool/mslink.py | 14 +- engine/SCons/Tool/mssdk.py | 2 +- engine/SCons/Tool/msvc.py | 17 +- engine/SCons/Tool/msvs.py | 233 ++-- engine/SCons/Tool/mwcc.py | 11 +- engine/SCons/Tool/mwld.py | 4 +- engine/SCons/Tool/nasm.py | 2 +- engine/SCons/Tool/packaging/__init__.py | 32 +- engine/SCons/Tool/packaging/ipk.py | 12 +- engine/SCons/Tool/packaging/msi.py | 27 +- engine/SCons/Tool/packaging/rpm.py | 48 +- engine/SCons/Tool/packaging/src_tarbz2.py | 2 +- engine/SCons/Tool/packaging/src_targz.py | 2 +- engine/SCons/Tool/packaging/src_zip.py | 2 +- engine/SCons/Tool/packaging/tarbz2.py | 2 +- engine/SCons/Tool/packaging/targz.py | 2 +- engine/SCons/Tool/packaging/zip.py | 2 +- engine/SCons/Tool/pdf.py | 2 +- engine/SCons/Tool/pdflatex.py | 4 +- engine/SCons/Tool/pdftex.py | 6 +- engine/SCons/Tool/qt.py | 4 +- engine/SCons/Tool/rmic.py | 5 +- engine/SCons/Tool/rpcgen.py | 2 +- engine/SCons/Tool/rpm.py | 2 +- engine/SCons/Tool/sgiar.py | 2 +- engine/SCons/Tool/sgic++.py | 2 +- engine/SCons/Tool/sgicc.py | 2 +- engine/SCons/Tool/sgilink.py | 2 +- engine/SCons/Tool/sunar.py | 2 +- engine/SCons/Tool/sunc++.py | 2 +- engine/SCons/Tool/suncc.py | 2 +- engine/SCons/Tool/sunf77.py | 2 +- engine/SCons/Tool/sunf90.py | 2 +- engine/SCons/Tool/sunf95.py | 2 +- engine/SCons/Tool/sunlink.py | 2 +- engine/SCons/Tool/swig.py | 20 +- engine/SCons/Tool/tar.py | 2 +- engine/SCons/Tool/tex.py | 38 +- engine/SCons/Tool/textfile.py | 6 +- engine/SCons/Tool/tlib.py | 2 +- engine/SCons/Tool/wix.py | 5 +- engine/SCons/Tool/yacc.py | 5 +- engine/SCons/Tool/zip.py | 13 +- engine/SCons/Util.py | 669 +++++------ engine/SCons/Variables/BoolVariable.py | 6 +- engine/SCons/Variables/EnumVariable.py | 22 +- engine/SCons/Variables/ListVariable.py | 34 +- engine/SCons/Variables/PackageVariable.py | 13 +- engine/SCons/Variables/PathVariable.py | 4 +- engine/SCons/Variables/__init__.py | 53 +- engine/SCons/Warnings.py | 98 +- engine/SCons/__init__.py | 12 +- engine/SCons/compat/__init__.py | 271 ++--- engine/SCons/compat/_scons_UserString.py | 98 -- engine/SCons/compat/_scons_builtins.py | 150 +++ engine/SCons/compat/_scons_collections.py | 45 + engine/SCons/compat/_scons_dbm.py | 45 + engine/SCons/compat/_scons_hashlib.py | 27 +- engine/SCons/compat/_scons_io.py | 45 + engine/SCons/compat/_scons_itertools.py | 124 -- engine/SCons/compat/_scons_optparse.py | 1725 ---------------------------- engine/SCons/compat/_scons_sets.py | 56 +- engine/SCons/compat/_scons_sets15.py | 176 --- engine/SCons/compat/_scons_shlex.py | 325 ------ engine/SCons/compat/_scons_subprocess.py | 55 +- engine/SCons/compat/_scons_textwrap.py | 382 ------ engine/SCons/compat/builtins.py | 187 --- engine/SCons/cpp.py | 55 +- engine/SCons/dblite.py | 57 +- engine/SCons/exitfuncs.py | 4 +- 191 files changed, 2430 insertions(+), 5756 deletions(-) delete mode 100644 engine/SCons/compat/_scons_UserString.py create mode 100644 engine/SCons/compat/_scons_builtins.py create mode 100644 engine/SCons/compat/_scons_collections.py create mode 100644 engine/SCons/compat/_scons_dbm.py create mode 100644 engine/SCons/compat/_scons_io.py delete mode 100644 engine/SCons/compat/_scons_itertools.py delete mode 100644 engine/SCons/compat/_scons_optparse.py delete mode 100644 engine/SCons/compat/_scons_sets15.py delete mode 100644 engine/SCons/compat/_scons_shlex.py delete mode 100644 engine/SCons/compat/_scons_textwrap.py delete mode 100644 engine/SCons/compat/builtins.py (limited to 'engine') diff --git a/engine/SCons/Action.py b/engine/SCons/Action.py index 3e766d9..7cad8a5 100644 --- a/engine/SCons/Action.py +++ b/engine/SCons/Action.py @@ -97,13 +97,15 @@ way for wrapping up the functions. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -__revision__ = "src/engine/SCons/Action.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Action.py 5023 2010/06/14 22:05:46 scons" + +import SCons.compat -import cPickle import dis import os +# compat layer imports "cPickle" for us if it's available. +import pickle import re -import string import sys import subprocess @@ -117,7 +119,7 @@ import SCons.Subst is_String = SCons.Util.is_String is_List = SCons.Util.is_List -class _null: +class _null(object): pass print_actions = 1 @@ -153,7 +155,7 @@ else: else: result.append(c) i = i+1 - return string.join(result, '') + return ''.join(result) strip_quotes = re.compile('^[\'"](.*)[\'"]$') @@ -208,8 +210,8 @@ def _object_contents(obj): except AttributeError: # Should be a pickable Python object. try: - return cPickle.dumps(obj) - except (cPickle.PicklingError, TypeError): + return pickle.dumps(obj) + except (pickle.PicklingError, TypeError): # This is weird, but it seems that nested classes # are unpickable. The Python docs say it should # always be a PicklingError, but some Python @@ -249,19 +251,19 @@ def _code_contents(code): # Note that we also always ignore the first entry of co_consts # which contains the function doc string. We assume that the # function does not access its doc string. - contents.append(',(' + string.join(map(_object_contents,code.co_consts[1:]),',') + ')') + contents.append(',(' + ','.join(map(_object_contents,code.co_consts[1:])) + ')') # The code contents depends on the variable names used to # accessed global variable, as changing the variable name changes # the variable actually accessed and therefore changes the # function result. - contents.append(',(' + string.join(map(_object_contents,code.co_names),',') + ')') + contents.append(',(' + ','.join(map(_object_contents,code.co_names)) + ')') # The code contents depends on its actual code!!! contents.append(',(' + str(remove_set_lineno_codes(code.co_code)) + ')') - return string.join(contents, '') + return ''.join(contents) def _function_contents(func): @@ -271,7 +273,7 @@ def _function_contents(func): # The function contents depends on the value of defaults arguments if func.func_defaults: - contents.append(',(' + string.join(map(_object_contents,func.func_defaults),',') + ')') + contents.append(',(' + ','.join(map(_object_contents,func.func_defaults)) + ')') else: contents.append(',()') @@ -284,12 +286,12 @@ def _function_contents(func): #xxx = [_object_contents(x.cell_contents) for x in closure] try: - xxx = map(lambda x: _object_contents(x.cell_contents), closure) + xxx = [_object_contents(x.cell_contents) for x in closure] except AttributeError: xxx = [] - contents.append(',(' + string.join(xxx, ',') + ')') + contents.append(',(' + ','.join(xxx) + ')') - return string.join(contents, '') + return ''.join(contents) def _actionAppend(act1, act2): @@ -299,7 +301,7 @@ def _actionAppend(act1, act2): a1 = Action(act1) a2 = Action(act2) if a1 is None or a2 is None: - raise TypeError, "Cannot append %s to %s" % (type(act1), type(act2)) + raise TypeError("Cannot append %s to %s" % (type(act1), type(act2))) if isinstance(a1, ListAction): if isinstance(a2, ListAction): return ListAction(a1.list + a2.list) @@ -353,8 +355,7 @@ def _do_create_action(act, kw): return act if is_List(act): - #TODO(1.5) return CommandAction(act, **kw) - return apply(CommandAction, (act,), kw) + return CommandAction(act, **kw) if callable(act): try: @@ -378,10 +379,9 @@ def _do_create_action(act, kw): # like a function or a CommandGenerator in that variable # instead of a string. return LazyAction(var, kw) - commands = string.split(str(act), '\n') + commands = str(act).split('\n') if len(commands) == 1: - #TODO(1.5) return CommandAction(commands[0], **kw) - return apply(CommandAction, (commands[0],), kw) + return CommandAction(commands[0], **kw) # The list of string commands may include a LazyAction, so we # reprocess them via _do_create_list_action. return _do_create_list_action(commands, kw) @@ -409,7 +409,7 @@ def Action(act, *args, **kw): return _do_create_list_action(act, kw) return _do_create_action(act, kw) -class ActionBase: +class ActionBase(object): """Base class for all types of action objects that can be held by other objects (Builders, Executors, etc.) This provides the common methods for manipulating and combining those actions.""" @@ -434,7 +434,7 @@ class ActionBase: if is_String(vl): vl = (vl,) for v in vl: result.append(env.subst('${'+v+'}')) - return string.join(result, '') + return ''.join(result) def __add__(self, other): return _actionAppend(self, other) @@ -450,7 +450,7 @@ class ActionBase: # and CommandGeneratorAction will use this env # when it calls its _generate method. self.presub_env = env - lines = string.split(str(self), '\n') + lines = str(self).split('\n') self.presub_env = None # don't need this any more return lines @@ -497,7 +497,7 @@ class _ActionAction(ActionBase): SCons.Util.AddMethod(self, batch_key, 'batch_key') def print_cmd_line(self, s, target, source, env): - sys.stdout.write(s + "\n") + sys.stdout.write(s + u"\n") def __call__(self, target, source, env, exitstatfunc=_null, @@ -534,9 +534,9 @@ class _ActionAction(ActionBase): if executor: target = executor.get_all_targets() source = executor.get_all_sources() - t = string.join(map(str, target), ' and ') - l = string.join(self.presub_lines(env), '\n ') - out = "Building %s with action:\n %s\n" % (t, l) + t = ' and '.join(map(str, target)) + l = '\n '.join(self.presub_lines(env)) + out = u"Building %s with action:\n %s\n" % (t, l) sys.stdout.write(out) cmd = None if show and self.strfunction: @@ -590,7 +590,7 @@ def _string_from_cmd_list(cmd_list): if ' ' in arg or '\t' in arg: arg = '"' + arg + '"' cl.append(arg) - return string.join(cl) + return ' '.join(cl) # A fiddlin' little function that has an 'import SCons.Environment' which # can't be moved to the top level without creating an import loop. Since @@ -617,7 +617,7 @@ def get_default_ENV(env): # it in the long run as more and more places use subprocess, but I'm sure # it'll have to be tweaked to get the full desired functionality. # one special arg (so far?), 'error', to tell what to do with exceptions. -def _subproc(env, cmd, error = 'ignore', **kw): +def _subproc(scons_env, cmd, error = 'ignore', **kw): """Do common setup for a subprocess.Popen() call""" # allow std{in,out,err} to be "'devnull'" io = kw.get('stdin') @@ -632,7 +632,7 @@ def _subproc(env, cmd, error = 'ignore', **kw): # Figure out what shell environment to use ENV = kw.get('env', None) - if ENV is None: ENV = get_default_ENV(env) + if ENV is None: ENV = get_default_ENV(scons_env) # Ensure that the ENV values are all strings: new_env = {} @@ -642,7 +642,7 @@ def _subproc(env, cmd, error = 'ignore', **kw): # because that's a pretty common list-like value to stick # in an environment variable: value = SCons.Util.flatten_sequence(value) - new_env[key] = string.join(map(str, value), os.pathsep) + new_env[key] = os.pathsep.join(map(str, value)) else: # It's either a string or something else. If it's a string, # we still want to call str() because it might be a *Unicode* @@ -655,16 +655,16 @@ def _subproc(env, cmd, error = 'ignore', **kw): try: #FUTURE return subprocess.Popen(cmd, **kw) - return apply(subprocess.Popen, (cmd,), kw) + return subprocess.Popen(cmd, **kw) except EnvironmentError, e: if error == 'raise': raise # return a dummy Popen instance that only returns error - class dummyPopen: + class dummyPopen(object): def __init__(self, e): self.exception = e def communicate(self): return ('','') def wait(self): return -self.exception.errno stdin = None - class f: + class f(object): def read(self): return '' def readline(self): return '' stdout = stderr = f() @@ -684,17 +684,16 @@ class CommandAction(_ActionAction): # variables. if __debug__: logInstanceCreation(self, 'Action.CommandAction') - #TODO(1.5) _ActionAction.__init__(self, **kw) - apply(_ActionAction.__init__, (self,), kw) + _ActionAction.__init__(self, **kw) if is_List(cmd): - if filter(is_List, cmd): - raise TypeError, "CommandAction should be given only " \ - "a single command" + if list(filter(is_List, cmd)): + raise TypeError("CommandAction should be given only " \ + "a single command") self.cmd_list = cmd def __str__(self): if is_List(self.cmd_list): - return string.join(map(str, self.cmd_list), ' ') + return ' '.join(map(str, self.cmd_list)) return str(self.cmd_list) def process(self, target, source, env, executor=None): @@ -704,7 +703,7 @@ class CommandAction(_ActionAction): result = env.subst_list(self.cmd_list, 0, target, source) silent = None ignore = None - while 1: + while True: try: c = result[0][0][0] except IndexError: c = None if c == '@': silent = 1 @@ -771,7 +770,7 @@ class CommandAction(_ActionAction): # path list, because that's a pretty common list-like # value to stick in an environment variable: value = flatten_sequence(value) - ENV[key] = string.join(map(str, value), os.pathsep) + ENV[key] = os.pathsep.join(map(str, value)) else: # If it isn't a string or a list, then we just coerce # it to a string, which is the proper way to handle @@ -782,7 +781,7 @@ class CommandAction(_ActionAction): if executor: target = executor.get_all_targets() source = executor.get_all_sources() - cmd_list, ignore, silent = self.process(target, map(rfile, source), env, executor) + cmd_list, ignore, silent = self.process(target, list(map(rfile, source)), env, executor) # Use len() to filter out any "command" that's zero-length. for cmd_line in filter(len, cmd_list): @@ -806,7 +805,7 @@ class CommandAction(_ActionAction): from SCons.Subst import SUBST_SIG cmd = self.cmd_list if is_List(cmd): - cmd = string.join(map(str, cmd)) + cmd = ' '.join(map(str, cmd)) else: cmd = str(cmd) if executor: @@ -859,8 +858,7 @@ class CommandGeneratorAction(ActionBase): source=source, env=env, for_signature=for_signature) - #TODO(1.5) gen_cmd = Action(ret, **self.gen_kw) - gen_cmd = apply(Action, (ret,), self.gen_kw) + gen_cmd = Action(ret, **self.gen_kw) if not gen_cmd: raise SCons.Errors.UserError("Object returned from command generator: %s cannot be used to create an Action." % repr(ret)) return gen_cmd @@ -885,7 +883,9 @@ class CommandGeneratorAction(ActionBase): show=_null, execute=_null, chdir=_null, executor=None): act = self._generate(target, source, env, 0, executor) if act is None: - raise UserError("While building `%s': Cannot deduce file extension from source files: %s" % (repr(map(str, target)), repr(map(str, source)))) + raise UserError("While building `%s': " + "Cannot deduce file extension from source files: %s" + % (repr(list(map(str, target))), repr(list(map(str, source))))) return act(target, source, env, exitstatfunc, presub, show, execute, chdir, executor) @@ -930,7 +930,7 @@ class LazyAction(CommandGeneratorAction, CommandAction): def __init__(self, var, kw): if __debug__: logInstanceCreation(self, 'Action.LazyAction') #FUTURE CommandAction.__init__(self, '${'+var+'}', **kw) - apply(CommandAction.__init__, (self, '${'+var+'}'), kw) + CommandAction.__init__(self, '${'+var+'}', **kw) self.var = SCons.Util.to_String(var) self.gen_kw = kw @@ -945,8 +945,7 @@ class LazyAction(CommandGeneratorAction, CommandAction): c = env.get(self.var, '') else: c = '' - #TODO(1.5) gen_cmd = Action(c, **self.gen_kw) - gen_cmd = apply(Action, (c,), self.gen_kw) + gen_cmd = Action(c, **self.gen_kw) if not gen_cmd: raise SCons.Errors.UserError("$%s value %s cannot be used to create an Action." % (self.var, repr(c))) return gen_cmd @@ -955,10 +954,8 @@ class LazyAction(CommandGeneratorAction, CommandAction): return self._generate_cache(env) def __call__(self, target, source, env, *args, **kw): - args = (self, target, source, env) + args c = self.get_parent_class(env) - #TODO(1.5) return c.__call__(*args, **kw) - return apply(c.__call__, args, kw) + return c.__call__(self, target, source, env, *args, **kw) def get_presig(self, target, source, env): c = self.get_parent_class(env) @@ -986,8 +983,7 @@ class FunctionAction(_ActionAction): # This is weird, just do the best we can. self.funccontents = _object_contents(execfunction) - #TODO(1.5) _ActionAction.__init__(self, **kw) - apply(_ActionAction.__init__, (self,), kw) + _ActionAction.__init__(self, **kw) def function_name(self): try: @@ -1018,7 +1014,7 @@ class FunctionAction(_ActionAction): else: s = str_for_display() return s - return '[' + string.join(map(quote, a), ", ") + ']' + return '[' + ", ".join(map(quote, a)) + ']' try: strfunc = self.execfunction.strfunction except AttributeError: @@ -1045,7 +1041,7 @@ class FunctionAction(_ActionAction): if executor: target = executor.get_all_targets() source = executor.get_all_sources() - rsources = map(rfile, source) + rsources = list(map(rfile, source)) try: result = self.execfunction(target=target, source=rsources, env=env) except KeyboardInterrupt, e: @@ -1095,40 +1091,34 @@ class FunctionAction(_ActionAction): class ListAction(ActionBase): """Class for lists of other actions.""" - def __init__(self, list): + def __init__(self, actionlist): if __debug__: logInstanceCreation(self, 'Action.ListAction') def list_of_actions(x): if isinstance(x, ActionBase): return x return Action(x) - self.list = map(list_of_actions, list) + self.list = list(map(list_of_actions, actionlist)) # our children will have had any varlist # applied; we don't need to do it again self.varlist = () self.targets = '$TARGETS' def genstring(self, target, source, env): - return string.join(map(lambda a, t=target, s=source, e=env: - a.genstring(t, s, e), - self.list), - '\n') + return '\n'.join([a.genstring(target, source, env) for a in self.list]) def __str__(self): - return string.join(map(str, self.list), '\n') + return '\n'.join(map(str, self.list)) def presub_lines(self, env): return SCons.Util.flatten_sequence( - map(lambda a, env=env: a.presub_lines(env), self.list)) + [a.presub_lines(env) for a in self.list]) def get_presig(self, target, source, env): """Return the signature contents of this action list. Simple concatenation of the signatures of the elements. """ - return string.join(map(lambda x, t=target, s=source, e=env: - x.get_contents(t, s, e), - self.list), - "") + return "".join([x.get_contents(target, source, env) for x in self.list]) def __call__(self, target, source, env, exitstatfunc=_null, presub=_null, show=_null, execute=_null, chdir=_null, executor=None): @@ -1153,9 +1143,9 @@ class ListAction(ActionBase): for act in self.list: for var in act.get_varlist(target, source, env, executor): result[var] = True - return result.keys() + return list(result.keys()) -class ActionCaller: +class ActionCaller(object): """A class for delaying calling an Action function with specific (positional and keyword) arguments until the Action is actually executed. @@ -1204,9 +1194,7 @@ class ActionCaller: return self.parent.convert(s) def subst_args(self, target, source, env): - return map(lambda x, self=self, t=target, s=source, e=env: - self.subst(x, t, s, e), - self.args) + return [self.subst(x, target, source, env) for x in self.args] def subst_kw(self, target, source, env): kw = {} @@ -1217,20 +1205,17 @@ class ActionCaller: def __call__(self, target, source, env, executor=None): args = self.subst_args(target, source, env) kw = self.subst_kw(target, source, env) - #TODO(1.5) return self.parent.actfunc(*args, **kw) - return apply(self.parent.actfunc, args, kw) + return self.parent.actfunc(*args, **kw) def strfunction(self, target, source, env): args = self.subst_args(target, source, env) kw = self.subst_kw(target, source, env) - #TODO(1.5) return self.parent.strfunc(*args, **kw) - return apply(self.parent.strfunc, args, kw) + return self.parent.strfunc(*args, **kw) def __str__(self): - #TODO(1.5) return self.parent.strfunc(*self.args, **self.kw) - return apply(self.parent.strfunc, self.args, self.kw) + return self.parent.strfunc(*self.args, **self.kw) -class ActionFactory: +class ActionFactory(object): """A factory class that will wrap up an arbitrary function as an SCons-executable Action object. diff --git a/engine/SCons/Builder.py b/engine/SCons/Builder.py index 7a9a028..3b4f2e8 100644 --- a/engine/SCons/Builder.py +++ b/engine/SCons/Builder.py @@ -96,12 +96,10 @@ There are the following methods for internal use within this module: # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -__revision__ = "src/engine/SCons/Builder.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Builder.py 5023 2010/06/14 22:05:46 scons" -import UserDict -import UserList +import collections import SCons.Action from SCons.Debug import logInstanceCreation @@ -113,17 +111,16 @@ import SCons.Node.FS import SCons.Util import SCons.Warnings -class _Null: +class _Null(object): pass _null = _Null def match_splitext(path, suffixes = []): if suffixes: - matchsuf = filter(lambda S,path=path: path[-len(S):] == S, - suffixes) + matchsuf = [S for S in suffixes if path[-len(S):] == S] if matchsuf: - suf = max(map(None, map(len, matchsuf), matchsuf))[1] + suf = max([(len(_f),_f) for _f in matchsuf])[1] return [path[:-len(suf)], path[-len(suf):]] return SCons.Util.splitext(path) @@ -139,7 +136,7 @@ class DictCmdGenerator(SCons.Util.Selector): self.source_ext_match = source_ext_match def src_suffixes(self): - return self.keys() + return list(self.keys()) def add_action(self, suffix, action): """Add a suffix-action pair to the mapping. @@ -156,22 +153,25 @@ class DictCmdGenerator(SCons.Util.Selector): for src in map(str, source): my_ext = match_splitext(src, suffixes)[1] if ext and my_ext != ext: - raise UserError("While building `%s' from `%s': Cannot build multiple sources with different extensions: %s, %s" % (repr(map(str, target)), src, ext, my_ext)) + raise UserError("While building `%s' from `%s': Cannot build multiple sources with different extensions: %s, %s" + % (repr(list(map(str, target))), src, ext, my_ext)) ext = my_ext else: ext = match_splitext(str(source[0]), self.src_suffixes())[1] if not ext: #return ext - raise UserError("While building `%s': Cannot deduce file extension from source files: %s" % (repr(map(str, target)), repr(map(str, source)))) + raise UserError("While building `%s': " + "Cannot deduce file extension from source files: %s" + % (repr(list(map(str, target))), repr(list(map(str, source))))) try: ret = SCons.Util.Selector.__call__(self, env, source, ext) except KeyError, e: - raise UserError("Ambiguous suffixes after environment substitution: %s == %s == %s" % (e[0], e[1], e[2])) + raise UserError("Ambiguous suffixes after environment substitution: %s == %s == %s" % (e.args[0], e.args[1], e.args[2])) if ret is None: raise UserError("While building `%s' from `%s': Don't know how to build from a source file with suffix `%s'. Expected a suffix in this list: %s." % \ - (repr(map(str, target)), repr(map(str, source)), ext, repr(self.keys()))) + (repr(list(map(str, target))), repr(list(map(str, source))), ext, repr(list(self.keys())))) return ret class CallableSelector(SCons.Util.Selector): @@ -197,7 +197,7 @@ class DictEmitter(SCons.Util.Selector): target, source = emitter(target, source, env) return (target, source) -class ListEmitter(UserList.UserList): +class ListEmitter(collections.UserList): """A callable list of emitters that calls each in sequence, returning the result. """ @@ -215,7 +215,7 @@ misleading_keywords = { 'sources' : 'source', } -class OverrideWarner(UserDict.UserDict): +class OverrideWarner(collections.UserDict): """A class for warning about keyword arguments that we use as overrides in a Builder call. @@ -224,14 +224,14 @@ class OverrideWarner(UserDict.UserDict): warnings once, no matter how many Builders are invoked. """ def __init__(self, dict): - UserDict.UserDict.__init__(self, dict) + collections.UserDict.__init__(self, dict) if __debug__: logInstanceCreation(self, 'Builder.OverrideWarner') self.already_warned = None def warn(self): if self.already_warned: return for k in self.keys(): - if misleading_keywords.has_key(k): + if k in misleading_keywords: alt = misleading_keywords[k] msg = "Did you mean to use `%s' instead of `%s'?" % (alt, k) SCons.Warnings.warn(SCons.Warnings.MisleadingKeywordsWarning, msg) @@ -240,14 +240,14 @@ class OverrideWarner(UserDict.UserDict): def Builder(**kw): """A factory for builder objects.""" composite = None - if kw.has_key('generator'): - if kw.has_key('action'): - raise UserError, "You must not specify both an action and a generator." + if 'generator' in kw: + if 'action' in kw: + raise UserError("You must not specify both an action and a generator.") kw['action'] = SCons.Action.CommandGeneratorAction(kw['generator'], {}) del kw['generator'] - elif kw.has_key('action'): + elif 'action' in kw: source_ext_match = kw.get('source_ext_match', 1) - if kw.has_key('source_ext_match'): + if 'source_ext_match' in kw: del kw['source_ext_match'] if SCons.Util.is_Dict(kw['action']): composite = DictCmdGenerator(kw['action'], source_ext_match) @@ -256,7 +256,7 @@ def Builder(**kw): else: kw['action'] = SCons.Action.Action(kw['action']) - if kw.has_key('emitter'): + if 'emitter' in kw: emitter = kw['emitter'] if SCons.Util.is_String(emitter): # This allows users to pass in an Environment @@ -265,14 +265,14 @@ def Builder(**kw): # a callable to use as the actual emitter. var = SCons.Util.get_environment_var(emitter) if not var: - raise UserError, "Supplied emitter '%s' does not appear to refer to an Environment variable" % emitter + raise UserError("Supplied emitter '%s' does not appear to refer to an Environment variable" % emitter) kw['emitter'] = EmitterProxy(var) elif SCons.Util.is_Dict(emitter): kw['emitter'] = DictEmitter(emitter) elif SCons.Util.is_List(emitter): kw['emitter'] = ListEmitter(emitter) - result = apply(BuilderBase, (), kw) + result = BuilderBase(**kw) if not composite is None: result = CompositeBuilder(result, composite) @@ -289,7 +289,7 @@ def _node_errors(builder, env, tlist, slist): # were specified. for t in tlist: if t.side_effect: - raise UserError, "Multiple ways to build the same target were specified for: %s" % t + raise UserError("Multiple ways to build the same target were specified for: %s" % t) if t.has_explicit_builder(): if not t.env is None and not t.env is env: action = t.builder.action @@ -301,24 +301,24 @@ def _node_errors(builder, env, tlist, slist): SCons.Warnings.warn(SCons.Warnings.DuplicateEnvironmentWarning, msg) else: msg = "Two environments with different actions were specified for the same target: %s" % t - raise UserError, msg + raise UserError(msg) if builder.multi: if t.builder != builder: msg = "Two different builders (%s and %s) were specified for the same target: %s" % (t.builder.get_name(env), builder.get_name(env), t) - raise UserError, msg + raise UserError(msg) # TODO(batch): list constructed each time! if t.get_executor().get_all_targets() != tlist: - msg = "Two different target lists have a target in common: %s (from %s and from %s)" % (t, map(str, t.get_executor().get_all_targets()), map(str, tlist)) - raise UserError, msg + msg = "Two different target lists have a target in common: %s (from %s and from %s)" % (t, list(map(str, t.get_executor().get_all_targets())), list(map(str, tlist))) + raise UserError(msg) elif t.sources != slist: - msg = "Multiple ways to build the same target were specified for: %s (from %s and from %s)" % (t, map(str, t.sources), map(str, slist)) - raise UserError, msg + msg = "Multiple ways to build the same target were specified for: %s (from %s and from %s)" % (t, list(map(str, t.sources)), list(map(str, slist))) + raise UserError(msg) if builder.single_source: if len(slist) > 1: - raise UserError, "More than one source given for single-source builder: targets=%s sources=%s" % (map(str,tlist), map(str,slist)) + raise UserError("More than one source given for single-source builder: targets=%s sources=%s" % (list(map(str,tlist)), list(map(str,slist)))) -class EmitterProxy: +class EmitterProxy(object): """This is a callable class that can act as a Builder emitter. It holds on to a string that is a key into an Environment dictionary, and will @@ -334,7 +334,7 @@ class EmitterProxy: # Recursively substitute the variable. # We can't use env.subst() because it deals only # in strings. Maybe we should change that? - while SCons.Util.is_String(emitter) and env.has_key(emitter): + while SCons.Util.is_String(emitter) and emitter in env: emitter = env[emitter] if callable(emitter): target, source = emitter(target, source, env) @@ -348,7 +348,7 @@ class EmitterProxy: def __cmp__(self, other): return cmp(self.var, other.var) -class BuilderBase: +class BuilderBase(object): """Base class for Builders, objects that create output nodes (files) from input nodes (files). """ @@ -387,14 +387,14 @@ class BuilderBase: suffix = CallableSelector(suffix) self.env = env self.single_source = single_source - if overrides.has_key('overrides'): - SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, + if 'overrides' in overrides: + SCons.Warnings.warn(SCons.Warnings.DeprecatedBuilderKeywordsWarning, "The \"overrides\" keyword to Builder() creation has been deprecated;\n" +\ "\tspecify the items as keyword arguments to the Builder() call instead.") overrides.update(overrides['overrides']) del overrides['overrides'] - if overrides.has_key('scanner'): - SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, + if 'scanner' in overrides: + SCons.Warnings.warn(SCons.Warnings.DeprecatedBuilderKeywordsWarning, "The \"scanner\" keyword to Builder() creation has been deprecated;\n" "\tuse: source_scanner or target_scanner as appropriate.") del overrides['scanner'] @@ -427,7 +427,7 @@ class BuilderBase: self.src_builder = src_builder def __nonzero__(self): - raise InternalError, "Do not test for the Node.builder attribute directly; use Node.has_builder() instead" + raise InternalError("Do not test for the Node.builder attribute directly; use Node.has_builder() instead") def get_name(self, env): """Attempts to get the name of the Builder. @@ -438,8 +438,8 @@ class BuilderBase: name (if there is one) or the name of the class (by default).""" try: - index = env['BUILDERS'].values().index(self) - return env['BUILDERS'].keys()[index] + index = list(env['BUILDERS'].values()).index(self) + return list(env['BUILDERS'].keys())[index] except (AttributeError, KeyError, TypeError, ValueError): try: return self.name @@ -493,7 +493,7 @@ class BuilderBase: except IndexError: tlist = [] else: - splitext = lambda S,self=self,env=env: self.splitext(S,env) + splitext = lambda S: self.splitext(S,env) tlist = [ t_from_s(pre, suf, splitext) ] else: target = self._adjustixes(target, pre, suf, self.ensure_suffix) @@ -573,8 +573,8 @@ class BuilderBase: if executor is None: if not self.action: fmt = "Builder %s must have an action to build %s." - raise UserError, fmt % (self.get_name(env or self.env), - map(str,tlist)) + raise UserError(fmt % (self.get_name(env or self.env), + list(map(str,tlist)))) key = self.action.batch_key(env or self.env, tlist, slist) if key: try: @@ -611,7 +611,7 @@ class BuilderBase: ekw = self.executor_kw.copy() ekw['chdir'] = chdir if kw: - if kw.has_key('srcdir'): + if 'srcdir' in kw: def prependDirIfRelative(f, srcdir=kw['srcdir']): import os.path if SCons.Util.is_String(f) and not os.path.isabs(f): @@ -619,7 +619,7 @@ class BuilderBase: return f if not SCons.Util.is_List(source): source = [source] - source = map(prependDirIfRelative, source) + source = list(map(prependDirIfRelative, source)) del kw['srcdir'] if self.overrides: env_kw = self.overrides.copy() @@ -658,9 +658,7 @@ class BuilderBase: src_suffix = [] elif not SCons.Util.is_List(src_suffix): src_suffix = [ src_suffix ] - adjust = lambda suf, s=self: \ - callable(suf) and suf or s.adjust_suffix(suf) - self.src_suffix = map(adjust, src_suffix) + self.src_suffix = [callable(suf) and suf or self.adjust_suffix(suf) for suf in src_suffix] def get_src_suffix(self, env): """Get the first src_suffix in the list of src_suffixes.""" @@ -723,7 +721,7 @@ class BuilderBase: lengths = list(set(map(len, src_suffixes))) def match_src_suffix(name, src_suffixes=src_suffixes, lengths=lengths): - node_suffixes = map(lambda l, n=name: n[-l:], lengths) + node_suffixes = [name[-l:] for l in lengths] for suf in src_suffixes: if suf in node_suffixes: return suf @@ -749,8 +747,7 @@ class BuilderBase: # target, then filter out any sources that this # Builder isn't capable of building. if len(tlist) > 1: - mss = lambda t, m=match_src_suffix: m(t.name) - tlist = filter(mss, tlist) + tlist = [t for t in tlist if match_src_suffix(t.name)] result.extend(tlist) else: result.append(s) @@ -819,7 +816,7 @@ class BuilderBase: return memo_dict[memo_key] except KeyError: pass - suffixes = map(lambda x, s=self, e=env: e.subst(x), self.src_suffix) + suffixes = [env.subst(x) for x in self.src_suffix] memo_dict[memo_key] = suffixes return suffixes @@ -838,7 +835,7 @@ class BuilderBase: sdict[s] = 1 for builder in self.get_src_builders(env): for s in builder.src_suffixes(env): - if not sdict.has_key(s): + if s not in sdict: sdict[s] = 1 suffixes.append(s) return suffixes @@ -857,6 +854,8 @@ class CompositeBuilder(SCons.Util.Proxy): self.cmdgen = cmdgen self.builder = builder + __call__ = SCons.Util.Delegate('__call__') + def add_action(self, suffix, action): self.cmdgen.add_action(suffix, action) self.set_src_suffix(self.cmdgen.src_suffixes()) diff --git a/engine/SCons/CacheDir.py b/engine/SCons/CacheDir.py index 6977621..6b2e174 100644 --- a/engine/SCons/CacheDir.py +++ b/engine/SCons/CacheDir.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/CacheDir.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/CacheDir.py 5023 2010/06/14 22:05:46 scons" __doc__ = """ CacheDir support @@ -29,7 +29,6 @@ CacheDir support import os.path import stat -import string import sys import SCons.Action @@ -101,7 +100,7 @@ def CachePushFunc(target, source, env): # has beaten us creating the directory. if not fs.isdir(cachedir): msg = errfmt % (str(target), cachefile) - raise SCons.Errors.EnvironmentError, msg + raise SCons.Errors.EnvironmentError(msg) try: if fs.islink(t.path): @@ -122,7 +121,7 @@ def CachePushFunc(target, source, env): CachePush = SCons.Action.Action(CachePushFunc, None) -class CacheDir: +class CacheDir(object): def __init__(self, path): try: @@ -158,7 +157,7 @@ class CacheDir: return None, None sig = node.get_cachedir_bsig() - subdir = string.upper(sig[0]) + subdir = sig[0].upper() dir = os.path.join(self.path, subdir) return dir, os.path.join(dir, sig) diff --git a/engine/SCons/Conftest.py b/engine/SCons/Conftest.py index e995e77..04a6bc2 100644 --- a/engine/SCons/Conftest.py +++ b/engine/SCons/Conftest.py @@ -101,7 +101,6 @@ Autoconf-like configuration support; low level implementation of tests. # import re -import string from types import IntType # @@ -230,7 +229,7 @@ int main() def _check_empty_program(context, comp, text, language, use_shared = False): """Return 0 on success, 1 otherwise.""" - if not context.env.has_key(comp) or not context.env[comp]: + if comp not in context.env or not context.env[comp]: # The compiler construction variable is not set or empty return 1 @@ -636,7 +635,7 @@ return 0; """ % (call or "") if call: - i = string.find(call, "\n") + i = call.find("\n") if i > 0: calltext = call[:i] + ".." elif call[-1] == ';': @@ -723,14 +722,14 @@ def _Have(context, key, have, comment = None): Give "have" as is should appear in the header file, include quotes when desired and escape special characters! """ - key_up = string.upper(key) + key_up = key.upper() key_up = re.sub('[^A-Z0-9_]', '_', key_up) context.havedict[key_up] = have if have == 1: line = "#define %s 1\n" % key_up elif have == 0: line = "/* #undef %s */\n" % key_up - elif type(have) == IntType: + elif isinstance(have, IntType): line = "#define %s %d\n" % (key_up, have) else: line = "#define %s %s\n" % (key_up, str(have)) @@ -755,7 +754,7 @@ def _LogFailed(context, text, msg): """ if LogInputFiles: context.Log("Failed program was:\n") - lines = string.split(text, '\n') + lines = text.split('\n') if len(lines) and lines[-1] == '': lines = lines[:-1] # remove trailing empty line n = 1 diff --git a/engine/SCons/Debug.py b/engine/SCons/Debug.py index afff44b..ec7dbbd 100644 --- a/engine/SCons/Debug.py +++ b/engine/SCons/Debug.py @@ -1,7 +1,6 @@ """SCons.Debug -Code for debugging SCons internal things. Not everything here is -guaranteed to work all the way back to Python 1.5.2, and shouldn't be +Code for debugging SCons internal things. Shouldn't be needed by most users. """ @@ -29,42 +28,31 @@ needed by most users. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Debug.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Debug.py 5023 2010/06/14 22:05:46 scons" import os -import string import sys import time - -# Recipe 14.10 from the Python Cookbook. -try: - import weakref -except ImportError: - def logInstanceCreation(instance, name=None): - pass -else: - def logInstanceCreation(instance, name=None): - if name is None: - name = instance.__class__.__name__ - if not tracked_classes.has_key(name): - tracked_classes[name] = [] - tracked_classes[name].append(weakref.ref(instance)) - - +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 == '*': - c = tracked_classes.keys() - c.sort() - return c + return sorted(tracked_classes.keys()) else: - return string.split(s) + return s.split() def fetchLoggedInstances(classes="*"): classnames = string_to_classes(classes) - return map(lambda cn: (cn, len(tracked_classes[cn])), classnames) + return [(cn, len(tracked_classes[cn])) for cn in classnames] def countLoggedInstances(classes, file=sys.stdout): for classname in string_to_classes(classes): @@ -94,8 +82,12 @@ if sys.platform[:5] == "linux": # Linux doesn't actually support memory usage stats from getrusage(). def memory(): mstr = open('/proc/self/stat').read() - mstr = string.split(mstr)[22] + 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 @@ -149,21 +141,15 @@ def caller_trace(back=0): # print a single caller and its callers, if any def _dump_one_caller(key, file, level=0): - l = [] - for c,v in caller_dicts[key].items(): - l.append((-v,c)) - l.sort() leader = ' '*level - for v,c in l: + 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 caller_dicts.has_key(c): + if c in caller_dicts: _dump_one_caller(c, file, level+1) # print each call tree def dump_caller_counts(file=sys.stdout): - keys = caller_bases.keys() - keys.sort() - for k in keys: + 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) @@ -175,15 +161,12 @@ shorten_list = [ ] if os.sep != '/': - def platformize(t): - return (string.replace(t[0], '/', os.sep), t[1]) - shorten_list = map(platformize, shorten_list) - del platformize + 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 = string.find(f, t[0]) + i = f.find(t[0]) if i >= 0: if t[1]: i = i + len(t[0]) diff --git a/engine/SCons/Defaults.py b/engine/SCons/Defaults.py index c353134..8530aa3 100644 --- a/engine/SCons/Defaults.py +++ b/engine/SCons/Defaults.py @@ -31,19 +31,16 @@ from distutils.msvccompiler. # 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 4720 2010/03/24 03:14:11 jars" - +__revision__ = "src/engine/SCons/Defaults.py 5023 2010/06/14 22:05:46 scons" import os -import os.path import errno import shutil import stat -import string import time -import types import sys import SCons.Action @@ -88,7 +85,7 @@ def DefaultEnvironment(*args, **kw): global _default_env if not _default_env: import SCons.Util - _default_env = apply(SCons.Environment.Environment, args, kw) + _default_env = SCons.Environment.Environment(*args, **kw) if SCons.Util.md5: _default_env.Decider('MD5') else: @@ -120,7 +117,7 @@ def SharedFlagChecker(source, target, env): 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]) + 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) @@ -165,7 +162,7 @@ def get_paths_str(dest): elem_strs = [] for element in dest: elem_strs.append('"' + str(element) + '"') - return '[' + string.join(elem_strs, ', ') + ']' + return '[' + ', '.join(elem_strs) + ']' else: return '"' + str(dest) + '"' @@ -225,7 +222,8 @@ def mkdir_func(dest): os.makedirs(str(entry)) except os.error, e: p = str(entry) - if (e[0] == errno.EEXIST or (sys.platform=='win32' and e[0]==183)) \ + 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: @@ -315,16 +313,16 @@ def _concat_ixes(prefix, list, suffix, env): return result -def _stripixes(prefix, list, suffix, stripprefixes, stripsuffixes, env, c=None): +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 elements and strips them + 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 list: - return list + if not itms: + return itms if not callable(c): env_c = env['_concat'] @@ -337,11 +335,11 @@ def _stripixes(prefix, list, suffix, stripprefixes, stripsuffixes, env, c=None): else: c = _concat_ixes - stripprefixes = map(env.subst, SCons.Util.flatten(stripprefixes)) - stripsuffixes = map(env.subst, SCons.Util.flatten(stripsuffixes)) + 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(list).subst_path(env, None, None): + for l in SCons.PathList.PathList(itms).subst_path(env, None, None): if isinstance(l, SCons.Node.FS.File): stripped.append(l) continue @@ -374,7 +372,7 @@ def processDefines(defs): if SCons.Util.is_List(defs): l = [] for d in defs: - if SCons.Util.is_List(d) or type(d) is types.TupleType: + if SCons.Util.is_List(d) or isinstance(d, tuple): l.append(str(d[0]) + '=' + str(d[1])) else: l.append(str(d)) @@ -386,10 +384,7 @@ def processDefines(defs): # Consequently, we have to sort the keys to ensure a # consistent order... l = [] - keys = defs.keys() - keys.sort() - for k in keys: - v = defs[k] + for k,v in sorted(defs.items()): if v is None: l.append(str(k)) else: @@ -405,7 +400,7 @@ def _defines(prefix, defs, suffix, env, c=_concat_ixes): return c(prefix, env.subst_path(processDefines(defs)), suffix, env) -class NullCmdGenerator: +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. @@ -423,7 +418,7 @@ class NullCmdGenerator: def __call__(self, target, source, env, for_signature=None): return self.cmd -class Variable_Method_Caller: +class Variable_Method_Caller(object): """A class for finding a construction variable on the stack and calling one of its methods. @@ -439,18 +434,18 @@ class Variable_Method_Caller: self.variable = variable self.method = method def __call__(self, *args, **kw): - try: 1/0 + 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 frame.f_locals.has_key(variable): + if variable in frame.f_locals: v = frame.f_locals[variable] if v: method = getattr(v, self.method) - return apply(method, args, kw) + return method(*args, **kw) frame = frame.f_back return None diff --git a/engine/SCons/Environment.py b/engine/SCons/Environment.py index ac6de99..50a357d 100644 --- a/engine/SCons/Environment.py +++ b/engine/SCons/Environment.py @@ -30,9 +30,8 @@ Environment # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Environment.py 5023 2010/06/14 22:05:46 scons" import copy @@ -40,8 +39,7 @@ import os import sys import re import shlex -import string -from UserDict import UserDict +from collections import UserDict import SCons.Action import SCons.Builder @@ -61,7 +59,7 @@ import SCons.Tool import SCons.Util import SCons.Warnings -class _Null: +class _Null(object): pass _null = _Null @@ -98,11 +96,11 @@ def apply_tools(env, tools, toolpath): if not tools: return # Filter out null tools from the list. - for tool in filter(None, tools): - if SCons.Util.is_List(tool) or type(tool)==type(()): + 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 = apply(env.Tool, [toolname], toolargs) + tool = env.Tool(toolname, **toolargs) else: env.Tool(tool) @@ -173,7 +171,7 @@ def _delete_duplicates(l, keep_last): l.reverse() for i in l: try: - if not seen.has_key(i): + if i not in seen: result.append(i) seen[i]=1 except TypeError: @@ -196,7 +194,7 @@ def _delete_duplicates(l, keep_last): # BuilderWrapper a subclass that overrides __call__() to enforce specific # Builder calling conventions, simplified some of our higher-layer code. -class MethodWrapper: +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 @@ -221,7 +219,7 @@ class MethodWrapper: def __call__(self, *args, **kwargs): nargs = (self.object,) + args - return apply(self.method, nargs, kwargs) + return self.method(*nargs, **kwargs) def clone(self, new_object): """ @@ -257,7 +255,7 @@ class BuilderWrapper(MethodWrapper): target = [target] if source is not None and not SCons.Util.is_List(source): source = [source] - return apply(MethodWrapper.__call__, (self, target, source) + args, kw) + return MethodWrapper.__call__(self, target, source, *args, **kw) def __repr__(self): return '' % repr(self.name) @@ -271,7 +269,7 @@ class BuilderWrapper(MethodWrapper): elif name == 'builder': return self.method else: - raise AttributeError, name + raise AttributeError(name) def __setattr__(self, name, value): if name == 'env': @@ -290,7 +288,7 @@ class BuilderWrapper(MethodWrapper): # future, so leave it for now. #def execute(self, **kw): # kw['env'] = self.env - # apply(self.builder.execute, (), kw) + # self.builder.execute(**kw) class BuilderDict(UserDict): """This is a dictionary-like class used by an Environment to hold @@ -337,7 +335,7 @@ def is_valid_construction_var(varstr): -class SubstitutionEnvironment: +class SubstitutionEnvironment(object): """Base class for different flavors of construction environments. This class contains a minimal set of methods that handle contruction @@ -395,7 +393,7 @@ class SubstitutionEnvironment: # 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 = self._special_set.keys() + self._special_set_keys = list(self._special_set.keys()) def __cmp__(self, other): return cmp(self._dict, other._dict) @@ -419,7 +417,7 @@ class SubstitutionEnvironment: # 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 then this test. + # 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). @@ -430,9 +428,9 @@ class SubstitutionEnvironment: # 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 not self._dict.has_key(key) \ + if key not in self._dict \ and not _is_valid_var.match(key): - raise SCons.Errors.UserError, "Illegal construction variable `%s'" % key + raise SCons.Errors.UserError("Illegal construction variable `%s'" % key) self._dict[key] = value def get(self, key, default=None): @@ -440,13 +438,13 @@ class SubstitutionEnvironment: return self._dict.get(key, default) def has_key(self, key): - return self._dict.has_key(key) + return key in self._dict def __contains__(self, key): return self._dict.__contains__(key) def items(self): - return self._dict.items() + return list(self._dict.items()) def arg2nodes(self, args, node_factory=_null, lookup_list=_null, **kw): if node_factory is _null: @@ -471,7 +469,7 @@ class SubstitutionEnvironment: if SCons.Util.is_String(n): # n = self.subst(n, raw=1, **kw) kw['raw'] = 1 - n = apply(self.subst, (n,), kw) + n = self.subst(n, **kw) if node_factory: n = node_factory(n) if SCons.Util.is_List(n): @@ -481,7 +479,7 @@ class SubstitutionEnvironment: elif node_factory: # v = node_factory(self.subst(v, raw=1, **kw)) kw['raw'] = 1 - v = node_factory(apply(self.subst, (v,), kw)) + v = node_factory(self.subst(v, **kw)) if SCons.Util.is_List(v): nodes.extend(v) else: @@ -566,7 +564,7 @@ class SubstitutionEnvironment: # 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 = string.join(map(SCons.Util.to_String_for_subst, p), '') + p = ''.join(map(SCons.Util.to_String_for_subst, p)) else: p = s(p) r.append(p) @@ -586,12 +584,11 @@ class SubstitutionEnvironment: # othewise force a shell if not SCons.Util.is_List(command): kw['shell'] = True # run constructed command - #TODO(1.5) p = SCons.Action._subproc(self, command, **kw) - p = apply(SCons.Action._subproc, (self, command), kw) + p = SCons.Action._subproc(self, command, **kw) out,err = p.communicate() status = p.wait() if err: - sys.stderr.write(err) + sys.stderr.write(unicode(err)) if status: raise OSError("'%s' exited %d" % (command, status)) return out @@ -610,8 +607,7 @@ class SubstitutionEnvironment: Removes the specified function's MethodWrapper from the added_methods list, so we don't re-bind it when making a clone. """ - is_not_func = lambda dm, f=function: not dm.method is f - self.added_methods = filter(is_not_func, self.added_methods) + self.added_methods = [dm for dm in self.added_methods if not dm.method is function] def Override(self, overrides): """ @@ -664,15 +660,13 @@ class SubstitutionEnvironment: 'RPATH' : [], } - # The use of the "me" parameter to provide our own name for - # recursion is an egregious hack to support Python 2.1 and before. - def do_parse(arg, me, self = self, dict = dict): + 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: me(t, me) + for t in arg: do_parse(t) return # if arg is a command, execute it @@ -681,11 +675,11 @@ class SubstitutionEnvironment: # utility function to deal with -D option def append_define(name, dict = dict): - t = string.split(name, '=') + t = name.split('=') if len(t) == 1: dict['CPPDEFINES'].append(name) else: - dict['CPPDEFINES'].append([t[0], string.join(t[1:], '=')]) + 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 @@ -791,7 +785,7 @@ class SubstitutionEnvironment: dict['CCFLAGS'].append(arg) for arg in flags: - do_parse(arg, do_parse) + do_parse(arg) return dict def MergeFlags(self, args, unique=1, dict=None): @@ -807,7 +801,7 @@ class SubstitutionEnvironment: if not SCons.Util.is_Dict(args): args = self.ParseFlags(args) if not unique: - apply(self.Append, (), args) + self.Append(**args) return self for key, value in args.items(): if not value: @@ -866,21 +860,10 @@ class SubstitutionEnvironment: # if not pathval: # continue # if prepend: -# apply(self.PrependENVPath, (pathname, pathval)) +# self.PrependENVPath(pathname, pathval) # else: -# apply(self.AppendENVPath, (pathname, pathval)) - +# self.AppendENVPath(pathname, pathval) -# Used by the FindSourceFiles() method, below. -# Stuck here for support of pre-2.2 Python versions. -def build_source(ss, result): - for s in ss: - if isinstance(s, SCons.Node.FS.Dir): - build_source(s.all_children(), result) - elif s.has_builder(): - build_source(s.sources, result) - elif isinstance(s.disambiguate(), SCons.Node.FS.File): - result.append(s) def default_decide_source(dependency, target, prev_ni): f = SCons.Defaults.DefaultEnvironment().decide_source @@ -979,15 +962,15 @@ class Base(SubstitutionEnvironment): # Apply the passed-in and customizable variables to the # environment before calling the tools, because they may use # some of them during initialization. - if kw.has_key('options'): + if 'options' in kw: # Backwards compatibility: they may stll be using the # old "options" keyword. variables = kw['options'] del kw['options'] - apply(self.Replace, (), kw) - keys = kw.keys() + self.Replace(**kw) + keys = list(kw.keys()) if variables: - keys = keys + variables.keys() + keys = keys + list(variables.keys()) variables.Update(self) save = {} @@ -1100,7 +1083,7 @@ class Base(SubstitutionEnvironment): for scanner in scanners: for k in scanner.get_skeys(self): if k and self['PLATFORM'] == 'win32': - k = string.lower(k) + k = k.lower() result[k] = scanner self._memo['_gsm'] = result @@ -1111,7 +1094,7 @@ class Base(SubstitutionEnvironment): """Find the appropriate scanner given a key (usually a file suffix). """ if skey and self['PLATFORM'] == 'win32': - skey = string.lower(skey) + skey = skey.lower() return self._gsm().get(skey) def scanner_map_delete(self, kw=None): @@ -1240,13 +1223,13 @@ class Base(SubstitutionEnvironment): """ orig = '' - if self._dict.has_key(envname) and self._dict[envname].has_key(name): + 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 not self._dict.has_key(envname): + if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv @@ -1261,7 +1244,7 @@ class Base(SubstitutionEnvironment): for key, val in kw.items(): if SCons.Util.is_List(val): val = _delete_duplicates(val, delete_existing) - if not self._dict.has_key(key) or self._dict[key] in ('', None): + 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): @@ -1271,9 +1254,9 @@ class Base(SubstitutionEnvironment): if not SCons.Util.is_List(dk): dk = [dk] if delete_existing: - dk = filter(lambda x, val=val: x not in val, dk) + dk = [x for x in dk if x not in val] else: - val = filter(lambda x, dk=dk: x not in dk, val) + val = [x for x in val if x not in dk] self._dict[key] = dk + val else: dk = self._dict[key] @@ -1281,14 +1264,14 @@ class Base(SubstitutionEnvironment): # 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) + dk = [x for x in dk if x not in val] self._dict[key] = dk + [val] else: if not val in dk: self._dict[key] = dk + [val] else: if delete_existing: - dk = filter(lambda x, val=val: x not in val, dk) + dk = [x for x in dk if x not in val] self._dict[key] = dk + val self.scanner_map_delete(kw) @@ -1327,12 +1310,12 @@ class Base(SubstitutionEnvironment): new = {} for key, value in kw.items(): new[key] = SCons.Subst.scons_subst_once(value, self, key) - apply(clone.Replace, (), new) + clone.Replace(**new) apply_tools(clone, tools, toolpath) # apply them again in case the tools overwrote them - apply(clone.Replace, (), new) + clone.Replace(**new) # Finally, apply any flags to be merged in if parse_flags: clone.MergeFlags(parse_flags) @@ -1346,7 +1329,7 @@ class Base(SubstitutionEnvironment): 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 apply(self.Clone, args, kw) + return self.Clone(*args, **kw) def _changed_build(self, dependency, target, prev_ni): if dependency.changed_state(target, prev_ni): @@ -1383,7 +1366,7 @@ class Base(SubstitutionEnvironment): 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." + 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 @@ -1393,7 +1376,7 @@ class Base(SubstitutionEnvironment): elif function == 'timestamp-match': function = self._changed_timestamp_match elif not callable(function): - raise UserError, "Unknown Decider value %s" % repr(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 @@ -1416,7 +1399,7 @@ class Base(SubstitutionEnvironment): def Dictionary(self, *args): if not args: return self._dict - dlist = map(lambda x, s=self: s._dict[x], args) + dlist = [self._dict[x] for x in args] if len(dlist) == 1: dlist = dlist[0] return dlist @@ -1472,7 +1455,7 @@ class Base(SubstitutionEnvironment): return env.MergeFlags(cmd, unique) function = parse_conf if SCons.Util.is_List(command): - command = string.join(command) + command = ' '.join(command) command = self.subst(command) return function(self, self.backtick(command)) @@ -1494,23 +1477,25 @@ class Base(SubstitutionEnvironment): raise return lines = SCons.Util.LogicalLines(fp).readlines() - lines = filter(lambda l: l[0] != '#', lines) + lines = [l for l in lines if l[0] != '#'] tdlist = [] for line in lines: try: - target, depends = string.split(line, ':', 1) - except (AttributeError, TypeError, ValueError): - # Python 1.5.2 throws TypeError if line isn't a string, - # Python 2.x throws AttributeError because it tries - # to call line.split(). Either can throw ValueError - # if the line doesn't split into two or more elements. + 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((string.split(target), string.split(depends))) + tdlist.append((target.split(), depends.split())) if only_one: - targets = reduce(lambda x, y: x+y, map(lambda p: p[0], tdlist)) + 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) + raise SCons.Errors.UserError( + "More than one dependency target found in `%s': %s" + % (filename, targets)) for target, depends in tdlist: self.Depends(target, depends) @@ -1596,13 +1581,13 @@ class Base(SubstitutionEnvironment): """ orig = '' - if self._dict.has_key(envname) and self._dict[envname].has_key(name): + 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 not self._dict.has_key(envname): + if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv @@ -1617,7 +1602,7 @@ class Base(SubstitutionEnvironment): for key, val in kw.items(): if SCons.Util.is_List(val): val = _delete_duplicates(val, not delete_existing) - if not self._dict.has_key(key) or self._dict[key] in ('', None): + 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): @@ -1627,9 +1612,9 @@ class Base(SubstitutionEnvironment): if not SCons.Util.is_List(dk): dk = [dk] if delete_existing: - dk = filter(lambda x, val=val: x not in val, dk) + dk = [x for x in dk if x not in val] else: - val = filter(lambda x, dk=dk: x not in dk, val) + val = [x for x in val if x not in dk] self._dict[key] = val + dk else: dk = self._dict[key] @@ -1637,14 +1622,14 @@ class Base(SubstitutionEnvironment): # 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) + 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 = filter(lambda x, val=val: x not in val, dk) + dk = [x for x in dk if x not in val] self._dict[key] = val + dk self.scanner_map_delete(kw) @@ -1690,9 +1675,9 @@ class Base(SubstitutionEnvironment): def SetDefault(self, **kw): for k in kw.keys(): - if self._dict.has_key(k): + if k in self._dict: del kw[k] - apply(self.Replace, (), kw) + self.Replace(**kw) def _find_toolpath_dir(self, tp): return self.fs.Dir(self.subst(tp)).srcnode().abspath @@ -1702,8 +1687,8 @@ class Base(SubstitutionEnvironment): tool = self.subst(tool) if toolpath is None: toolpath = self.get('toolpath', []) - toolpath = map(self._find_toolpath_dir, toolpath) - tool = apply(SCons.Tool.Tool, (tool, toolpath), kw) + 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=[]): @@ -1741,15 +1726,15 @@ class Base(SubstitutionEnvironment): if SCons.Util.is_String(a): a = self.subst(a) return a - nargs = map(subst_string, args) + nargs = list(map(subst_string, args)) nkw = self.subst_kw(kw) - return apply(SCons.Action.Action, nargs, nkw) + 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 map(lambda n: n.get_executor(), nodes): + for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 for executor in uniq.keys(): executor.add_pre_action(action) @@ -1759,7 +1744,7 @@ class Base(SubstitutionEnvironment): nodes = self.arg2nodes(files, self.fs.Entry) action = SCons.Action.Action(action) uniq = {} - for executor in map(lambda n: n.get_executor(), nodes): + for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 for executor in uniq.keys(): executor.add_post_action(action) @@ -1769,7 +1754,7 @@ class Base(SubstitutionEnvironment): tlist = self.arg2nodes(target, self.ans.Alias) if not SCons.Util.is_List(source): source = [source] - source = filter(None, source) + source = [_f for _f in source if _f] if not action: if not source: @@ -1796,7 +1781,7 @@ class Base(SubstitutionEnvironment): 'multi' : 1, 'is_explicit' : None, }) - bld = apply(SCons.Builder.Builder, (), nkw) + 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 @@ -1813,7 +1798,7 @@ class Base(SubstitutionEnvironment): b = bld else: nkw['action'] = b.action + action - b = apply(SCons.Builder.Builder, (), nkw) + b = SCons.Builder.Builder(**nkw) t.convert() result.extend(b(self, t, t.sources + source)) return result @@ -1827,14 +1812,16 @@ class Base(SubstitutionEnvironment): return tlist def BuildDir(self, *args, **kw): - if kw.has_key('build_dir'): + 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 apply(self.VariantDir, args, kw) + return self.VariantDir(*args, **kw) def Builder(self, **kw): nkw = self.subst_kw(kw) - return apply(SCons.Builder.Builder, [], nkw) + return SCons.Builder.Builder(**nkw) def CacheDir(self, path): import SCons.CacheDir @@ -1862,7 +1849,7 @@ class Base(SubstitutionEnvironment): nkw['custom_tests'] = self.subst_kw(nkw['custom_tests']) except KeyError: pass - return apply(SCons.SConf.SConf, nargs, nkw) + return SCons.SConf.SConf(*nargs, **nkw) def Command(self, target, source, action, **kw): """Builds the supplied target files from the supplied @@ -1877,8 +1864,8 @@ class Base(SubstitutionEnvironment): try: bkw['source_scanner'] = kw['source_scanner'] except KeyError: pass else: del kw['source_scanner'] - bld = apply(SCons.Builder.Builder, (), bkw) - return apply(bld, (self, target, source), kw) + bld = SCons.Builder.Builder(**bkw) + return bld(self, target, source, **kw) def Depends(self, target, dependency): """Explicity specify that 'target's depend on 'dependency'.""" @@ -1895,9 +1882,9 @@ class Base(SubstitutionEnvironment): if SCons.Util.is_Sequence(s): result=[] for e in s: - result.append(apply(self.fs.Dir, (e,) + args, kw)) + result.append(self.fs.Dir(e, *args, **kw)) return result - return apply(self.fs.Dir, (s,) + args, kw) + return self.fs.Dir(s, *args, **kw) def NoClean(self, *targets): """Tags a target so that it will not be cleaned by -c""" @@ -1924,17 +1911,17 @@ class Base(SubstitutionEnvironment): if SCons.Util.is_Sequence(s): result=[] for e in s: - result.append(apply(self.fs.Entry, (e,) + args, kw)) + result.append(self.fs.Entry(e, *args, **kw)) return result - return apply(self.fs.Entry, (s,) + args, kw) + return self.fs.Entry(s, *args, **kw) def Environment(self, **kw): - return apply(SCons.Environment.Environment, [], self.subst_kw(kw)) + return SCons.Environment.Environment(**self.subst_kw(kw)) def Execute(self, action, *args, **kw): """Directly execute an action through an Environment """ - action = apply(self.Action, (action,) + args, kw) + action = self.Action(action, *args, **kw) result = action([], [], self) if isinstance(result, SCons.Errors.BuildError): errstr = result.errstr @@ -1952,9 +1939,9 @@ class Base(SubstitutionEnvironment): if SCons.Util.is_Sequence(s): result=[] for e in s: - result.append(apply(self.fs.File, (e,) + args, kw)) + result.append(self.fs.File(e, *args, **kw)) return result - return apply(self.fs.File, (s,) + args, kw) + return self.fs.File(s, *args, **kw) def FindFile(self, file, dirs): file = self.subst(file) @@ -1965,7 +1952,7 @@ class Base(SubstitutionEnvironment): return SCons.Util.flatten(sequence) def GetBuildPath(self, files): - result = map(str, self.arg2nodes(files, self.fs.Entry)) + result = list(map(str, self.arg2nodes(files, self.fs.Entry))) if SCons.Util.is_List(files): return result else: @@ -2007,7 +1994,7 @@ class Base(SubstitutionEnvironment): def Repository(self, *dirs, **kw): dirs = self.arg2nodes(list(dirs), self.fs.Dir) - apply(self.fs.Repository, dirs, kw) + self.fs.Repository(*dirs, **kw) def Requires(self, target, prerequisite): """Specify that 'prerequisite' must be built before 'target', @@ -2026,7 +2013,7 @@ class Base(SubstitutionEnvironment): arg = self.subst(arg) nargs.append(arg) nkw = self.subst_kw(kw) - return apply(SCons.Scanner.Base, nargs, nkw) + return SCons.Scanner.Base(*nargs, **nkw) def SConsignFile(self, name=".sconsign", dbm_module=None): if name is not None: @@ -2048,7 +2035,7 @@ class Base(SubstitutionEnvironment): 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) + 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) @@ -2058,6 +2045,9 @@ class Base(SubstitutionEnvironment): 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) @@ -2074,12 +2064,12 @@ class Base(SubstitutionEnvironment): 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." + 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 + raise UserError("Unknown source signature type '%s'" % type) def Split(self, arg): """This function converts a string or list into a list of strings @@ -2093,9 +2083,9 @@ class Base(SubstitutionEnvironment): 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 map(self.subst, arg) + return list(map(self.subst, arg)) elif SCons.Util.is_String(arg): - return string.split(self.subst(arg)) + return self.subst(arg).split() else: return [self.subst(arg)] @@ -2110,7 +2100,7 @@ class Base(SubstitutionEnvironment): 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." + 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 @@ -2119,7 +2109,7 @@ class Base(SubstitutionEnvironment): elif type == 'source': self.decide_target = self._changed_source else: - raise UserError, "Unknown target signature type '%s'"%type + raise UserError("Unknown target signature type '%s'"%type) def Value(self, value, built_value=None): """ @@ -2137,17 +2127,15 @@ class Base(SubstitutionEnvironment): node = self.arg2nodes(node, self.fs.Entry)[0] sources = [] - # Uncomment this and get rid of the global definition when we - # drop support for pre-2.2 Python versions. - #def build_source(ss, result): - # for s in ss: - # if isinstance(s, SCons.Node.FS.Dir): - # build_source(s.all_children(), result) - # elif s.has_builder(): - # build_source(s.sources, result) - # elif isinstance(s.disambiguate(), SCons.Node.FS.File): - # result.append(s) - build_source(node.all_children(), 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()) # THIS CODE APPEARS TO HAVE NO EFFECT # # get the final srcnode for all nodes, this means stripping any @@ -2208,7 +2196,7 @@ class OverrideEnvironment(Base): 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 + raise SCons.Errors.UserError("Illegal construction variable `%s'" % key) self.__dict__['overrides'][key] = value def __delitem__(self, key): try: @@ -2235,7 +2223,7 @@ class OverrideEnvironment(Base): self.__dict__['overrides'][key] return 1 except KeyError: - return self.__dict__['__subject'].has_key(key) + return key in self.__dict__['__subject'] def __contains__(self, key): if self.__dict__['overrides'].__contains__(key): return 1 @@ -2247,7 +2235,7 @@ class OverrideEnvironment(Base): return d def items(self): """Emulates the items() method of dictionaries.""" - return self.Dictionary().items() + return list(self.Dictionary().items()) # Overridden private construction environment methods. def _update(self, dict): @@ -2314,13 +2302,13 @@ def NoSubstitutionProxy(subject): nkw = kwargs.copy() nkw['gvars'] = {} self.raw_to_mode(nkw) - return apply(SCons.Subst.scons_subst_list, nargs, 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.raw_to_mode(nkw) - return apply(SCons.Subst.scons_subst, nargs, nkw) + return SCons.Subst.scons_subst(*nargs, **nkw) return _NoSubstitutionProxy(subject) # Local Variables: diff --git a/engine/SCons/Errors.py b/engine/SCons/Errors.py index 69b389a..542bc47 100644 --- a/engine/SCons/Errors.py +++ b/engine/SCons/Errors.py @@ -28,7 +28,7 @@ and user errors in SCons. """ -__revision__ = "src/engine/SCons/Errors.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Errors.py 5023 2010/06/14 22:05:46 scons" import SCons.Util @@ -133,7 +133,7 @@ class ExplicitExit(Exception): self.node = node self.status = status self.exitstatus = status - apply(Exception.__init__, (self,) + args) + Exception.__init__(self, *args) def convert_to_BuildError(status, exc_info=None): """ @@ -157,9 +157,7 @@ def convert_to_BuildError(status, exc_info=None): status=status, # might be 0, OK here exitstatus=status, # might be 0, OK here exc_info=exc_info) - # TODO(1.5): - #elif isinstance(status, (StopError, UserError)): - elif isinstance(status, StopError) or isinstance(status, UserError): + elif isinstance(status, (StopError, UserError)): buildError = BuildError( errstr=str(status), status=2, diff --git a/engine/SCons/Executor.py b/engine/SCons/Executor.py index 44a1b9e..7bb450a 100644 --- a/engine/SCons/Executor.py +++ b/engine/SCons/Executor.py @@ -26,19 +26,17 @@ Nodes. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Executor.py 5023 2010/06/14 22:05:46 scons" -import string -import UserList +import collections from SCons.Debug import logInstanceCreation import SCons.Errors import SCons.Memoize -class Batch: +class Batch(object): """Remembers exact association between targets and sources of executor.""" def __init__(self, targets=[], sources=[]): @@ -47,15 +45,15 @@ class Batch: -class TSList(UserList.UserList): +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 UserList.UserList purely so that the + 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 - UserList.UserList methods in practice. + collections.UserList methods in practice. """ def __init__(self, func): self.func = func @@ -76,7 +74,7 @@ class TSList(UserList.UserList): nl = self.func() return repr(nl) -class TSObject: +class TSObject(object): """A class that implements $TARGET or $SOURCE expansions by wrapping an Executor method. """ @@ -110,7 +108,7 @@ def rfile(node): return rfile() -class Executor: +class Executor(object): """A class for controlling instances of executing an action. This largely exists to hold a single association of an action, @@ -161,10 +159,10 @@ class Executor: ut = [] for b in self.batches: if b.targets[0].is_up_to_date(): - us.extend(map(rfile, b.sources)) + us.extend(list(map(rfile, b.sources))) ut.extend(b.targets) else: - cs.extend(map(rfile, b.sources)) + 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) @@ -190,14 +188,14 @@ class Executor: return rfile(self.batches[0].sources[0]).get_subst_proxy() def _get_sources(self, *args, **kw): - return SCons.Util.NodeList(map(lambda n: rfile(n).get_subst_proxy(), self.get_all_sources())) + 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(map(lambda n: n.get_subst_proxy(), self.get_all_targets())) + return SCons.Util.NodeList([n.get_subst_proxy() for n in self.get_all_targets()]) def _get_unchanged_sources(self, *args, **kw): try: @@ -226,7 +224,7 @@ class Executor: if not SCons.Util.is_List(action): if not action: import SCons.Errors - raise SCons.Errors.UserError, "Executor must have an action." + raise SCons.Errors.UserError("Executor must have an action.") action = [action] self.action_list = action @@ -237,16 +235,14 @@ class Executor: """Returns all targets for all batches of this Executor.""" result = [] for batch in self.batches: - # TODO(1.5): remove the list() cast - result.extend(list(batch.targets)) + 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: - # TODO(1.5): remove the list() cast - result.extend(list(batch.sources)) + result.extend(batch.sources) return result def get_all_children(self): @@ -271,8 +267,7 @@ class Executor: """ result = SCons.Util.UniqueList([]) for target in self.get_all_targets(): - # TODO(1.5): remove the list() cast - result.extend(list(target.prerequisites)) + result.extend(target.prerequisites) return result def get_action_side_effects(self): @@ -342,7 +337,7 @@ class Executor: for act in self.get_action_list(): #args = (self.get_all_targets(), self.get_all_sources(), env) args = ([], [], env) - status = apply(act, args, kw) + status = act(*args, **kw) if isinstance(status, SCons.Errors.BuildError): status.executor = self raise status @@ -372,7 +367,7 @@ class Executor: # TODO(batch): extend to multiple batches assert (len(self.batches) == 1) # TODO(batch): remove duplicates? - sources = filter(lambda x, s=self.batches[0].sources: x not in s, sources) + sources = [x for x in sources if x not in self.batches[0].sources] self.batches[0].sources.extend(sources) def get_sources(self): @@ -394,7 +389,7 @@ class Executor: 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]) + raise SCons.Errors.StopError(msg % (s, self.batches[0].targets[0])) def add_pre_action(self, action): self.pre_actions.append(action) @@ -406,9 +401,10 @@ class Executor: def my_str(self): env = self.get_build_env() - get = lambda action, t=self.get_all_targets(), s=self.get_all_sources(), e=env: \ - action.genstring(t, s, e) - return string.join(map(get, self.get_action_list()), "\n") + return "\n".join([action.genstring(self.get_all_targets(), + self.get_all_sources(), + env) + for action in self.get_action_list()]) def __str__(self): @@ -417,7 +413,7 @@ class Executor: def nullify(self): self.cleanup() self.do_execute = self.do_nothing - self.my_str = lambda S=self: '' + self.my_str = lambda: '' memoizer_counters.append(SCons.Memoize.CountValue('get_contents')) @@ -431,9 +427,10 @@ class Executor: except KeyError: pass env = self.get_build_env() - get = lambda action, t=self.get_all_targets(), s=self.get_all_sources(), e=env: \ - action.get_contents(t, s, e) - result = string.join(map(get, self.get_action_list()), "") + 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 @@ -521,7 +518,7 @@ class Executor: idict = {} for i in ignore: idict[i] = 1 - sourcelist = filter(lambda s, i=idict: not i.has_key(s), sourcelist) + sourcelist = [s for s in sourcelist if s not in idict] memo_dict[key] = sourcelist @@ -547,7 +544,7 @@ def GetBatchExecutor(key): return _batch_executors[key] def AddBatchExecutor(key, executor): - assert not _batch_executors.has_key(key) + assert key not in _batch_executors _batch_executors[key] = executor nullenv = None @@ -569,7 +566,7 @@ def get_NullEnvironment(): nullenv = NullEnvironment() return nullenv -class Null: +class Null(object): """A null Executor, with a null build Environment, that does nothing when the rest of the methods call it. diff --git a/engine/SCons/Job.py b/engine/SCons/Job.py index e3d7f0f..bbf1def 100644 --- a/engine/SCons/Job.py +++ b/engine/SCons/Job.py @@ -29,7 +29,9 @@ stop, and wait on jobs. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Job.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Job.py 5023 2010/06/14 22:05:46 scons" + +import SCons.compat import os import signal @@ -50,7 +52,7 @@ default_stack_size = 256 interrupt_msg = 'Build interrupted.' -class InterruptState: +class InterruptState(object): def __init__(self): self.interrupted = False @@ -61,7 +63,7 @@ class InterruptState: return self.interrupted -class Jobs: +class Jobs(object): """An instance of this class initializes N jobs, and provides methods for starting, stopping, and waiting on all N jobs. """ @@ -127,7 +129,7 @@ class Jobs: turns out that it very difficult to stop the build process by throwing asynchronously an exception such as KeyboardInterrupt. For example, the python Condition - variables (threading.Condition) and Queue's do not seem to + variables (threading.Condition) and queue's do not seem to asynchronous-exception-safe. It would require adding a whole bunch of try/finally block and except KeyboardInterrupt all over the place. @@ -161,7 +163,7 @@ class Jobs: except AttributeError: pass -class Serial: +class Serial(object): """This class is used to execute tasks in series, and is more efficient than Parallel, but is only appropriate for non-parallel builds. Only one instance of this class should be in existence at a time. @@ -187,7 +189,7 @@ class Serial: fails to execute (i.e. execute() raises an exception), then the job will stop.""" - while 1: + while True: task = self.taskmaster.next_task() if task is None: @@ -221,7 +223,7 @@ class Serial: # Parallel class (and its dependent classes) will work if the interpreter # doesn't support threads. try: - import Queue + import queue import threading except ImportError: pass @@ -240,7 +242,7 @@ else: self.start() def run(self): - while 1: + while True: task = self.requestQueue.get() if task is None: @@ -262,7 +264,7 @@ else: self.resultsQueue.put((task, ok)) - class ThreadPool: + class ThreadPool(object): """This class is responsible for spawning and managing worker threads.""" def __init__(self, num, stack_size, interrupted): @@ -271,8 +273,8 @@ else: One must specify the stack size of the worker threads. The stack size is specified in kilobytes. """ - self.requestQueue = Queue.Queue(0) - self.resultsQueue = Queue.Queue(0) + self.requestQueue = queue.Queue(0) + self.resultsQueue = queue.Queue(0) try: prev_size = threading.stack_size(stack_size*1024) @@ -293,9 +295,7 @@ else: worker = Worker(self.requestQueue, self.resultsQueue, interrupted) self.workers.append(worker) - # Once we drop Python 1.5 we can change the following to: - #if 'prev_size' in locals(): - if 'prev_size' in locals().keys(): + if 'prev_size' in locals(): threading.stack_size(prev_size) def put(self, task): @@ -338,7 +338,7 @@ else: worker.join(1.0) self.workers = [] - class Parallel: + class Parallel(object): """This class is used to execute tasks in parallel, and is somewhat less efficient than Serial, but is appropriate for parallel builds. @@ -374,7 +374,7 @@ else: jobs = 0 - while 1: + while True: # Start up as many available tasks as we're # allowed to. while jobs < self.maxjobs: @@ -402,7 +402,7 @@ else: # Let any/all completed tasks finish up before we go # back and put the next batch of tasks on the queue. - while 1: + while True: task, ok = self.tp.get() jobs = jobs - 1 diff --git a/engine/SCons/Memoize.py b/engine/SCons/Memoize.py index 5d9f01c..6be415b 100644 --- a/engine/SCons/Memoize.py +++ b/engine/SCons/Memoize.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Memoize.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Memoize.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Memoizer @@ -119,14 +119,14 @@ This collected caching logic nicely, but had two drawbacks: to figure out how to optimize the underlying methods. """ -import new +import types # A flag controlling whether or not we actually use memoization. use_memoizer = None CounterList = [] -class Counter: +class Counter(object): """ Base class for counting memoization hits and misses. @@ -165,11 +165,11 @@ class CountValue(Counter): """ def __call__(self, *args, **kw): obj = args[0] - if obj._memo.has_key(self.method_name): + if self.method_name in obj._memo: self.hit = self.hit + 1 else: self.miss = self.miss + 1 - return apply(self.underlying_method, args, kw) + return self.underlying_method(*args, **kw) class CountDict(Counter): """ @@ -199,91 +199,43 @@ class CountDict(Counter): except KeyError: self.miss = self.miss + 1 else: - key = apply(self.keymaker, args, kw) - if memo_dict.has_key(key): + key = self.keymaker(*args, **kw) + if key in memo_dict: self.hit = self.hit + 1 else: self.miss = self.miss + 1 - return apply(self.underlying_method, args, kw) + return self.underlying_method(*args, **kw) -class Memoizer: +class Memoizer(object): """Object which performs caching of method calls for its 'primary' instance.""" def __init__(self): pass -# Find out if we support metaclasses (Python 2.2 and later). +def Dump(title=None): + if title: + print title + CounterList.sort() + for counter in CounterList: + counter.display() -class M: +class Memoized_Metaclass(type): def __init__(cls, name, bases, cls_dict): - cls.use_metaclass = 1 - def fake_method(self): - pass - new.instancemethod(fake_method, None, cls) - -try: - class A: - __metaclass__ = M - - use_metaclass = A.use_metaclass -except AttributeError: - use_metaclass = None - reason = 'no metaclasses' -except TypeError: - use_metaclass = None - reason = 'new.instancemethod() bug' -else: - del A - -del M - -if not use_metaclass: - - def Dump(title): - pass + 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) - try: - class Memoized_Metaclass(type): - # Just a place-holder so pre-metaclass Python versions don't - # have to have special code for the Memoized classes. - pass - except TypeError: - class Memoized_Metaclass: - # A place-holder so pre-metaclass Python versions don't - # have to have special code for the Memoized classes. - pass - - def EnableMemoization(): - import SCons.Warnings - msg = 'memoization is not supported in this version of Python (%s)' - raise SCons.Warnings.NoMetaclassSupportWarning, msg % reason - -else: - - 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 = new.instancemethod(counter, None, cls) - setattr(cls, method_name, replacement_method) - - def EnableMemoization(): - global use_memoizer - use_memoizer = 1 +def EnableMemoization(): + global use_memoizer + use_memoizer = 1 # Local Variables: # tab-width:4 diff --git a/engine/SCons/Node/Alias.py b/engine/SCons/Node/Alias.py index ff4a47e..291ac4d 100644 --- a/engine/SCons/Node/Alias.py +++ b/engine/SCons/Node/Alias.py @@ -30,23 +30,22 @@ This creates a hash of global Aliases (dummy targets). # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Node/Alias.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Node/Alias.py 5023 2010/06/14 22:05:46 scons" -import string -import UserDict +import collections import SCons.Errors import SCons.Node import SCons.Util -class AliasNameSpace(UserDict.UserDict): +class AliasNameSpace(collections.UserDict): def Alias(self, name, **kw): if isinstance(name, SCons.Node.Alias.Alias): return name try: a = self[name] except KeyError: - a = apply(SCons.Node.Alias.Alias, (name,), kw) + a = SCons.Node.Alias.Alias(name, **kw) self[name] = a return a @@ -95,8 +94,8 @@ class Alias(SCons.Node.Node): def get_contents(self): """The contents of an alias is the concatenation of the content signatures of all its sources.""" - childsigs = map(lambda n: n.get_csig(), self.children()) - return string.join(childsigs, '') + childsigs = [n.get_csig() for n in self.children()] + return ''.join(childsigs) def sconsign(self): """An Alias is not recorded in .sconsign files""" diff --git a/engine/SCons/Node/FS.py b/engine/SCons/Node/FS.py index 10641e9..9298d98 100644 --- a/engine/SCons/Node/FS.py +++ b/engine/SCons/Node/FS.py @@ -31,73 +31,17 @@ that can be used by scripts or modules looking for the canonical default. # 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/Node/FS.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Node/FS.py 5023 2010/06/14 22:05:46 scons" -from itertools import izip -import cStringIO import fnmatch import os -import os.path import re import shutil import stat -import string import sys import time - -try: - import codecs -except ImportError: - pass -else: - # TODO(2.2): Remove when 2.3 becomes the minimal supported version. - try: - codecs.BOM_UTF8 - except AttributeError: - codecs.BOM_UTF8 = '\xef\xbb\xbf' - try: - codecs.BOM_UTF16_LE - codecs.BOM_UTF16_BE - except AttributeError: - codecs.BOM_UTF16_LE = '\xff\xfe' - codecs.BOM_UTF16_BE = '\xfe\xff' - - # Provide a wrapper function to handle decoding differences in - # different versions of Python. Normally, we'd try to do this in the - # compat layer (and maybe it still makes sense to move there?) but - # that doesn't provide a way to supply the string class used in - # pre-2.3 Python versions with a .decode() method that all strings - # naturally have. Plus, the 2.[01] encodings behave differently - # enough that we have to settle for a lowest-common-denominator - # wrapper approach. - # - # Note that the 2.[012] implementations below may be inefficient - # because they perform an explicit look up of the encoding for every - # decode, but they're old enough (and we want to stop supporting - # them soon enough) that it's not worth complicating the interface. - # Think of it as additional incentive for people to upgrade... - try: - ''.decode - except AttributeError: - # 2.0 through 2.2: strings have no .decode() method - try: - codecs.lookup('ascii').decode - except AttributeError: - # 2.0 and 2.1: encodings are a tuple of functions, and the - # decode() function returns a (result, length) tuple. - def my_decode(contents, encoding): - return codecs.lookup(encoding)[1](contents)[0] - else: - # 2.2: encodings are an object with methods, and the - # .decode() method returns just the decoded bytes. - def my_decode(contents, encoding): - return codecs.lookup(encoding).decode(contents) - else: - # 2.3 or later: use the .decode() string method - def my_decode(contents, encoding): - return contents.decode(encoding) +import codecs import SCons.Action from SCons.Debug import logInstanceCreation @@ -256,11 +200,11 @@ def set_duplicate(duplicate): } if not duplicate in Valid_Duplicates: - raise SCons.Errors.InternalError, ("The argument of set_duplicate " + raise SCons.Errors.InternalError("The argument of set_duplicate " "should be in Valid_Duplicates") global Link_Funcs Link_Funcs = [] - for func in string.split(duplicate,'-'): + for func in duplicate.split('-'): if link_dict[func]: Link_Funcs.append(link_dict[func]) @@ -334,7 +278,7 @@ def get_MkdirBuilder(): name = "MkdirBuilder") return MkdirBuilder -class _Null: +class _Null(object): pass _null = _Null() @@ -373,25 +317,23 @@ if os.path.normcase("TeSt") == os.path.normpath("TeSt") and not _is_cygwin: return x else: def _my_normcase(x): - return string.upper(x) + return x.upper() -class DiskChecker: +class DiskChecker(object): def __init__(self, type, do, ignore): self.type = type self.do = do self.ignore = ignore - self.set_do() - def set_do(self): - self.__call__ = self.do - def set_ignore(self): - self.__call__ = self.ignore + self.func = do + def __call__(self, *args, **kw): + return self.func(*args, **kw) def set(self, list): if self.type in list: - self.set_do() + self.func = self.do else: - self.set_ignore() + self.func = self.ignore def do_diskcheck_match(node, predicate, errorfmt): result = predicate() @@ -407,7 +349,7 @@ def do_diskcheck_match(node, predicate, errorfmt): except (AttributeError, KeyError): pass if result: - raise TypeError, errorfmt % node.abspath + raise TypeError(errorfmt % node.abspath) def ignore_diskcheck_match(node, predicate, errorfmt): pass @@ -459,11 +401,14 @@ def set_diskcheck(list): dc.set(list) def diskcheck_types(): - return map(lambda dc: dc.type, diskcheckers) + return [dc.type for dc in diskcheckers] class EntryProxy(SCons.Util.Proxy): + + __str__ = SCons.Util.Delegate('__str__') + def __get_abspath(self): entry = self.get() return SCons.Subst.SpecialAttrWrapper(entry.get_abspath(), @@ -497,7 +442,7 @@ class EntryProxy(SCons.Util.Proxy): return self else: entry = self.get() - r = string.replace(entry.get_path(), os.sep, '/') + r = entry.get_path().replace(os.sep, '/') return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_posix") def __get_windows_path(self): @@ -507,7 +452,7 @@ class EntryProxy(SCons.Util.Proxy): return self else: entry = self.get() - r = string.replace(entry.get_path(), os.sep, '\\') + r = entry.get_path().replace(os.sep, '\\') return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_windows") def __get_srcnode(self): @@ -620,8 +565,8 @@ class Base(SCons.Node.Node): """ if isinstance(self, klass) or klass is Entry: return - raise TypeError, "Tried to lookup %s '%s' as a %s." %\ - (self.__class__.__name__, self.path, klass.__name__) + raise TypeError("Tried to lookup %s '%s' as a %s." %\ + (self.__class__.__name__, self.path, klass.__name__)) def get_dir(self): return self.dir @@ -647,7 +592,7 @@ class Base(SCons.Node.Node): return self._memo['_save_str'] except KeyError: pass - result = intern(self._get_str()) + result = sys.intern(self._get_str()) self._memo['_save_str'] = result return result @@ -753,8 +698,8 @@ class Base(SCons.Node.Node): try: i = path_elems.index(dir) except ValueError: pass else: path_elems = path_elems[i+1:] - path_elems = map(lambda n: n.name, path_elems) - return string.join(path_elems, os.sep) + path_elems = [n.name for n in path_elems] + return os.sep.join(path_elems) def set_src_builder(self, builder): """Set the source code builder for this node.""" @@ -911,7 +856,7 @@ class Entry(Base): self._morph() elif must_exist: msg = "No such file or directory: '%s'" % self.abspath - raise SCons.Errors.UserError, msg + raise SCons.Errors.UserError(msg) else: self.__class__ = File self._morph() @@ -990,7 +935,7 @@ class Entry(Base): def rel_path(self, other): d = self.disambiguate() if d.__class__ is Entry: - raise "rel_path() could not disambiguate File/Dir" + raise Exception("rel_path() could not disambiguate File/Dir") return d.rel_path(other) def new_ninfo(self): @@ -1010,7 +955,7 @@ class Entry(Base): _classEntry = Entry -class LocalFS: +class LocalFS(object): if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass @@ -1249,7 +1194,7 @@ class FS(LocalFS): root = directory.root if os.sep != '/': - p = string.replace(p, os.sep, '/') + p = p.replace(os.sep, '/') return root._lookup_abs(p, fsclass, create) def Entry(self, name, directory = None, create = 1): @@ -1294,11 +1239,11 @@ class FS(LocalFS): if not isinstance(variant_dir, SCons.Node.Node): variant_dir = self.Dir(variant_dir) if src_dir.is_under(variant_dir): - raise SCons.Errors.UserError, "Source directory cannot be under variant directory." + raise SCons.Errors.UserError("Source directory cannot be under variant directory.") if variant_dir.srcdir: if variant_dir.srcdir == src_dir: return # We already did this. - raise SCons.Errors.UserError, "'%s' already has a source directory: '%s'."%(variant_dir, variant_dir.srcdir) + raise SCons.Errors.UserError("'%s' already has a source directory: '%s'."%(variant_dir, variant_dir.srcdir)) variant_dir.link(src_dir, duplicate) def Repository(self, *dirs): @@ -1327,12 +1272,12 @@ class FS(LocalFS): if start_dir.is_under(bd): # If already in the build-dir location, don't reflect return [orig], fmt % str(orig) - p = apply(os.path.join, [bd.path] + tail) + p = os.path.join(bd.path, *tail) targets.append(self.Entry(p)) tail = [dir.name] + tail dir = dir.up() if targets: - message = fmt % string.join(map(str, targets)) + message = fmt % ' '.join(map(str, targets)) return targets, message def Glob(self, pathname, ondisk=True, source=True, strings=False, cwd=None): @@ -1574,9 +1519,9 @@ class Dir(Base): i = self.path_elements.index(other) + 1 path_elems = ['..'] * (len(self.path_elements) - i) \ - + map(lambda n: n.name, other.path_elements[i:]) + + [n.name for n in other.path_elements[i:]] - result = string.join(path_elems, os.sep) + result = os.sep.join(path_elems) memo_dict[other] = result @@ -1622,7 +1567,7 @@ class Dir(Base): """A null "builder" for directories.""" global MkdirBuilder if self.builder is not MkdirBuilder: - apply(SCons.Node.Node.build, [self,], kw) + SCons.Node.Node.build(self, **kw) # # @@ -1641,7 +1586,7 @@ class Dir(Base): if p is None: # Don't use while: - else: for this condition because # if so, then parent is None and has no .path attribute. - raise SCons.Errors.StopError, parent.path + raise SCons.Errors.StopError(parent.path) parent = p listDirs.reverse() for dirnode in listDirs: @@ -1682,12 +1627,9 @@ class Dir(Base): """Return content signatures and names of all our children separated by new-lines. Ensure that the nodes are sorted.""" contents = [] - name_cmp = lambda a, b: cmp(a.name, b.name) - sorted_children = self.children()[:] - sorted_children.sort(name_cmp) - for node in sorted_children: + for node in sorted(self.children(), key=lambda t: t.name): contents.append('%s %s\n' % (node.get_csig(), node.name)) - return string.join(contents, '') + return ''.join(contents) def get_csig(self): """Compute the content signature for Directory nodes. In @@ -1783,7 +1725,7 @@ class Dir(Base): d[name] = result return result else: - return d.has_key(name) + return name in d memoizer_counters.append(SCons.Memoize.CountValue('srcdir_list')) @@ -1911,12 +1853,11 @@ class Dir(Base): in any way (or ignored, passing None is common). """ entries = self.entries - names = entries.keys() + names = list(entries.keys()) names.remove('.') names.remove('..') func(arg, self, names) - select_dirs = lambda n, e=entries: isinstance(e[n], Dir) - for dirname in filter(select_dirs, names): + for dirname in [n for n in names if isinstance(entries[n], Dir)]: entries[dirname].walk(func, arg) def glob(self, pathname, ondisk=True, source=False, strings=False): @@ -1953,9 +1894,8 @@ class Dir(Base): """ dirname, basename = os.path.split(pathname) if not dirname: - result = self._glob1(basename, ondisk, source, strings) - result.sort(lambda a, b: cmp(str(a), str(b))) - return result + return sorted(self._glob1(basename, ondisk, source, strings), + key=lambda t: str(t)) if has_glob_magic(dirname): list = self.glob(dirname, ondisk, source, strings=False) else: @@ -1964,10 +1904,9 @@ class Dir(Base): for dir in list: r = dir._glob1(basename, ondisk, source, strings) if strings: - r = map(lambda x, d=str(dir): os.path.join(d, x), r) + r = [os.path.join(str(dir), x) for x in r] result.extend(r) - result.sort(lambda a, b: cmp(str(a), str(b))) - return result + return sorted(result, key=lambda a: str(a)) def _glob1(self, pattern, ondisk=True, source=False, strings=False): """ @@ -1990,9 +1929,8 @@ class Dir(Base): # We use the .name attribute from the Node because the keys of # the dir.entries dictionary are normalized (that is, all upper # case) on case-insensitive systems like Windows. - #node_names = [ v.name for k, v in dir.entries.items() if k not in ('.', '..') ] - entry_names = filter(lambda n: n not in ('.', '..'), dir.entries.keys()) - node_names = map(lambda n, e=dir.entries: e[n].name, entry_names) + node_names = [ v.name for k, v in dir.entries.items() + if k not in ('.', '..') ] names.extend(node_names) if not strings: # Make sure the working directory (self) actually has @@ -2015,7 +1953,7 @@ class Dir(Base): # after we exit this loop. if pattern[0] != '.': #disk_names = [ d for d in disk_names if d[0] != '.' ] - disk_names = filter(lambda x: x[0] != '.', disk_names) + disk_names = [x for x in disk_names if x[0] != '.'] disk_names = fnmatch.filter(disk_names, pattern) dirEntry = dir.Entry for name in disk_names: @@ -2031,14 +1969,14 @@ class Dir(Base): names = set(names) if pattern[0] != '.': #names = [ n for n in names if n[0] != '.' ] - names = filter(lambda x: x[0] != '.', names) + names = [x for x in names if x[0] != '.'] names = fnmatch.filter(names, pattern) if strings: return names #return [ self.entries[_my_normcase(n)] for n in names ] - return map(lambda n, e=self.entries: e[_my_normcase(n)], names) + return [self.entries[_my_normcase(n)] for n in names] class RootDir(Dir): """A class for the root directory of a file system. @@ -2111,7 +2049,7 @@ class RootDir(Dir): except KeyError: if not create: msg = "No such file or directory: '%s' in '%s' (and create is False)" % (p, str(self)) - raise SCons.Errors.UserError, msg + raise SCons.Errors.UserError(msg) # There is no Node for this path name, and we're allowed # to create it. dir_name, file_name = os.path.split(p) @@ -2200,7 +2138,7 @@ class FileBuildInfo(SCons.Node.BuildInfoBase): except AttributeError: s = str(n) else: - s = string.replace(s, os.sep, '/') + s = s.replace(os.sep, '/') return s for attr in ['bsources', 'bdepends', 'bimplicit']: try: @@ -2208,7 +2146,7 @@ class FileBuildInfo(SCons.Node.BuildInfoBase): except AttributeError: pass else: - setattr(self, attr, map(node_to_str, val)) + setattr(self, attr, list(map(node_to_str, val))) def convert_from_sconsign(self, dir, name): """ Converts a newly-read FileBuildInfo object for in-SCons use @@ -2238,7 +2176,7 @@ class FileBuildInfo(SCons.Node.BuildInfoBase): except AttributeError: continue nodes = [] - for s, ni in izip(strings, nodeinfos): + for s, ni in zip(strings, nodeinfos): if not isinstance(s, SCons.Node.Node): s = ni.str_to_node(s) nodes.append(s) @@ -2247,11 +2185,11 @@ class FileBuildInfo(SCons.Node.BuildInfoBase): result = [] bkids = self.bsources + self.bdepends + self.bimplicit bkidsigs = self.bsourcesigs + self.bdependsigs + self.bimplicitsigs - for bkid, bkidsig in izip(bkids, bkidsigs): + for bkid, bkidsig in zip(bkids, bkidsigs): result.append(str(bkid) + ': ' + - string.join(bkidsig.format(names=names), ' ')) + ' '.join(bkidsig.format(names=names))) result.append('%s [%s]' % (self.bactsig, self.bact)) - return string.join(result, '\n') + return '\n'.join(result) class File(Base): """A class for files in a file system. @@ -2286,9 +2224,7 @@ class File(Base): def Dirs(self, pathlist): """Create a list of directories relative to the SConscript directory of this file.""" - # TODO(1.5) - # return [self.Dir(p) for p in pathlist] - return map(lambda p, s=self: s.Dir(p), pathlist) + return [self.Dir(p) for p in pathlist] def File(self, name): """Create a file node named 'name' relative to @@ -2336,38 +2272,24 @@ class File(Base): raise return contents - try: - import codecs - except ImportError: - get_text_contents = get_contents - else: - # This attempts to figure out what the encoding of the text is - # based upon the BOM bytes, and then decodes the contents so that - # it's a valid python string. - def get_text_contents(self): - contents = self.get_contents() - # The behavior of various decode() methods and functions - # w.r.t. the initial BOM bytes is different for different - # encodings and/or Python versions. ('utf-8' does not strip - # them, but has a 'utf-8-sig' which does; 'utf-16' seems to - # strip them; etc.) Just side step all the complication by - # explicitly stripping the BOM before we decode(). - if contents.startswith(codecs.BOM_UTF8): - contents = contents[len(codecs.BOM_UTF8):] - # TODO(2.2): Remove when 2.3 becomes floor. - #contents = contents.decode('utf-8') - contents = my_decode(contents, 'utf-8') - elif contents.startswith(codecs.BOM_UTF16_LE): - contents = contents[len(codecs.BOM_UTF16_LE):] - # TODO(2.2): Remove when 2.3 becomes floor. - #contents = contents.decode('utf-16-le') - contents = my_decode(contents, 'utf-16-le') - elif contents.startswith(codecs.BOM_UTF16_BE): - contents = contents[len(codecs.BOM_UTF16_BE):] - # TODO(2.2): Remove when 2.3 becomes floor. - #contents = contents.decode('utf-16-be') - contents = my_decode(contents, 'utf-16-be') - return contents + # This attempts to figure out what the encoding of the text is + # based upon the BOM bytes, and then decodes the contents so that + # it's a valid python string. + def get_text_contents(self): + contents = self.get_contents() + # The behavior of various decode() methods and functions + # w.r.t. the initial BOM bytes is different for different + # encodings and/or Python versions. ('utf-8' does not strip + # them, but has a 'utf-8-sig' which does; 'utf-16' seems to + # strip them; etc.) Just sidestep all the complication by + # explicitly stripping the BOM before we decode(). + if contents.startswith(codecs.BOM_UTF8): + return contents[len(codecs.BOM_UTF8):].decode('utf-8') + if contents.startswith(codecs.BOM_UTF16_LE): + return contents[len(codecs.BOM_UTF16_LE):].decode('utf-16-le') + if contents.startswith(codecs.BOM_UTF16_BE): + return contents[len(codecs.BOM_UTF16_BE):].decode('utf-16-be') + return contents def get_content_hash(self): """ @@ -2603,7 +2525,7 @@ class File(Base): if scanner: # result = [n.disambiguate() for n in scanner(self, env, path)] result = scanner(self, env, path) - result = map(lambda N: N.disambiguate(), result) + result = [N.disambiguate() for N in result] else: result = [] @@ -2741,7 +2663,7 @@ class File(Base): self._createDir() except SCons.Errors.StopError, drive: desc = "No drive `%s' for target `%s'." % (drive, self) - raise SCons.Errors.StopError, desc + raise SCons.Errors.StopError(desc) # # @@ -2760,7 +2682,7 @@ class File(Base): e = Link(self, src, None) if isinstance(e, SCons.Errors.BuildError): desc = "Cannot duplicate `%s' in `%s': %s." % (src.path, self.dir.path, e.errstr) - raise SCons.Errors.StopError, desc + raise SCons.Errors.StopError(desc) self.linked = 1 # The Link() action may or may not have actually # created the file, depending on whether the -n @@ -3019,7 +2941,7 @@ class File(Base): children = self.children() executor = self.get_executor() # sigs = [n.get_cachedir_csig() for n in children] - sigs = map(lambda n: n.get_cachedir_csig(), children) + sigs = [n.get_cachedir_csig() for n in children] sigs.append(SCons.Util.MD5signature(executor.get_contents())) sigs.append(self.path) result = self.cachesig = SCons.Util.MD5collect(sigs) @@ -3034,7 +2956,7 @@ def get_default_fs(): default_fs = FS() return default_fs -class FileFinder: +class FileFinder(object): """ """ if SCons.Memoize.use_memoizer: @@ -3117,8 +3039,8 @@ class FileFinder: if verbose and not callable(verbose): if not SCons.Util.is_String(verbose): verbose = "find_file" - verbose = ' %s: ' % verbose - verbose = lambda s, v=verbose: sys.stdout.write(v + s) + _verbose = u' %s: ' % verbose + verbose = lambda s: sys.stdout.write(_verbose + s) filedir, filename = os.path.split(filename) if filedir: @@ -3150,10 +3072,10 @@ class FileFinder: # if isinstance(node, Dir) or isinstance(node, Entry): # return node # return None - #paths = filter(None, map(filedir_lookup, paths)) + #paths = [_f for _f in map(filedir_lookup, paths) if _f] self.default_filedir = filedir - paths = filter(None, map(self.filedir_lookup, paths)) + paths = [_f for _f in map(self.filedir_lookup, paths) if _f] result = None for dir in paths: diff --git a/engine/SCons/Node/Python.py b/engine/SCons/Node/Python.py index 53c2c80..be99d28 100644 --- a/engine/SCons/Node/Python.py +++ b/engine/SCons/Node/Python.py @@ -27,7 +27,7 @@ Python nodes. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Node/Python.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Node/Python.py 5023 2010/06/14 22:05:46 scons" import SCons.Node @@ -67,7 +67,7 @@ class Value(SCons.Node.Node): def build(self, **kw): if not hasattr(self, 'built_value'): - apply (SCons.Node.Node.build, (self,), kw) + SCons.Node.Node.build(self, **kw) is_up_to_date = SCons.Node.Node.children_are_up_to_date diff --git a/engine/SCons/Node/__init__.py b/engine/SCons/Node/__init__.py index b0570b0..8d15b58 100644 --- a/engine/SCons/Node/__init__.py +++ b/engine/SCons/Node/__init__.py @@ -40,14 +40,12 @@ be able to depend on any other type of "thing." # 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/Node/__init__.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Node/__init__.py 5023 2010/06/14 22:05:46 scons" +import collections import copy -from itertools import chain, izip -import string -import UserList +from itertools import chain from SCons.Debug import logInstanceCreation import SCons.Executor @@ -57,7 +55,7 @@ import SCons.Util from SCons.Debug import Trace def classname(obj): - return string.split(str(obj.__class__), '.')[-1] + return str(obj.__class__).split('.')[-1] # Node states # @@ -99,7 +97,7 @@ Annotate = do_nothing # Classes for signature info for Nodes. -class NodeInfoBase: +class NodeInfoBase(object): """ The generic base class for signature information for a Node. @@ -107,7 +105,7 @@ class NodeInfoBase: logic for dealing with their own Node-specific signature information. """ current_version_id = 1 - def __init__(self, node): + def __init__(self, node=None): # Create an object attribute from the class attribute so it ends up # in the pickled data in the .sconsign file. self._version_id = self.current_version_id @@ -136,8 +134,7 @@ class NodeInfoBase: try: field_list = self.field_list except AttributeError: - field_list = self.__dict__.keys() - field_list.sort() + field_list = sorted(self.__dict__.keys()) fields = [] for field in field_list: try: @@ -150,7 +147,7 @@ class NodeInfoBase: fields.append(f) return fields -class BuildInfoBase: +class BuildInfoBase(object): """ The generic base class for build information for a Node. @@ -161,7 +158,7 @@ class BuildInfoBase: implicit dependencies, and action information. """ current_version_id = 1 - def __init__(self, node): + def __init__(self, node=None): # Create an object attribute from the class attribute so it ends up # in the pickled data in the .sconsign file. self._version_id = self.current_version_id @@ -172,7 +169,7 @@ class BuildInfoBase: def merge(self, other): self.__dict__.update(other.__dict__) -class Node: +class Node(object): """The base Node class, for entities that we know how to build, or use to build other Nodes. """ @@ -182,7 +179,7 @@ class Node: memoizer_counters = [] - class Attrs: + class Attrs(object): pass def __init__(self): @@ -351,12 +348,12 @@ class Node: for d in self.depends: if d.missing(): msg = "Explicit dependency `%s' not found, needed by target `%s'." - raise SCons.Errors.StopError, msg % (d, self) + raise SCons.Errors.StopError(msg % (d, self)) if self.implicit is not None: for i in self.implicit: if i.missing(): msg = "Implicit dependency `%s' not found, needed by target `%s'." - raise SCons.Errors.StopError, msg % (i, self) + raise SCons.Errors.StopError(msg % (i, self)) self.binfo = self.get_binfo() def build(self, **kw): @@ -372,7 +369,7 @@ class Node: """ try: - apply(self.get_executor(), (self,), kw) + self.get_executor()(self, **kw) except SCons.Errors.BuildError, e: e.node = self raise @@ -548,8 +545,7 @@ class Node: deps = [] while nodes: n = nodes.pop(0) - d = filter(lambda x, seen=seen: not seen.has_key(x), - n.get_found_includes(env, scanner, path)) + d = [x for x in n.get_found_includes(env, scanner, path) if x not in seen] if d: deps.extend(d) for n in d: @@ -832,7 +828,7 @@ class Node: except TypeError, e: e = e.args[0] if SCons.Util.is_List(e): - s = map(str, e) + s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) @@ -849,7 +845,7 @@ class Node: except TypeError, e: e = e.args[0] if SCons.Util.is_List(e): - s = map(str, e) + s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) @@ -863,7 +859,7 @@ class Node: except TypeError, e: e = e.args[0] if SCons.Util.is_List(e): - s = map(str, e) + s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) @@ -1053,7 +1049,7 @@ class Node: if t: Trace(': old %s new %s' % (len(then), len(children))) result = True - for child, prev_ni in izip(children, then): + for child, prev_ni in zip(children, then): if child.changed_since_last_build(self, prev_ni): if t: Trace(': %s changed' % child) result = True @@ -1199,8 +1195,8 @@ class Node: new_bkids = new.bsources + new.bdepends + new.bimplicit new_bkidsigs = new.bsourcesigs + new.bdependsigs + new.bimplicitsigs - osig = dict(izip(old_bkids, old_bkidsigs)) - nsig = dict(izip(new_bkids, new_bkidsigs)) + osig = dict(zip(old_bkids, old_bkidsigs)) + nsig = dict(zip(new_bkids, new_bkidsigs)) # The sources and dependencies we'll want to report are all stored # as relative paths to this target's directory, but we want to @@ -1215,11 +1211,11 @@ class Node: lines = [] - removed = filter(lambda x, nk=new_bkids: not x in nk, old_bkids) + removed = [x for x in old_bkids if not x in new_bkids] if removed: - removed = map(stringify, removed) + removed = list(map(stringify, removed)) fmt = "`%s' is no longer a dependency\n" - lines.extend(map(lambda s, fmt=fmt: fmt % s, removed)) + lines.extend([fmt % s for s in removed]) for k in new_bkids: if not k in old_bkids: @@ -1229,14 +1225,14 @@ class Node: if len(lines) == 0 and old_bkids != new_bkids: lines.append("the dependency order changed:\n" + - "%sold: %s\n" % (' '*15, map(stringify, old_bkids)) + - "%snew: %s\n" % (' '*15, map(stringify, new_bkids))) + "%sold: %s\n" % (' '*15, list(map(stringify, old_bkids))) + + "%snew: %s\n" % (' '*15, list(map(stringify, new_bkids)))) if len(lines) == 0: def fmt_with_title(title, strlines): - lines = string.split(strlines, '\n') + lines = strlines.split('\n') sep = '\n' + ' '*(15 + len(title)) - return ' '*15 + title + string.join(lines, sep) + '\n' + return ' '*15 + title + sep.join(lines) + '\n' if old.bactsig != new.bactsig: if old.bact == new.bact: lines.append("the contents of the build action changed\n" + @@ -1254,31 +1250,22 @@ class Node: return "%s %s" % (preamble, lines[0]) else: lines = ["%s:\n" % preamble] + lines - return string.join(lines, ' '*11) - -try: - [].extend(UserList.UserList([])) -except TypeError: - # Python 1.5.2 doesn't allow a list to be extended by list-like - # objects (such as UserList instances), so just punt and use - # real lists. - def NodeList(l): - return l -else: - class NodeList(UserList.UserList): - def __str__(self): - return str(map(str, self.data)) + return ( ' '*11).join(lines) + +class NodeList(collections.UserList): + def __str__(self): + return str(list(map(str, self.data))) def get_children(node, parent): return node.children() def ignore_cycle(node, stack): pass def do_nothing(node, parent): pass -class Walker: +class Walker(object): """An iterator for walking a Node tree. This is depth-first, children are visited before the parent. The Walker object can be initialized with any node, and - returns the next node on the descent with each next() call. + returns the next node on the descent with each get_next() call. 'kids_func' is an optional function that will be called to get the children of a node instead of calling 'children'. 'cycle_func' is an optional function that will be called @@ -1298,7 +1285,7 @@ class Walker: self.history = {} # used to efficiently detect and avoid cycles self.history[node] = None - def next(self): + def get_next(self): """Return the next node for this walk of the tree. This function is intentionally iterative, not recursive, @@ -1310,7 +1297,7 @@ class Walker: node = self.stack[-1].wkids.pop(0) if not self.stack[-1].wkids: self.stack[-1].wkids = None - if self.history.has_key(node): + if node in self.history: self.cycle_func(node, self.stack) else: node.wkids = copy.copy(self.kids_func(node, self.stack[-1])) diff --git a/engine/SCons/Options/BoolOption.py b/engine/SCons/Options/BoolOption.py index f0db8c9..f066a49 100644 --- a/engine/SCons/Options/BoolOption.py +++ b/engine/SCons/Options/BoolOption.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Options/BoolOption.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Options/BoolOption.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Place-holder for the old SCons.Options module hierarchy @@ -41,7 +41,7 @@ def BoolOption(*args, **kw): msg = "The BoolOption() function is deprecated; use the BoolVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True - return apply(SCons.Variables.BoolVariable, args, kw) + return SCons.Variables.BoolVariable(*args, **kw) # Local Variables: # tab-width:4 diff --git a/engine/SCons/Options/EnumOption.py b/engine/SCons/Options/EnumOption.py index 985cff9..b541108 100644 --- a/engine/SCons/Options/EnumOption.py +++ b/engine/SCons/Options/EnumOption.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Options/EnumOption.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Options/EnumOption.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Place-holder for the old SCons.Options module hierarchy @@ -41,7 +41,7 @@ def EnumOption(*args, **kw): msg = "The EnumOption() function is deprecated; use the EnumVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True - return apply(SCons.Variables.EnumVariable, args, kw) + return SCons.Variables.EnumVariable(*args, **kw) # Local Variables: # tab-width:4 diff --git a/engine/SCons/Options/ListOption.py b/engine/SCons/Options/ListOption.py index 56c3196..abc98a4 100644 --- a/engine/SCons/Options/ListOption.py +++ b/engine/SCons/Options/ListOption.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Options/ListOption.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Options/ListOption.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Place-holder for the old SCons.Options module hierarchy @@ -41,7 +41,7 @@ def ListOption(*args, **kw): msg = "The ListOption() function is deprecated; use the ListVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True - return apply(SCons.Variables.ListVariable, args, kw) + return SCons.Variables.ListVariable(*args, **kw) # Local Variables: # tab-width:4 diff --git a/engine/SCons/Options/PackageOption.py b/engine/SCons/Options/PackageOption.py index 597865b..db6cac9 100644 --- a/engine/SCons/Options/PackageOption.py +++ b/engine/SCons/Options/PackageOption.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Options/PackageOption.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Options/PackageOption.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Place-holder for the old SCons.Options module hierarchy @@ -41,7 +41,7 @@ def PackageOption(*args, **kw): msg = "The PackageOption() function is deprecated; use the PackageVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True - return apply(SCons.Variables.PackageVariable, args, kw) + return SCons.Variables.PackageVariable(*args, **kw) # Local Variables: # tab-width:4 diff --git a/engine/SCons/Options/PathOption.py b/engine/SCons/Options/PathOption.py index 04d56c2..e31960d 100644 --- a/engine/SCons/Options/PathOption.py +++ b/engine/SCons/Options/PathOption.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Options/PathOption.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Options/PathOption.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Place-holder for the old SCons.Options module hierarchy @@ -35,7 +35,7 @@ import SCons.Warnings warned = False -class _PathOptionClass: +class _PathOptionClass(object): def warn(self): global warned if not warned: @@ -45,27 +45,27 @@ class _PathOptionClass: def __call__(self, *args, **kw): self.warn() - return apply(SCons.Variables.PathVariable, args, kw) + return SCons.Variables.PathVariable(*args, **kw) def PathAccept(self, *args, **kw): self.warn() - return apply(SCons.Variables.PathVariable.PathAccept, args, kw) + return SCons.Variables.PathVariable.PathAccept(*args, **kw) def PathIsDir(self, *args, **kw): self.warn() - return apply(SCons.Variables.PathVariable.PathIsDir, args, kw) + return SCons.Variables.PathVariable.PathIsDir(*args, **kw) def PathIsDirCreate(self, *args, **kw): self.warn() - return apply(SCons.Variables.PathVariable.PathIsDirCreate, args, kw) + return SCons.Variables.PathVariable.PathIsDirCreate(*args, **kw) def PathIsFile(self, *args, **kw): self.warn() - return apply(SCons.Variables.PathVariable.PathIsFile, args, kw) + return SCons.Variables.PathVariable.PathIsFile(*args, **kw) def PathExists(self, *args, **kw): self.warn() - return apply(SCons.Variables.PathVariable.PathExists, args, kw) + return SCons.Variables.PathVariable.PathExists(*args, **kw) PathOption = _PathOptionClass() diff --git a/engine/SCons/Options/__init__.py b/engine/SCons/Options/__init__.py index b4960b1..63de8ed 100644 --- a/engine/SCons/Options/__init__.py +++ b/engine/SCons/Options/__init__.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Options/__init__.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Options/__init__.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Place-holder for the old SCons.Options module hierarchy @@ -48,24 +48,17 @@ class Options(SCons.Variables.Variables): msg = "The Options class is deprecated; use the Variables class instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True - apply(SCons.Variables.Variables.__init__, - (self,) + args, - kw) + SCons.Variables.Variables.__init__(self, *args, **kw) def AddOptions(self, *args, **kw): - return apply(SCons.Variables.Variables.AddVariables, - (self,) + args, - kw) + return SCons.Variables.Variables.AddVariables(self, *args, **kw) def UnknownOptions(self, *args, **kw): - return apply(SCons.Variables.Variables.UnknownVariables, - (self,) + args, - kw) + return SCons.Variables.Variables.UnknownVariables(self, *args, **kw) def FormatOptionHelpText(self, *args, **kw): - return apply(SCons.Variables.Variables.FormatVariableHelpText, - (self,) + args, - kw) + return SCons.Variables.Variables.FormatVariableHelpText(self, *args, + **kw) # Local Variables: # tab-width:4 diff --git a/engine/SCons/PathList.py b/engine/SCons/PathList.py index 307edd8..764b0b8 100644 --- a/engine/SCons/PathList.py +++ b/engine/SCons/PathList.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/PathList.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/PathList.py 5023 2010/06/14 22:05:46 scons" __doc__ = """SCons.PathList @@ -33,7 +33,6 @@ Do the Right Thing (almost) regardless of how the variable is specified. """ import os -import string import SCons.Memoize import SCons.Node @@ -67,7 +66,7 @@ def node_conv(obj): result = get() return result -class _PathList: +class _PathList(object): """ An actual PathList object. """ @@ -98,14 +97,14 @@ class _PathList: over and over for each target. """ if SCons.Util.is_String(pathlist): - pathlist = string.split(pathlist, os.pathsep) + pathlist = pathlist.split(os.pathsep) elif not SCons.Util.is_Sequence(pathlist): pathlist = [pathlist] pl = [] for p in pathlist: try: - index = string.find(p, '$') + index = p.find('$') except (AttributeError, TypeError): type = TYPE_OBJECT else: @@ -142,7 +141,7 @@ class _PathList: return tuple(result) -class PathListCache: +class PathListCache(object): """ A class to handle caching of PathList lookups. diff --git a/engine/SCons/Platform/__init__.py b/engine/SCons/Platform/__init__.py index 33cad25..7e6288d 100644 --- a/engine/SCons/Platform/__init__.py +++ b/engine/SCons/Platform/__init__.py @@ -42,13 +42,12 @@ their own platform definition. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/__init__.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/__init__.py 5023 2010/06/14 22:05:46 scons" import SCons.compat import imp import os -import string import sys import tempfile @@ -69,15 +68,15 @@ def platform_default(): if osname == 'posix': if sys.platform == 'cygwin': return 'cygwin' - elif string.find(sys.platform, 'irix') != -1: + elif sys.platform.find('irix') != -1: return 'irix' - elif string.find(sys.platform, 'sunos') != -1: + elif sys.platform.find('sunos') != -1: return 'sunos' - elif string.find(sys.platform, 'hp-ux') != -1: + elif sys.platform.find('hp-ux') != -1: return 'hpux' - elif string.find(sys.platform, 'aix') != -1: + elif sys.platform.find('aix') != -1: return 'aix' - elif string.find(sys.platform, 'darwin') != -1: + elif sys.platform.find('darwin') != -1: return 'darwin' else: return 'posix' @@ -94,7 +93,7 @@ def platform_module(name = platform_default()): our execution environment. """ full_name = 'SCons.Platform.' + name - if not sys.modules.has_key(full_name): + if full_name not in sys.modules: if os.name == 'java': eval(full_name) else: @@ -112,7 +111,7 @@ def platform_module(name = platform_default()): importer = zipimport.zipimporter( sys.modules['SCons.Platform'].__path__[0] ) mod = importer.load_module(full_name) except ImportError: - raise SCons.Errors.UserError, "No platform named '%s'" % name + raise SCons.Errors.UserError("No platform named '%s'" % name) setattr(SCons.Platform, name, mod) return sys.modules[full_name] @@ -121,14 +120,18 @@ def DefaultToolList(platform, env): """ return SCons.Tool.tool_list(platform, env) -class PlatformSpec: - def __init__(self, name): +class PlatformSpec(object): + def __init__(self, name, generate): self.name = name + self.generate = generate + + def __call__(self, *args, **kw): + return self.generate(*args, **kw) def __str__(self): return self.name -class TempFileMunge: +class TempFileMunge(object): """A callable class. You can set an Environment variable to this, then call it with a string argument, then it will perform temporary file substitution on it. This is used to circumvent the long command @@ -167,7 +170,10 @@ class TempFileMunge: except ValueError: maxline = 2048 - if (reduce(lambda x, y: x + len(y), cmd, 0) + len(cmd)) <= maxline: + length = 0 + for c in cmd: + length += len(c) + if length <= maxline: return self.cmd # We do a normpath because mktemp() has what appears to be @@ -184,7 +190,7 @@ class TempFileMunge: if env['SHELL'] and env['SHELL'] == 'sh': # The sh shell will try to escape the backslashes in the # path, so unescape them. - native_tmp = string.replace(native_tmp, '\\', r'\\\\') + native_tmp = native_tmp.replace('\\', r'\\\\') # In Cygwin, we want to use rm to delete the temporary # file, because del does not exist in the sh shell. rm = env.Detect('rm') or 'del' @@ -198,8 +204,8 @@ class TempFileMunge: if not prefix: prefix = '@' - args = map(SCons.Subst.quote_spaces, cmd[1:]) - os.write(fd, string.join(args, " ") + "\n") + args = list(map(SCons.Subst.quote_spaces, cmd[1:])) + os.write(fd, " ".join(args) + "\n") os.close(fd) # XXX Using the SCons.Action.print_actions value directly # like this is bogus, but expedient. This class should @@ -218,15 +224,14 @@ class TempFileMunge: # reach into SCons.Action directly. if SCons.Action.print_actions: print("Using tempfile "+native_tmp+" for command line:\n"+ - str(cmd[0]) + " " + string.join(args," ")) + str(cmd[0]) + " " + " ".join(args)) return [ cmd[0], prefix + native_tmp + '\n' + rm, native_tmp ] def Platform(name = platform_default()): """Select a canned Platform specification. """ module = platform_module(name) - spec = PlatformSpec(name) - spec.__call__ = module.generate + spec = PlatformSpec(name, module.generate) return spec # Local Variables: diff --git a/engine/SCons/Platform/aix.py b/engine/SCons/Platform/aix.py index 039d3d4..e729bcb 100644 --- a/engine/SCons/Platform/aix.py +++ b/engine/SCons/Platform/aix.py @@ -30,10 +30,9 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/aix.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/aix.py 5023 2010/06/14 22:05:46 scons" import os -import string import posix @@ -51,9 +50,9 @@ def get_xlc(env, xlc=None, xlc_r=None, packages=[]): cmd = "lslpp -fc " + package + " 2>/dev/null | egrep '" + xlc + "([^-_a-zA-Z0-9].*)?$'" line = os.popen(cmd).readline() if line: - v, p = string.split(line, ':')[1:3] - xlcVersion = string.split(v)[1] - xlcPath = string.split(p)[0] + v, p = line.split(':')[1:3] + xlcVersion = v.split()[1] + xlcPath = p.split()[0] xlcPath = xlcPath[:xlcPath.rindex('/')] break return (xlcPath, xlc, xlc_r, xlcVersion) diff --git a/engine/SCons/Platform/cygwin.py b/engine/SCons/Platform/cygwin.py index 0105ae9..854a2c5 100644 --- a/engine/SCons/Platform/cygwin.py +++ b/engine/SCons/Platform/cygwin.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/cygwin.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/cygwin.py 5023 2010/06/14 22:05:46 scons" import posix from SCons.Platform import TempFileMunge diff --git a/engine/SCons/Platform/darwin.py b/engine/SCons/Platform/darwin.py index 18c58f2..4d62517 100644 --- a/engine/SCons/Platform/darwin.py +++ b/engine/SCons/Platform/darwin.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/darwin.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/darwin.py 5023 2010/06/14 22:05:46 scons" import posix diff --git a/engine/SCons/Platform/hpux.py b/engine/SCons/Platform/hpux.py index d5ce3bb..4544dfb 100644 --- a/engine/SCons/Platform/hpux.py +++ b/engine/SCons/Platform/hpux.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/hpux.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/hpux.py 5023 2010/06/14 22:05:46 scons" import posix diff --git a/engine/SCons/Platform/irix.py b/engine/SCons/Platform/irix.py index 95df7eb..3daebf5 100644 --- a/engine/SCons/Platform/irix.py +++ b/engine/SCons/Platform/irix.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/irix.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/irix.py 5023 2010/06/14 22:05:46 scons" import posix diff --git a/engine/SCons/Platform/os2.py b/engine/SCons/Platform/os2.py index 973ac6b..e74a22c 100644 --- a/engine/SCons/Platform/os2.py +++ b/engine/SCons/Platform/os2.py @@ -30,11 +30,11 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/os2.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/os2.py 5023 2010/06/14 22:05:46 scons" import win32 def generate(env): - if not env.has_key('ENV'): + if 'ENV' not in env: env['ENV'] = {} env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' diff --git a/engine/SCons/Platform/posix.py b/engine/SCons/Platform/posix.py index 67aef3e..1f19277 100644 --- a/engine/SCons/Platform/posix.py +++ b/engine/SCons/Platform/posix.py @@ -30,12 +30,11 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/posix.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/posix.py 5023 2010/06/14 22:05:46 scons" import errno import os import os.path -import string import subprocess import sys import select @@ -53,14 +52,14 @@ def escape(arg): slash = '\\' special = '"$()' - arg = string.replace(arg, slash, slash+slash) + arg = arg.replace(slash, slash+slash) for c in special: - arg = string.replace(arg, c, slash+c) + arg = arg.replace(c, slash+c) return '"' + arg + '"' def exec_system(l, env): - stat = os.system(string.join(l)) + stat = os.system(' '.join(l)) if stat & 0xff: return stat | 0x80 return stat >> 8 @@ -90,22 +89,22 @@ def exec_fork(l, env): return stat >> 8 def _get_env_command(sh, escape, cmd, args, env): - s = string.join(args) + s = ' '.join(args) if env: l = ['env', '-'] + \ - map(lambda t, e=escape: e(t[0])+'='+e(t[1]), env.items()) + \ + [escape(t[0])+'='+escape(t[1]) for t in env.items()] + \ [sh, '-c', escape(s)] - s = string.join(l) + s = ' '.join(l) return s def env_spawn(sh, escape, cmd, args, env): return exec_system([_get_env_command( sh, escape, cmd, args, env)], env) def spawnvpe_spawn(sh, escape, cmd, args, env): - return exec_spawnvpe([sh, '-c', string.join(args)], env) + return exec_spawnvpe([sh, '-c', ' '.join(args)], env) def fork_spawn(sh, escape, cmd, args, env): - return exec_fork([sh, '-c', string.join(args)], env) + return exec_fork([sh, '-c', ' '.join(args)], env) def process_cmd_output(cmd_stdout, cmd_stderr, stdout, stderr): stdout_eof = stderr_eof = 0 @@ -131,7 +130,7 @@ def process_cmd_output(cmd_stdout, cmd_stderr, stdout, stderr): raise def exec_popen3(l, env, stdout, stderr): - proc = subprocess.Popen(string.join(l), + proc = subprocess.Popen(' '.join(l), stdout=stdout, stderr=stderr, shell=True) @@ -198,7 +197,7 @@ def piped_env_spawn(sh, escape, cmd, args, env, stdout, stderr): def piped_fork_spawn(sh, escape, cmd, args, env, stdout, stderr): # spawn using fork / exec and providing a pipe for the command's # stdout / stderr stream - return exec_piped_fork([sh, '-c', string.join(args)], + return exec_piped_fork([sh, '-c', ' '.join(args)], env, stdout, stderr) @@ -217,7 +216,7 @@ def generate(env): # os.fork()/os.exec() works better than os.system(). There may just # not be a default that works best for all users. - if os.__dict__.has_key('spawnvpe'): + if 'spawnvpe' in os.__dict__: spawn = spawnvpe_spawn elif env.Detect('env'): spawn = env_spawn @@ -229,7 +228,7 @@ def generate(env): else: pspawn = piped_fork_spawn - if not env.has_key('ENV'): + if 'ENV' not in env: env['ENV'] = {} env['ENV']['PATH'] = '/usr/local/bin:/opt/bin:/bin:/usr/bin' env['OBJPREFIX'] = '' diff --git a/engine/SCons/Platform/sunos.py b/engine/SCons/Platform/sunos.py index 0a816db..f855aa8 100644 --- a/engine/SCons/Platform/sunos.py +++ b/engine/SCons/Platform/sunos.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/sunos.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/sunos.py 5023 2010/06/14 22:05:46 scons" import posix diff --git a/engine/SCons/Platform/win32.py b/engine/SCons/Platform/win32.py index 1443099..57d9bdc 100644 --- a/engine/SCons/Platform/win32.py +++ b/engine/SCons/Platform/win32.py @@ -30,11 +30,10 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Platform/win32.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Platform/win32.py 5023 2010/06/14 22:05:46 scons" import os import os.path -import string import sys import tempfile @@ -61,27 +60,27 @@ except AttributeError: else: parallel_msg = None - import __builtin__ + import builtins - _builtin_file = __builtin__.file - _builtin_open = __builtin__.open + _builtin_file = builtins.file + _builtin_open = builtins.open def _scons_file(*args, **kw): - fp = apply(_builtin_file, args, kw) + fp = _builtin_file(*args, **kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(fp.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) return fp def _scons_open(*args, **kw): - fp = apply(_builtin_open, args, kw) + fp = _builtin_open(*args, **kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(fp.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) return fp - __builtin__.file = _scons_file - __builtin__.open = _scons_open + builtins.file = _scons_file + builtins.open = _scons_open @@ -109,11 +108,11 @@ def piped_spawn(sh, escape, cmd, args, env, stdout, stderr): stderrRedirected = 0 for arg in args: # are there more possibilities to redirect stdout ? - if (string.find( arg, ">", 0, 1 ) != -1 or - string.find( arg, "1>", 0, 2 ) != -1): + if (arg.find( ">", 0, 1 ) != -1 or + arg.find( "1>", 0, 2 ) != -1): stdoutRedirected = 1 # are there more possibilities to redirect stderr ? - if string.find( arg, "2>", 0, 2 ) != -1: + if arg.find( "2>", 0, 2 ) != -1: stderrRedirected = 1 # redirect output of non-redirected streams to our tempfiles @@ -124,7 +123,7 @@ def piped_spawn(sh, escape, cmd, args, env, stdout, stderr): # actually do the spawn try: - args = [sh, '/C', escape(string.join(args)) ] + args = [sh, '/C', escape(' '.join(args)) ] ret = os.spawnve(os.P_WAIT, sh, args, env) except OSError, e: # catch any error @@ -162,7 +161,7 @@ def exec_spawn(l, env): result = 127 if len(l) > 2: if len(l[2]) < 1000: - command = string.join(l[0:3]) + command = ' '.join(l[0:3]) else: command = l[0] else: @@ -174,7 +173,7 @@ def spawn(sh, escape, cmd, args, env): if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 - return exec_spawn([sh, '/C', escape(string.join(args))], env) + return exec_spawn([sh, '/C', escape(' '.join(args))], env) # Windows does not allow special characters in file names anyway, so no # need for a complex escape function, we will just quote the arg, except @@ -240,7 +239,7 @@ def get_program_files_dir(): # Determine which windows CPU were running on. -class ArchDefinition: +class ArchDefinition(object): """ A class for defining architecture-specific settings and logic. """ @@ -318,7 +317,7 @@ def generate(env): tmp_path = systemroot + os.pathsep + \ os.path.join(systemroot,'System32') tmp_pathext = '.com;.exe;.bat;.cmd' - if os.environ.has_key('PATHEXT'): + if 'PATHEXT' in os.environ: tmp_pathext = os.environ['PATHEXT'] cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext) if not cmd_interp: @@ -330,7 +329,7 @@ def generate(env): cmd_interp = env.Detect('command') - if not env.has_key('ENV'): + if 'ENV' not in env: env['ENV'] = {} # Import things from the external environment to the construction @@ -347,7 +346,7 @@ def generate(env): if v: env['ENV'][var] = v - if not env['ENV'].has_key('COMSPEC'): + if 'COMSPEC' not in env['ENV']: v = os.environ.get("COMSPEC") if v: env['ENV']['COMSPEC'] = v diff --git a/engine/SCons/SConf.py b/engine/SCons/SConf.py index 57ec0ca..bce935e 100644 --- a/engine/SCons/SConf.py +++ b/engine/SCons/SConf.py @@ -26,15 +26,15 @@ Autoconf-like configuration support. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/SConf.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/SConf.py 5023 2010/06/14 22:05:46 scons" +import SCons.compat + +import io import os import re -import string -import StringIO import sys import traceback -import types import SCons.Action import SCons.Builder @@ -79,7 +79,7 @@ def SetCacheMode(mode): elif mode == "cache": cache_mode = CACHE else: - raise ValueError, "SCons.SConf.SetCacheMode: Unknown mode " + mode + raise ValueError("SCons.SConf.SetCacheMode: Unknown mode " + mode) progress_display = SCons.Util.display # will be overwritten by SCons.Script def SetProgressDisplay(display): @@ -96,7 +96,7 @@ sconf_global = None # current sconf object def _createConfigH(target, source, env): t = open(str(target[0]), "w") - defname = re.sub('[^A-Za-z0-9_]', '_', string.upper(str(target[0]))) + defname = re.sub('[^A-Za-z0-9_]', '_', str(target[0]).upper()) t.write("""#ifndef %(DEFNAME)s_SEEN #define %(DEFNAME)s_SEEN @@ -153,12 +153,7 @@ def _createSource( target, source, env ): fd.close() def _stringSource( target, source, env ): return (str(target[0]) + ' <-\n |' + - string.replace( source[0].get_contents(), - '\n', "\n |" ) ) - -# python 2.2 introduces types.BooleanType -BooleanTypes = [types.IntType] -if hasattr(types, 'BooleanType'): BooleanTypes.append(types.BooleanType) + source[0].get_contents().replace( '\n', "\n |" ) ) class SConfBuildInfo(SCons.Node.FS.FileBuildInfo): """ @@ -174,13 +169,13 @@ class SConfBuildInfo(SCons.Node.FS.FileBuildInfo): self.string = string -class Streamer: +class Streamer(object): """ 'Sniffer' for a file-like writable object. Similar to the unix tool tee. """ def __init__(self, orig): self.orig = orig - self.s = StringIO.StringIO() + self.s = io.StringIO() def write(self, str): if self.orig: @@ -222,8 +217,7 @@ class SConfBuildTask(SCons.Taskmaster.AlwaysTask): "The stored build information has an unexpected class: %s" % bi.__class__) else: self.display("The original builder output was:\n" + - string.replace(" |" + str(bi.string), - "\n", "\n |")) + (" |" + str(bi.string)).replace("\n", "\n |")) def failed(self): # check, if the reason was a ConfigureDryRunError or a @@ -246,7 +240,7 @@ class SConfBuildTask(SCons.Taskmaster.AlwaysTask): def excepthook(type, value, tb): traceback.print_tb(tb) print type, value - apply(excepthook, self.exc_info()) + excepthook(*self.exc_info()) return SCons.Taskmaster.Task.failed(self) def collect_node_states(self): @@ -374,7 +368,7 @@ class SConfBuildTask(SCons.Taskmaster.AlwaysTask): sconsign.set_entry(t.name, sconsign_entry) sconsign.merge() -class SConfBase: +class SConfBase(object): """This is simply a class to represent a configure context. After creating a SConf object, you can call any tests. After finished with your tests, be sure to call the Finish() method, which returns the modified @@ -400,8 +394,7 @@ class SConfBase: SConfFS = SCons.Node.FS.default_fs or \ SCons.Node.FS.FS(env.fs.pathTop) if sconf_global is not None: - raise (SCons.Errors.UserError, - "Only one SConf object may be active at one time") + raise SCons.Errors.UserError self.env = env if log_file is not None: log_file = SConfFS.File(env.subst(log_file)) @@ -465,7 +458,7 @@ class SConfBase: lines.append(define_str) lines.append('') - self.config_h_text = self.config_h_text + string.join(lines, '\n') + self.config_h_text = self.config_h_text + '\n'.join(lines) def BuildNodes(self, nodes): """ @@ -635,17 +628,16 @@ class SConfBase: return( 1, outputStr) return (0, "") - class TestWrapper: + class TestWrapper(object): """A wrapper around Tests (to ensure sanity)""" def __init__(self, test, sconf): self.test = test self.sconf = sconf def __call__(self, *args, **kw): if not self.sconf.active: - raise (SCons.Errors.UserError, - "Test called after sconf.Finish()") + raise SCons.Errors.UserError context = CheckContext(self.sconf) - ret = apply(self.test, (context,) + args, kw) + ret = self.test(context, *args, **kw) if self.sconf.config_h is not None: self.sconf.config_h_text = self.sconf.config_h_text + context.config_h context.Result("error: no result") @@ -689,7 +681,7 @@ class SConfBase: if self.logfile is not None and not dryrun: # truncate logfile, if SConf.Configure is called for the first time # in a build - if _ac_config_logs.has_key(self.logfile): + if self.logfile in _ac_config_logs: log_mode = "a" else: _ac_config_logs[self.logfile] = None @@ -724,7 +716,7 @@ class SConfBase: global sconf_global, _ac_config_hs if not self.active: - raise SCons.Errors.UserError, "Finish may be called only once!" + raise SCons.Errors.UserError("Finish may be called only once!") if self.logstream is not None and not dryrun: self.logstream.write("\n") self.logstream.close() @@ -739,7 +731,7 @@ class SConfBase: _ac_config_hs[self.config_h] = self.config_h_text self.env.fs = self.lastEnvFs -class CheckContext: +class CheckContext(object): """Provides a context for configure tests. Defines how a test writes to the screen and log file. @@ -788,15 +780,15 @@ class CheckContext: string. In case of an integer, the written text will be 'yes' or 'no'. The result is only displayed when self.did_show_result is not set. """ - if type(res) in BooleanTypes: + if isinstance(res, (int, bool)): if res: text = "yes" else: text = "no" - elif type(res) == types.StringType: + elif isinstance(res, str): text = res else: - raise TypeError, "Expected string, int or bool, got " + str(type(res)) + raise TypeError("Expected string, int or bool, got " + str(type(res))) if self.did_show_result == 0: # Didn't show result yet, do it now. @@ -804,19 +796,19 @@ class CheckContext: self.did_show_result = 1 def TryBuild(self, *args, **kw): - return apply(self.sconf.TryBuild, args, kw) + return self.sconf.TryBuild(*args, **kw) def TryAction(self, *args, **kw): - return apply(self.sconf.TryAction, args, kw) + return self.sconf.TryAction(*args, **kw) def TryCompile(self, *args, **kw): - return apply(self.sconf.TryCompile, args, kw) + return self.sconf.TryCompile(*args, **kw) def TryLink(self, *args, **kw): - return apply(self.sconf.TryLink, args, kw) + return self.sconf.TryLink(*args, **kw) def TryRun(self, *args, **kw): - return apply(self.sconf.TryRun, args, kw) + return self.sconf.TryRun(*args, **kw) def __getattr__( self, attr ): if( attr == 'env' ): @@ -824,7 +816,7 @@ class CheckContext: elif( attr == 'lastTarget' ): return self.sconf.lastTarget else: - raise AttributeError, "CheckContext instance has no attribute '%s'" % attr + raise AttributeError("CheckContext instance has no attribute '%s'" % attr) #### Stuff used by Conftest.py (look there for explanations). @@ -889,7 +881,7 @@ def SConf(*args, **kw): del kw[bt] except KeyError: pass - return apply(SConfBase, args, kw) + return SConfBase(*args, **kw) else: return SCons.Util.Null() @@ -901,7 +893,7 @@ def CheckFunc(context, function_name, header = None, language = None): def CheckType(context, type_name, includes = "", language = None): res = SCons.Conftest.CheckType(context, type_name, - header = includes, language = language) + header = includes, language = language) context.did_show_result = 1 return not res @@ -933,7 +925,7 @@ def createIncludesFromHeaders(headers, leaveLast, include_quotes = '""'): for s in headers: l.append("#include %s%s%s\n" % (include_quotes[0], s, include_quotes[1])) - return string.join(l, ''), lastHeader + return ''.join(l), lastHeader def CheckHeader(context, header, include_quotes = '<>', language = None): """ diff --git a/engine/SCons/SConsign.py b/engine/SCons/SConsign.py index 8865c3d..25f8486 100644 --- a/engine/SCons/SConsign.py +++ b/engine/SCons/SConsign.py @@ -27,11 +27,13 @@ Writing and reading information to the .sconsign file or files. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/SConsign.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/SConsign.py 5023 2010/06/14 22:05:46 scons" + +import SCons.compat -import cPickle import os -import os.path +# compat layer imports "cPickle" for us if it's available. +import pickle import SCons.dblite import SCons.Warnings @@ -106,7 +108,7 @@ def write(): else: syncmethod() -class SConsignEntry: +class SConsignEntry(object): """ Wrapper class for the generic entry in a .sconsign file. The Node subclass populates it with attributes as it pleases. @@ -124,7 +126,7 @@ class SConsignEntry: def convert_from_sconsign(self, dir, name): self.binfo.convert_from_sconsign(dir, name) -class Base: +class Base(object): """ This is the controlling class for the signatures for the collection of entries associated with a specific directory. The actual directory @@ -201,8 +203,8 @@ class DB(Base): pass else: try: - self.entries = cPickle.loads(rawentries) - if type(self.entries) is not type({}): + self.entries = pickle.loads(rawentries) + if not isinstance(self.entries, dict): self.entries = {} raise TypeError except KeyboardInterrupt: @@ -239,7 +241,7 @@ class DB(Base): path = normcase(self.dir.path) for key, entry in self.entries.items(): entry.convert_to_sconsign() - db[path] = cPickle.dumps(self.entries, 1) + db[path] = pickle.dumps(self.entries, 1) if sync: try: @@ -260,8 +262,8 @@ class Dir(Base): if not fp: return - self.entries = cPickle.load(fp) - if type(self.entries) is not type({}): + self.entries = pickle.load(fp) + if not isinstance(self.entries, dict): self.entries = {} raise TypeError @@ -327,7 +329,7 @@ class DirFile(Dir): return for key, entry in self.entries.items(): entry.convert_to_sconsign() - cPickle.dump(self.entries, file, 1) + pickle.dump(self.entries, file, 1) file.close() if fname != self.sconsign: try: diff --git a/engine/SCons/Scanner/C.py b/engine/SCons/Scanner/C.py index a8f4be9..598d3b1 100644 --- a/engine/SCons/Scanner/C.py +++ b/engine/SCons/Scanner/C.py @@ -27,7 +27,7 @@ This module implements the depenency scanner for C/C++ code. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Scanner/C.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Scanner/C.py 5023 2010/06/14 22:05:46 scons" import SCons.Node.FS import SCons.Scanner @@ -44,7 +44,7 @@ class SConsCPPScanner(SCons.cpp.PreProcessor): missing. """ def __init__(self, *args, **kw): - apply(SCons.cpp.PreProcessor.__init__, (self,)+args, kw) + SCons.cpp.PreProcessor.__init__(self, *args, **kw) self.missing = [] def initialize_result(self, fname): self.result = SCons.Util.UniqueList([fname]) @@ -81,7 +81,7 @@ def dictify_CPPDEFINES(env): return {cppdefines : None} return cppdefines -class SConsCPPScannerWrapper: +class SConsCPPScannerWrapper(object): """ The SCons wrapper around a cpp.py scanner. diff --git a/engine/SCons/Scanner/D.py b/engine/SCons/Scanner/D.py index f657eeb..04bb5a7 100644 --- a/engine/SCons/Scanner/D.py +++ b/engine/SCons/Scanner/D.py @@ -30,10 +30,9 @@ Coded by Andy Friesen # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Scanner/D.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Scanner/D.py 5023 2010/06/14 22:05:46 scons" import re -import string import SCons.Scanner @@ -54,7 +53,7 @@ class D(SCons.Scanner.Classic): def find_include(self, include, source_dir, path): # translate dots (package separators) to slashes - inc = string.replace(include, '.', '/') + inc = include.replace('.', '/') i = SCons.Node.FS.find_file(inc + '.d', (source_dir,) + path) if i is None: diff --git a/engine/SCons/Scanner/Dir.py b/engine/SCons/Scanner/Dir.py index bb25324..172aa62 100644 --- a/engine/SCons/Scanner/Dir.py +++ b/engine/SCons/Scanner/Dir.py @@ -19,30 +19,29 @@ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -__revision__ = "src/engine/SCons/Scanner/Dir.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Scanner/Dir.py 5023 2010/06/14 22:05:46 scons" import SCons.Node.FS import SCons.Scanner def only_dirs(nodes): is_Dir = lambda n: isinstance(n.disambiguate(), SCons.Node.FS.Dir) - return filter(is_Dir, nodes) + return list(filter(is_Dir, nodes)) def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs - return apply(SCons.Scanner.Base, (scan_on_disk, "DirScanner"), kw) + return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw) def DirEntryScanner(**kw): """Return a prototype Scanner instance for "scanning" directory Nodes for their in-memory entries""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None - return apply(SCons.Scanner.Base, (scan_in_memory, "DirEntryScanner"), kw) + return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) skip_entry = {} @@ -67,7 +66,7 @@ for skip in skip_entry_list: skip_entry[skip] = 1 skip_entry[SCons.Node.FS._my_normcase(skip)] = 1 -do_not_scan = lambda k: not skip_entry.has_key(k) +do_not_scan = lambda k: k not in skip_entry def scan_on_disk(node, env, path=()): """ @@ -100,9 +99,8 @@ def scan_in_memory(node, env, path=()): # mixed Node types (Dirs and Files, for example) has a Dir as # the first entry. return [] - entry_list = filter(do_not_scan, entries.keys()) - entry_list.sort() - return map(lambda n, e=entries: e[n], entry_list) + entry_list = sorted(filter(do_not_scan, list(entries.keys()))) + return [entries[n] for n in entry_list] # Local Variables: # tab-width:4 diff --git a/engine/SCons/Scanner/Fortran.py b/engine/SCons/Scanner/Fortran.py index 1587368..8d023e7 100644 --- a/engine/SCons/Scanner/Fortran.py +++ b/engine/SCons/Scanner/Fortran.py @@ -25,12 +25,10 @@ This module implements the dependency scanner for Fortran code. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -__revision__ = "src/engine/SCons/Scanner/Fortran.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Scanner/Fortran.py 5023 2010/06/14 22:05:46 scons" import re -import string import SCons.Node import SCons.Node.FS @@ -75,7 +73,7 @@ class F90Scanner(SCons.Scanner.Classic): kw['skeys'] = suffixes kw['name'] = name - apply(SCons.Scanner.Current.__init__, (self,) + args, kw) + SCons.Scanner.Current.__init__(self, *args, **kw) def scan(self, node, env, path=()): @@ -94,12 +92,12 @@ class F90Scanner(SCons.Scanner.Classic): d = {} for m in defmodules: d[m] = 1 - modules = filter(lambda m, d=d: not d.has_key(m), modules) + modules = [m for m in modules if m not in d] #modules = self.undefinedModules(modules, defmodules) # Convert module name to a .mod filename suffix = env.subst('$FORTRANMODSUFFIX') - modules = map(lambda x, s=suffix: string.lower(x) + s, modules) + modules = [x.lower() + suffix for x in modules] # Remove unique items from the list mods_and_includes = SCons.Util.unique(includes+modules) node.includes = mods_and_includes @@ -123,9 +121,7 @@ class F90Scanner(SCons.Scanner.Classic): sortkey = self.sort_key(dep) nodes.append((sortkey, n)) - nodes.sort() - nodes = map(lambda pair: pair[1], nodes) - return nodes + return [pair[1] for pair in sorted(nodes)] def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files diff --git a/engine/SCons/Scanner/IDL.py b/engine/SCons/Scanner/IDL.py index f2169f8..507b9e1 100644 --- a/engine/SCons/Scanner/IDL.py +++ b/engine/SCons/Scanner/IDL.py @@ -28,7 +28,7 @@ Definition Language) files. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Scanner/IDL.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Scanner/IDL.py 5023 2010/06/14 22:05:46 scons" import SCons.Node.FS import SCons.Scanner diff --git a/engine/SCons/Scanner/LaTeX.py b/engine/SCons/Scanner/LaTeX.py index 01755f4..77be34c 100644 --- a/engine/SCons/Scanner/LaTeX.py +++ b/engine/SCons/Scanner/LaTeX.py @@ -27,10 +27,9 @@ This module implements the dependency scanner for LaTeX code. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Scanner/LaTeX.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Scanner/LaTeX.py 5023 2010/06/14 22:05:46 scons" import os.path -import string import re import SCons.Scanner @@ -41,7 +40,7 @@ TexGraphics = ['.eps', '.ps'] LatexGraphics = ['.pdf', '.png', '.jpg', '.gif', '.tif'] # Used as a return value of modify_env_var if the variable is not set. -class _Null: +class _Null(object): pass _null = _Null @@ -58,13 +57,10 @@ def modify_env_var(env, var, abspath): env.PrependENVPath(var, abspath) try: if SCons.Util.is_List(env[var]): - #TODO(1.5) - #env.PrependENVPath(var, [os.path.abspath(str(p)) for p in env[var]]) - env.PrependENVPath(var, map(lambda p: os.path.abspath(str(p)), env[var])) + env.PrependENVPath(var, [os.path.abspath(str(p)) for p in env[var]]) else: # Split at os.pathsep to convert into absolute path - #TODO(1.5) env.PrependENVPath(var, [os.path.abspath(p) for p in str(env[var]).split(os.pathsep)]) - env.PrependENVPath(var, map(lambda p: os.path.abspath(p), string.split(str(env[var]), os.pathsep))) + env.PrependENVPath(var, [os.path.abspath(p) for p in str(env[var]).split(os.pathsep)]) except KeyError: pass @@ -73,15 +69,13 @@ def modify_env_var(env, var, abspath): # does not work, refuses to append ":" (os.pathsep). if SCons.Util.is_List(env['ENV'][var]): - # TODO(1.5) - #env['ENV'][var] = os.pathsep.join(env['ENV'][var]) - env['ENV'][var] = string.join(env['ENV'][var], os.pathsep) + env['ENV'][var] = os.pathsep.join(env['ENV'][var]) # Append the trailing os.pathsep character here to catch the case with no env[var] env['ENV'][var] = env['ENV'][var] + os.pathsep return save -class FindENVPathDirs: +class FindENVPathDirs(object): """A class to bind a specific *PATH variable name to a function that will return all of the *path directories.""" def __init__(self, variable): @@ -165,7 +159,7 @@ class LaTeX(SCons.Scanner.Base): 'bibliographystyle': 'BSTINPUTS', 'usepackage': 'TEXINPUTS', 'lstinputlisting': 'TEXINPUTS'} - env_variables = SCons.Util.unique(keyword_paths.values()) + env_variables = SCons.Util.unique(list(keyword_paths.values())) def __init__(self, name, suffixes, graphics_extensions, *args, **kw): @@ -184,7 +178,7 @@ class LaTeX(SCons.Scanner.Base): return [] return self.scan_recurse(node, path) - class FindMultiPathDirs: + class FindMultiPathDirs(object): """The stock FindPathDirs function has the wrong granularity: it is called once per target, while we need the path that depends on what kind of included files is being searched. This wrapper @@ -212,7 +206,7 @@ class LaTeX(SCons.Scanner.Base): # To prevent "dict is not hashable error" return tuple(di.items()) - class LaTeXScanCheck: + class LaTeXScanCheck(object): """Skip all but LaTeX source files, i.e., do not scan *.eps, *.pdf, *.jpg, etc. """ @@ -231,7 +225,7 @@ class LaTeX(SCons.Scanner.Base): kw['scan_check'] = LaTeXScanCheck(suffixes) kw['name'] = name - apply(SCons.Scanner.Base.__init__, (self,) + args, kw) + SCons.Scanner.Base.__init__(self, *args, **kw) def _latex_names(self, include): filename = include[1] @@ -252,11 +246,12 @@ class LaTeX(SCons.Scanner.Base): if include[0] == 'includegraphics': base, ext = os.path.splitext( filename ) if ext == "": - #TODO(1.5) return [filename + e for e in self.graphics_extensions] - #return map(lambda e, f=filename: f+e, self.graphics_extensions + TexGraphics) - # use the line above to find dependency for PDF builder when only .eps figure is present - # Since it will be found if the user tell scons how to make the pdf figure leave it out for now. - return map(lambda e, f=filename: f+e, self.graphics_extensions) + #return [filename+e for e in self.graphics_extensions + TexGraphics] + # use the line above to find dependencies for the PDF builder + # when only an .eps figure is present. Since it will be found + # if the user tells scons how to make the pdf figure, leave + # it out for now. + return [filename+e for e in self.graphics_extensions] return [filename] def sort_key(self, include): @@ -303,7 +298,7 @@ class LaTeX(SCons.Scanner.Base): split_includes = [] for include in includes: inc_type = noopt_cre.sub('', include[0]) - inc_list = string.split(include[1],',') + inc_list = include[1].split(',') for j in range(len(inc_list)): split_includes.append( (inc_type, inc_list[j]) ) # @@ -336,19 +331,11 @@ class LaTeX(SCons.Scanner.Base): while queue: include = queue.pop() - # TODO(1.5): more compact: - #try: - # if seen[include[1]] == 1: - # continue - #except KeyError: - # seen[include[1]] = 1 try: - already_seen = seen[include[1]] + if seen[include[1]] == 1: + continue except KeyError: seen[include[1]] = 1 - already_seen = False - if already_seen: - continue # # Handle multiple filenames in include[1] @@ -366,10 +353,7 @@ class LaTeX(SCons.Scanner.Base): # recurse down queue.extend( self.scan(n) ) - # - nodes.sort() - nodes = map(lambda pair: pair[1], nodes) - return nodes + return [pair[1] for pair in sorted(nodes)] # Local Variables: # tab-width:4 diff --git a/engine/SCons/Scanner/Prog.py b/engine/SCons/Scanner/Prog.py index 395d39f..97f25b3 100644 --- a/engine/SCons/Scanner/Prog.py +++ b/engine/SCons/Scanner/Prog.py @@ -21,9 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Scanner/Prog.py 4720 2010/03/24 03:14:11 jars" - -import string +__revision__ = "src/engine/SCons/Scanner/Prog.py 5023 2010/06/14 22:05:46 scons" import SCons.Node import SCons.Node.FS @@ -37,7 +35,7 @@ def ProgramScanner(**kw): """Return a prototype Scanner instance for scanning executable files for static-lib dependencies""" kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') - ps = apply(SCons.Scanner.Base, [scan, "ProgramScanner"], kw) + ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps def scan(node, env, libpath = ()): @@ -53,7 +51,7 @@ def scan(node, env, libpath = ()): # There are no LIBS in this environment, so just return a null list: return [] if SCons.Util.is_String(libs): - libs = string.split(libs) + libs = libs.split() else: libs = SCons.Util.flatten(libs) diff --git a/engine/SCons/Scanner/RC.py b/engine/SCons/Scanner/RC.py index 23de58b..de7744b 100644 --- a/engine/SCons/Scanner/RC.py +++ b/engine/SCons/Scanner/RC.py @@ -28,7 +28,7 @@ Definition Language) files. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Scanner/RC.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Scanner/RC.py 5023 2010/06/14 22:05:46 scons" import SCons.Node.FS import SCons.Scanner diff --git a/engine/SCons/Scanner/__init__.py b/engine/SCons/Scanner/__init__.py index 987df51..2a6f299 100644 --- a/engine/SCons/Scanner/__init__.py +++ b/engine/SCons/Scanner/__init__.py @@ -27,16 +27,15 @@ The Scanner package for the SCons software construction utility. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Scanner/__init__.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Scanner/__init__.py 5023 2010/06/14 22:05:46 scons" import re -import string import SCons.Node.FS import SCons.Util -class _Null: +class _Null(object): pass # This is used instead of None as a default argument value so None can be @@ -56,13 +55,13 @@ def Scanner(function, *args, **kw): patterned on SCons code. """ if SCons.Util.is_Dict(function): - return apply(Selector, (function,) + args, kw) + return Selector(function, *args, **kw) else: - return apply(Base, (function,) + args, kw) + return Base(function, *args, **kw) -class FindPathDirs: +class FindPathDirs(object): """A class to bind a specific *PATH variable name to a function that will return all of the *path directories.""" def __init__(self, variable): @@ -80,7 +79,7 @@ class FindPathDirs: -class Base: +class Base(object): """ The base class for dependency scanners. This implements straightforward, single-pass scanning of a single file. @@ -171,7 +170,7 @@ class Base: if skeys is _null: if SCons.Util.is_Dict(function): - skeys = function.keys() + skeys = list(function.keys()) else: skeys = [] self.skeys = skeys @@ -218,7 +217,7 @@ class Base: nodes = [] for l in list: if self.node_class and not isinstance(l, self.node_class): - l = apply(node_factory, (l,), kw) + l = node_factory(l, **kw) nodes.append(l) return nodes @@ -280,9 +279,9 @@ class Selector(Base): for custom modules that may be out there.) """ def __init__(self, dict, *args, **kw): - apply(Base.__init__, (self, None,)+args, kw) + Base.__init__(self, None, *args, **kw) self.dict = dict - self.skeys = dict.keys() + self.skeys = list(dict.keys()) def __call__(self, node, env, path = ()): return self.select(node)(node, env, path) @@ -309,7 +308,7 @@ class Current(Base): def current_check(node, env): return not node.has_builder() or node.is_up_to_date() kw['scan_check'] = current_check - apply(Base.__init__, (self,) + args, kw) + Base.__init__(self, *args, **kw) class Classic(Current): """ @@ -339,7 +338,7 @@ class Classic(Current): kw['skeys'] = suffixes kw['name'] = name - apply(Current.__init__, (self,) + args, kw) + Current.__init__(self, *args, **kw) def find_include(self, include, source_dir, path): n = SCons.Node.FS.find_file(include, (source_dir,) + tuple(path)) @@ -360,7 +359,7 @@ class Classic(Current): includes = self.find_include_names (node) # Intern the names of the include files. Saves some memory # if the same header is included many times. - node.includes = map(SCons.Util.silent_intern, includes) + node.includes = list(map(SCons.Util.silent_intern, includes)) # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name @@ -379,12 +378,9 @@ class Classic(Current): SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node)) else: - sortkey = self.sort_key(include) - nodes.append((sortkey, n)) + nodes.append((self.sort_key(include), n)) - nodes.sort() - nodes = map(lambda pair: pair[1], nodes) - return nodes + return [pair[1] for pair in sorted(nodes)] class ClassicCPP(Classic): """ @@ -408,7 +404,7 @@ class ClassicCPP(Classic): return n, i def sort_key(self, include): - return SCons.Node.FS._my_normcase(string.join(include)) + return SCons.Node.FS._my_normcase(' '.join(include)) # Local Variables: # tab-width:4 diff --git a/engine/SCons/Script/Interactive.py b/engine/SCons/Script/Interactive.py index 6218021..52fc753 100644 --- a/engine/SCons/Script/Interactive.py +++ b/engine/SCons/Script/Interactive.py @@ -19,9 +19,8 @@ # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/Interactive.py 5023 2010/06/14 22:05:46 scons" __doc__ = """ SCons interactive mode @@ -90,7 +89,6 @@ import copy import os import re import shlex -import string import sys try: @@ -134,7 +132,7 @@ class SConsInteractiveCmd(cmd.Cmd): print "*** Unknown command: %s" % argv[0] def onecmd(self, line): - line = string.strip(line) + line = line.strip() if not line: print self.lastcmd return self.emptyline() @@ -144,7 +142,7 @@ class SConsInteractiveCmd(cmd.Cmd): elif line[0] == '?': line = 'help ' + line[1:] if os.sep == '\\': - line = string.replace(line, '\\', '\\\\') + line = line.replace('\\', '\\\\') argv = shlex.split(line) argv[0] = self.synonyms.get(argv[0], argv[0]) if not argv[0]: @@ -222,8 +220,8 @@ class SConsInteractiveCmd(cmd.Cmd): def get_unseen_children(node, parent, seen_nodes=seen_nodes): def is_unseen(node, seen_nodes=seen_nodes): - return not seen_nodes.has_key(node) - return filter(is_unseen, node.children(scan=1)) + 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 @@ -247,9 +245,9 @@ class SConsInteractiveCmd(cmd.Cmd): walker = SCons.Node.Walker(node, kids_func=get_unseen_children, eval_func=add_to_seen_nodes) - n = walker.next() + n = walker.get_next() while n: - n = walker.next() + n = walker.get_next() for node in seen_nodes.keys(): # Call node.clear() to clear most of the state @@ -307,7 +305,7 @@ class SConsInteractiveCmd(cmd.Cmd): def _strip_initial_spaces(self, s): #lines = s.split('\n') - lines = string.split(s, '\n') + lines = s.split('\n') spaces = re.match(' *', lines[0]).group(0) #def strip_spaces(l): # if l.startswith(spaces): @@ -318,8 +316,8 @@ class SConsInteractiveCmd(cmd.Cmd): if l[:len(spaces)] == spaces: l = l[len(spaces):] return l - lines = map(strip_spaces, lines) - return string.join(lines, '\n') + lines = list(map(strip_spaces, lines)) + return '\n'.join(lines) def do_exit(self, argv): """\ diff --git a/engine/SCons/Script/Main.py b/engine/SCons/Script/Main.py index 74a28f2..2bd1560 100644 --- a/engine/SCons/Script/Main.py +++ b/engine/SCons/Script/Main.py @@ -8,10 +8,11 @@ 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 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining @@ -32,13 +33,12 @@ it goes here. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/Main.py 5023 2010/06/14 22:05:46 scons" + +import SCons.compat import os -import os.path -import string import sys import time import traceback @@ -89,7 +89,7 @@ progress_display = SCons.Util.DisplayEngine() first_command_start = None last_command_end = None -class Progressor: +class Progressor(object): prev = '' count = 0 target_string = '$TARGET' @@ -107,7 +107,7 @@ class Progressor: self.func = obj elif SCons.Util.is_List(obj): self.func = self.spinner - elif string.find(obj, self.target_string) != -1: + elif obj.find(self.target_string) != -1: self.func = self.replace_string else: self.func = self.string @@ -132,7 +132,7 @@ class Progressor: self.write(self.obj) def replace_string(self, node): - self.write(string.replace(self.obj, self.target_string, str(node))) + self.write(self.obj.replace(self.target_string, str(node))) def __call__(self, node): self.count = self.count + 1 @@ -145,7 +145,7 @@ ProgressObject = SCons.Util.Null() def Progress(*args, **kw): global ProgressObject - ProgressObject = apply(Progressor, args, kw) + ProgressObject = Progressor(*args, **kw) # Task control. # @@ -207,12 +207,10 @@ class BuildTask(SCons.Taskmaster.OutOfDateTask): t = self.targets[0] if self.top and not t.has_builder() and not t.side_effect: if not t.exists(): - def classname(obj): - return string.split(str(obj.__class__), '.')[-1] - if classname(t) in ('File', 'Dir', 'Entry'): - errstr="Do not know how to make %s target `%s' (%s)." % (classname(t), t, t.abspath) + 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'." % (classname(t), t) + 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.") @@ -262,19 +260,16 @@ class BuildTask(SCons.Taskmaster.OutOfDateTask): node = buildError.node if not SCons.Util.is_List(node): node = [ node ] - nodename = string.join(map(str, 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 - # TODO(1.5) - #not isinstance( - # buildError.exc_info[1], - # (EnvironmentError, SCons.Errors.StopError, SCons.Errors.UserError))): - not isinstance(buildError.exc_info[1], EnvironmentError) and - not isinstance(buildError.exc_info[1], SCons.Errors.StopError) and - not isinstance(buildError.exc_info[1], SCons.Errors.UserError)): + 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: @@ -316,11 +311,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask): display("Removed " + pathstr) elif os.path.isdir(path) and not os.path.islink(path): # delete everything in the dir - entries = os.listdir(path) - # Sort for deterministic output (os.listdir() Can - # return entries in a random order). - entries.sort() - for e in entries: + for e in sorted(os.listdir(path)): p = os.path.join(path, e) s = os.path.join(pathstr, e) if os.path.isfile(p): @@ -345,7 +336,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask): for t in self.targets: if not t.isdir(): display("Removed " + str(t)) - if SCons.Environment.CleanTargets.has_key(target): + if target in SCons.Environment.CleanTargets: files = SCons.Environment.CleanTargets[target] for f in files: self.fs_delete(f.abspath, str(f), 0) @@ -366,7 +357,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask): else: if removed: display("Removed " + str(t)) - if SCons.Environment.CleanTargets.has_key(target): + if target in SCons.Environment.CleanTargets: files = SCons.Environment.CleanTargets[target] for f in files: self.fs_delete(f.abspath, str(f)) @@ -405,7 +396,7 @@ class QuestionTask(SCons.Taskmaster.AlwaysTask): pass -class TreePrinter: +class TreePrinter(object): def __init__(self, derived=False, prune=False, status=False): self.derived = derived self.prune = prune @@ -414,7 +405,7 @@ class TreePrinter: return node.all_children() def get_derived_children(self, node): children = node.all_children(None) - return filter(lambda x: x.has_builder(), children) + return [x for x in children if x.has_builder()] def display(self, t): if self.derived: func = self.get_derived_children @@ -425,13 +416,13 @@ class TreePrinter: def python_version_string(): - return string.split(sys.version)[0] + return sys.version.split()[0] def python_version_unsupported(version=sys.version_info): - return version < (1, 5, 2) + return version < unsupported_python_version def python_version_deprecated(version=sys.version_info): - return version < (2, 4, 0) + return version < deprecated_python_version # Global variables @@ -447,7 +438,7 @@ this_build_status = 0 # "exit status" of an individual build num_jobs = None delayed_warnings = [] -class FakeOptionParser: +class FakeOptionParser(object): """ A do-nothing option parser, used for the initial OptionsParser variable. @@ -459,7 +450,7 @@ class FakeOptionParser: without blowing up. """ - class FakeOptionValues: + class FakeOptionValues(object): def __getattr__(self, attr): return None values = FakeOptionValues() @@ -469,9 +460,9 @@ class FakeOptionParser: OptionsParser = FakeOptionParser() def AddOption(*args, **kw): - if not kw.has_key('default'): + if 'default' not in kw: kw['default'] = None - result = apply(OptionsParser.add_local_option, args, kw) + result = OptionsParser.add_local_option(*args, **kw) return result def GetOption(name): @@ -481,7 +472,7 @@ def SetOption(name, value): return OptionsParser.values.set_option(name, value) # -class Stats: +class Stats(object): def __init__(self): self.stats = [] self.labels = [] @@ -501,26 +492,24 @@ class CountStats(Stats): def do_print(self): stats_table = {} for s in self.stats: - for n in map(lambda t: t[0], s): + 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 - keys = stats_table.keys() - keys.sort() self.outfp.write("Object counts:\n") pre = [" "] post = [" %s\n"] l = len(self.stats) - fmt1 = string.join(pre + [' %7s']*l + post, '') - fmt2 = string.join(pre + [' %7d']*l + post, '') + fmt1 = ''.join(pre + [' %7s']*l + post) + fmt2 = ''.join(pre + [' %7d']*l + post) labels = self.labels[:l] labels.append(("", "Class")) - self.outfp.write(fmt1 % tuple(map(lambda x: x[0], labels))) - self.outfp.write(fmt1 % tuple(map(lambda x: x[1], labels))) - for k in keys: + 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)) @@ -532,7 +521,7 @@ class MemStats(Stats): self.stats.append(SCons.Debug.memory()) def do_print(self): fmt = 'Memory %-32s %12d\n' - for label, stats in map(None, self.labels, self.stats): + for label, stats in zip(self.labels, self.stats): self.outfp.write(fmt % (label, stats)) memory_stats = MemStats() @@ -563,7 +552,7 @@ def find_deepest_user_frame(tb): # of SCons: for frame in tb: filename = frame[0] - if string.find(filename, os.sep+'SCons'+os.sep) == -1: + if filename.find(os.sep+'SCons'+os.sep) == -1: return frame return tb[0] @@ -598,7 +587,7 @@ def _scons_internal_warning(e): *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[0]) + 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(): @@ -687,7 +676,7 @@ def _load_site_scons_dir(topdir, site_dir_name=None): site_dir = os.path.join(topdir.path, 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 + raise SCons.Errors.UserError("site dir %s not found."%site_dir) return site_init_filename = "site_init.py" @@ -714,7 +703,7 @@ def _load_site_scons_dir(topdir, site_dir_name=None): 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) + raise SCons.Errors.InternalError(fmt % repr(e)) try: # This is the magic. exec fp in m.__dict__ @@ -763,21 +752,8 @@ def _main(parser): # suppress) appropriate warnings about anything that might happen, # as configured by the user. - default_warnings = [ SCons.Warnings.CorruptSConsignWarning, + default_warnings = [ SCons.Warnings.WarningOnByDefault, SCons.Warnings.DeprecatedWarning, - SCons.Warnings.DuplicateEnvironmentWarning, - SCons.Warnings.FutureReservedVariableWarning, - SCons.Warnings.LinkWarning, - SCons.Warnings.MissingSConscriptWarning, - SCons.Warnings.NoMD5ModuleWarning, - SCons.Warnings.NoMetaclassSupportWarning, - SCons.Warnings.NoObjectCountWarning, - SCons.Warnings.NoParallelSupportWarning, - SCons.Warnings.MisleadingKeywordsWarning, - SCons.Warnings.ReservedVariableWarning, - SCons.Warnings.StackSizeWarning, - SCons.Warnings.VisualVersionMismatch, - SCons.Warnings.VisualCMissingWarning, ] for warning in default_warnings: @@ -855,7 +831,7 @@ def _main(parser): # 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." + raise SCons.Errors.UserError("No SConstruct file found.") if scripts[0] == "-": d = fs.getcwd() @@ -955,7 +931,7 @@ def _main(parser): # $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.enableWarningClass(SCons.Warnings.PythonVersionWarning) SCons.Warnings.process_warn_strings(options.warn) # Now that we've read the SConscript files, we can check for the @@ -1087,7 +1063,7 @@ def _build_targets(fs, options, targets, target_top): # or not a file, so go ahead and keep it as a default # target and let the engine sort it out: return 1 - d = filter(check_dir, SCons.Script.DEFAULT_TARGETS) + d = list(filter(check_dir, SCons.Script.DEFAULT_TARGETS)) SCons.Script.DEFAULT_TARGETS[:] = d target_top = None lookup_top = None @@ -1122,7 +1098,7 @@ def _build_targets(fs, options, targets, target_top): node = None return node - nodes = filter(None, map(Entry, targets)) + nodes = [_f for _f in map(Entry, targets) if _f] task_class = BuildTask # default action is to build targets opening_message = "Building targets ..." @@ -1154,7 +1130,7 @@ def _build_targets(fs, options, targets, target_top): # This is cribbed from the implementation of # random.shuffle() in Python 2.X. d = dependencies - for i in xrange(len(d)-1, 0, -1): + 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 @@ -1224,18 +1200,16 @@ def _build_targets(fs, options, targets, target_top): def _exec_main(parser, values): sconsflags = os.environ.get('SCONSFLAGS', '') - all_args = string.split(sconsflags) + sys.argv[1:] + all_args = sconsflags.split() + sys.argv[1:] options, args = parser.parse_args(all_args, values) - if type(options.debug) == type([]) and "pdb" in options.debug: + if isinstance(options.debug, list) and "pdb" in options.debug: import pdb pdb.Pdb().runcall(_main, parser) elif options.profile_file: - try: - from cProfile import Profile - except ImportError, e: - from profile import Profile + # 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 @@ -1285,7 +1259,7 @@ def main(): pass parts.append(version_string("engine", SCons)) parts.append("Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation") - version = string.join(parts, '') + version = ''.join(parts) import SConsOptions parser = SConsOptions.Parser(version) diff --git a/engine/SCons/Script/SConsOptions.py b/engine/SCons/Script/SConsOptions.py index 545162b..913a6ee 100644 --- a/engine/SCons/Script/SConsOptions.py +++ b/engine/SCons/Script/SConsOptions.py @@ -21,20 +21,14 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Script/SConsOptions.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/SConsOptions.py 5023 2010/06/14 22:05:46 scons" import optparse import re -import string import sys import textwrap -try: - no_hyphen_re = re.compile(r'(\s+|(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') -except re.error: - # Pre-2.0 Python versions don't have the (?<= negative - # look-behind assertion. - no_hyphen_re = re.compile(r'(\s+|-*\w{2,}-(?=\w{2,}))') +no_hyphen_re = re.compile(r'(\s+|(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') try: from gettext import gettext @@ -55,9 +49,10 @@ def diskcheck_convert(value): if value is None: return [] if not SCons.Util.is_List(value): - value = string.split(value, ',') + value = value.split(',') result = [] - for v in map(string.lower, value): + for v in value: + v = v.lower() if v == 'all': result = diskcheck_all elif v == 'none': @@ -65,7 +60,7 @@ def diskcheck_convert(value): elif v in diskcheck_all: result.append(v) else: - raise ValueError, v + raise ValueError(v) return result class SConsValues(optparse.Values): @@ -139,7 +134,7 @@ class SConsValues(optparse.Values): 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 + raise SCons.Errors.UserError("This option is not settable from a SConscript file: %s"%name) if name == 'num_jobs': try: @@ -147,19 +142,19 @@ class SConsValues(optparse.Values): if value < 1: raise ValueError except ValueError: - raise SCons.Errors.UserError, "A positive integer is required: %s"%repr(value) + 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) + 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) + 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 + 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) @@ -167,8 +162,8 @@ class SConsValues(optparse.Values): try: value = diskcheck_convert(value) except ValueError, v: - raise SCons.Errors.UserError, "Not a valid diskcheck value: %s"%v - if not self.__dict__.has_key('diskcheck'): + 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. @@ -177,12 +172,12 @@ class SConsValues(optparse.Values): try: value = int(value) except ValueError: - raise SCons.Errors.UserError, "An integer is required: %s"%repr(value) + 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) + raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'warn': if SCons.Util.is_String(value): value = [value] @@ -197,7 +192,7 @@ class SConsOption(optparse.Option): if self.nargs in (1, '?'): return self.check_value(opt, value) else: - return tuple(map(lambda v, o=opt, s=self: s.check_value(o, v), value)) + return tuple([self.check_value(opt, v) for v in value]) def process(self, opt, value, values, parser): @@ -214,7 +209,7 @@ class SConsOption(optparse.Option): 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] + raise SCons.Errors.UserError(fmt % self._short_opts[0]) try: _orig_CONST_ACTIONS = optparse.Option.CONST_ACTIONS @@ -292,7 +287,7 @@ class SConsOptionParser(optparse.OptionParser): # Value explicitly attached to arg? Pretend it's the next # argument. if "=" in arg: - (opt, next_arg) = string.split(arg, "=", 1) + (opt, next_arg) = arg.split("=", 1) rargs.insert(0, next_arg) had_explicit_value = True else: @@ -356,7 +351,7 @@ class SConsOptionParser(optparse.OptionParser): group = self.add_option_group(group) self.local_option_group = group - result = apply(group.add_option, args, kw) + result = group.add_option(*args, **kw) if result: # The option was added succesfully. We now have to add the @@ -461,7 +456,7 @@ class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter): result.append("%*s%s\n" % (self.help_position, "", line)) elif opts[-1] != "\n": result.append("\n") - return string.join(result, "") + return "".join(result) # For consistent help output across Python versions, we provide a # subclass copy of format_option_strings() and these two variables. @@ -473,7 +468,7 @@ class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter): def format_option_strings(self, option): """Return a comma-separated list of option strings & metavariables.""" if option.takes_value(): - metavar = option.metavar or string.upper(option.dest) + metavar = option.metavar or option.dest.upper() short_opts = [] for sopt in option._short_opts: short_opts.append(self._short_opt_fmt % (sopt, metavar)) @@ -489,7 +484,7 @@ class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter): else: opts = long_opts + short_opts - return string.join(opts, ", ") + return ", ".join(opts) def Parser(version): """ @@ -580,7 +575,7 @@ def Parser(version): raise OptionValueError("Warning: %s is not a valid config type" % value) setattr(parser.values, option.dest, value) opt_config_help = "Controls Configure subsystem: %s." \ - % string.join(config_options, ", ") + % ", ".join(config_options) op.add_option('--config', nargs=1, type="string", dest="config", default="auto", @@ -604,7 +599,7 @@ def Parser(version): debug_options = ["count", "explain", "findlibs", "includes", "memoizer", "memory", "objects", "pdb", "presub", "stacktrace", - "time"] + deprecated_debug_options.keys() + "time"] + list(deprecated_debug_options.keys()) def opt_debug(option, opt, value, parser, debug_options=debug_options, @@ -618,12 +613,12 @@ def Parser(version): parser.values.delayed_warnings = [] msg = deprecated_debug_options[value] w = "The --debug=%s option is deprecated%s." % (value, msg) - t = (SCons.Warnings.DeprecatedWarning, w) + 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." \ - % string.join(debug_options, ", ") + % ", ".join(debug_options) op.add_option('--debug', nargs=1, type="string", dest="debug", default=[], @@ -654,7 +649,7 @@ def Parser(version): SCons.Node.FS.set_duplicate(value) opt_duplicate_help = "Set the preferred duplication methods. Must be one of " \ - + string.join(SCons.Node.FS.Valid_Duplicates, ", ") + + ", ".join(SCons.Node.FS.Valid_Duplicates) op.add_option('--duplicate', nargs=1, type="string", @@ -802,7 +797,7 @@ def Parser(version): def opt_tree(option, opt, value, parser, tree_options=tree_options): import Main tp = Main.TreePrinter() - for o in string.split(value, ','): + for o in value.split(','): if o == 'all': tp.derived = False elif o == 'derived': @@ -816,7 +811,7 @@ def Parser(version): parser.values.tree_printers.append(tp) opt_tree_help = "Print a dependency tree in various formats: %s." \ - % string.join(tree_options, ", ") + % ", ".join(tree_options) op.add_option('--tree', nargs=1, type="string", @@ -846,7 +841,7 @@ def Parser(version): def opt_warn(option, opt, value, parser, tree_options=tree_options): if SCons.Util.is_String(value): - value = string.split(value, ',') + value = value.split(',') parser.values.warn.extend(value) op.add_option('--warn', '--warning', diff --git a/engine/SCons/Script/SConscript.py b/engine/SCons/Script/SConscript.py index 98a3126..5a22db7 100644 --- a/engine/SCons/Script/SConscript.py +++ b/engine/SCons/Script/SConscript.py @@ -26,9 +26,9 @@ files. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/SConscript.py 5023 2010/06/14 22:05:46 scons" import SCons import SCons.Action @@ -45,14 +45,12 @@ import SCons.Script.Main import SCons.Tool import SCons.Util +import collections import os import os.path import re -import string import sys import traceback -import types -import UserList # The following variables used to live in this module. Some # SConscript files out there may have referred to them directly as @@ -80,7 +78,7 @@ 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 + try: 1//0 except ZeroDivisionError: # Don't start iterating with the current stack-frame to # prevent creating reference cycles (f_back is safe). @@ -116,11 +114,11 @@ def compute_exports(exports): except KeyError: retval[export] = glob[export] except KeyError, x: - raise SCons.Errors.UserError, "Export of non-existent variable '%s'"%x + raise SCons.Errors.UserError("Export of non-existent variable '%s'"%x) return retval -class Frame: +class Frame(object): """A frame on the SConstruct/SConscript call stack""" def __init__(self, fs, exports, sconscript): self.globals = BuildDefaultGlobals() @@ -145,10 +143,10 @@ def Return(*vars, **kw): try: fvars = SCons.Util.flatten(vars) for var in fvars: - for v in string.split(var): + 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 + raise SCons.Errors.UserError("Return of non-existent variable '%s'"%x) if len(retval) == 1: call_stack[-1].retval = retval[0] @@ -312,7 +310,7 @@ def SConscript_exception(file=sys.stderr): up to where we exec the SConscript.""" exc_type, exc_value, exc_tb = sys.exc_info() tb = exc_tb - while tb and not tb.tb_frame.f_locals.has_key(stack_bottom): + 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 @@ -334,11 +332,11 @@ 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 not tb.tb_frame.f_locals.has_key(stack_bottom): + 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" + 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 @@ -369,7 +367,7 @@ class SConsEnvironment(SCons.Environment.Base): This is complicated by the fact that a version string can be something like 3.2b1.""" - version = string.split(string.split(version_string, ' ')[0], '.') + version = version_string.split(' ')[0].split('.') v_major = int(version[0]) v_minor = int(re.match('\d+', version[1]).group()) if len(version) >= 3: @@ -380,7 +378,7 @@ class SConsEnvironment(SCons.Environment.Base): def _get_SConscript_filenames(self, ls, kw): """ - Convert the parameters passed to # SConscript() calls into a list + 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. @@ -391,16 +389,15 @@ class SConsEnvironment(SCons.Environment.Base): try: dirs = kw["dirs"] except KeyError: - raise SCons.Errors.UserError, \ - "Invalid SConscript usage - no parameters" + raise SCons.Errors.UserError("Invalid SConscript usage - no parameters") if not SCons.Util.is_List(dirs): dirs = [ dirs ] - dirs = map(str, dirs) + dirs = list(map(str, dirs)) name = kw.get('name', 'SConscript') - files = map(lambda n, name = name: os.path.join(n, name), dirs) + files = [os.path.join(n, name) for n in dirs] elif len(ls) == 1: @@ -413,8 +410,7 @@ class SConsEnvironment(SCons.Environment.Base): else: - raise SCons.Errors.UserError, \ - "Invalid SConscript() usage - too many arguments" + raise SCons.Errors.UserError("Invalid SConscript() usage - too many arguments") if not SCons.Util.is_List(files): files = [ files ] @@ -425,8 +421,7 @@ class SConsEnvironment(SCons.Environment.Base): 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" + 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: @@ -457,9 +452,9 @@ class SConsEnvironment(SCons.Environment.Base): def Configure(self, *args, **kw): if not SCons.Script.sconscript_reading: - raise SCons.Errors.UserError, "Calling Configure from Builders is not supported." + raise SCons.Errors.UserError("Calling Configure from Builders is not supported.") kw['_depth'] = kw.get('_depth', 0) + 1 - return apply(SCons.Environment.Base.Configure, (self,)+args, kw) + return SCons.Environment.Base.Configure(self, *args, **kw) def Default(self, *targets): SCons.Script._Set_Default_Targets(self, targets) @@ -484,7 +479,7 @@ class SConsEnvironment(SCons.Environment.Base): except AttributeError: python_ver = self._get_major_minor_revision(sys.version)[:2] if python_ver < (major, minor): - v = string.split(sys.version, " ", 1)[0] + v = sys.version.split(" ", 1)[0] print "Python %d.%d or greater required, but you have Python %s" %(major,minor,v) sys.exit(2) @@ -520,21 +515,24 @@ class SConsEnvironment(SCons.Environment.Base): globals.update(global_exports) globals.update(exports) else: - if exports.has_key(v): + 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 + 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 = map(subst, x) + x = list(map(subst, x)) else: x = subst(x) return x - ls = map(subst_element, ls) + ls = list(map(subst_element, ls)) subst_kw = {} for key, val in kw.items(): if SCons.Util.is_String(val): @@ -550,7 +548,7 @@ class SConsEnvironment(SCons.Environment.Base): files, exports = self._get_SConscript_filenames(ls, subst_kw) subst_kw['exports'] = exports - return apply(_SConscript, [self.fs,] + files, subst_kw) + return _SConscript(self.fs, *files, **subst_kw) def SConscriptChdir(self, flag): global sconscript_chdir @@ -567,9 +565,9 @@ 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." + raise SCons.Errors.UserError("Calling Configure from Builders is not supported.") kw['_depth'] = 1 - return apply(SCons.SConf.SConf, args, kw) + 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() @@ -595,7 +593,7 @@ def get_DefaultEnvironmentProxy(): _DefaultEnvironmentProxy = SCons.Environment.NoSubstitutionProxy(default_env) return _DefaultEnvironmentProxy -class DefaultEnvironmentCall: +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 @@ -613,7 +611,7 @@ class DefaultEnvironmentCall: def __call__(self, *args, **kw): env = self.factory() method = getattr(env, self.method_name) - return apply(method, args, kw) + return method(*args, **kw) def BuildDefaultGlobals(): @@ -629,7 +627,7 @@ def BuildDefaultGlobals(): import SCons.Script d = SCons.Script.__dict__ def not_a_module(m, d=d, mtype=type(SCons.Script)): - return type(d[m]) != mtype + return not isinstance(d[m], mtype) for m in filter(not_a_module, dir(SCons.Script)): GlobalDict[m] = d[m] diff --git a/engine/SCons/Script/__init__.py b/engine/SCons/Script/__init__.py index 97af6da..b5b5222 100644 --- a/engine/SCons/Script/__init__.py +++ b/engine/SCons/Script/__init__.py @@ -34,15 +34,14 @@ it goes here. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Script/__init__.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/__init__.py 5023 2010/06/14 22:05:46 scons" import time start_time = time.time() +import collections import os -import string import sys -import UserList # Special chicken-and-egg handling of the "--debug=memoizer" flag: # @@ -58,16 +57,15 @@ import UserList # the "--debug=memoizer" flag and enable Memoizer before we import any # of the other modules that use it. -_args = sys.argv + string.split(os.environ.get('SCONSFLAGS', '')) +_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 (inability to --debug=memoizer on - # Python 1.5.2 because it doesn't have metaclasses). Arrange - # for it to be displayed or not after warnings are configured. + # 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)) @@ -184,7 +182,7 @@ CScan = SCons.Defaults.CScan DefaultEnvironment = SCons.Defaults.DefaultEnvironment # Other variables we provide. -class TargetList(UserList.UserList): +class TargetList(collections.UserList): def _do_nothing(self, *args, **kw): pass def _add_Default(self, list): @@ -211,7 +209,7 @@ _build_plus_default = TargetList() def _Add_Arguments(alist): for arg in alist: - a, b = string.split(arg, '=', 1) + a, b = arg.split('=', 1) ARGUMENTS[a] = b ARGLIST.append((a, b)) diff --git a/engine/SCons/Sig.py b/engine/SCons/Sig.py index 1da6ccb..49c00bf 100644 --- a/engine/SCons/Sig.py +++ b/engine/SCons/Sig.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Sig.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Sig.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Place-holder for the old SCons.Sig module hierarchy @@ -40,7 +40,7 @@ import SCons.Warnings msg = 'The SCons.Sig module no longer exists.\n' \ ' Remove the following "import SCons.Sig" line to eliminate this warning:' -SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, msg) +SCons.Warnings.warn(SCons.Warnings.DeprecatedSigModuleWarning, msg) default_calc = None default_module = None diff --git a/engine/SCons/Subst.py b/engine/SCons/Subst.py index fe18f08..d9b029a 100644 --- a/engine/SCons/Subst.py +++ b/engine/SCons/Subst.py @@ -25,15 +25,11 @@ SCons string substitution. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Subst.py 5023 2010/06/14 22:05:46 scons" +import collections import re -import string -import types -import UserList -import UserString import SCons.Errors @@ -50,19 +46,19 @@ AllowableExceptions = (IndexError, NameError) def SetAllowableExceptions(*excepts): global AllowableExceptions - AllowableExceptions = filter(None, excepts) + 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) + raise SCons.Errors.BuildError(target[0], msg) else: - raise SCons.Errors.UserError, msg + raise SCons.Errors.UserError(msg) -class Literal: +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 @@ -82,7 +78,7 @@ class Literal: def is_literal(self): return 1 -class SpecialAttrWrapper: +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 @@ -121,7 +117,7 @@ def quote_spaces(arg): else: return str(arg) -class CmdStringHolder(UserString.UserString): +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 @@ -129,7 +125,7 @@ class CmdStringHolder(UserString.UserString): proper escape sequences inserted. """ def __init__(self, cmd, literal=None): - UserString.UserString.__init__(self, cmd) + collections.UserString.__init__(self, cmd) self.literal = literal def is_literal(self): @@ -152,7 +148,7 @@ class CmdStringHolder(UserString.UserString): else: return self.data -def escape_list(list, escape_func): +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): @@ -162,9 +158,9 @@ def escape_list(list, escape_func): return obj else: return e(escape_func) - return map(escape, list) + return list(map(escape, mylist)) -class NLWrapper: +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 @@ -183,28 +179,28 @@ class NLWrapper: def _return_nodelist(self): return self.nodelist def _gen_nodelist(self): - list = self.list - if list is None: - list = [] - elif not is_Sequence(list): - list = [list] + 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(map(self.func, list)) + 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(UserList.UserList): +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 UserList.UserList purely so that the + 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 - UserList.UserList methods in practice. + collections.UserList methods in practice. """ def __init__(self, nl): self.nl = nl @@ -225,7 +221,7 @@ class Targets_or_Sources(UserList.UserList): nl = self.nl._create_nodelist() return repr(nl) -class Target_or_Source: +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 @@ -240,7 +236,7 @@ class Target_or_Source: 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 + raise AttributeError("NodeList has no attribute: %s" % attr) return getattr(nl0, attr) def __str__(self): nl = self.nl._create_nodelist() @@ -256,9 +252,6 @@ class Target_or_Source: class NullNodeList(SCons.Util.NullSeq): def __call__(self, *args, **kwargs): return '' def __str__(self): return '' - # TODO(1.5): unneeded after new-style classes introduce iterators - def __getitem__(self, i): - raise IndexError NullNodesList = NullNodeList() @@ -344,7 +337,7 @@ _regex_remove = [ _rm, None, _remove ] def _rm_list(list): #return [ l for l in list if not l in ('$(', '$)') ] - return filter(lambda l: not l in ('$(', '$)'), list) + return [l for l in list if not l in ('$(', '$)')] def _remove_list(list): result = [] @@ -399,10 +392,10 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ handles separating command lines into lists of arguments, so see that function if that's what you're looking for. """ - if type(strSubst) == types.StringType and string.find(strSubst, '$') < 0: + if isinstance(strSubst, str) and strSubst.find('$') < 0: return strSubst - class StringSubber: + class StringSubber(object): """A class to construct the results of a scons_subst() call. This binds a specific construction environment, mode, target and @@ -438,7 +431,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ return s else: key = s[1:] - if key[0] == '{' or string.find(key, '.') >= 0: + if key[0] == '{' or key.find('.') >= 0: if key[0] == '{': key = key[1:-1] try: @@ -450,9 +443,9 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ return '' raise_exception(e, lvars['TARGETS'], s) else: - if lvars.has_key(key): + if key in lvars: s = lvars[key] - elif self.gvars.has_key(key): + elif key in self.gvars: s = self.gvars[key] elif not NameError in AllowableExceptions: raise_exception(NameError(key), lvars['TARGETS'], s) @@ -472,13 +465,13 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ # are probably more the exception than the norm, # so it should be tolerable for now. lv = lvars.copy() - var = string.split(key, '.')[0] + 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 map(func, s) + return list(map(func, s)) elif callable(s): try: s = s(target=lvars['TARGETS'], @@ -507,8 +500,8 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ if is_String(args) and not isinstance(args, CmdStringHolder): args = str(args) # In case it's a UserString. try: - def sub_match(match, conv=self.conv, expand=self.expand, lvars=lvars): - return conv(expand(match.group(1), lvars)) + 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 @@ -523,7 +516,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ if len(result) == 1: result = result[0] else: - result = string.join(map(str, result), '') + result = ''.join(map(str, result)) return result else: return self.expand(args, lvars) @@ -540,7 +533,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ # 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 not lvars.has_key('TARGET'): + if 'TARGET' not in lvars: d = subst_dict(target, source) if d: lvars = lvars.copy() @@ -571,7 +564,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ if mode != SUBST_RAW: # Compress strings of white space characters into # a single space. - result = string.strip(_space_sep.sub(' ', result)) + result = _space_sep.sub(' ', result).strip() elif is_Sequence(result): remove = _list_remove[mode] if remove: @@ -595,7 +588,7 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv # Subst_List_Strings[strSubst] = 1 # import SCons.Debug # SCons.Debug.caller_trace(1) - class ListSubber(UserList.UserList): + class ListSubber(collections.UserList): """A class to construct the results of a scons_subst_list() call. Like StringSubber, this class binds a specific construction @@ -612,16 +605,16 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv internally. """ def __init__(self, env, mode, conv, gvars): - UserList.UserList.__init__(self, []) + 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, s=self: s.append(x) + self.add_strip = lambda x: self.append(x) else: - self.add_strip = lambda x, s=self: None + self.add_strip = lambda x: None self.in_strip = None self.next_line() @@ -653,7 +646,7 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv self.close_strip('$)') else: key = s[1:] - if key[0] == '{' or string.find(key, '.') >= 0: + if key[0] == '{' or key.find('.') >= 0: if key[0] == '{': key = key[1:-1] try: @@ -665,9 +658,9 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv return raise_exception(e, lvars['TARGETS'], s) else: - if lvars.has_key(key): + if key in lvars: s = lvars[key] - elif self.gvars.has_key(key): + elif key in self.gvars: s = self.gvars[key] elif not NameError in AllowableExceptions: raise_exception(NameError(), lvars['TARGETS'], s) @@ -680,7 +673,7 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv # string for the value of the variable name # we just expanded. lv = lvars.copy() - var = string.split(key, '.')[0] + var = key.split('.')[0] lv[var] = '' self.substitute(s, lv, 0) self.this_word() @@ -735,7 +728,7 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv """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.""" - UserList.UserList.append(self, []) + collections.UserList.append(self, []) self.next_word() def this_word(self): @@ -834,7 +827,7 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv # 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 not lvars.has_key('TARGET'): + if 'TARGET' not in lvars: d = subst_dict(target, source) if d: lvars = lvars.copy() @@ -870,7 +863,7 @@ def scons_subst_once(strSubst, env, key): We do this with some straightforward, brute-force code here... """ - if type(strSubst) == types.StringType and string.find(strSubst, '$') < 0: + if isinstance(strSubst, str) and strSubst.find('$') < 0: return strSubst matchlist = ['$' + key, '${' + key + '}'] @@ -880,7 +873,7 @@ def scons_subst_once(strSubst, env, key): if a in matchlist: a = val if is_Sequence(a): - return string.join(map(str, a)) + return ' '.join(map(str, a)) else: return str(a) diff --git a/engine/SCons/Taskmaster.py b/engine/SCons/Taskmaster.py index ec81af2..68ac1f5 100644 --- a/engine/SCons/Taskmaster.py +++ b/engine/SCons/Taskmaster.py @@ -19,7 +19,6 @@ # 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. @@ -48,11 +47,10 @@ interface and the SCons build engine. There are two key classes here: target(s) that it decides need to be evaluated and/or built. """ -__revision__ = "src/engine/SCons/Taskmaster.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Taskmaster.py 5023 2010/06/14 22:05:46 scons" from itertools import chain import operator -import string import sys import traceback @@ -75,7 +73,7 @@ NODE_FAILED = SCons.Node.failed CollectStats = None -class Stats: +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 @@ -107,13 +105,12 @@ fmt = "%(considered)3d "\ "%(build)3d " def dump_stats(): - StatsNodes.sort(lambda a, b: cmp(str(a), str(b))) - for n in StatsNodes: + for n in sorted(StatsNodes, key=lambda a: str(a)): print (fmt % n.stats.__dict__) + str(n) -class Task: +class Task(object): """ Default SCons build engine task. @@ -165,7 +162,7 @@ class Task: the Action is actually called to build the targets. """ T = self.tm.trace - if T: T.write(self.trace_message('Task.prepare()', self.node)) + 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 @@ -204,8 +201,9 @@ class Task: # Deprecation Cycle) so the desired behavior is explicitly # determined by which concrete subclass is used. #raise NotImplementedError - msg = ('Direct use of the Taskmaster.Task class will be deprecated\n' - + '\tin a future release.') + 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 @@ -218,7 +216,7 @@ class Task: prepare(), executed() or failed(). """ T = self.tm.trace - if T: T.write(self.trace_message('Task.execute()', self.node)) + if T: T.write(self.trace_message(u'Task.execute()', self.node)) try: everything_was_cached = 1 @@ -370,7 +368,7 @@ class Task: This is the default behavior for building only what's necessary. """ T = self.tm.trace - if T: T.write(self.trace_message('Task.make_ready_current()', + if T: T.write(self.trace_message(u'Task.make_ready_current()', self.node)) self.out_of_date = [] @@ -415,7 +413,7 @@ class Task: that can be put back on the candidates list. """ T = self.tm.trace - if T: T.write(self.trace_message('Task.postprocess()', self.node)) + 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 @@ -432,7 +430,7 @@ class Task: # 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('Task.postprocess()', + if T: T.write(self.trace_message(u'Task.postprocess()', t, 'removing')) pending_children.discard(t) @@ -451,7 +449,7 @@ class Task: for p, subtract in parents.items(): p.ref_count = p.ref_count - subtract - if T: T.write(self.trace_message('Task.postprocess()', + if T: T.write(self.trace_message(u'Task.postprocess()', p, 'adjusted parent ref count')) if p.ref_count == 0: @@ -552,7 +550,7 @@ def find_cycle(stack, visited): return None -class Taskmaster: +class Taskmaster(object): """ The Taskmaster for walking the dependency DAG. """ @@ -735,12 +733,12 @@ class Taskmaster: self.ready_exc = None T = self.trace - if T: T.write('\n' + self.trace_message('Looking for a node to evaluate')) + if T: T.write(u'\n' + self.trace_message('Looking for a node to evaluate')) - while 1: + while True: node = self.next_candidate() if node is None: - if T: T.write(self.trace_message('No candidate anymore.') + '\n') + if T: T.write(self.trace_message('No candidate anymore.') + u'\n') return None node = node.disambiguate() @@ -763,7 +761,7 @@ class Taskmaster: else: S = None - if T: T.write(self.trace_message(' Considering node %s and its children:' % self.trace_node(node))) + 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: @@ -771,7 +769,7 @@ class Taskmaster: 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(' already handled (executed)')) + if T: T.write(self.trace_message(u' already handled (executed)')) continue executor = node.get_executor() @@ -802,7 +800,7 @@ class Taskmaster: for child in chain(executor.get_all_prerequisites(), children): childstate = child.get_state() - if T: T.write(self.trace_message(' ' + self.trace_node(child))) + if T: T.write(self.trace_message(u' ' + self.trace_node(child))) if childstate == NODE_NO_STATE: children_not_visited.append(child) @@ -861,7 +859,7 @@ class Taskmaster: # 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(' adjusted ref count: %s, child %s' % + if T: T.write(self.trace_message(u' adjusted ref count: %s, child %s' % (self.trace_node(node), repr(str(child))))) if T: @@ -887,7 +885,7 @@ class Taskmaster: # 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('Evaluating %s\n' % + if T: T.write(self.trace_message(u'Evaluating %s\n' % self.trace_node(node))) # For debugging only: @@ -952,17 +950,8 @@ class Taskmaster: T.write(self.trace_message(' removing node %s from the pending children set\n' % self.trace_node(n))) try: - while 1: - try: - node = to_visit.pop() - except AttributeError: - # Python 1.5.2 - if len(to_visit): - node = to_visit[0] - to_visit.remove(node) - else: - break - + while len(to_visit): + node = to_visit.pop() node_func(node) # Prune recursion by flushing the waiting children @@ -982,7 +971,7 @@ class Taskmaster: pass # We have the stick back the pending_children list into the - # task master because the python 1.5.2 compatibility does not + # taskmaster because the python 1.5.2 compatibility does not # allow us to use in-place updates self.pending_children = pending_children @@ -999,16 +988,12 @@ class Taskmaster: if not self.pending_children: return - # TODO(1.5) - #nclist = [ (n, find_cycle([n], set())) for n in self.pending_children ] - nclist = map(lambda n: (n, find_cycle([n], set())), self.pending_children) + nclist = [(n, find_cycle([n], set())) for n in self.pending_children] - # TODO(1.5) - #genuine_cycles = [ - # node for node, cycle in nclist - # if cycle or node.get_state() != NODE_EXECUTED - #] - genuine_cycles = filter(lambda t: t[1] or t[0].get_state() != NODE_EXECUTED, nclist) + 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. @@ -1017,13 +1002,13 @@ class Taskmaster: desc = 'Found dependency cycle(s):\n' for node, cycle in nclist: if cycle: - desc = desc + " " + string.join(map(str, cycle), " -> ") + "\n" + 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 + raise SCons.Errors.UserError(desc) # Local Variables: # tab-width:4 diff --git a/engine/SCons/Tool/386asm.py b/engine/SCons/Tool/386asm.py index 0891e96..5b8c8cb 100644 --- a/engine/SCons/Tool/386asm.py +++ b/engine/SCons/Tool/386asm.py @@ -32,7 +32,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/386asm.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/386asm.py 5023 2010/06/14 22:05:46 scons" from SCons.Tool.PharLapCommon import addPharLapPaths import SCons.Util diff --git a/engine/SCons/Tool/BitKeeper.py b/engine/SCons/Tool/BitKeeper.py index 121f579..a155a42 100644 --- a/engine/SCons/Tool/BitKeeper.py +++ b/engine/SCons/Tool/BitKeeper.py @@ -32,7 +32,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/BitKeeper.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/BitKeeper.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Builder @@ -44,6 +44,8 @@ def generate(env): 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) diff --git a/engine/SCons/Tool/CVS.py b/engine/SCons/Tool/CVS.py index b30c319..bb9f956 100644 --- a/engine/SCons/Tool/CVS.py +++ b/engine/SCons/Tool/CVS.py @@ -8,7 +8,6 @@ selection method. """ -# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining @@ -29,9 +28,8 @@ selection method. # 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/CVS.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/CVS.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Builder @@ -43,6 +41,8 @@ def generate(env): def CVSFactory(repos, module='', env=env): """ """ + import SCons.Warnings as W + W.warn(W.DeprecatedSourceCodeWarning, """The CVS() factory is deprecated and there is no replacement.""") # fail if repos is not an absolute path name? if module != '': # Don't use os.path.join() because the name we fetch might diff --git a/engine/SCons/Tool/FortranCommon.py b/engine/SCons/Tool/FortranCommon.py index 53c48e4..db89f96 100644 --- a/engine/SCons/Tool/FortranCommon.py +++ b/engine/SCons/Tool/FortranCommon.py @@ -27,10 +27,9 @@ Stuff for processing Fortran, common to all fortran dialects. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/FortranCommon.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/FortranCommon.py 5023 2010/06/14 22:05:46 scons" import re -import string import os.path import SCons.Action @@ -73,7 +72,7 @@ def _fortranEmitter(target, source, env): # Convert module name to a .mod filename suffix = env.subst('$FORTRANMODSUFFIX', target=target, source=source) moddir = env.subst('$FORTRANMODDIR', target=target, source=source) - modules = map(lambda x, s=suffix: string.lower(x) + s, modules) + modules = [x.lower() + suffix for x in modules] for m in modules: target.append(env.fs.File(m, moddir)) return (target, source) @@ -91,8 +90,8 @@ def ComputeFortranSuffixes(suffixes, ppsuffixes): pre-processed. Both should be sequences, not strings.""" assert len(suffixes) > 0 s = suffixes[0] - sup = string.upper(s) - upper_suffixes = map(string.upper, suffixes) + sup = s.upper() + upper_suffixes = [_.upper() for _ in suffixes] if SCons.Util.case_sensitive_suffixes(s, sup): ppsuffixes.extend(upper_suffixes) else: @@ -135,17 +134,17 @@ def DialectAddToEnv(env, dialect, suffixes, ppsuffixes, support_module = 0): static_obj.add_emitter(suffix, FortranEmitter) shared_obj.add_emitter(suffix, ShFortranEmitter) - if not env.has_key('%sFLAGS' % dialect): + if '%sFLAGS' % dialect not in env: env['%sFLAGS' % dialect] = SCons.Util.CLVar('') - if not env.has_key('SH%sFLAGS' % dialect): + if 'SH%sFLAGS' % dialect not in env: env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect) # If a tool does not define fortran prefix/suffix for include path, use C ones - if not env.has_key('INC%sPREFIX' % dialect): + if 'INC%sPREFIX' % dialect not in env: env['INC%sPREFIX' % dialect] = '$INCPREFIX' - if not env.has_key('INC%sSUFFIX' % dialect): + if 'INC%sSUFFIX' % dialect not in env: env['INC%sSUFFIX' % dialect] = '$INCSUFFIX' env['_%sINCFLAGS' % dialect] = '$( ${_concat(INC%sPREFIX, %sPATH, INC%sSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' % (dialect, dialect, dialect) diff --git a/engine/SCons/Tool/JavaCommon.py b/engine/SCons/Tool/JavaCommon.py index 635659a..bd6a30b 100644 --- a/engine/SCons/Tool/JavaCommon.py +++ b/engine/SCons/Tool/JavaCommon.py @@ -27,12 +27,11 @@ Stuff for processing Java. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/JavaCommon.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/JavaCommon.py 5023 2010/06/14 22:05:46 scons" import os import os.path import re -import string java_parsing = 1 @@ -60,7 +59,7 @@ if java_parsing: r'\d*\.\d*|[A-Za-z_][\w\$\.]*|<[A-Za-z_]\w+>|' + r'/\*|\*/|\[\])') - class OuterState: + 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): @@ -68,7 +67,7 @@ if java_parsing: 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 + raise NotImplementedError(msg) self.version = version self.listClasses = [] @@ -127,7 +126,7 @@ if java_parsing: self.brackets = self.brackets - 1 if len(self.stackBrackets) and \ self.brackets == self.stackBrackets[-1]: - self.listOutputs.append(string.join(self.listClasses, '$')) + self.listOutputs.append('$'.join(self.listClasses)) self.localClasses.pop() self.listClasses.pop() self.anonStacksStack.pop() @@ -179,7 +178,7 @@ if java_parsing: self.__getAnonStack()[-1] = self.__getAnonStack()[-1] + 1 for anon in self.__getAnonStack(): className.append(str(anon)) - self.listOutputs.append(string.join(className, '$')) + self.listOutputs.append('$'.join(className)) self.nextAnon = self.nextAnon + 1 self.__getAnonStack().append(0) @@ -187,7 +186,7 @@ if java_parsing: def setPackage(self, package): self.package = package - class AnonClassState: + class AnonClassState(object): """A state that looks for anonymous inner classes.""" def __init__(self, old_state): # outer_state is always an instance of OuterState @@ -222,7 +221,7 @@ if java_parsing: self.outer_state.addAnonClass() return self.old_state.parseToken(token) - class SkipState: + 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): @@ -234,7 +233,7 @@ if java_parsing: return self.old_state return self - class ClassState: + 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 @@ -261,7 +260,7 @@ if java_parsing: self.outer_state.anonStacksStack.append([0]) return self.outer_state - class IgnoreState: + class IgnoreState(object): """A state that will ignore all tokens until it gets to a specified token.""" def __init__(self, ignore_until, old_state): @@ -272,7 +271,7 @@ if java_parsing: return self.old_state return self - class PackageState: + 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): @@ -298,7 +297,7 @@ if java_parsing: currstate = currstate.parseToken(token) if trace: trace(token, currstate) if initial.package: - package = string.replace(initial.package, '.', os.sep) + package = initial.package.replace('.', os.sep) return (package, initial.listOutputs) else: diff --git a/engine/SCons/Tool/MSCommon/__init__.py b/engine/SCons/Tool/MSCommon/__init__.py index a612d9b..6389078 100644 --- a/engine/SCons/Tool/MSCommon/__init__.py +++ b/engine/SCons/Tool/MSCommon/__init__.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/MSCommon/__init__.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/MSCommon/__init__.py 5023 2010/06/14 22:05:46 scons" __doc__ = """ Common functions for Microsoft Visual Studio and Visual C/C++. diff --git a/engine/SCons/Tool/MSCommon/arch.py b/engine/SCons/Tool/MSCommon/arch.py index 34de46c..ba6d2d6 100644 --- a/engine/SCons/Tool/MSCommon/arch.py +++ b/engine/SCons/Tool/MSCommon/arch.py @@ -21,14 +21,14 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/MSCommon/arch.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/MSCommon/arch.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Module to define supported Windows chip architectures. """ import os -class ArchDefinition: +class ArchDefinition(object): """ A class for defining architecture-specific settings and logic. """ diff --git a/engine/SCons/Tool/MSCommon/common.py b/engine/SCons/Tool/MSCommon/common.py index 2303d2b..ef1aae9 100644 --- a/engine/SCons/Tool/MSCommon/common.py +++ b/engine/SCons/Tool/MSCommon/common.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/MSCommon/common.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/MSCommon/common.py 5023 2010/06/14 22:05:46 scons" __doc__ = """ Common helper functions for working with the Microsoft tool chain. @@ -99,46 +99,78 @@ def has_reg(value): # Functions for fetching environment variable settings from batch files. -def normalize_env(env, keys): +def normalize_env(env, keys, force=False): """Given a dictionary representing a shell environment, add the variables from os.environ needed for the processing of .bat files; the keys are controlled by the keys argument. It also makes sure the environment values are correctly encoded. - Note: the environment is copied""" + If force=True, then all of the key values that exist are copied + into the returned dictionary. If force=false, values are only + copied if the key does not already exist in the copied dictionary. + + Note: the environment is copied.""" normenv = {} if env: for k in env.keys(): normenv[k] = copy.deepcopy(env[k]).encode('mbcs') for k in keys: - if os.environ.has_key(k): + if k in os.environ and (force or not k in normenv): normenv[k] = os.environ[k].encode('mbcs') return normenv def get_output(vcbat, args = None, env = None): """Parse the output of given bat file, with given args.""" + + if env is None: + # Create a blank environment, for use in launching the tools + env = SCons.Environment.Environment(tools=[]) + + # TODO: This is a hard-coded list of the variables that (may) need + # to be imported from os.environ[] for v[sc]*vars*.bat file + # execution to work. This list should really be either directly + # controlled by vc.py, or else derived from the common_tools_var + # settings in vs.py. + vars = [ + 'COMSPEC', + 'VS90COMNTOOLS', + 'VS80COMNTOOLS', + 'VS71COMNTOOLS', + 'VS70COMNTOOLS', + 'VS60COMNTOOLS', + ] + env['ENV'] = normalize_env(env['ENV'], vars, force=False) + if args: debug("Calling '%s %s'" % (vcbat, args)) - popen = subprocess.Popen('"%s" %s & set' % (vcbat, args), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - env=env) + popen = SCons.Action._subproc(env, + '"%s" %s & set' % (vcbat, args), + stdin = 'devnull', + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) else: debug("Calling '%s'" % vcbat) - popen = subprocess.Popen('"%s" & set' % vcbat, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - env=env) + popen = SCons.Action._subproc(env, + '"%s" & set' % vcbat, + stdin = 'devnull', + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) # Use the .stdout and .stderr attributes directly because the # .communicate() method uses the threading module on Windows # and won't work under Pythons not built with threading. stdout = popen.stdout.read() + stderr = popen.stderr.read() + if stderr: + # TODO: find something better to do with stderr; + # this at least prevents errors from getting swallowed. + import sys + sys.stderr.write(stderr) if popen.wait() != 0: - raise IOError(popen.stderr.read().decode("mbcs")) + raise IOError(stderr.decode("mbcs")) output = stdout.decode("mbcs") return output @@ -147,9 +179,7 @@ def parse_output(output, keep = ("INCLUDE", "LIB", "LIBPATH", "PATH")): # dkeep is a dict associating key: path_list, where key is one item from # keep, and pat_list the associated list of paths - # TODO(1.5): replace with the following list comprehension: - #dkeep = dict([(i, []) for i in keep]) - dkeep = dict(map(lambda i: (i, []), keep)) + dkeep = dict([(i, []) for i in keep]) # rdk will keep the regex to match the .bat file output line starts rdk = {} diff --git a/engine/SCons/Tool/MSCommon/netframework.py b/engine/SCons/Tool/MSCommon/netframework.py index bd123dc..30be811 100644 --- a/engine/SCons/Tool/MSCommon/netframework.py +++ b/engine/SCons/Tool/MSCommon/netframework.py @@ -19,16 +19,14 @@ # 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/MSCommon/netframework.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/MSCommon/netframework.py 5023 2010/06/14 22:05:46 scons" __doc__ = """ """ import os import re -import string from common import read_reg, debug @@ -58,14 +56,14 @@ def query_versions(): contents = os.listdir(froot) l = re.compile('v[0-9]+.*') - versions = filter(lambda e, l=l: l.match(e), contents) + versions = [e for e in contents if l.match(e)] def versrt(a,b): # since version numbers aren't really floats... aa = a[1:] bb = b[1:] - aal = string.split(aa, '.') - bbl = string.split(bb, '.') + aal = aa.split('.') + bbl = bb.split('.') # sequence comparison in python is lexicographical # which is exactly what we want. # Note we sort backwards so the highest version is first. diff --git a/engine/SCons/Tool/MSCommon/sdk.py b/engine/SCons/Tool/MSCommon/sdk.py index 54be8ca..6debeb6 100644 --- a/engine/SCons/Tool/MSCommon/sdk.py +++ b/engine/SCons/Tool/MSCommon/sdk.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/MSCommon/sdk.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/MSCommon/sdk.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Module to detect the Platform/Windows SDK @@ -58,7 +58,7 @@ _CURINSTALLED_SDK_HKEY_ROOT = \ r"Software\Microsoft\Microsoft SDKs\Windows\CurrentInstallFolder" -class SDKDefinition: +class SDKDefinition(object): """ An abstract base class for trying to find installed SDK directories. """ @@ -131,7 +131,7 @@ class WindowsSDK(SDKDefinition): """ HKEY_FMT = r'Software\Microsoft\Microsoft SDKs\Windows\v%s\InstallationFolder' def __init__(self, *args, **kw): - apply(SDKDefinition.__init__, (self,)+args, kw) + SDKDefinition.__init__(self, *args, **kw) self.hkey_data = self.version class PlatformSDK(SDKDefinition): @@ -140,7 +140,7 @@ class PlatformSDK(SDKDefinition): """ HKEY_FMT = r'Software\Microsoft\MicrosoftSDK\InstalledSDKS\%s\Install Dir' def __init__(self, *args, **kw): - apply(SDKDefinition.__init__, (self,)+args, kw) + SDKDefinition.__init__(self, *args, **kw) self.hkey_data = self.uuid # @@ -310,9 +310,9 @@ def get_cur_sdk_dir_from_reg(): return val def get_sdk_by_version(mssdk): - if not SupportedSDKMap.has_key(mssdk): + if mssdk not in SupportedSDKMap: msg = "SDK version %s is not supported" % repr(mssdk) - raise SCons.Errors.UserError, msg + raise SCons.Errors.UserError(msg) get_installed_sdks() return InstalledSDKMap.get(mssdk) @@ -328,22 +328,22 @@ def get_default_sdk(): def mssdk_setup_env(env): debug('sdk.py:mssdk_setup_env()') - if env.has_key('MSSDK_DIR'): + if 'MSSDK_DIR' in env: sdk_dir = env['MSSDK_DIR'] if sdk_dir is None: return sdk_dir = env.subst(sdk_dir) debug('sdk.py:mssdk_setup_env: Using MSSDK_DIR:%s'%sdk_dir) - elif env.has_key('MSSDK_VERSION'): + elif 'MSSDK_VERSION' in env: sdk_version = env['MSSDK_VERSION'] if sdk_version is None: msg = "SDK version %s is not installed" % repr(mssdk) - raise SCons.Errors.UserError, msg + raise SCons.Errors.UserError(msg) sdk_version = env.subst(sdk_version) mssdk = get_sdk_by_version(sdk_version) sdk_dir = mssdk.get_sdk_dir() debug('sdk.py:mssdk_setup_env: Using MSSDK_VERSION:%s'%sdk_dir) - elif env.has_key('MSVS_VERSION'): + elif 'MSVS_VERSION' in env: msvs_version = env['MSVS_VERSION'] debug('sdk.py:mssdk_setup_env:Getting MSVS_VERSION from env:%s'%msvs_version) if msvs_version is None: @@ -382,7 +382,7 @@ def mssdk_exists(version=None): sdks = get_installed_sdks() if version is None: return len(sdks) > 0 - return sdks.has_key(version) + return version in sdks # Local Variables: # tab-width:4 diff --git a/engine/SCons/Tool/MSCommon/vc.py b/engine/SCons/Tool/MSCommon/vc.py index 5ea5a53..f07f34c 100644 --- a/engine/SCons/Tool/MSCommon/vc.py +++ b/engine/SCons/Tool/MSCommon/vc.py @@ -30,15 +30,15 @@ # * test on 64 bits XP + VS 2005 (and VS 6 if possible) # * SDK # * Assembly -__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Module for Visual C/C++ detection and configuration. """ import SCons.compat -import string import os import platform +from string import digits as string_digits import SCons.Warnings @@ -71,13 +71,16 @@ class BatchFileExecutionError(VisualCException): # Dict to 'canonalize' the arch _ARCH_TO_CANONICAL = { - "x86": "x86", - "amd64": "amd64", - "i386": "x86", - "emt64": "amd64", - "x86_64": "amd64", - "itanium": "ia64", - "ia64": "ia64", + "amd64" : "amd64", + "emt64" : "amd64", + "i386" : "x86", + "i486" : "x86", + "i586" : "x86", + "i686" : "x86", + "ia64" : "ia64", + "itanium" : "ia64", + "x86" : "x86", + "x86_64" : "amd64", } # Given a (host, target) tuple, return the argument for the bat file. Both host @@ -91,6 +94,8 @@ _HOST_TARGET_ARCH_TO_BAT_ARCH = { } def get_host_target(env): + debug('vc.py:get_host_target()') + host_platform = env.get('HOST_ARCH') if not host_platform: host_platform = platform.machine() @@ -99,22 +104,29 @@ def get_host_target(env): # PROCESSOR_ARCHITECTURE. if not host_platform: host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '') - target_platform = env.get('TARGET_ARCH') - if not target_platform: + + # Retain user requested TARGET_ARCH + req_target_platform = env.get('TARGET_ARCH') + debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform) + + if req_target_platform: + # If user requested a specific platform then only try that one. + target_platform = req_target_platform + else: target_platform = host_platform - + try: - host = _ARCH_TO_CANONICAL[host_platform] + host = _ARCH_TO_CANONICAL[host_platform.lower()] except KeyError, e: msg = "Unrecognized host architecture %s" raise ValueError(msg % repr(host_platform)) try: - target = _ARCH_TO_CANONICAL[target_platform] + target = _ARCH_TO_CANONICAL[target_platform.lower()] except KeyError, e: raise ValueError("Unrecognized target architecture %s" % target_platform) - return (host, target) + return (host, target,req_target_platform) _VCVER = ["10.0", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"] @@ -136,17 +148,19 @@ _VCVER_TO_PRODUCT_DIR = { '6.0': [ r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir'] } - + def msvc_version_to_maj_min(msvc_version): - t = msvc_version.split(".") - if not len(t) == 2: - raise ValueError("Unrecognized version %s" % msvc_version) - try: - maj = int(t[0]) - min = int(t[1]) - return maj, min - except ValueError, e: - raise ValueError("Unrecognized version %s" % msvc_version) + msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.']) + + t = msvc_version_numeric.split(".") + if not len(t) == 2: + raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric)) + try: + maj = int(t[0]) + min = int(t[1]) + return maj, min + except ValueError, e: + raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric)) def is_host_target_supported(host_target, msvc_version): """Return True if the given (host, target) tuple is supported given the @@ -206,7 +220,7 @@ def find_vc_pdir(msvc_version): raise MissingConfiguration("registry dir %s not found on the filesystem" % comps) return None -def find_batch_file(env,msvc_version): +def find_batch_file(env,msvc_version,host_arch,target_arch): """ Find the location of the batch script which should set up the compiler for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress @@ -218,7 +232,7 @@ def find_batch_file(env,msvc_version): debug('vc.py: find_batch_file() pdir:%s'%pdir) # filter out e.g. "Exp" from the version name - msvc_ver_numeric = string.join(filter(lambda x: x in string.digits + ".", msvc_version), '') + msvc_ver_numeric = ''.join([x for x in msvc_version if x in string_digits + "."]) vernum = float(msvc_ver_numeric) if 7 <= vernum < 8: pdir = os.path.join(pdir, os.pardir, "Common7", "Tools") @@ -234,7 +248,6 @@ def find_batch_file(env,msvc_version): batfilename = None installed_sdks=get_installed_sdks() - (host_arch,target_arch)=get_host_target(env) for _sdk in installed_sdks: sdk_bat_file=_sdk.get_sdk_vc_script(host_arch,target_arch) sdk_bat_file_path=os.path.join(pdir,sdk_bat_file) @@ -330,6 +343,73 @@ def msvc_setup_env_once(env): msvc_setup_env(env) env["MSVC_SETUP_RUN"] = True +def msvc_find_valid_batch_script(env,version): + debug('vc.py:msvc_find_valid_batch_script()') + # Find the host platform, target platform, and if present the requested + # target platform + (host_platform, target_platform,req_target_platform) = get_host_target(env) + + # If the user hasn't specifically requested a TARGET_ARCH, and + # The TARGET_ARCH is amd64 then also try 32 bits if there are no viable + # 64 bit tools installed + try_target_archs = [target_platform] + if not req_target_platform and target_platform=='amd64': + try_target_archs.append('x86') + + d = None + for tp in try_target_archs: + # Set to current arch. + env['TARGET_ARCH']=tp + + debug("vc.py:msvc_find_valid_batch_script() trying target_platform:%s"%tp) + host_target = (host_platform, tp) + if not is_host_target_supported(host_target, version): + warn_msg = "host, target = %s not supported for MSVC version %s" % \ + (host_target, version) + SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) + arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target] + + # Try to locate a batch file for this host/target platform combo + try: + (vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp) + debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script)) + except VisualCException, e: + msg = str(e) + debug('Caught exception while looking for batch file (%s)' % msg) + warn_msg = "VC version %s not installed. " + \ + "C/C++ compilers are most likely not set correctly.\n" + \ + " Installed versions are: %s" + warn_msg = warn_msg % (version, cached_get_installed_vcs()) + SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) + continue + + # Try to use the located batch file for this host/target platform combo + debug('vc.py:msvc_find_valid_batch_script() use_script 2 %s, args:%s\n' % (repr(vc_script), arg)) + if vc_script: + try: + d = script_env(vc_script, args=arg) + except BatchFileExecutionError, e: + debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e)) + vc_script=None + if not vc_script and sdk_script: + debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script)) + try: + d = script_env(sdk_script,args=[]) + except BatchFileExecutionError,e: + debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e)) + continue + elif not vc_script and not sdk_script: + debug('vc.py:msvc_find_valid_batch_script() use_script 6: Neither VC script nor SDK script found') + continue + + # If we cannot find a viable installed compiler, reset the TARGET_ARCH + # To it's initial value + if not d: + env['TARGET_ARCH']=req_target_platform + + return d + + def msvc_setup_env(env): debug('msvc_setup_env()') @@ -347,50 +427,16 @@ def msvc_setup_env(env): env['MSVS_VERSION'] = version env['MSVS'] = {} - try: - (vc_script,sdk_script) = find_batch_file(env,version) - debug('vc.py:msvc_setup_env() vc_script:%s sdk_script:%s'%(vc_script,sdk_script)) - except VisualCException, e: - msg = str(e) - debug('Caught exception while looking for batch file (%s)' % msg) - warn_msg = "VC version %s not installed. " + \ - "C/C++ compilers are most likely not set correctly.\n" + \ - " Installed versions are: %s" - warn_msg = warn_msg % (version, cached_get_installed_vcs()) - SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) - return None - debug('vc.py:msvc_setup_env() vc_script:%s sdk_script:%s'%(vc_script,sdk_script)) use_script = env.get('MSVC_USE_SCRIPT', True) if SCons.Util.is_String(use_script): - debug('use_script 1 %s\n' % repr(use_script)) + debug('vc.py:msvc_setup_env() use_script 1 %s\n' % repr(use_script)) d = script_env(use_script) - elif use_script: - host_platform, target_platform = get_host_target(env) - host_target = (host_platform, target_platform) - if not is_host_target_supported(host_target, version): - warn_msg = "host, target = %s not supported for MSVC version %s" % \ - (host_target, version) - SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) - arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target] - debug('use_script 2 %s, args:%s\n' % (repr(vc_script), arg)) - if vc_script: - try: - d = script_env(vc_script, args=arg) - except BatchFileExecutionError, e: - debug('use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e)) - vc_script=None - if not vc_script and sdk_script: - debug('use_script 4: trying sdk script: %s'%(sdk_script)) - try: - d = script_env(sdk_script,args=[]) - except BatchFileExecutionError,e: - debug('use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e)) - return None - elif not vc_script and not sdk_script: - debug('use_script 6: Neither VC script nor SDK script found') - return None - + elif use_script: + d = msvc_find_valid_batch_script(env,version) + debug('vc.py:msvc_setup_env() use_script 2 %s\n' % d) + if not d: + return d else: debug('MSVC_USE_SCRIPT set to False') warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \ diff --git a/engine/SCons/Tool/MSCommon/vs.py b/engine/SCons/Tool/MSCommon/vs.py index e634a18..06030e2 100644 --- a/engine/SCons/Tool/MSCommon/vs.py +++ b/engine/SCons/Tool/MSCommon/vs.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/MSCommon/vs.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/MSCommon/vs.py 5023 2010/06/14 22:05:46 scons" __doc__ = """Module to detect Visual Studio and/or Visual C/C++ """ @@ -40,7 +40,7 @@ from common import debug, \ import SCons.Tool.MSCommon.vc -class VisualStudio: +class VisualStudio(object): """ An abstract base class for trying to find installed versions of Visual Studio. @@ -385,9 +385,9 @@ def get_vs_by_version(msvs): global SupportedVSMap debug('vs.py:get_vs_by_version()') - if not SupportedVSMap.has_key(msvs): + if msvs not in SupportedVSMap: msg = "Visual Studio version %s is not supported" % repr(msvs) - raise SCons.Errors.UserError, msg + raise SCons.Errors.UserError(msg) get_installed_visual_studios() vs = InstalledVSMap.get(msvs) debug('InstalledVSMap:%s'%InstalledVSMap) @@ -415,15 +415,13 @@ def get_default_version(env): version: str the default version. """ - if not env.has_key('MSVS') or not SCons.Util.is_Dict(env['MSVS']): - # TODO(1.5): - #versions = [vs.version for vs in get_installed_visual_studios()] - versions = map(lambda vs: vs.version, get_installed_visual_studios()) + if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']): + versions = [vs.version for vs in get_installed_visual_studios()] env['MSVS'] = {'VERSIONS' : versions} else: versions = env['MSVS'].get('VERSIONS', []) - if not env.has_key('MSVS_VERSION'): + if 'MSVS_VERSION' not in env: if versions: env['MSVS_VERSION'] = versions[0] #use highest version by default else: @@ -451,7 +449,7 @@ def get_default_arch(env): arch = 'x86' elif not arch in msvs.get_supported_arch(): fmt = "Visual Studio version %s does not support architecture %s" - raise SCons.Errors.UserError, fmt % (env['MSVS_VERSION'], arch) + raise SCons.Errors.UserError(fmt % (env['MSVS_VERSION'], arch)) return arch @@ -473,11 +471,15 @@ def msvs_setup_env(env): vars = ('LIB', 'LIBPATH', 'PATH', 'INCLUDE') msvs_list = get_installed_visual_studios() - # TODO(1.5): - #vscommonvarnames = [ vs.common_tools_var for vs in msvs_list ] - vscommonvarnames = map(lambda vs: vs.common_tools_var, msvs_list) - nenv = normalize_env(env['ENV'], vscommonvarnames + ['COMSPEC']) - output = get_output(batfilename, arch, env=nenv) + vscommonvarnames = [vs.common_tools_var for vs in msvs_list] + save_ENV = env['ENV'] + nenv = normalize_env(env['ENV'], + ['COMSPEC'] + vscommonvarnames, + force=True) + try: + output = get_output(batfilename, arch, env=nenv) + finally: + env['ENV'] = save_ENV vars = parse_output(output, vars) for k, v in vars.items(): @@ -487,9 +489,7 @@ def query_versions(): """Query the system to get available versions of VS. A version is considered when a batfile is found.""" msvs_list = get_installed_visual_studios() - # TODO(1.5) - #versions = [ msvs.version for msvs in msvs_list ] - versions = map(lambda msvs: msvs.version, msvs_list) + versions = [msvs.version for msvs in msvs_list] return versions # Local Variables: diff --git a/engine/SCons/Tool/Perforce.py b/engine/SCons/Tool/Perforce.py index 08da75b..43d9f6e 100644 --- a/engine/SCons/Tool/Perforce.py +++ b/engine/SCons/Tool/Perforce.py @@ -8,7 +8,6 @@ selection method. """ -# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining @@ -29,9 +28,8 @@ selection method. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/Perforce.py 5023 2010/06/14 22:05:46 scons" import os @@ -44,7 +42,6 @@ import 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' ] @@ -57,6 +54,8 @@ def generate(env): 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) diff --git a/engine/SCons/Tool/PharLapCommon.py b/engine/SCons/Tool/PharLapCommon.py index 2cfb02a..64dd02f 100644 --- a/engine/SCons/Tool/PharLapCommon.py +++ b/engine/SCons/Tool/PharLapCommon.py @@ -29,14 +29,13 @@ Phar Lap ETS tool chain. Right now, this is linkloc and # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/PharLapCommon.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/PharLapCommon.py 5023 2010/06/14 22:05:46 scons" import os import os.path import SCons.Errors import SCons.Util import re -import string def getPharLapPath(): """Reads the registry to find the installed path of the Phar Lap ETS @@ -46,7 +45,7 @@ def getPharLapPath(): be found.""" if not SCons.Util.can_read_reg: - raise SCons.Errors.InternalError, "No Windows registry module was found" + raise SCons.Errors.InternalError("No Windows registry module was found") try: k=SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Pharlap\\ETS') @@ -62,7 +61,7 @@ def getPharLapPath(): 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?" + 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]+)') @@ -79,7 +78,7 @@ def getPharLapVersion(): 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?" + 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)) @@ -97,14 +96,14 @@ def addPathIfNotExists(env_dict, key, path, sep=os.pathsep): is_list = 1 paths = env_dict[key] if not SCons.Util.is_List(env_dict[key]): - paths = string.split(paths, sep) + paths = paths.split(sep) is_list = 0 - if not os.path.normcase(path) in map(os.path.normcase, paths): + 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] = string.join(paths, sep) + env_dict[key] = sep.join(paths) except KeyError: env_dict[key] = path diff --git a/engine/SCons/Tool/RCS.py b/engine/SCons/Tool/RCS.py index 4d14af7..5c5a6bd 100644 --- a/engine/SCons/Tool/RCS.py +++ b/engine/SCons/Tool/RCS.py @@ -8,7 +8,6 @@ selection method. """ -# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining @@ -29,9 +28,8 @@ selection method. # 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/RCS.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/RCS.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Builder @@ -43,6 +41,8 @@ def generate(env): def RCSFactory(env=env): """ """ + import SCons.Warnings as W + W.warn(W.DeprecatedSourceCodeWarning, """The RCS() factory is deprecated and there is no replacement.""") act = SCons.Action.Action('$RCS_COCOM', '$RCS_COCOMSTR') return SCons.Builder.Builder(action = act, env = env) diff --git a/engine/SCons/Tool/SCCS.py b/engine/SCons/Tool/SCCS.py index 2893291..2983b83 100644 --- a/engine/SCons/Tool/SCCS.py +++ b/engine/SCons/Tool/SCCS.py @@ -8,7 +8,6 @@ selection method. """ -# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining @@ -29,9 +28,8 @@ selection method. # 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/SCCS.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/SCCS.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Builder @@ -43,6 +41,8 @@ def generate(env): def SCCSFactory(env=env): """ """ + import SCons.Warnings as W + W.warn(W.DeprecatedSourceCodeWarning, """The SCCS() factory is deprecated and there is no replacement.""") act = SCons.Action.Action('$SCCSCOM', '$SCCSCOMSTR') return SCons.Builder.Builder(action = act, env = env) diff --git a/engine/SCons/Tool/Subversion.py b/engine/SCons/Tool/Subversion.py index 51a670a..26ff700 100644 --- a/engine/SCons/Tool/Subversion.py +++ b/engine/SCons/Tool/Subversion.py @@ -8,7 +8,6 @@ selection method. """ -# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining @@ -29,9 +28,8 @@ selection method. # 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/Subversion.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/Subversion.py 5023 2010/06/14 22:05:46 scons" import os.path @@ -46,6 +44,8 @@ def generate(env): def SubversionFactory(repos, module='', env=env): """ """ # fail if repos is not an absolute path name? + import SCons.Warnings as W + W.warn(W.DeprecatedSourceCodeWarning, """The Subversion() factory is deprecated and there is no replacement.""") if module != '': module = os.path.join(module, '') act = SCons.Action.Action('$SVNCOM', '$SVNCOMSTR') diff --git a/engine/SCons/Tool/__init__.py b/engine/SCons/Tool/__init__.py index 4a41a8c..e38d85f 100644 --- a/engine/SCons/Tool/__init__.py +++ b/engine/SCons/Tool/__init__.py @@ -34,9 +34,8 @@ tool definition. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/__init__.py 5023 2010/06/14 22:05:46 scons" import imp import sys @@ -85,7 +84,7 @@ for suffix in LaTeXSuffixes: SourceFileScanner.add_scanner(suffix, LaTeXScanner) SourceFileScanner.add_scanner(suffix, PDFLaTeXScanner) -class Tool: +class Tool(object): def __init__(self, name, toolpath=[], **kw): self.name = name self.toolpath = toolpath + DefaultToolpath @@ -113,7 +112,7 @@ class Tool: file.close() except ImportError, e: if str(e)!="No module named %s"%self.name: - raise SCons.Errors.EnvironmentError, e + raise SCons.Errors.EnvironmentError(e) try: import zipimport except ImportError: @@ -143,7 +142,7 @@ class Tool: return module except ImportError, e: if str(e)!="No module named %s"%self.name: - raise SCons.Errors.EnvironmentError, e + raise SCons.Errors.EnvironmentError(e) try: import zipimport importer = zipimport.zipimporter( sys.modules['SCons.Tool'].__path__[0] ) @@ -152,10 +151,10 @@ class Tool: return module except ImportError, e: m = "No tool named '%s': %s" % (self.name, e) - raise SCons.Errors.EnvironmentError, m + raise SCons.Errors.EnvironmentError(m) except ImportError, e: m = "No tool named '%s': %s" % (self.name, e) - raise SCons.Errors.EnvironmentError, m + raise SCons.Errors.EnvironmentError(m) def __call__(self, env, *args, **kw): if self.init_kw is not None: @@ -170,7 +169,7 @@ class Tool: env.Append(TOOLS = [ self.name ]) if hasattr(self, 'options'): import SCons.Variables - if not env.has_key('options'): + if 'options' not in env: from SCons.Script import ARGUMENTS env['options']=SCons.Variables.Variables(args=ARGUMENTS) opts=env['options'] @@ -178,7 +177,7 @@ class Tool: self.options(opts) opts.Update(env) - apply(self.generate, ( env, ) + args, kw) + self.generate(env, *args, **kw) def __str__(self): return self.name @@ -428,7 +427,7 @@ def CreateJavaFileBuilder(env): env['JAVASUFFIX'] = '.java' return java_file -class ToolInitializerMethod: +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, @@ -474,9 +473,9 @@ class ToolInitializerMethod: builder = self.get_builder(env) if builder is None: return [], [] - return apply(builder, args, kw) + return builder(*args, **kw) -class ToolInitializer: +class ToolInitializer(object): """ A class for delayed initialization of Tools modules. @@ -530,9 +529,9 @@ class ToolInitializer: def Initializers(env): ToolInitializer(env, ['install'], ['_InternalInstall', '_InternalInstallAs']) def Install(self, *args, **kw): - return apply(self._InternalInstall, args, kw) + return self._InternalInstall(*args, **kw) def InstallAs(self, *args, **kw): - return apply(self._InternalInstallAs, args, kw) + return self._InternalInstallAs(*args, **kw) env.AddMethod(Install) env.AddMethod(InstallAs) @@ -546,7 +545,7 @@ def FindTool(tools, env): def FindAllTools(tools, env): def ToolExists(tool, env=env): return Tool(tool).exists(env) - return filter (ToolExists, tools) + return list(filter (ToolExists, tools)) def tool_list(platform, env): @@ -646,27 +645,34 @@ def tool_list(platform, env): fortran_compiler = FindTool(fortran_compilers, env) or fortran_compilers[0] ar = FindTool(ars, env) or ars[0] - other_tools = FindAllTools(['BitKeeper', 'CVS', - 'dmd', - 'filesystem', - 'dvipdf', 'dvips', 'gs', - 'jar', 'javac', 'javah', - 'latex', 'lex', - 'm4', #'midl', 'msvs', - 'pdflatex', 'pdftex', 'Perforce', - 'RCS', 'rmic', 'rpcgen', - 'SCCS', - # 'Subversion', - 'swig', - 'tar', 'tex', - 'yacc', 'zip', 'rpm', 'wix']+other_plat_tools, - env) + 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 filter(lambda x: x, tools) + return [x for x in tools if x] # Local Variables: # tab-width:4 diff --git a/engine/SCons/Tool/aixc++.py b/engine/SCons/Tool/aixc++.py index 035ece4..62c5ef7 100644 --- a/engine/SCons/Tool/aixc++.py +++ b/engine/SCons/Tool/aixc++.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/aixc++.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/aixc++.py 5023 2010/06/14 22:05:46 scons" import os.path diff --git a/engine/SCons/Tool/aixcc.py b/engine/SCons/Tool/aixcc.py index 1c6ae14..bf1de34 100644 --- a/engine/SCons/Tool/aixcc.py +++ b/engine/SCons/Tool/aixcc.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/aixcc.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/aixcc.py 5023 2010/06/14 22:05:46 scons" import os.path diff --git a/engine/SCons/Tool/aixf77.py b/engine/SCons/Tool/aixf77.py index a5a9d8c..f680247 100644 --- a/engine/SCons/Tool/aixf77.py +++ b/engine/SCons/Tool/aixf77.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/aixf77.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/aixf77.py 5023 2010/06/14 22:05:46 scons" import os.path diff --git a/engine/SCons/Tool/aixlink.py b/engine/SCons/Tool/aixlink.py index 0e1b974..9531a4b 100644 --- a/engine/SCons/Tool/aixlink.py +++ b/engine/SCons/Tool/aixlink.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/aixlink.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/aixlink.py 5023 2010/06/14 22:05:46 scons" import os import os.path diff --git a/engine/SCons/Tool/applelink.py b/engine/SCons/Tool/applelink.py index a56462d..4b3ae77 100644 --- a/engine/SCons/Tool/applelink.py +++ b/engine/SCons/Tool/applelink.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/applelink.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/applelink.py 5023 2010/06/14 22:05:46 scons" import SCons.Util diff --git a/engine/SCons/Tool/ar.py b/engine/SCons/Tool/ar.py index b0ae76b..68effb1 100644 --- a/engine/SCons/Tool/ar.py +++ b/engine/SCons/Tool/ar.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/ar.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/ar.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Tool diff --git a/engine/SCons/Tool/as.py b/engine/SCons/Tool/as.py index bdd00db..f18ff57 100644 --- a/engine/SCons/Tool/as.py +++ b/engine/SCons/Tool/as.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/as.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/as.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Tool diff --git a/engine/SCons/Tool/bcc32.py b/engine/SCons/Tool/bcc32.py index 67325d0..b7c7bf2 100644 --- a/engine/SCons/Tool/bcc32.py +++ b/engine/SCons/Tool/bcc32.py @@ -27,11 +27,10 @@ XXX # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/bcc32.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/bcc32.py 5023 2010/06/14 22:05:46 scons" import os import os.path -import string import SCons.Defaults import SCons.Tool diff --git a/engine/SCons/Tool/c++.py b/engine/SCons/Tool/c++.py index d74cd96..907324d 100644 --- a/engine/SCons/Tool/c++.py +++ b/engine/SCons/Tool/c++.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/c++.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/c++.py 5023 2010/06/14 22:05:46 scons" import os.path diff --git a/engine/SCons/Tool/cc.py b/engine/SCons/Tool/cc.py index c565225..c3a6b92 100644 --- a/engine/SCons/Tool/cc.py +++ b/engine/SCons/Tool/cc.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/cc.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/cc.py 5023 2010/06/14 22:05:46 scons" import SCons.Tool import SCons.Defaults @@ -45,7 +45,7 @@ def add_common_cc_variables(env): Add underlying common "C compiler" variables that are used by multiple tools (specifically, c++). """ - if not env.has_key('_CCCOMCOM'): + 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. @@ -56,10 +56,10 @@ def add_common_cc_variables(env): if env['PLATFORM'] == 'darwin': env['_CCCOMCOM'] = env['_CCCOMCOM'] + ' $_FRAMEWORKPATH' - if not env.has_key('CCFLAGS'): + if 'CCFLAGS' not in env: env['CCFLAGS'] = SCons.Util.CLVar('') - if not env.has_key('SHCCFLAGS'): + if 'SHCCFLAGS' not in env: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') def generate(env): @@ -73,18 +73,6 @@ def generate(env): shared_obj.add_action(suffix, SCons.Defaults.ShCAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) -#<<<<<<< .working -# -# 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' -#======= -#>>>>>>> .merge-right.r1907 add_common_cc_variables(env) diff --git a/engine/SCons/Tool/cvf.py b/engine/SCons/Tool/cvf.py index 7930a38..4860241 100644 --- a/engine/SCons/Tool/cvf.py +++ b/engine/SCons/Tool/cvf.py @@ -27,7 +27,7 @@ Tool-specific initialization for the Compaq Visual Fortran compiler. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/cvf.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/cvf.py 5023 2010/06/14 22:05:46 scons" import fortran diff --git a/engine/SCons/Tool/default.py b/engine/SCons/Tool/default.py index b477c7b..a2883d7 100644 --- a/engine/SCons/Tool/default.py +++ b/engine/SCons/Tool/default.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/default.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/default.py 5023 2010/06/14 22:05:46 scons" import SCons.Tool diff --git a/engine/SCons/Tool/dmd.py b/engine/SCons/Tool/dmd.py index d5dc5c1..a269354 100644 --- a/engine/SCons/Tool/dmd.py +++ b/engine/SCons/Tool/dmd.py @@ -54,10 +54,9 @@ Lib tool variables: # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/dmd.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/dmd.py 5023 2010/06/14 22:05:46 scons" import os -import string import SCons.Action import SCons.Builder @@ -112,7 +111,7 @@ def generate(env): # This is merely for the convenience of the dependency scanner. dmd_path = env.WhereIs(dc) if dmd_path: - x = string.rindex(dmd_path, dc) + x = dmd_path.rindex(dc) phobosDir = dmd_path[:x] + '/../src/phobos' if os.path.isdir(phobosDir): env.Append(DPATH = [phobosDir]) diff --git a/engine/SCons/Tool/dvi.py b/engine/SCons/Tool/dvi.py index ce91cca..7eb9de4 100644 --- a/engine/SCons/Tool/dvi.py +++ b/engine/SCons/Tool/dvi.py @@ -27,7 +27,7 @@ Common DVI Builder definition for various other Tool modules that use it. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/dvi.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/dvi.py 5023 2010/06/14 22:05:46 scons" import SCons.Builder import SCons.Tool diff --git a/engine/SCons/Tool/dvipdf.py b/engine/SCons/Tool/dvipdf.py index cf6909d..1b352b3 100644 --- a/engine/SCons/Tool/dvipdf.py +++ b/engine/SCons/Tool/dvipdf.py @@ -29,9 +29,8 @@ selection method. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/dvipdf.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Defaults @@ -88,7 +87,7 @@ def PDFEmitter(target, source, env): """ def strip_suffixes(n): return not SCons.Util.splitext(str(n))[1] in ['.aux', '.log'] - source = filter(strip_suffixes, source) + source = list(filter(strip_suffixes, source)) return (target, source) def generate(env): diff --git a/engine/SCons/Tool/dvips.py b/engine/SCons/Tool/dvips.py index be8a5fe..d6e7006 100644 --- a/engine/SCons/Tool/dvips.py +++ b/engine/SCons/Tool/dvips.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/dvips.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/dvips.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Builder diff --git a/engine/SCons/Tool/f77.py b/engine/SCons/Tool/f77.py index 17e7b6e..d4ec887 100644 --- a/engine/SCons/Tool/f77.py +++ b/engine/SCons/Tool/f77.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/f77.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/f77.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Scanner.Fortran diff --git a/engine/SCons/Tool/f90.py b/engine/SCons/Tool/f90.py index 8db5824..b8829b7 100644 --- a/engine/SCons/Tool/f90.py +++ b/engine/SCons/Tool/f90.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/f90.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/f90.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Scanner.Fortran diff --git a/engine/SCons/Tool/f95.py b/engine/SCons/Tool/f95.py index fc00566..66be308 100644 --- a/engine/SCons/Tool/f95.py +++ b/engine/SCons/Tool/f95.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/f95.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/f95.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Tool diff --git a/engine/SCons/Tool/filesystem.py b/engine/SCons/Tool/filesystem.py index c015390..6bceb14 100644 --- a/engine/SCons/Tool/filesystem.py +++ b/engine/SCons/Tool/filesystem.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/filesystem.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/filesystem.py 5023 2010/06/14 22:05:46 scons" import SCons from SCons.Tool.install import copyFunc @@ -44,12 +44,12 @@ def copyto_emitter(target, source, env): n_target = [] for t in target: - n_target = n_target + map( lambda s, t=t: t.File( str( s ) ), source ) + n_target = n_target + [t.File( str( s ) ) for s in source] return (n_target, source) def copy_action_func(target, source, env): - assert( len(target) == len(source) ), "\ntarget: %s\nsource: %s" %(map(str, target),map(str, source)) + assert( len(target) == len(source) ), "\ntarget: %s\nsource: %s" %(list(map(str, target)),list(map(str, source))) for t, s in zip(target, source): if copyFunc(t.get_path(), s.get_path(), env): diff --git a/engine/SCons/Tool/fortran.py b/engine/SCons/Tool/fortran.py index fea2660..f7b4e8d 100644 --- a/engine/SCons/Tool/fortran.py +++ b/engine/SCons/Tool/fortran.py @@ -31,10 +31,9 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/fortran.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/fortran.py 5023 2010/06/14 22:05:46 scons" import re -import string import SCons.Action import SCons.Defaults diff --git a/engine/SCons/Tool/g++.py b/engine/SCons/Tool/g++.py index 019939a..fa93329 100644 --- a/engine/SCons/Tool/g++.py +++ b/engine/SCons/Tool/g++.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/g++.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/g++.py 5023 2010/06/14 22:05:46 scons" import os.path import re diff --git a/engine/SCons/Tool/g77.py b/engine/SCons/Tool/g77.py index 3b50b6d..c21f34b 100644 --- a/engine/SCons/Tool/g77.py +++ b/engine/SCons/Tool/g77.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/g77.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/g77.py 5023 2010/06/14 22:05:46 scons" import SCons.Util from SCons.Tool.FortranCommon import add_all_to_env, add_f77_to_env diff --git a/engine/SCons/Tool/gas.py b/engine/SCons/Tool/gas.py index 52255ab..0ec021a 100644 --- a/engine/SCons/Tool/gas.py +++ b/engine/SCons/Tool/gas.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/gas.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/gas.py 5023 2010/06/14 22:05:46 scons" as_module = __import__('as', globals(), locals(), []) diff --git a/engine/SCons/Tool/gcc.py b/engine/SCons/Tool/gcc.py index 5994854..5d1a7d5 100644 --- a/engine/SCons/Tool/gcc.py +++ b/engine/SCons/Tool/gcc.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/gcc.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/gcc.py 5023 2010/06/14 22:05:46 scons" import cc import os diff --git a/engine/SCons/Tool/gfortran.py b/engine/SCons/Tool/gfortran.py index 863e82a..2a3872e 100644 --- a/engine/SCons/Tool/gfortran.py +++ b/engine/SCons/Tool/gfortran.py @@ -32,7 +32,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/gfortran.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/gfortran.py 5023 2010/06/14 22:05:46 scons" import SCons.Util diff --git a/engine/SCons/Tool/gnulink.py b/engine/SCons/Tool/gnulink.py index 71071f1..9845a69 100644 --- a/engine/SCons/Tool/gnulink.py +++ b/engine/SCons/Tool/gnulink.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/gnulink.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/gnulink.py 5023 2010/06/14 22:05:46 scons" import SCons.Util diff --git a/engine/SCons/Tool/gs.py b/engine/SCons/Tool/gs.py index 0e6deef..8ab63d7 100644 --- a/engine/SCons/Tool/gs.py +++ b/engine/SCons/Tool/gs.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/gs.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/gs.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Platform @@ -69,7 +69,7 @@ def generate(env): def exists(env): - if env.has_key('PS2PDF'): + if 'PS2PDF' in env: return env.Detect(env['PS2PDF']) else: return env.Detect(gs) or SCons.Util.WhereIs(gs) diff --git a/engine/SCons/Tool/hpc++.py b/engine/SCons/Tool/hpc++.py index 28d766f..5be3854 100644 --- a/engine/SCons/Tool/hpc++.py +++ b/engine/SCons/Tool/hpc++.py @@ -31,10 +31,9 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/hpc++.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/hpc++.py 5023 2010/06/14 22:05:46 scons" import os.path -import string import SCons.Util @@ -67,8 +66,8 @@ def generate(env): env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS +Z') # determine version of aCC line = os.popen(acc + ' -V 2>&1').readline().rstrip() - if string.find(line, 'aCC: HP ANSI C++') == 0: - env['CXXVERSION'] = string.split(line)[-1] + if line.find('aCC: HP ANSI C++') == 0: + env['CXXVERSION'] = line.split()[-1] if env['PLATFORM'] == 'cygwin': env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') diff --git a/engine/SCons/Tool/hpcc.py b/engine/SCons/Tool/hpcc.py index f2ab04f..24b48c7 100644 --- a/engine/SCons/Tool/hpcc.py +++ b/engine/SCons/Tool/hpcc.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/hpcc.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/hpcc.py 5023 2010/06/14 22:05:46 scons" import SCons.Util diff --git a/engine/SCons/Tool/hplink.py b/engine/SCons/Tool/hplink.py index f6eff45..b2ad1ca 100644 --- a/engine/SCons/Tool/hplink.py +++ b/engine/SCons/Tool/hplink.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/hplink.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/hplink.py 5023 2010/06/14 22:05:46 scons" import os import os.path diff --git a/engine/SCons/Tool/icc.py b/engine/SCons/Tool/icc.py index 0d4e617..fd5affe 100644 --- a/engine/SCons/Tool/icc.py +++ b/engine/SCons/Tool/icc.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/icc.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/icc.py 5023 2010/06/14 22:05:46 scons" import cc diff --git a/engine/SCons/Tool/icl.py b/engine/SCons/Tool/icl.py index ce98156..f1da778 100644 --- a/engine/SCons/Tool/icl.py +++ b/engine/SCons/Tool/icl.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/icl.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/icl.py 5023 2010/06/14 22:05:46 scons" import SCons.Tool.intelc @@ -40,10 +40,10 @@ import SCons.Tool.intelc def generate(*args, **kw): """Add Builders and construction variables for icl to an Environment.""" - return apply(SCons.Tool.intelc.generate, args, kw) + return SCons.Tool.intelc.generate(*args, **kw) def exists(*args, **kw): - return apply(SCons.Tool.intelc.exists, args, kw) + return SCons.Tool.intelc.exists(*args, **kw) # Local Variables: # tab-width:4 diff --git a/engine/SCons/Tool/ifl.py b/engine/SCons/Tool/ifl.py index 93dc977..17ceb34 100644 --- a/engine/SCons/Tool/ifl.py +++ b/engine/SCons/Tool/ifl.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/ifl.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/ifl.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults from SCons.Scanner.Fortran import FortranScan @@ -43,12 +43,12 @@ def generate(env): SCons.Tool.SourceFileScanner.add_scanner('.i', fscan) SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan) - if not env.has_key('FORTRANFILESUFFIXES'): + if 'FORTRANFILESUFFIXES' not in env: env['FORTRANFILESUFFIXES'] = ['.i'] else: env['FORTRANFILESUFFIXES'].append('.i') - if not env.has_key('F90FILESUFFIXES'): + if 'F90FILESUFFIXES' not in env: env['F90FILESUFFIXES'] = ['.i90'] else: env['F90FILESUFFIXES'].append('.i90') diff --git a/engine/SCons/Tool/ifort.py b/engine/SCons/Tool/ifort.py index 047afba..06bf484 100644 --- a/engine/SCons/Tool/ifort.py +++ b/engine/SCons/Tool/ifort.py @@ -32,9 +32,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/ifort.py 4720 2010/03/24 03:14:11 jars" - -import string +__revision__ = "src/engine/SCons/Tool/ifort.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults from SCons.Scanner.Fortran import FortranScan @@ -48,12 +46,12 @@ def generate(env): SCons.Tool.SourceFileScanner.add_scanner('.i', fscan) SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan) - if not env.has_key('FORTRANFILESUFFIXES'): + if 'FORTRANFILESUFFIXES' not in env: env['FORTRANFILESUFFIXES'] = ['.i'] else: env['FORTRANFILESUFFIXES'].append('.i') - if not env.has_key('F90FILESUFFIXES'): + if 'F90FILESUFFIXES' not in env: env['F90FILESUFFIXES'] = ['.i90'] else: env['F90FILESUFFIXES'].append('.i90') @@ -75,7 +73,7 @@ def generate(env): for dialect in ['F77', 'F90', 'FORTRAN', 'F95']: for var in ['%sCOM' % dialect, '%sPPCOM' % dialect, 'SH%sCOM' % dialect, 'SH%sPPCOM' % dialect]: - env[var] = string.replace(env[var], '-o $TARGET', '-object:$TARGET') + env[var] = env[var].replace('-o $TARGET', '-object:$TARGET') env['FORTRANMODDIRPREFIX'] = "/module:" else: env['FORTRANMODDIRPREFIX'] = "-module " diff --git a/engine/SCons/Tool/ilink.py b/engine/SCons/Tool/ilink.py index 4d8395f..71025d1 100644 --- a/engine/SCons/Tool/ilink.py +++ b/engine/SCons/Tool/ilink.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/ilink.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/ilink.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Tool diff --git a/engine/SCons/Tool/ilink32.py b/engine/SCons/Tool/ilink32.py index 1765193..fb570f8 100644 --- a/engine/SCons/Tool/ilink32.py +++ b/engine/SCons/Tool/ilink32.py @@ -27,7 +27,7 @@ XXX # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/ilink32.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/ilink32.py 5023 2010/06/14 22:05:46 scons" import SCons.Tool import SCons.Tool.bcc32 diff --git a/engine/SCons/Tool/install.py b/engine/SCons/Tool/install.py index 0d7b9d5..7b61bde 100644 --- a/engine/SCons/Tool/install.py +++ b/engine/SCons/Tool/install.py @@ -30,7 +30,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/install.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/install.py 5023 2010/06/14 22:05:46 scons" import os import shutil @@ -54,7 +54,7 @@ def copyFunc(dest, source, env): 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)) + 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): @@ -76,7 +76,7 @@ def installFunc(target, source, env): 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."%(map(str, source), map(str, target)) + "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 @@ -108,7 +108,7 @@ def add_targets_to_INSTALLED_FILES(target, source, env): _UNIQUE_INSTALLED_FILES = None return (target, source) -class DESTDIR_factory: +class DESTDIR_factory(object): """ a node factory, where all files will be relative to the dir supplied in the constructor. """ @@ -135,7 +135,7 @@ 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." + raise SCons.Errors.UserError("Both target and dir defined for Install(), only one may be defined.") if not dir: dir=target @@ -149,7 +149,7 @@ def InstallBuilderWrapper(env, target=None, source=None, dir=None, **kw): 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) + 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: @@ -159,14 +159,14 @@ def InstallBuilderWrapper(env, target=None, source=None, dir=None, **kw): # 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(apply(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(apply(BaseInstallBuilder, (env, tgt, src), kw)) + result.extend(BaseInstallBuilder(env, tgt, src, **kw)) return result added = None diff --git a/engine/SCons/Tool/intelc.py b/engine/SCons/Tool/intelc.py index a9b23d3..10e92cd 100644 --- a/engine/SCons/Tool/intelc.py +++ b/engine/SCons/Tool/intelc.py @@ -30,15 +30,15 @@ selection method. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/intelc.py 5023 2010/06/14 22:05:46 scons" import math, sys, os.path, glob, string, re is_windows = sys.platform == 'win32' is_win64 = is_windows and (os.environ['PROCESSOR_ARCHITECTURE'] == 'AMD64' or - (os.environ.has_key('PROCESSOR_ARCHITEW6432') and + ('PROCESSOR_ARCHITEW6432' in os.environ and os.environ['PROCESSOR_ARCHITEW6432'] == 'AMD64')) is_linux = sys.platform == 'linux2' is_mac = sys.platform == 'darwin' @@ -69,7 +69,7 @@ def uniquify(s): u = {} for x in s: u[x] = 1 - return u.keys() + return list(u.keys()) def linux_ver_normalize(vstr): """Normalize a Linux compiler version number. @@ -81,7 +81,7 @@ def linux_ver_normalize(vstr): 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.; + return float(vmaj) * 10. + float(vmin) + float(build) / 1000.; else: f = float(vstr) if is_windows: @@ -117,9 +117,8 @@ def check_abi(abi): try: abi = valid_abis[abi] except KeyError: - raise SCons.Errors.UserError, \ - "Intel compiler: Invalid ABI %s, valid values are %s"% \ - (abi, valid_abis.keys()) + raise SCons.Errors.UserError("Intel compiler: Invalid ABI %s, valid values are %s"% \ + (abi, list(valid_abis.keys()))) return abi def vercmp(a, b): @@ -156,16 +155,14 @@ def get_intel_registry_value(valuename, version=None, abi=None): 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) + 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) + raise MissingRegistryError("%s\\%s was not found in the registry."%(K, valuename)) def get_all_compiler_versions(): @@ -243,9 +240,7 @@ def get_all_compiler_versions(): m = re.search(r'([0-9.]+)$', d) if m: versions.append(m.group(1)) - versions = uniquify(versions) # remove dups - versions.sort(vercmp) - return versions + return sorted(uniquify(versions)) # remove dups def get_intel_compiler_top(version, abi): """ @@ -257,13 +252,12 @@ def get_intel_compiler_top(version, abi): if is_windows: if not SCons.Util.can_read_reg: - raise NoRegistryModuleError, "No Windows registry module was found" + 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/ 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) + raise MissingDirError("Can't find Intel compiler in %s"%(top)) elif is_mac or is_linux: # first dir is new (>=9.0) style, second is old (8.0) style. dirs=('/opt/intel/cc/%s', '/opt/intel_cc_%s') @@ -275,8 +269,7 @@ def get_intel_compiler_top(version, abi): top = d%version break if not top: - raise MissingDirError, \ - "Can't find version %s Intel compiler in %s (abi='%s')"%(version,top, abi) + raise MissingDirError("Can't find version %s Intel compiler in %s (abi='%s')"%(version,top, abi)) return top @@ -312,9 +305,8 @@ def generate(env, version=None, abi=None, topdir=None, verbose=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)) + raise SCons.Errors.UserError("Invalid Intel compiler version %s: "%version + \ + "installed versions are %s"%(', '.join(vlist))) version = v # if abi is unspecified, use ia32 @@ -406,7 +398,7 @@ def generate(env, version=None, abi=None, topdir=None, verbose=0): # 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], string.split(path, os.pathsep)) + 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: @@ -445,7 +437,7 @@ def generate(env, version=None, abi=None, topdir=None, verbose=0): 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 (string.find(ld, '@') != -1 or os.path.exists(ld)): + if ld and (ld.find('@') != -1 or os.path.exists(ld)): licdir = ld break if not licdir: diff --git a/engine/SCons/Tool/ipkg.py b/engine/SCons/Tool/ipkg.py index 3e8d223..c692053 100644 --- a/engine/SCons/Tool/ipkg.py +++ b/engine/SCons/Tool/ipkg.py @@ -33,10 +33,9 @@ packages fake_root. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/ipkg.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/ipkg.py 5023 2010/06/14 22:05:46 scons" import os -import string import SCons.Builder @@ -53,11 +52,8 @@ def generate(env): env['IPKG'] = 'ipkg-build' env['IPKGCOM'] = '$IPKG $IPKGFLAGS ${SOURCE}' - # TODO(1.5) - #env['IPKGUSER'] = os.popen('id -un').read().strip() - #env['IPKGGROUP'] = os.popen('id -gn').read().strip() - env['IPKGUSER'] = string.strip(os.popen('id -un').read()) - env['IPKGGROUP'] = string.strip(os.popen('id -gn').read()) + 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' diff --git a/engine/SCons/Tool/jar.py b/engine/SCons/Tool/jar.py index 2aaab96..9cb4eff 100644 --- a/engine/SCons/Tool/jar.py +++ b/engine/SCons/Tool/jar.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/jar.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/jar.py 5023 2010/06/14 22:05:46 scons" import SCons.Subst import SCons.Util diff --git a/engine/SCons/Tool/javac.py b/engine/SCons/Tool/javac.py index df237a8..66651c3 100644 --- a/engine/SCons/Tool/javac.py +++ b/engine/SCons/Tool/javac.py @@ -29,13 +29,11 @@ selection method. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -__revision__ = "src/engine/SCons/Tool/javac.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/javac.py 5023 2010/06/14 22:05:46 scons" import os import os.path -import string import SCons.Action import SCons.Builder @@ -45,7 +43,7 @@ import SCons.Util def classname(path): """Turn a string (path name) into a Java class name.""" - return string.replace(os.path.normpath(path), os.sep, '.') + return os.path.normpath(path).replace(os.sep, '.') def emit_java_classes(target, source, env): """Create and return lists of source java files @@ -67,27 +65,25 @@ def emit_java_classes(target, source, env): slist = [] js = _my_normcase(java_suffix) - find_java = lambda n, js=js, ljs=len(js): _my_normcase(n[-ljs:]) == js for entry in source: entry = entry.rentry().disambiguate() if isinstance(entry, SCons.Node.FS.File): slist.append(entry) elif isinstance(entry, SCons.Node.FS.Dir): result = SCons.Util.OrderedDict() - def visit(arg, dirname, names, fj=find_java, dirnode=entry.rdir()): - java_files = filter(fj, names) - # The on-disk entries come back in arbitrary order. Sort - # them so our target and source lists are determinate. - java_files.sort() - mydir = dirnode.Dir(dirname) - java_paths = map(lambda f, d=mydir: d.File(f), java_files) + dirnode = entry.rdir() + def find_java_files(arg, dirpath, filenames): + java_files = sorted([n for n in filenames + if _my_normcase(n).endswith(js)]) + mydir = dirnode.Dir(dirpath) + java_paths = [mydir.File(f) for f in java_files] for jp in java_paths: arg[jp] = True + for dirpath, dirnames, filenames in os.walk(dirnode.get_abspath()): + find_java_files(result, dirpath, filenames) + entry.walk(find_java_files, result) - os.path.walk(entry.rdir().get_abspath(), visit, result) - entry.walk(visit, result) - - slist.extend(result.keys()) + slist.extend(list(result.keys())) else: raise SCons.Errors.UserError("Java source must be File or Dir, not '%s'" % entry.__class__) @@ -139,7 +135,7 @@ JavaBuilder = SCons.Builder.Builder(action = JavaAction, target_factory = SCons.Node.FS.Entry, source_factory = SCons.Node.FS.Entry) -class pathopt: +class pathopt(object): """ Callable object for generating javac-style path options from a construction variable (e.g. -classpath, -sourcepath). @@ -156,8 +152,8 @@ class pathopt: if self.default: path = path + [ env[self.default] ] if path: - return [self.opt, string.join(path, os.pathsep)] - #return self.opt + " " + string.join(path, os.pathsep) + return [self.opt, os.pathsep.join(path)] + #return self.opt + " " + os.pathsep.join(path) else: return [] #return "" @@ -194,7 +190,7 @@ def Java(env, target, source, *args, **kw): b = env.JavaClassFile else: b = env.JavaClassDir - result.extend(apply(b, (t, s) + args, kw)) + result.extend(b(t, s, *args, **kw)) return result diff --git a/engine/SCons/Tool/javah.py b/engine/SCons/Tool/javah.py index 6a4314c..e92c423 100644 --- a/engine/SCons/Tool/javah.py +++ b/engine/SCons/Tool/javah.py @@ -31,10 +31,9 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/javah.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/javah.py 5023 2010/06/14 22:05:46 scons" import os.path -import string import SCons.Action import SCons.Builder @@ -93,7 +92,7 @@ def emit_java_headers(target, source, env): target[0]._morph() tlist = [] for s in source: - fname = string.replace(s.attributes.java_classname, '.', '_') + '.h' + fname = s.attributes.java_classname.replace('.', '_') + '.h' t = target[0].File(fname) t.attributes.java_lookupdir = target[0] tlist.append(t) @@ -112,7 +111,7 @@ def JavaHOutFlagGenerator(target, source, env, for_signature): def getJavaHClassPath(env,target, source, for_signature): path = "${SOURCE.attributes.java_classdir}" - if env.has_key('JAVACLASSPATH') and env['JAVACLASSPATH']: + if 'JAVACLASSPATH' in env and env['JAVACLASSPATH']: path = SCons.Util.AppendPath(path, env['JAVACLASSPATH']) return "-classpath %s" % (path) diff --git a/engine/SCons/Tool/latex.py b/engine/SCons/Tool/latex.py index 56db43f..e4f1a51 100644 --- a/engine/SCons/Tool/latex.py +++ b/engine/SCons/Tool/latex.py @@ -32,7 +32,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/latex.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/latex.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Defaults @@ -44,7 +44,7 @@ import SCons.Tool.tex def LaTeXAuxFunction(target = None, source= None, env=None): result = SCons.Tool.tex.InternalLaTeXAuxAction( SCons.Tool.tex.LaTeXAction, target, source, env ) if result != 0: - print env['LATEX']," returned an error, check the log file" + SCons.Tool.tex.check_file_error_message(env['LATEX']) return result LaTeXAuxAction = SCons.Action.Action(LaTeXAuxFunction, diff --git a/engine/SCons/Tool/lex.py b/engine/SCons/Tool/lex.py index 920ff5f..aad5004 100644 --- a/engine/SCons/Tool/lex.py +++ b/engine/SCons/Tool/lex.py @@ -31,12 +31,10 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/lex.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/lex.py 5023 2010/06/14 22:05:46 scons" import os.path -import string - import SCons.Action import SCons.Tool import SCons.Util @@ -62,7 +60,7 @@ def lexEmitter(target, source, env): if option[:l] == fileGenOption: # A file generating option is present, so add the # file name to the target list. - fileName = string.strip(option[l:]) + fileName = option[l:].strip() target.append(fileName) return (target, source) diff --git a/engine/SCons/Tool/link.py b/engine/SCons/Tool/link.py index 2b6ccec..5905fe9 100644 --- a/engine/SCons/Tool/link.py +++ b/engine/SCons/Tool/link.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/link.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/link.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Tool diff --git a/engine/SCons/Tool/linkloc.py b/engine/SCons/Tool/linkloc.py index abf29f4..ab5b735 100644 --- a/engine/SCons/Tool/linkloc.py +++ b/engine/SCons/Tool/linkloc.py @@ -32,7 +32,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/linkloc.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/linkloc.py 5023 2010/06/14 22:05:46 scons" import os.path import re @@ -61,7 +61,7 @@ def repl_linker_command(m): # to find it with recursive substitution return m.group(1) + '#' + m.group(2) -class LinklocGenerator: +class LinklocGenerator(object): def __init__(self, cmdline): self.cmdline = cmdline diff --git a/engine/SCons/Tool/m4.py b/engine/SCons/Tool/m4.py index 48935cf..f43b594 100644 --- a/engine/SCons/Tool/m4.py +++ b/engine/SCons/Tool/m4.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/m4.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/m4.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Builder diff --git a/engine/SCons/Tool/masm.py b/engine/SCons/Tool/masm.py index a4e91fc..5bb936a 100644 --- a/engine/SCons/Tool/masm.py +++ b/engine/SCons/Tool/masm.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/masm.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/masm.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Tool diff --git a/engine/SCons/Tool/midl.py b/engine/SCons/Tool/midl.py index f1f4375..67660d1 100644 --- a/engine/SCons/Tool/midl.py +++ b/engine/SCons/Tool/midl.py @@ -31,9 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/midl.py 4720 2010/03/24 03:14:11 jars" - -import string +__revision__ = "src/engine/SCons/Tool/midl.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Builder @@ -53,10 +51,10 @@ def midl_emitter(target, source, env): midlcom = env['MIDLCOM'] - if string.find(midlcom, '/proxy') != -1: + if midlcom.find('/proxy') != -1: proxy = base + '_p.c' t.append(proxy) - if string.find(midlcom, '/dlldata') != -1: + if midlcom.find('/dlldata') != -1: dlldata = base + '_data.c' t.append(dlldata) diff --git a/engine/SCons/Tool/mingw.py b/engine/SCons/Tool/mingw.py index e93f1ad..6df46e0 100644 --- a/engine/SCons/Tool/mingw.py +++ b/engine/SCons/Tool/mingw.py @@ -31,11 +31,10 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/mingw.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/mingw.py 5023 2010/06/14 22:05:46 scons" import os import os.path -import string import SCons.Action import SCons.Builder @@ -73,7 +72,7 @@ def shlib_emitter(target, source, env): 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") + 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'): diff --git a/engine/SCons/Tool/mslib.py b/engine/SCons/Tool/mslib.py index c568abd..a2933cb 100644 --- a/engine/SCons/Tool/mslib.py +++ b/engine/SCons/Tool/mslib.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/mslib.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/mslib.py 5023 2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Tool diff --git a/engine/SCons/Tool/mslink.py b/engine/SCons/Tool/mslink.py index 36ad2fe..c291ba9 100644 --- a/engine/SCons/Tool/mslink.py +++ b/engine/SCons/Tool/mslink.py @@ -31,7 +31,7 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/mslink.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/mslink.py 5023 2010/06/14 22:05:46 scons" import os.path @@ -103,7 +103,7 @@ def _dllEmitter(target, source, env, paramtp): 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('$%sSUFFIX' % paramtp) + raise SCons.Errors.UserError('A shared library should have exactly one target with the suffix: %s' % env.subst('$%sSUFFIX' % paramtp)) insert_def = env.subst("$WINDOWS_INSERT_DEF") if not insert_def in ['', '0', 0] and \ @@ -123,7 +123,7 @@ def _dllEmitter(target, source, env, paramtp): '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "WINDOWSSHLIBMANIFESTPREFIX", "WINDOWSSHLIBMANIFESTSUFFIX")) - if env.has_key('PDB') and env['PDB']: + if 'PDB' in env and env['PDB']: pdb = env.arg2nodes('$PDB', target=target, source=source)[0] extratargets.append(pdb) target[0].attributes.pdb = pdb @@ -161,7 +161,7 @@ def prog_emitter(target, source, env): exe = env.FindIxes(target, "PROGPREFIX", "PROGSUFFIX") if not exe: - raise SCons.Errors.UserError, "An executable should have exactly one target with the suffix: %s" % env.subst("$PROGSUFFIX") + raise SCons.Errors.UserError("An executable should have exactly one target with the suffix: %s" % env.subst("$PROGSUFFIX")) version_num, suite = SCons.Tool.msvs.msvs_parse_version(env.get('MSVS_VERSION', '6.0')) if version_num >= 8.0 and env.get('WINDOWS_INSERT_MANIFEST', 0): @@ -171,7 +171,7 @@ def prog_emitter(target, source, env): "PROGPREFIX", "PROGSUFFIX", "WINDOWSPROGMANIFESTPREFIX", "WINDOWSPROGMANIFESTSUFFIX")) - if env.has_key('PDB') and env['PDB']: + if 'PDB' in env and env['PDB']: pdb = env.arg2nodes('$PDB', target=target, source=source)[0] extratargets.append(pdb) target[0].attributes.pdb = pdb @@ -179,10 +179,10 @@ def prog_emitter(target, source, env): return (target+extratargets,source) def RegServerFunc(target, source, env): - if env.has_key('register') and env['register']: + if 'register' in env and env['register']: ret = regServerAction([target[0]], [source[0]], env) if ret: - raise SCons.Errors.UserError, "Unable to register %s" % target[0] + raise SCons.Errors.UserError("Unable to register %s" % target[0]) else: print "Registered %s sucessfully" % target[0] return ret diff --git a/engine/SCons/Tool/mssdk.py b/engine/SCons/Tool/mssdk.py index ed5bd5c..08898c6 100644 --- a/engine/SCons/Tool/mssdk.py +++ b/engine/SCons/Tool/mssdk.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/mssdk.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/mssdk.py 5023 2010/06/14 22:05:46 scons" """engine.SCons.Tool.mssdk diff --git a/engine/SCons/Tool/msvc.py b/engine/SCons/Tool/msvc.py index f145816..8c13580 100644 --- a/engine/SCons/Tool/msvc.py +++ b/engine/SCons/Tool/msvc.py @@ -31,11 +31,10 @@ selection method. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Tool/msvc.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/msvc.py 5023 2010/06/14 22:05:46 scons" import os.path import re -import string import sys import SCons.Action @@ -55,11 +54,11 @@ CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++'] def validate_vars(env): """Validate the PCH and PCHSTOP construction variables.""" - if env.has_key('PCH') and env['PCH']: - if not env.has_key('PCHSTOP'): - raise SCons.Errors.UserError, "The PCHSTOP construction must be defined if PCH is defined." + 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'] + 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.""" @@ -99,7 +98,7 @@ def object_emitter(target, source, env, parent_emitter): # 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 env.has_key('PCH'): + if 'PCH' in env: pch = env['PCH'] if str(target[0]) != SCons.Util.splitext(str(pch))[0] + '.obj': env.Depends(target, pch) @@ -254,9 +253,9 @@ def generate(env): 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 not env.has_key('ENV'): + if 'ENV' not in env: env['ENV'] = {} - if not env['ENV'].has_key('SystemRoot'): # required for dlls in the winsxs folders + 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): diff --git a/engine/SCons/Tool/msvs.py b/engine/SCons/Tool/msvs.py index 17bb9a0..34fc0e7 100644 --- a/engine/SCons/Tool/msvs.py +++ b/engine/SCons/Tool/msvs.py @@ -29,17 +29,18 @@ selection method. # 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 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Tool/msvs.py 5023 2010/06/14 22:05:46 scons" + +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 string import sys import SCons.Builder @@ -57,23 +58,10 @@ from SCons.Defaults import processDefines # DSP/DSW/SLN/VCPROJ files. ############################################################################## -def _hexdigest(s): - """Return a string as a string of hex characters. - """ - # NOTE: This routine is a method in the Python 2.0 interface - # of the native md5 module, but we want SCons to operate all - # the way back to at least Python 1.5.2, which doesn't have it. - h = string.hexdigits - r = '' - for c in s: - i = ord(c) - r = r + h[(i >> 4) & 0xF] + h[i & 0xF] - return r - def xmlify(s): - s = string.replace(s, "&", "&") # do this first - s = string.replace(s, "'", "'") - s = string.replace(s, '"', """) + s = s.replace("&", "&") # do this first + s = s.replace("'", "'") + s = s.replace('"', """) return s external_makefile_guid = '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}' @@ -88,9 +76,7 @@ def _generateGUID(slnfile, name): # 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)) - # TODO(1.5) - #solution = m.hexdigest().upper() - solution = string.upper(_hexdigest(m.digest())) + 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 @@ -116,7 +102,7 @@ def msvs_parse_version(s): # which works regardless of how we were invoked. def getExecScriptMain(env, xml=None): scons_home = env.get('SCONS_HOME') - if not scons_home and os.environ.has_key('SCONS_LIB_DIR'): + 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 @@ -139,7 +125,7 @@ else: python_executable = os.path.join('$$(PYTHON_ROOT)', os.path.split(sys.executable)[1]) -class Config: +class Config(object): pass def splitFully(path): @@ -161,7 +147,7 @@ def makeHierarchy(sources): if len(path): dict = hierarchy for part in path[:-1]: - if not dict.has_key(part): + if part not in dict: dict[part] = {} dict = dict[part] dict[path[-1]] = file @@ -169,7 +155,7 @@ def makeHierarchy(sources): # print 'Warning: failed to decompose path for '+str(file) return hierarchy -class _DSPGenerator: +class _DSPGenerator(object): """ Base class for DSP generators """ srcargs = [ @@ -188,23 +174,21 @@ class _DSPGenerator: else: self.dspabs = get_abspath() - if not env.has_key('variant'): - raise SCons.Errors.InternalError, \ - "You must specify a 'variant' argument (i.e. 'Debug' or " +\ - "'Release') to create an MSVSProject." + 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 not env.has_key('buildtarget') or env['buildtarget'] == None: + 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." + 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): @@ -219,14 +203,13 @@ class _DSPGenerator: for _ in variants: buildtarget.append(bt) - if not env.has_key('outdir') or env['outdir'] == None: + 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." + 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): @@ -241,14 +224,13 @@ class _DSPGenerator: for v in variants: outdir.append(s) - if not env.has_key('runfile') or env['runfile'] == None: + 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." + 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): @@ -269,7 +251,7 @@ class _DSPGenerator: self.env = env - if self.env.has_key('name'): + if 'name' in self.env: self.name = self.env['name'] else: self.name = os.path.basename(SCons.Util.splitext(self.dspfile)[0]) @@ -289,14 +271,14 @@ class _DSPGenerator: self.configs = {} self.nokeep = 0 - if env.has_key('nokeep') and env['variant'] != 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 self.env.has_key(t[1]): + 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]]: @@ -306,9 +288,9 @@ class _DSPGenerator: self.sources[t[0]].append(self.env[t[1]]) for n in sourcenames: - # TODO(1.5): - #self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower())) - self.sources[n].sort(lambda a, b: cmp(string.lower(a), string.lower(b))) + #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() @@ -367,8 +349,7 @@ class _GenerateV6DSP(_DSPGenerator): def PrintHeader(self): # pick a default config - confkeys = self.configs.keys() - confkeys.sort() + confkeys = sorted(self.configs.keys()) name = self.name confkey = confkeys[0] @@ -388,8 +369,7 @@ class _GenerateV6DSP(_DSPGenerator): '# PROP Scc_LocalPath ""\n\n') first = 1 - confkeys = self.configs.keys() - confkeys.sort() + confkeys = sorted(self.configs.keys()) for kind in confkeys: outdir = self.configs[kind].outdir buildtarget = self.configs[kind].buildtarget @@ -399,7 +379,7 @@ class _GenerateV6DSP(_DSPGenerator): else: self.file.write('\n!ELSEIF "$(CFG)" == "%s - Win32 %s"\n\n' % (name, kind)) - env_has_buildtarget = self.env.has_key('MSVSBUILDTARGET') + env_has_buildtarget = 'MSVSBUILDTARGET' in self.env if not env_has_buildtarget: self.env['MSVSBUILDTARGET'] = buildtarget @@ -407,9 +387,7 @@ class _GenerateV6DSP(_DSPGenerator): for base in ("BASE ",""): self.file.write('# PROP %sUse_MFC 0\n' '# PROP %sUse_Debug_Libraries ' % (base, base)) - # TODO(1.5): - #if kind.lower().find('debug') < 0: - if string.find(string.lower(kind), 'debug') < 0: + if kind.lower().find('debug') < 0: self.file.write('0\n') else: self.file.write('1\n') @@ -459,18 +437,12 @@ class _GenerateV6DSP(_DSPGenerator): 'Resource Files': 'r|rc|ico|cur|bmp|dlg|rc2|rct|bin|cnt|rtf|gif|jpg|jpeg|jpe', 'Other Files': ''} - cats = categories.keys() - # TODO(1.5): - #cats.sort(lambda a, b: cmp(a.lower(), b.lower())) - cats.sort(lambda a, b: cmp(string.lower(a), string.lower(b))) - for kind in cats: + 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') - # TODO(1.5) - #typelist = categories[kind].replace('|', ';') - typelist = string.replace(categories[kind], '|', ';') + typelist = categories[kind].replace('|', ';') self.file.write('# PROP Default_Filter "' + typelist + '"\n') for file in self.sources[kind]: @@ -493,9 +465,7 @@ class _GenerateV6DSP(_DSPGenerator): line = dspfile.readline() while line: - # TODO(1.5): - #if line.find("# End Project") > -1: - if string.find(line, "# End Project") > -1: + if line.find("# End Project") > -1: break line = dspfile.readline() @@ -539,7 +509,7 @@ class _GenerateV6DSP(_DSPGenerator): try: self.file = open(self.dspabs,'w') except IOError, detail: - raise SCons.Errors.InternalError, 'Unable to open "' + self.dspabs + '" for writing:' + str(detail) + raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail)) else: self.PrintHeader() self.PrintProject() @@ -664,8 +634,7 @@ class _GenerateV7DSP(_DSPGenerator): def PrintProject(self): self.file.write('\t\n') - confkeys = self.configs.keys() - confkeys.sort() + confkeys = sorted(self.configs.keys()) for kind in confkeys: variant = self.configs[kind].variant platform = self.configs[kind].platform @@ -674,7 +643,7 @@ class _GenerateV7DSP(_DSPGenerator): runfile = self.configs[kind].runfile cmdargs = self.configs[kind].cmdargs - env_has_buildtarget = self.env.has_key('MSVSBUILDTARGET') + env_has_buildtarget = 'MSVSBUILDTARGET' in self.env if not env_has_buildtarget: self.env['MSVSBUILDTARGET'] = buildtarget @@ -687,11 +656,8 @@ class _GenerateV7DSP(_DSPGenerator): rebuildcmd = xmlify(starting + self.env.subst('$MSVSREBUILDCOM', 1) + cmdargs) cleancmd = xmlify(starting + self.env.subst('$MSVSCLEANCOM', 1) + cmdargs) - # TODO(1.5) - #preprocdefs = xmlify(';'.join(self.env.get('CPPDEFINES', []))) - #includepath = xmlify(';'.join(self.env.get('CPPPATH', []))) - preprocdefs = xmlify(string.join(processDefines(self.env.get('CPPDEFINES', [])), ';')) - includepath = xmlify(string.join(self.env.get('CPPPATH', []), ';')) + preprocdefs = xmlify(';'.join(processDefines(self.env.get('CPPDEFINES', [])))) + includepath = xmlify(';'.join(self.env.get('CPPPATH', []))) if not env_has_buildtarget: del self.env['MSVSBUILDTARGET'] @@ -718,10 +684,7 @@ class _GenerateV7DSP(_DSPGenerator): self.file.write(pdata + '-->\n') def printSources(self, hierarchy, commonprefix): - sorteditems = hierarchy.items() - # TODO(1.5): - #sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower())) - sorteditems.sort(lambda a, b: cmp(string.lower(a[0]), string.lower(b[0]))) + sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower()) # First folders, then files for key, value in sorteditems: @@ -751,11 +714,8 @@ class _GenerateV7DSP(_DSPGenerator): self.file.write('\t\n') - cats = categories.keys() - # TODO(1.5) - #cats.sort(lambda a, b: cmp(a.lower(), b.lower())) - cats.sort(lambda a, b: cmp(string.lower(a), string.lower(b))) - cats = filter(lambda k, s=self: s.sources[k], cats) + 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 1: - s = map(os.path.normpath, sources) + 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 = map(lambda s, l=len(cp)+1: s[l:], sources) + sources = [s[len(cp)+1:] for s in sources] commonprefix = cp elif len(sources) == 1: commonprefix = os.path.dirname( sources[0] ) @@ -803,9 +763,7 @@ class _GenerateV7DSP(_DSPGenerator): line = dspfile.readline() while line: - # TODO(1.5) - #if line.find('