diff options
author | Greg Noel <GregNoel@tigris.org> | 2010-03-25 04:14:28 (GMT) |
---|---|---|
committer | Greg Noel <GregNoel@tigris.org> | 2010-03-25 04:14:28 (GMT) |
commit | 22d352500f1cd6bd0c53d788a5dc44a1fefa676e (patch) | |
tree | 0984fd581082c27cfbfbb7f94d5751b0e6fd2741 /src | |
parent | 75ac32ac8e32076e25b72a19eb56340cc585fa4e (diff) | |
download | SCons-22d352500f1cd6bd0c53d788a5dc44a1fefa676e.zip SCons-22d352500f1cd6bd0c53d788a5dc44a1fefa676e.tar.gz SCons-22d352500f1cd6bd0c53d788a5dc44a1fefa676e.tar.bz2 |
Move 2.0 changes collected in branches/pending back to trunk for further
development. Note that this set of changes is NOT backward-compatible;
the trunk no longer works with Python 1.5.2, 2.0, or 2.1.
Diffstat (limited to 'src')
137 files changed, 1292 insertions, 1391 deletions
diff --git a/src/engine/SCons/Action.py b/src/engine/SCons/Action.py index 41c73ad..35c7316 100644 --- a/src/engine/SCons/Action.py +++ b/src/engine/SCons/Action.py @@ -96,6 +96,7 @@ way for wrapping up the functions. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -103,7 +104,6 @@ import cPickle import dis import os import re -import string import sys import subprocess @@ -153,7 +153,7 @@ else: else: result.append(c) i = i+1 - return string.join(result, '') + return ''.join(result) strip_quotes = re.compile('^[\'"](.*)[\'"]$') @@ -249,19 +249,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 +271,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 +284,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): @@ -354,7 +354,7 @@ def _do_create_action(act, kw): 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 +378,10 @@ 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) @@ -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 @@ -534,8 +534,8 @@ 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 ') + t = ' and '.join(map(str, target)) + l = '\n '.join(self.presub_lines(env)) out = "Building %s with action:\n %s\n" % (t, l) sys.stdout.write(out) cmd = None @@ -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 @@ -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,7 +655,7 @@ 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 @@ -685,16 +685,16 @@ class CommandAction(_ActionAction): 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): + 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): @@ -771,7 +771,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 +782,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 +806,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: @@ -860,7 +860,7 @@ class CommandGeneratorAction(ActionBase): 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 +885,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 +932,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 @@ -946,7 +948,7 @@ class LazyAction(CommandGeneratorAction, CommandAction): 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 +957,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) @@ -987,7 +987,7 @@ class FunctionAction(_ActionAction): 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 +1018,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 +1045,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 +1095,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): @@ -1204,9 +1198,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 = {} @@ -1218,17 +1210,17 @@ class ActionCaller: 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: """A factory class that will wrap up an arbitrary function diff --git a/src/engine/SCons/ActionTests.py b/src/engine/SCons/ActionTests.py index ef91af4..12756e5 100644 --- a/src/engine/SCons/ActionTests.py +++ b/src/engine/SCons/ActionTests.py @@ -37,7 +37,6 @@ class GlobalActFunc: import os import re import StringIO -import string import sys import types import unittest @@ -68,16 +67,16 @@ try: except: pass f.close() -if os.environ.has_key( 'ACTPY_PIPE' ): - if os.environ.has_key( 'PIPE_STDOUT_FILE' ): +if 'ACTPY_PIPE' in os.environ: + if 'PIPE_STDOUT_FILE' in os.environ: stdout_msg = open(os.environ['PIPE_STDOUT_FILE'], 'r').read() else: - stdout_msg = "act.py: stdout: executed act.py %s\\n" % string.join(sys.argv[1:]) + stdout_msg = "act.py: stdout: executed act.py %s\\n" % ' '.join(sys.argv[1:]) sys.stdout.write( stdout_msg ) - if os.environ.has_key( 'PIPE_STDERR_FILE' ): + if 'PIPE_STDERR_FILE' in os.environ: stderr_msg = open(os.environ['PIPE_STDERR_FILE'], 'r').read() else: - stderr_msg = "act.py: stderr: executed act.py %s\\n" % string.join(sys.argv[1:]) + stderr_msg = "act.py: stderr: executed act.py %s\\n" % ' '.join(sys.argv[1:]) sys.stderr.write( stderr_msg ) sys.exit(0) """) @@ -147,7 +146,7 @@ class Environment: def __setitem__(self, item, value): self.d[item] = value def has_key(self, item): - return self.d.has_key(item) + return item in self.d def get(self, key, value=None): return self.d.get(key, value) def items(self): @@ -193,7 +192,7 @@ _null = SCons.Action._null def test_varlist(pos_call, str_call, cmd, cmdstrfunc, **kw): def call_action(a, pos_call=pos_call, str_call=str_call, kw=kw): #FUTURE a = SCons.Action.Action(*a, **kw) - a = apply(SCons.Action.Action, a, kw) + a = SCons.Action.Action(*a, **kw) # returned object must provide these entry points assert hasattr(a, '__call__') assert hasattr(a, 'get_contents') @@ -229,7 +228,7 @@ def test_positional_args(pos_callback, cmd, **kw): """Test that Action() returns the expected type and that positional args work. """ #FUTURE act = SCons.Action.Action(cmd, **kw) - act = apply(SCons.Action.Action, (cmd,), kw) + act = SCons.Action.Action(cmd, **kw) pos_callback(act) assert act.varlist is (), act.varlist @@ -237,7 +236,7 @@ def test_positional_args(pos_callback, cmd, **kw): # only valid cmdstrfunc is None def none(a): pass #FUTURE test_varlist(pos_callback, none, cmd, None, **kw) - apply(test_varlist, (pos_callback, none, cmd, None), kw) + test_varlist(pos_callback, none, cmd, None, **kw) else: # _ActionAction should have set these assert hasattr(act, 'strfunction') @@ -251,29 +250,29 @@ def test_positional_args(pos_callback, cmd, **kw): assert hasattr(a, 'strfunction') assert a.cmdstr == 'cmdstr', a.cmdstr #FUTURE test_varlist(pos_callback, cmdstr, cmd, 'cmdstr', **kw) - apply(test_varlist, (pos_callback, cmdstr, cmd, 'cmdstr'), kw) + test_varlist(pos_callback, cmdstr, cmd, 'cmdstr', **kw) def fun(): pass def strfun(a, fun=fun): assert a.strfunction is fun, a.strfunction assert a.cmdstr == _null, a.cmdstr #FUTURE test_varlist(pos_callback, strfun, cmd, fun, **kw) - apply(test_varlist, (pos_callback, strfun, cmd, fun), kw) + test_varlist(pos_callback, strfun, cmd, fun, **kw) def none(a): assert hasattr(a, 'strfunction') assert a.cmdstr is None, a.cmdstr #FUTURE test_varlist(pos_callback, none, cmd, None, **kw) - apply(test_varlist, (pos_callback, none, cmd, None), kw) + test_varlist(pos_callback, none, cmd, None, **kw) """Test handling of bad cmdstrfunc arguments """ try: #FUTURE a = SCons.Action.Action(cmd, [], **kw) - a = apply(SCons.Action.Action, (cmd, []), kw) + a = SCons.Action.Action(cmd, [], **kw) except SCons.Errors.UserError, e: s = str(e) m = 'Invalid command display variable' - assert string.find(s, m) != -1, 'Unexpected string: %s' % s + assert s.find(m) != -1, 'Unexpected string: %s' % s else: raise Exception, "did not catch expected UserError" @@ -490,7 +489,7 @@ class _ActionActionTestCase(unittest.TestCase): except SCons.Errors.UserError, e: s = str(e) m = 'Cannot have both strfunction and cmdstr args to Action()' - assert string.find(s, m) != -1, 'Unexpected string: %s' % s + assert s.find(m) != -1, 'Unexpected string: %s' % s else: raise Exception, "did not catch expected UserError" @@ -752,8 +751,7 @@ class _ActionActionTestCase(unittest.TestCase): sum = act1 + act2 assert isinstance(sum, SCons.Action.ListAction), str(sum) assert len(sum.list) == 3, len(sum.list) - assert map(lambda x: isinstance(x, SCons.Action.ActionBase), - sum.list) == [ 1, 1, 1 ] + assert [isinstance(x, SCons.Action.ActionBase) for x in sum.list] == [ 1, 1, 1 ] sum = act1 + act1 assert isinstance(sum, SCons.Action.ListAction), str(sum) @@ -1050,7 +1048,7 @@ class CommandActionTestCase(unittest.TestCase): cmd3 = r'%s %s %s ${TARGETS}' % (_python_, act_py, outfile) act = SCons.Action.CommandAction(cmd3) - r = act(map(DummyNode, ['aaa', 'bbb']), [], env.Clone()) + r = act(list(map(DummyNode, ['aaa', 'bbb'])), [], env.Clone()) assert r == 0 c = test.read(outfile, 'r') assert c == "act.py: 'aaa' 'bbb'\n", c @@ -1077,7 +1075,7 @@ class CommandActionTestCase(unittest.TestCase): act = SCons.Action.CommandAction(cmd5) env5 = Environment() - if scons_env.has_key('ENV'): + if 'ENV' in scons_env: env5['ENV'] = scons_env['ENV'] PATH = scons_env['ENV'].get('PATH', '') else: @@ -1332,8 +1330,8 @@ class CommandActionTestCase(unittest.TestCase): # that scheme, then all of the '__t1__' and '__s6__' file names # in the asserts below would change to 't1' and 's6' and the # like. - t = map(DummyNode, ['t1', 't2', 't3', 't4', 't5', 't6']) - s = map(DummyNode, ['s1', 's2', 's3', 's4', 's5', 's6']) + t = list(map(DummyNode, ['t1', 't2', 't3', 't4', 't5', 't6'])) + s = list(map(DummyNode, ['s1', 's2', 's3', 's4', 's5', 's6'])) env = Environment() a = SCons.Action.CommandAction(["$TARGET"]) @@ -1528,7 +1526,7 @@ class CommandGeneratorActionTestCase(unittest.TestCase): def f_local(target, source, env, for_signature, LocalFunc=LocalFunc): return SCons.Action.Action(LocalFunc, varlist=['XYZ']) - matches_foo = map(lambda x: x + "foo", func_matches) + matches_foo = [x + "foo" for x in func_matches] a = self.factory(f_global) c = a.get_contents(target=[], source=[], env=env) @@ -1676,7 +1674,7 @@ class FunctionActionTestCase(unittest.TestCase): c = a.get_contents(target=[], source=[], env=Environment()) assert c in func_matches, repr(c) - matches_foo = map(lambda x: x + "foo", func_matches) + matches_foo = [x + "foo" for x in func_matches] a = factory(GlobalFunc, varlist=['XYZ']) c = a.get_contents(target=[], source=[], env=Environment()) @@ -1892,7 +1890,7 @@ class LazyActionTestCase(unittest.TestCase): c = a.get_contents(target=[], source=[], env=env) assert c in func_matches, repr(c) - matches_foo = map(lambda x: x + "foo", func_matches) + matches_foo = [x + "foo" for x in func_matches] env = Environment(FOO = factory(GlobalFunc, varlist=['XYZ'])) c = a.get_contents(target=[], source=[], env=env) @@ -2096,7 +2094,7 @@ if __name__ == "__main__": ActionCompareTestCase ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Builder.py b/src/engine/SCons/Builder.py index 6405da3..c999afd 100644 --- a/src/engine/SCons/Builder.py +++ b/src/engine/SCons/Builder.py @@ -97,6 +97,7 @@ There are the following methods for internal use within this module: # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -120,10 +121,9 @@ _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(list(map(None, list(map(len, matchsuf)), matchsuf)))[1] return [path[:-len(suf)], path[-len(suf):]] return SCons.Util.splitext(path) @@ -156,14 +156,17 @@ 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) @@ -171,7 +174,7 @@ class DictCmdGenerator(SCons.Util.Selector): raise UserError("Ambiguous suffixes after environment substitution: %s == %s == %s" % (e[0], e[1], e[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(self.keys()))) return ret class CallableSelector(SCons.Util.Selector): @@ -231,7 +234,7 @@ class OverrideWarner(UserDict.UserDict): 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 +243,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'): + 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 +259,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 @@ -272,7 +275,7 @@ def Builder(**kw): 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) @@ -308,15 +311,15 @@ def _node_errors(builder, env, tlist, slist): 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)) + 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)) + 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: """This is a callable class that can act as a @@ -334,7 +337,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) @@ -387,13 +390,13 @@ class BuilderBase: suffix = CallableSelector(suffix) self.env = env self.single_source = single_source - if overrides.has_key('overrides'): + if 'overrides' in overrides: SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, "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'): + if 'scanner' in overrides: SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning, "The \"scanner\" keyword to Builder() creation has been deprecated;\n" "\tuse: source_scanner or target_scanner as appropriate.") @@ -493,7 +496,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) @@ -574,7 +577,7 @@ class BuilderBase: 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)) + list(map(str,tlist))) key = self.action.batch_key(env or self.env, tlist, slist) if key: try: @@ -611,7 +614,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 +622,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 +661,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 +724,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 +750,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 +819,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 +838,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 diff --git a/src/engine/SCons/BuilderTests.py b/src/engine/SCons/BuilderTests.py index dc60d06..d14f777 100644 --- a/src/engine/SCons/BuilderTests.py +++ b/src/engine/SCons/BuilderTests.py @@ -118,14 +118,16 @@ class Environment: self.d[item] = var def __getitem__(self, item): return self.d[item] + def __contains__(self, item): + return self.d.__contains__(item) def has_key(self, item): - return self.d.has_key(item) + return item in self.d def keys(self): return self.d.keys() def get(self, key, value=None): return self.d.get(key, value) def Override(self, overrides): - env = apply(Environment, (), self.d) + env = Environment(**self.d) env.d.update(overrides) env.scanner = self.scanner return env @@ -255,7 +257,7 @@ class BuilderTestCase(unittest.TestCase): l.extend(ul) except TypeError: def mystr(l): - return str(map(str, l)) + return str(list(map(str, l))) else: mystr = str @@ -264,14 +266,14 @@ class BuilderTestCase(unittest.TestCase): tlist = builder(env, target = [nnn1, nnn2], source = []) s = mystr(tlist) assert s == "['nnn1', 'nnn2']", s - l = map(str, tlist) + l = list(map(str, tlist)) assert l == ['nnn1', 'nnn2'], l tlist = builder(env, target = 'n3', source = 'n4') s = mystr(tlist) assert s == "['n3']", s target = tlist[0] - l = map(str, tlist) + l = list(map(str, tlist)) assert l == ['n3'], l assert target.name == 'n3' assert target.sources[0].name == 'n4' @@ -279,7 +281,7 @@ class BuilderTestCase(unittest.TestCase): tlist = builder(env, target = 'n4 n5', source = ['n6 n7']) s = mystr(tlist) assert s == "['n4 n5']", s - l = map(str, tlist) + l = list(map(str, tlist)) assert l == ['n4 n5'], l target = tlist[0] assert target.name == 'n4 n5' @@ -288,7 +290,7 @@ class BuilderTestCase(unittest.TestCase): tlist = builder(env, target = ['n8 n9'], source = 'n10 n11') s = mystr(tlist) assert s == "['n8 n9']", s - l = map(str, tlist) + l = list(map(str, tlist)) assert l == ['n8 n9'], l target = tlist[0] assert target.name == 'n8 n9' @@ -618,7 +620,7 @@ class BuilderTestCase(unittest.TestCase): src_suffix='.obj', suffix='.exe') tgt = b2(env, target=None, source=['foo$OBJSUFFIX']) - s = map(str, tgt[0].sources) + s = list(map(str, tgt[0].sources)) assert s == ['foo.obj'], s def test_suffix(self): @@ -715,10 +717,10 @@ class BuilderTestCase(unittest.TestCase): # support anyway, don't bother trying to test for it. pass else: - s = map(str, tgts) + s = list(map(str, tgts)) expect = [test.workpath('2.out'), test.workpath('3.out')] - expect = map(os.path.normcase, expect) - assert map(os.path.normcase, s) == expect, s + expect = list(map(os.path.normcase, expect)) + assert list(map(os.path.normcase, s)) == expect, s for t in tgts: t.prepare() tgts[0].build() tgts[1].build() @@ -744,7 +746,7 @@ class BuilderTestCase(unittest.TestCase): for t in target: open(str(t), 'w').write("function2\n") for t in tlist: - if not t in map(str, target): + if not t in list(map(str, target)): open(t, 'w').write("function2\n") return 1 @@ -773,7 +775,7 @@ class BuilderTestCase(unittest.TestCase): for t in target: open(str(t), 'w').write("function3\n") for t in tlist: - if not t in map(str, target): + if not t in list(map(str, target)): open(t, 'w').write("function3\n") return 1 @@ -811,17 +813,17 @@ class BuilderTestCase(unittest.TestCase): tgt = builder2(env, target='baz', source=sources)[0] s = str(tgt) assert s == 'baz', s - s = map(str, tgt.sources) + s = list(map(str, tgt.sources)) assert s == ['test.foo', 'test2.foo', 'test3.txt', 'test4.foo'], s - s = map(str, tgt.sources[0].sources) + s = list(map(str, tgt.sources[0].sources)) assert s == ['test.bar'], s tgt = builder2(env, None, 'aaa.bar')[0] s = str(tgt) assert s == 'aaa', s - s = map(str, tgt.sources) + s = list(map(str, tgt.sources)) assert s == ['aaa.foo'], s - s = map(str, tgt.sources[0].sources) + s = list(map(str, tgt.sources[0].sources)) assert s == ['aaa.bar'], s builder3 = SCons.Builder.Builder(action='bld3') @@ -841,11 +843,11 @@ class BuilderTestCase(unittest.TestCase): tgt = builder6(env, 'test', 'test.i')[0] s = str(tgt) assert s == 'test.exe', s - s = map(str, tgt.sources) + s = list(map(str, tgt.sources)) assert s == ['test_wrap.obj'], s - s = map(str, tgt.sources[0].sources) + s = list(map(str, tgt.sources[0].sources)) assert s == ['test_wrap.c'], s - s = map(str, tgt.sources[0].sources[0].sources) + s = list(map(str, tgt.sources[0].sources[0].sources)) assert s == ['test.i'], s def test_target_scanner(self): @@ -1198,14 +1200,14 @@ class BuilderTestCase(unittest.TestCase): tgt = builder(env, target='foo3', source='bar', foo=1) assert len(tgt) == 2, len(tgt) - assert 'foo3' in map(str, tgt), map(str, tgt) - assert 'bar1' in map(str, tgt), map(str, tgt) + assert 'foo3' in list(map(str, tgt)), list(map(str, tgt)) + assert 'bar1' in list(map(str, tgt)), list(map(str, tgt)) tgt = builder(env, target='foo4', source='bar', bar=1)[0] assert str(tgt) == 'foo4', str(tgt) assert len(tgt.sources) == 2, len(tgt.sources) - assert 'baz' in map(str, tgt.sources), map(str, tgt.sources) - assert 'bar' in map(str, tgt.sources), map(str, tgt.sources) + assert 'baz' in list(map(str, tgt.sources)), list(map(str, tgt.sources)) + assert 'bar' in list(map(str, tgt.sources)), list(map(str, tgt.sources)) env2=Environment(FOO=emit) builder2=SCons.Builder.Builder(action='foo', @@ -1226,14 +1228,14 @@ class BuilderTestCase(unittest.TestCase): tgt = builder2(env2, target='foo6', source='bar', foo=2) assert len(tgt) == 2, len(tgt) - assert 'foo6' in map(str, tgt), map(str, tgt) - assert 'bar2' in map(str, tgt), map(str, tgt) + assert 'foo6' in list(map(str, tgt)), list(map(str, tgt)) + assert 'bar2' in list(map(str, tgt)), list(map(str, tgt)) tgt = builder2(env2, target='foo7', source='bar', bar=1)[0] assert str(tgt) == 'foo7', str(tgt) assert len(tgt.sources) == 2, len(tgt.sources) - assert 'baz' in map(str, tgt.sources), map(str, tgt.sources) - assert 'bar' in map(str, tgt.sources), map(str, tgt.sources) + assert 'baz' in list(map(str, tgt.sources)), list(map(str, tgt.sources)) + assert 'bar' in list(map(str, tgt.sources)), list(map(str, tgt.sources)) def test_emitter_preserve_builder(self): """Test an emitter not overwriting a newly-set builder""" @@ -1262,12 +1264,12 @@ class BuilderTestCase(unittest.TestCase): env = Environment() def emit4a(target, source, env): - source = map(str, source) - target = map(lambda x: 'emit4a-' + x[:-3], source) + source = list(map(str, source)) + target = ['emit4a-' + x[:-3] for x in source] return (target, source) def emit4b(target, source, env): - source = map(str, source) - target = map(lambda x: 'emit4b-' + x[:-3], source) + source = list(map(str, source)) + target = ['emit4b-' + x[:-3] for x in source] return (target, source) builder = SCons.Builder.Builder(action='foo', @@ -1283,8 +1285,8 @@ class BuilderTestCase(unittest.TestCase): assert str(tgt) == 'ccc', str(tgt) def emit4c(target, source, env): - source = map(str, source) - target = map(lambda x: 'emit4c-' + x[:-3], source) + source = list(map(str, source)) + target = ['emit4c-' + x[:-3] for x in source] return (target, source) builder.add_emitter('.4c', emit4c) @@ -1296,29 +1298,29 @@ class BuilderTestCase(unittest.TestCase): env = Environment() def emit1a(target, source, env): - source = map(str, source) - target = target + map(lambda x: 'emit1a-' + x[:-2], source) + source = list(map(str, source)) + target = target + ['emit1a-' + x[:-2] for x in source] return (target, source) def emit1b(target, source, env): - source = map(str, source) - target = target + map(lambda x: 'emit1b-' + x[:-2], source) + source = list(map(str, source)) + target = target + ['emit1b-' + x[:-2] for x in source] return (target, source) builder1 = SCons.Builder.Builder(action='foo', emitter=[emit1a, emit1b], node_factory=MyNode) tgts = builder1(env, target='target-1', source='aaa.1') - tgts = map(str, tgts) + tgts = list(map(str, tgts)) assert tgts == ['target-1', 'emit1a-aaa', 'emit1b-aaa'], tgts # Test a list of emitter functions through the environment. def emit2a(target, source, env): - source = map(str, source) - target = target + map(lambda x: 'emit2a-' + x[:-2], source) + source = list(map(str, source)) + target = target + ['emit2a-' + x[:-2] for x in source] return (target, source) def emit2b(target, source, env): - source = map(str, source) - target = target + map(lambda x: 'emit2b-' + x[:-2], source) + source = list(map(str, source)) + target = target + ['emit2b-' + x[:-2] for x in source] return (target, source) builder2 = SCons.Builder.Builder(action='foo', emitter='$EMITTERLIST', @@ -1327,7 +1329,7 @@ class BuilderTestCase(unittest.TestCase): env = Environment(EMITTERLIST = [emit2a, emit2b]) tgts = builder2(env, target='target-2', source='aaa.2') - tgts = map(str, tgts) + tgts = list(map(str, tgts)) assert tgts == ['target-2', 'emit2a-aaa', 'emit2b-aaa'], tgts def test_emitter_TARGET_SOURCE(self): @@ -1345,8 +1347,8 @@ class BuilderTestCase(unittest.TestCase): targets = builder(env, target = 'TTT', source ='SSS') sources = targets[0].sources - targets = map(str, targets) - sources = map(str, sources) + targets = list(map(str, targets)) + sources = list(map(str, sources)) assert targets == ['TTT', 'SSS.s1', 'TTT.t1'], targets assert sources == ['SSS', 'TTT.t2', 'SSS.s2'], targets @@ -1358,53 +1360,53 @@ class BuilderTestCase(unittest.TestCase): tgt = b(env, None, 'aaa')[0] assert str(tgt) == 'aaa.o', str(tgt) - assert len(tgt.sources) == 1, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'aaa', map(str, tgt.sources) + assert len(tgt.sources) == 1, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'aaa', list(map(str, tgt.sources)) tgt = b(env, None, 'bbb.c')[0] assert str(tgt) == 'bbb.o', str(tgt) - assert len(tgt.sources) == 1, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'bbb.c', map(str, tgt.sources) + assert len(tgt.sources) == 1, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'bbb.c', list(map(str, tgt.sources)) tgt = b(env, None, 'ccc.x.c')[0] assert str(tgt) == 'ccc.x.o', str(tgt) - assert len(tgt.sources) == 1, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'ccc.x.c', map(str, tgt.sources) + assert len(tgt.sources) == 1, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'ccc.x.c', list(map(str, tgt.sources)) tgt = b(env, None, ['d0.c', 'd1.c'])[0] assert str(tgt) == 'd0.o', str(tgt) - assert len(tgt.sources) == 2, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'd0.c', map(str, tgt.sources) - assert str(tgt.sources[1]) == 'd1.c', map(str, tgt.sources) + assert len(tgt.sources) == 2, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'd0.c', list(map(str, tgt.sources)) + assert str(tgt.sources[1]) == 'd1.c', list(map(str, tgt.sources)) tgt = b(env, target = None, source='eee')[0] assert str(tgt) == 'eee.o', str(tgt) - assert len(tgt.sources) == 1, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'eee', map(str, tgt.sources) + assert len(tgt.sources) == 1, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'eee', list(map(str, tgt.sources)) tgt = b(env, target = None, source='fff.c')[0] assert str(tgt) == 'fff.o', str(tgt) - assert len(tgt.sources) == 1, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'fff.c', map(str, tgt.sources) + assert len(tgt.sources) == 1, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'fff.c', list(map(str, tgt.sources)) tgt = b(env, target = None, source='ggg.x.c')[0] assert str(tgt) == 'ggg.x.o', str(tgt) - assert len(tgt.sources) == 1, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'ggg.x.c', map(str, tgt.sources) + assert len(tgt.sources) == 1, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'ggg.x.c', list(map(str, tgt.sources)) tgt = b(env, target = None, source=['h0.c', 'h1.c'])[0] assert str(tgt) == 'h0.o', str(tgt) - assert len(tgt.sources) == 2, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'h0.c', map(str, tgt.sources) - assert str(tgt.sources[1]) == 'h1.c', map(str, tgt.sources) + assert len(tgt.sources) == 2, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'h0.c', list(map(str, tgt.sources)) + assert str(tgt.sources[1]) == 'h1.c', list(map(str, tgt.sources)) w = b(env, target='i0.w', source=['i0.x'])[0] y = b(env, target='i1.y', source=['i1.z'])[0] tgt = b(env, None, source=[w, y])[0] assert str(tgt) == 'i0.o', str(tgt) - assert len(tgt.sources) == 2, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'i0.w', map(str, tgt.sources) - assert str(tgt.sources[1]) == 'i1.y', map(str, tgt.sources) + assert len(tgt.sources) == 2, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'i0.w', list(map(str, tgt.sources)) + assert str(tgt.sources[1]) == 'i1.y', list(map(str, tgt.sources)) def test_get_name(self): """Test getting name of builder. @@ -1642,7 +1644,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/CacheDir.py b/src/engine/SCons/CacheDir.py index 73bfe6b..d585888 100644 --- a/src/engine/SCons/CacheDir.py +++ b/src/engine/SCons/CacheDir.py @@ -29,7 +29,6 @@ CacheDir support import os.path import stat -import string import sys import SCons.Action @@ -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/src/engine/SCons/CacheDirTests.py b/src/engine/SCons/CacheDirTests.py index 5e63548..5447509 100644 --- a/src/engine/SCons/CacheDirTests.py +++ b/src/engine/SCons/CacheDirTests.py @@ -286,7 +286,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Conftest.py b/src/engine/SCons/Conftest.py index e995e77..9221e2f 100644 --- a/src/engine/SCons/Conftest.py +++ b/src/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,7 +722,7 @@ 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: @@ -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/src/engine/SCons/Debug.py b/src/engine/SCons/Debug.py index 90e5a82..a6c0cb5 100644 --- a/src/engine/SCons/Debug.py +++ b/src/engine/SCons/Debug.py @@ -32,7 +32,6 @@ needed by most users. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os -import string import sys import time @@ -46,7 +45,7 @@ else: def logInstanceCreation(instance, name=None): if name is None: name = instance.__class__.__name__ - if not tracked_classes.has_key(name): + if name not in tracked_classes: tracked_classes[name] = [] tracked_classes[name].append(weakref.ref(instance)) @@ -60,11 +59,11 @@ def string_to_classes(s): c.sort() return c 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,7 +93,7 @@ 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) else: try: @@ -156,7 +155,7 @@ def _dump_one_caller(key, file, level=0): leader = ' '*level for v,c in l: 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 @@ -175,15 +174,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/src/engine/SCons/Defaults.py b/src/engine/SCons/Defaults.py index 7ce981d..2f48d0d 100644 --- a/src/engine/SCons/Defaults.py +++ b/src/engine/SCons/Defaults.py @@ -41,7 +41,6 @@ import os.path import errno import shutil import stat -import string import time import types import sys @@ -88,7 +87,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: @@ -165,7 +164,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) + '"' @@ -315,16 +314,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 +336,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 @@ -446,11 +445,11 @@ class Variable_Method_Caller: 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/src/engine/SCons/DefaultsTests.py b/src/engine/SCons/DefaultsTests.py index 3d9c1ee..8534cf8 100644 --- a/src/engine/SCons/DefaultsTests.py +++ b/src/engine/SCons/DefaultsTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import StringIO import sys import types @@ -83,7 +82,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Environment.py b/src/engine/SCons/Environment.py index f840dfc..3ebba12 100644 --- a/src/engine/SCons/Environment.py +++ b/src/engine/SCons/Environment.py @@ -31,6 +31,7 @@ Environment # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -40,7 +41,6 @@ import os import sys import re import shlex -import string from UserDict import UserDict import SCons.Action @@ -98,11 +98,11 @@ def apply_tools(env, tools, toolpath): if not tools: return # Filter out null tools from the list. - for tool in filter(None, tools): + for tool in [_f for _f in tools if _f]: if SCons.Util.is_List(tool) or type(tool)==type(()): 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 +173,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: @@ -221,7 +221,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 +257,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 '<BuilderWrapper %s>' % repr(self.name) @@ -290,7 +290,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 @@ -430,7 +430,7 @@ 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 self._dict[key] = value @@ -440,7 +440,7 @@ 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) @@ -471,7 +471,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 +481,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 +566,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) @@ -587,7 +587,7 @@ class SubstitutionEnvironment: 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: @@ -610,8 +610,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): """ @@ -681,11 +680,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 @@ -807,7 +806,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,9 +865,9 @@ 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. @@ -979,12 +978,12 @@ 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) + self.Replace(**kw) keys = kw.keys() if variables: keys = keys + variables.keys() @@ -1100,7 +1099,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 +1110,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 +1239,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 +1260,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 +1270,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 +1280,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 +1326,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 +1345,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): @@ -1416,7 +1415,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 +1471,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,11 +1493,11 @@ 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) + target, depends = line.split(':', 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 @@ -1506,11 +1505,13 @@ class Base(SubstitutionEnvironment): # if the 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 = reduce(lambda x, y: x+y, [p[0] for p in tdlist]) 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 +1597,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 +1618,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 +1628,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 +1638,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 +1691,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 +1703,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 +1742,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 +1760,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 +1770,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 +1797,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 +1814,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 +1828,14 @@ class Base(SubstitutionEnvironment): return tlist def BuildDir(self, *args, **kw): - if kw.has_key('build_dir'): + 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 +1863,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 +1878,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 +1896,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 +1925,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 +1953,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 +1966,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 +2008,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 +2027,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: @@ -2093,9 +2094,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)] @@ -2235,7 +2236,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 @@ -2314,13 +2315,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/src/engine/SCons/EnvironmentTests.py b/src/engine/SCons/EnvironmentTests.py index aa80952..7d3d33e 100644 --- a/src/engine/SCons/EnvironmentTests.py +++ b/src/engine/SCons/EnvironmentTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import copy import os -import string import StringIO import sys import TestCmd @@ -44,14 +43,14 @@ def diff_env(env1, env2): keys = d.keys() keys.sort() for k in keys: - if env1.has_key(k): - if env2.has_key(k): + if k in env1: + if k in env2: if env1[k] != env2[k]: s1 = s1 + " " + repr(k) + " : " + repr(env1[k]) + "\n" s2 = s2 + " " + repr(k) + " : " + repr(env2[k]) + "\n" else: s1 = s1 + " " + repr(k) + " : " + repr(env1[k]) + "\n" - elif env2.has_key(k): + elif k in env2: s2 = s2 + " " + repr(k) + " : " + repr(env2[k]) + "\n" s1 = s1 + "}\n" s2 = s2 + "}\n" @@ -66,14 +65,14 @@ def diff_dict(d1, d2): keys = d.keys() keys.sort() for k in keys: - if d1.has_key(k): - if d2.has_key(k): + if k in d1: + if k in d2: if d1[k] != d2[k]: s1 = s1 + " " + repr(k) + " : " + repr(d1[k]) + "\n" s2 = s2 + " " + repr(k) + " : " + repr(d2[k]) + "\n" else: s1 = s1 + " " + repr(k) + " : " + repr(d1[k]) + "\n" - elif env2.has_key(k): + elif k in env2: s2 = s2 + " " + repr(k) + " : " + repr(d2[k]) + "\n" s1 = s1 + "}\n" s2 = s2 + "}\n" @@ -132,7 +131,7 @@ class Scanner: class CLVar(UserList.UserList): def __init__(self, seq): if type(seq) == type(''): - seq = string.split(seq) + seq = seq.split() UserList.UserList.__init__(self, seq) def __add__(self, other): return UserList.UserList.__add__(self, CLVar(other)) @@ -158,15 +157,15 @@ def test_tool( env ): class TestEnvironmentFixture: def TestEnvironment(self, *args, **kw): - if not kw or not kw.has_key('tools'): + if not kw or 'tools' not in kw: kw['tools'] = [test_tool] default_keys = { 'CC' : 'cc', 'CCFLAGS' : '-DNDEBUG', 'ENV' : { 'TMP' : '/tmp' } } for key, value in default_keys.items(): - if not kw.has_key(key): + if key not in kw: kw[key] = value - if not kw.has_key('BUILDERS'): + if 'BUILDERS' not in kw: static_obj = SCons.Builder.Builder(action = {}, emitter = {}, suffix = '.o', @@ -174,7 +173,7 @@ class TestEnvironmentFixture: kw['BUILDERS'] = {'Object' : static_obj} static_obj.add_action('.cpp', 'fake action') - env = apply(Environment, args, kw) + env = Environment(*args, **kw) return env class SubstitutionTestCase(unittest.TestCase): @@ -183,7 +182,7 @@ class SubstitutionTestCase(unittest.TestCase): """Test initializing a SubstitutionEnvironment """ env = SubstitutionEnvironment() - assert not env.has_key('__env__') + assert '__env__' not in env def test___cmp__(self): """Test comparing SubstitutionEnvironments @@ -231,8 +230,8 @@ class SubstitutionTestCase(unittest.TestCase): """Test the SubstitutionEnvironment has_key() method """ env = SubstitutionEnvironment(XXX = 'x') - assert env.has_key('XXX') - assert not env.has_key('YYY') + assert 'XXX' in env + assert 'YYY' not in env def test_contains(self): """Test the SubstitutionEnvironment __contains__() method @@ -264,7 +263,7 @@ class SubstitutionTestCase(unittest.TestCase): class X(SCons.Node.Node): pass def Factory(name, directory = None, create = 1, dict=dict, X=X): - if not dict.has_key(name): + if name not in dict: dict[name] = X() dict[name].name = name return dict[name] @@ -390,7 +389,7 @@ class SubstitutionTestCase(unittest.TestCase): DummyNode, target=targets, source=sources) - names = map(lambda n: n.name, nodes) + names = [n.name for n in nodes] assert names == ['t1-a', 's1-b', 't2-c', 's2-d'], names def test_gvars(self): @@ -577,16 +576,16 @@ class SubstitutionTestCase(unittest.TestCase): assert r == ['foo', 'xxx', 'bar'], r r = env.subst_path(['$FOO', '$LIST', '$BAR']) - assert map(str, r) == ['foo', 'one two', 'bar'], r + assert list(map(str, r)) == ['foo', 'one two', 'bar'], r r = env.subst_path(['$FOO', '$TARGET', '$SOURCE', '$BAR']) assert r == ['foo', '', '', 'bar'], r r = env.subst_path(['$FOO', '$TARGET', '$BAR'], target=MyNode('ttt')) - assert map(str, r) == ['foo', 'ttt', 'bar'], r + assert list(map(str, r)) == ['foo', 'ttt', 'bar'], r r = env.subst_path(['$FOO', '$SOURCE', '$BAR'], source=MyNode('sss')) - assert map(str, r) == ['foo', 'sss', 'bar'], r + assert list(map(str, r)) == ['foo', 'sss', 'bar'], r n = MyObj() @@ -830,7 +829,7 @@ sys.exit(0) assert d['LIBPATH'] == ['/usr/fax', 'foo', 'C:\\Program Files\\ASCEND'], d['LIBPATH'] - LIBS = map(str, d['LIBS']) + LIBS = list(map(str, d['LIBS'])) assert LIBS == ['xxx', 'yyy', 'ascend'], (d['LIBS'], LIBS) assert d['LINKFLAGS'] == ['-Wl,-link', '-pthread', '-mno-cygwin', '-mwindows', @@ -845,7 +844,7 @@ sys.exit(0) """ env = SubstitutionEnvironment() env.MergeFlags('') - assert not env.has_key('CCFLAGS'), env['CCFLAGS'] + assert 'CCFLAGS' not in env, env['CCFLAGS'] env.MergeFlags('-X') assert env['CCFLAGS'] == ['-X'], env['CCFLAGS'] env.MergeFlags('-X') @@ -909,8 +908,8 @@ class BaseTestCase(unittest.TestCase,TestEnvironmentFixture): env2 = self.TestEnvironment(XXX = 'x', YYY = 'y') assert env1 == env2, diff_env(env1, env2) - assert not env1.has_key('__env__') - assert not env2.has_key('__env__') + assert '__env__' not in env1 + assert '__env__' not in env2 def test_variables(self): """Test that variables only get applied once.""" @@ -1088,69 +1087,69 @@ env4.builder1.env, env3) env = Environment() try: del env['SCANNERS'] except KeyError: pass - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [None, None, None, None, None], s env = self.TestEnvironment(SCANNERS = []) - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [None, None, None, None, None], s env.Replace(SCANNERS = [s1]) - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [s1, s1, None, None, None], s env.Append(SCANNERS = [s2]) - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [s1, s1, None, s2, None], s env.AppendUnique(SCANNERS = [s3]) - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [s1, s1, None, s2, s3], s env = env.Clone(SCANNERS = [s2]) - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [None, None, None, s2, None], s env['SCANNERS'] = [s1] - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [s1, s1, None, None, None], s env.PrependUnique(SCANNERS = [s2, s1]) - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [s1, s1, None, s2, None], s env.Prepend(SCANNERS = [s3]) - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [s1, s1, None, s3, s3], s # Verify behavior of case-insensitive suffix matches on Windows. - uc_suffixes = map(string.upper, suffixes) + uc_suffixes = [_.upper() for _ in suffixes] env = Environment(SCANNERS = [s1, s2, s3], PLATFORM = 'linux') - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [s1, s1, None, s2, s3], s - s = map(env.get_scanner, uc_suffixes) + s = list(map(env.get_scanner, uc_suffixes)) assert s == [None, None, None, None, None], s env['PLATFORM'] = 'win32' - s = map(env.get_scanner, uc_suffixes) + s = list(map(env.get_scanner, uc_suffixes)) assert s == [s1, s1, None, s2, s3], s # Verify behavior for a scanner returning None (on Windows # where we might try to perform case manipulation on None). env.Replace(SCANNERS = [s4]) - s = map(env.get_scanner, suffixes) + s = list(map(env.get_scanner, suffixes)) assert s == [None, None, None, None, None], s def test_ENV(self): """Test setting the external ENV in Environments """ env = Environment() - assert env.Dictionary().has_key('ENV') + assert 'ENV' in env.Dictionary() env = self.TestEnvironment(ENV = { 'PATH' : '/foo:/bar' }) assert env.Dictionary('ENV')['PATH'] == '/foo:/bar' @@ -1182,7 +1181,7 @@ env4.builder1.env, env3) except warning: exc_caught = 1 assert exc_caught, "Did not catch ReservedVariableWarning for `%s'" % kw - assert not env4.has_key(kw), "`%s' variable was incorrectly set" % kw + assert kw not in env4, "`%s' variable was incorrectly set" % kw finally: SCons.Warnings.warningAsException(old) @@ -1204,7 +1203,7 @@ env4.builder1.env, env3) except warning: exc_caught = 1 assert exc_caught, "Did not catch FutureReservedVariableWarning for `%s'" % kw - assert env4.has_key(kw), "`%s' variable was not set" % kw + assert kw in env4, "`%s' variable was not set" % kw finally: SCons.Warnings.warningAsException(old) @@ -1233,7 +1232,7 @@ env4.builder1.env, env3) path = drive + path path = os.path.normpath(path) drive, path = os.path.splitdrive(path) - return string.lower(drive) + path + return drive.lower() + path env = dict.TestEnvironment(LIBS = [ 'foo', 'bar', 'baz' ], LIBLINKPREFIX = 'foo', @@ -1310,7 +1309,7 @@ env4.builder1.env, env3) if arg not in ('$(','$)','-I'): return np(str(arg)) return arg - flags = map(normalize_if_path, flags) + flags = list(map(normalize_if_path, flags)) assert flags == expect, flags def test_platform(self): @@ -1776,8 +1775,8 @@ def exists(env): assert env1.Dictionary('XXX') is env2.Dictionary('XXX') assert 4 in env2.Dictionary('YYY') assert not 4 in env1.Dictionary('YYY') - assert env2.Dictionary('ZZZ').has_key(5) - assert not env1.Dictionary('ZZZ').has_key(5) + assert 5 in env2.Dictionary('ZZZ') + assert 5 not in env1.Dictionary('ZZZ') # env1 = self.TestEnvironment(BUILDERS = {'b1' : Builder()}) @@ -1953,16 +1952,16 @@ def generate(env): xxx, zzz = env.Dictionary('XXX', 'ZZZ') assert xxx == 'x' assert zzz == 'z' - assert env.Dictionary().has_key('BUILDERS') - assert env.Dictionary().has_key('CC') - assert env.Dictionary().has_key('CCFLAGS') - assert env.Dictionary().has_key('ENV') + assert 'BUILDERS' in env.Dictionary() + assert 'CC' in env.Dictionary() + assert 'CCFLAGS' in env.Dictionary() + assert 'ENV' in env.Dictionary() assert env['XXX'] == 'x' env['XXX'] = 'foo' assert env.Dictionary('XXX') == 'foo' del env['XXX'] - assert not env.Dictionary().has_key('XXX') + assert 'XXX' not in env.Dictionary() def test_FindIxes(self): "Test FindIxes()" @@ -2105,8 +2104,8 @@ f5: \ del dlist[:] env.ParseDepends('$SINGLE', only_one=1) - t = map(str, tlist) - d = map(str, dlist) + t = list(map(str, tlist)) + d = list(map(str, dlist)) assert t == ['f0'], t assert d == ['d1', 'd2', 'd3'], d @@ -2114,8 +2113,8 @@ f5: \ del dlist[:] env.ParseDepends(test.workpath('multiple')) - t = map(str, tlist) - d = map(str, dlist) + t = list(map(str, tlist)) + d = list(map(str, dlist)) assert t == ['f1', 'f2', 'f3', 'f4', 'f5'], t assert d == ['foo', 'bar', 'abc', 'def', 'ghi', 'jkl', 'mno'], d @@ -2519,21 +2518,21 @@ def generate(env): test.workpath('sub2'), test.workpath('sub3'), test.workpath('sub4'), - ] + string.split(env_path, os.pathsep) + ] + env_path.split(os.pathsep) pathdirs_1243 = [ test.workpath('sub1'), test.workpath('sub2'), test.workpath('sub4'), test.workpath('sub3'), - ] + string.split(env_path, os.pathsep) + ] + env_path.split(os.pathsep) - path = string.join(pathdirs_1234, os.pathsep) + path = os.pathsep.join(pathdirs_1234) env = self.TestEnvironment(ENV = {'PATH' : path}) wi = env.WhereIs('xxx.exe') assert wi == test.workpath(sub3_xxx_exe), wi wi = env.WhereIs('xxx.exe', pathdirs_1243) assert wi == test.workpath(sub4_xxx_exe), wi - wi = env.WhereIs('xxx.exe', string.join(pathdirs_1243, os.pathsep)) + wi = env.WhereIs('xxx.exe', os.pathsep.join(pathdirs_1243)) assert wi == test.workpath(sub4_xxx_exe), wi wi = env.WhereIs('xxx.exe', reject = sub3_xxx_exe) @@ -2541,13 +2540,13 @@ def generate(env): wi = env.WhereIs('xxx.exe', pathdirs_1243, reject = sub3_xxx_exe) assert wi == test.workpath(sub4_xxx_exe), wi - path = string.join(pathdirs_1243, os.pathsep) + path = os.pathsep.join(pathdirs_1243) env = self.TestEnvironment(ENV = {'PATH' : path}) wi = env.WhereIs('xxx.exe') assert wi == test.workpath(sub4_xxx_exe), wi wi = env.WhereIs('xxx.exe', pathdirs_1234) assert wi == test.workpath(sub3_xxx_exe), wi - wi = env.WhereIs('xxx.exe', string.join(pathdirs_1234, os.pathsep)) + wi = env.WhereIs('xxx.exe', os.pathsep.join(pathdirs_1234)) assert wi == test.workpath(sub3_xxx_exe), wi if sys.platform == 'win32': @@ -2558,13 +2557,13 @@ def generate(env): assert wi == test.workpath(sub4_xxx_exe), wi wi = env.WhereIs('xxx', path = pathdirs_1234, pathext = '.BAT;.EXE') - assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi + assert wi.lower() == test.workpath(sub3_xxx_exe).lower(), wi # Test that we return a normalized path even when # the path contains forward slashes. forward_slash = test.workpath('') + '/sub3' wi = env.WhereIs('xxx', path = forward_slash, pathext = '.EXE') - assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi + assert wi.lower() == test.workpath(sub3_xxx_exe).lower(), wi @@ -2637,37 +2636,37 @@ def generate(env): tgt = env.Alias('export_alias', [ 'asrc1', '$FOO' ])[0] assert str(tgt) == 'export_alias', tgt - assert len(tgt.sources) == 2, map(str, tgt.sources) - assert str(tgt.sources[0]) == 'asrc1', map(str, tgt.sources) - assert str(tgt.sources[1]) == 'kkk', map(str, tgt.sources) + assert len(tgt.sources) == 2, list(map(str, tgt.sources)) + assert str(tgt.sources[0]) == 'asrc1', list(map(str, tgt.sources)) + assert str(tgt.sources[1]) == 'kkk', list(map(str, tgt.sources)) n = env.Alias(tgt, source = ['$BAR', 'asrc4'])[0] assert n is tgt, n - assert len(tgt.sources) == 4, map(str, tgt.sources) - assert str(tgt.sources[2]) == 'lll', map(str, tgt.sources) - assert str(tgt.sources[3]) == 'asrc4', map(str, tgt.sources) + assert len(tgt.sources) == 4, list(map(str, tgt.sources)) + assert str(tgt.sources[2]) == 'lll', list(map(str, tgt.sources)) + assert str(tgt.sources[3]) == 'asrc4', list(map(str, tgt.sources)) n = env.Alias('$EA', 'asrc5')[0] assert n is tgt, n - assert len(tgt.sources) == 5, map(str, tgt.sources) - assert str(tgt.sources[4]) == 'asrc5', map(str, tgt.sources) + assert len(tgt.sources) == 5, list(map(str, tgt.sources)) + assert str(tgt.sources[4]) == 'asrc5', list(map(str, tgt.sources)) t1, t2 = env.Alias(['t1', 't2'], ['asrc6', 'asrc7']) assert str(t1) == 't1', t1 assert str(t2) == 't2', t2 - assert len(t1.sources) == 2, map(str, t1.sources) - assert str(t1.sources[0]) == 'asrc6', map(str, t1.sources) - assert str(t1.sources[1]) == 'asrc7', map(str, t1.sources) - assert len(t2.sources) == 2, map(str, t2.sources) - assert str(t2.sources[0]) == 'asrc6', map(str, t2.sources) - assert str(t2.sources[1]) == 'asrc7', map(str, t2.sources) + assert len(t1.sources) == 2, list(map(str, t1.sources)) + assert str(t1.sources[0]) == 'asrc6', list(map(str, t1.sources)) + assert str(t1.sources[1]) == 'asrc7', list(map(str, t1.sources)) + assert len(t2.sources) == 2, list(map(str, t2.sources)) + assert str(t2.sources[0]) == 'asrc6', list(map(str, t2.sources)) + assert str(t2.sources[1]) == 'asrc7', list(map(str, t2.sources)) tgt = env.Alias('add', 's1') tgt = env.Alias('add', 's2')[0] - s = map(str, tgt.sources) + s = list(map(str, tgt.sources)) assert s == ['s1', 's2'], s tgt = env.Alias(tgt, 's3')[0] - s = map(str, tgt.sources) + s = list(map(str, tgt.sources)) assert s == ['s1', 's2', 's3'], s tgt = env.Alias('act', None, "action1")[0] @@ -2770,20 +2769,20 @@ def generate(env): fff = env.arg2nodes('fff')[0] t = env.Clean('foo', 'aaa') - l = map(str, CT[foo]) + l = list(map(str, CT[foo])) assert l == ['aaa'], l t = env.Clean(foo, ['$BAR', 'ccc']) - l = map(str, CT[foo]) + l = list(map(str, CT[foo])) assert l == ['aaa', 'bbb', 'ccc'], l eee = env.arg2nodes('eee')[0] t = env.Clean('$FOO', 'ddd') - l = map(str, CT[fff]) + l = list(map(str, CT[fff])) assert l == ['ddd'], l t = env.Clean(fff, [eee, 'fff']) - l = map(str, CT[fff]) + l = list(map(str, CT[fff])) assert l == ['ddd', 'eee', 'fff'], l def test_Command(self): @@ -2794,25 +2793,25 @@ def generate(env): assert t.builder is not None assert t.builder.action.__class__.__name__ == 'CommandAction' assert t.builder.action.cmd_list == 'buildfoo $target $source' - assert 'foo1.in' in map(lambda x: x.path, t.sources) - assert 'foo2.in' in map(lambda x: x.path, t.sources) + assert 'foo1.in' in [x.path for x in t.sources] + assert 'foo2.in' in [x.path for x in t.sources] sub = env.fs.Dir('sub') t = env.Command(target='bar.out', source='sub', action='buildbar $target $source')[0] - assert 'sub' in map(lambda x: x.path, t.sources) + assert 'sub' in [x.path for x in t.sources] def testFunc(env, target, source): assert str(target[0]) == 'foo.out' - assert 'foo1.in' in map(str, source) and 'foo2.in' in map(str, source), map(str, source) + assert 'foo1.in' in list(map(str, source)) and 'foo2.in' in list(map(str, source)), list(map(str, source)) return 0 t = env.Command(target='foo.out', source=['foo1.in','foo2.in'], action=testFunc)[0] assert t.builder is not None assert t.builder.action.__class__.__name__ == 'FunctionAction' t.build() - assert 'foo1.in' in map(lambda x: x.path, t.sources) - assert 'foo2.in' in map(lambda x: x.path, t.sources) + assert 'foo1.in' in [x.path for x in t.sources] + assert 'foo2.in' in [x.path for x in t.sources] x = [] def test2(baz, x=x): @@ -2829,7 +2828,7 @@ def generate(env): action = 'foo', X = 'xxx')[0] assert str(t) == 'xxx.out', str(t) - assert 'xxx.in' in map(lambda x: x.path, t.sources) + assert 'xxx.in' in [x.path for x in t.sources] env = self.TestEnvironment(source_scanner = 'should_not_find_this') t = env.Command(target='file.out', source='file.in', @@ -3422,9 +3421,9 @@ def generate(env): bad_msg = '%s is not reserved, but got omitted; see Environment.construction_var_name_ok' added.append('INIT') for x in self.reserved_variables: - assert not env.has_key(x), env[x] + assert x not in env, env[x] for x in added: - assert env.has_key(x), bad_msg % x + assert x in env, bad_msg % x env.Append(TARGETS = 'targets', SOURCES = 'sources', @@ -3437,9 +3436,9 @@ def generate(env): APPEND = 'append') added.append('APPEND') for x in self.reserved_variables: - assert not env.has_key(x), env[x] + assert x not in env, env[x] for x in added: - assert env.has_key(x), bad_msg % x + assert x in env, bad_msg % x env.AppendUnique(TARGETS = 'targets', SOURCES = 'sources', @@ -3452,9 +3451,9 @@ def generate(env): APPENDUNIQUE = 'appendunique') added.append('APPENDUNIQUE') for x in self.reserved_variables: - assert not env.has_key(x), env[x] + assert x not in env, env[x] for x in added: - assert env.has_key(x), bad_msg % x + assert x in env, bad_msg % x env.Prepend(TARGETS = 'targets', SOURCES = 'sources', @@ -3467,9 +3466,9 @@ def generate(env): PREPEND = 'prepend') added.append('PREPEND') for x in self.reserved_variables: - assert not env.has_key(x), env[x] + assert x not in env, env[x] for x in added: - assert env.has_key(x), bad_msg % x + assert x in env, bad_msg % x env.Prepend(TARGETS = 'targets', SOURCES = 'sources', @@ -3482,9 +3481,9 @@ def generate(env): PREPENDUNIQUE = 'prependunique') added.append('PREPENDUNIQUE') for x in self.reserved_variables: - assert not env.has_key(x), env[x] + assert x not in env, env[x] for x in added: - assert env.has_key(x), bad_msg % x + assert x in env, bad_msg % x env.Replace(TARGETS = 'targets', SOURCES = 'sources', @@ -3497,9 +3496,9 @@ def generate(env): REPLACE = 'replace') added.append('REPLACE') for x in self.reserved_variables: - assert not env.has_key(x), env[x] + assert x not in env, env[x] for x in added: - assert env.has_key(x), bad_msg % x + assert x in env, bad_msg % x copy = env.Clone(TARGETS = 'targets', SOURCES = 'sources', @@ -3511,9 +3510,9 @@ def generate(env): UNCHANGED_TARGETS = 'unchanged_targets', COPY = 'copy') for x in self.reserved_variables: - assert not copy.has_key(x), env[x] + assert x not in copy, env[x] for x in added + ['COPY']: - assert copy.has_key(x), bad_msg % x + assert x in copy, bad_msg % x over = env.Override({'TARGETS' : 'targets', 'SOURCES' : 'sources', @@ -3525,9 +3524,9 @@ def generate(env): 'UNCHANGED_TARGETS' : 'unchanged_targets', 'OVERRIDE' : 'override'}) for x in self.reserved_variables: - assert not over.has_key(x), over[x] + assert x not in over, over[x] for x in added + ['OVERRIDE']: - assert over.has_key(x), bad_msg % x + assert x in over, bad_msg % x def test_parse_flags(self): '''Test the Base class parse_flags argument''' @@ -3548,7 +3547,7 @@ def generate(env): # all we have to show is that it gets to MergeFlags internally env = Environment(tools = []) env2 = env.Clone(parse_flags = '-X') - assert not env.has_key('CCFLAGS') + assert 'CCFLAGS' not in env assert env2['CCFLAGS'] == ['-X'], env2['CCFLAGS'] env = Environment(tools = [], CCFLAGS=None) @@ -3558,9 +3557,9 @@ def generate(env): env = Environment(tools = [], CPPDEFINES = 'FOO') env2 = env.Clone(parse_flags = '-std=c99 -X -DBAR') - assert not env.has_key('CFLAGS') + assert 'CFLAGS' not in env assert env2['CFLAGS'] == ['-std=c99'], env2['CFLAGS'] - assert not env.has_key('CCFLAGS') + assert 'CCFLAGS' not in env assert env2['CCFLAGS'] == ['-X'], env2['CCFLAGS'] assert env['CPPDEFINES'] == 'FOO', env['CPPDEFINES'] assert env2['CPPDEFINES'] == ['FOO','BAR'], env2['CPPDEFINES'] @@ -3594,19 +3593,19 @@ class OverrideEnvironmentTestCase(unittest.TestCase,TestEnvironmentFixture): env, env2, env3 = self.envs del env3['XXX'] - assert not env.has_key('XXX'), "env has XXX?" - assert not env2.has_key('XXX'), "env2 has XXX?" - assert not env3.has_key('XXX'), "env3 has XXX?" + assert 'XXX' not in env, "env has XXX?" + assert 'XXX' not in env2, "env2 has XXX?" + assert 'XXX' not in env3, "env3 has XXX?" del env3['YYY'] - assert not env.has_key('YYY'), "env has YYY?" - assert not env2.has_key('YYY'), "env2 has YYY?" - assert not env3.has_key('YYY'), "env3 has YYY?" + assert 'YYY' not in env, "env has YYY?" + assert 'YYY' not in env2, "env2 has YYY?" + assert 'YYY' not in env3, "env3 has YYY?" del env3['ZZZ'] - assert not env.has_key('ZZZ'), "env has ZZZ?" - assert not env2.has_key('ZZZ'), "env2 has ZZZ?" - assert not env3.has_key('ZZZ'), "env3 has ZZZ?" + assert 'ZZZ' not in env, "env has ZZZ?" + assert 'ZZZ' not in env2, "env2 has ZZZ?" + assert 'ZZZ' not in env3, "env3 has ZZZ?" def test_get(self): """Test the OverrideEnvironment get() method""" @@ -3624,15 +3623,15 @@ class OverrideEnvironmentTestCase(unittest.TestCase,TestEnvironmentFixture): def test_has_key(self): """Test the OverrideEnvironment has_key() method""" env, env2, env3 = self.envs - assert env.has_key('XXX'), env.has_key('XXX') - assert env2.has_key('XXX'), env2.has_key('XXX') - assert env3.has_key('XXX'), env3.has_key('XXX') - assert env.has_key('YYY'), env.has_key('YYY') - assert env2.has_key('YYY'), env2.has_key('YYY') - assert env3.has_key('YYY'), env3.has_key('YYY') - assert not env.has_key('ZZZ'), env.has_key('ZZZ') - assert not env2.has_key('ZZZ'), env2.has_key('ZZZ') - assert env3.has_key('ZZZ'), env3.has_key('ZZZ') + assert 'XXX' in env, 'XXX' in env + assert 'XXX' in env2, 'XXX' in env2 + assert 'XXX' in env3, 'XXX' in env3 + assert 'YYY' in env, 'YYY' in env + assert 'YYY' in env2, 'YYY' in env2 + assert 'YYY' in env3, 'YYY' in env3 + assert 'ZZZ' not in env, 'ZZZ' in env + assert 'ZZZ' not in env2, 'ZZZ' in env2 + assert 'ZZZ' in env3, 'ZZZ' in env3 def test_contains(self): """Test the OverrideEnvironment __contains__() method""" @@ -3819,7 +3818,7 @@ class OverrideEnvironmentTestCase(unittest.TestCase,TestEnvironmentFixture): # all we have to show is that it gets to MergeFlags internally env = SubstitutionEnvironment() env2 = env.Override({'parse_flags' : '-X'}) - assert not env.has_key('CCFLAGS') + assert 'CCFLAGS' not in env assert env2['CCFLAGS'] == ['-X'], env2['CCFLAGS'] env = SubstitutionEnvironment(CCFLAGS=None) @@ -3829,9 +3828,9 @@ class OverrideEnvironmentTestCase(unittest.TestCase,TestEnvironmentFixture): env = SubstitutionEnvironment(CPPDEFINES = 'FOO') env2 = env.Override({'parse_flags' : '-std=c99 -X -DBAR'}) - assert not env.has_key('CFLAGS') + assert 'CFLAGS' not in env assert env2['CFLAGS'] == ['-std=c99'], env2['CFLAGS'] - assert not env.has_key('CCFLAGS') + assert 'CCFLAGS' not in env assert env2['CCFLAGS'] == ['-X'], env2['CCFLAGS'] assert env['CPPDEFINES'] == 'FOO', env['CPPDEFINES'] assert env2['CPPDEFINES'] == ['FOO','BAR'], env2['CPPDEFINES'] @@ -3933,9 +3932,9 @@ class NoSubstitutionProxyTestCase(unittest.TestCase,TestEnvironmentFixture): args = ('$XXX $TARGET $SOURCE $YYY',) kw = {'target' : DummyNode('ttt'), 'source' : DummyNode('sss')} - x = apply(env.subst_target_source, args, kw) + x = env.subst_target_source(*args, **kw) assert x == 'x ttt sss y', x - x = apply(proxy.subst_target_source, args, kw) + x = proxy.subst_target_source(*args, **kw) assert x == ' ttt sss ', x class EnvironmentVariableTestCase(unittest.TestCase): @@ -3982,7 +3981,7 @@ if __name__ == "__main__": EnvironmentVariableTestCase ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Errors.py b/src/engine/SCons/Errors.py index 562cbcf..813e08c 100644 --- a/src/engine/SCons/Errors.py +++ b/src/engine/SCons/Errors.py @@ -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): """ diff --git a/src/engine/SCons/Executor.py b/src/engine/SCons/Executor.py index 4da42d5..aaf71b8 100644 --- a/src/engine/SCons/Executor.py +++ b/src/engine/SCons/Executor.py @@ -27,10 +27,10 @@ Nodes. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" -import string import UserList from SCons.Debug import logInstanceCreation @@ -161,10 +161,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 +190,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: @@ -342,7 +342,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 +372,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): @@ -406,9 +406,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 +418,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 +432,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 +523,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 +549,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 diff --git a/src/engine/SCons/ExecutorTests.py b/src/engine/SCons/ExecutorTests.py index 205553a..aaafa07 100644 --- a/src/engine/SCons/ExecutorTests.py +++ b/src/engine/SCons/ExecutorTests.py @@ -23,7 +23,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" -import string import sys import unittest @@ -39,7 +38,7 @@ class MyEnvironment: def Override(self, overrides): d = self._dict.copy() d.update(overrides) - return apply(MyEnvironment, (), d) + return MyEnvironment(**d) def _update(self, dict): self._dict.update(dict) @@ -48,11 +47,11 @@ class MyAction: self.actions = actions def __call__(self, target, source, env, **kw): for action in self.actions: - apply(action, (target, source, env), kw) + action(target, source, env, **kw) def genstring(self, target, source, env): - return string.join(['GENSTRING'] + map(str, self.actions) + target + source) + return ' '.join(['GENSTRING'] + list(map(str, self.actions)) + target + source) def get_contents(self, target, source, env): - return string.join(self.actions + target + source) + return ' '.join(self.actions + target + source) def get_implicit_deps(self, target, source, env): return [] @@ -79,7 +78,7 @@ class MyNode: [], [self], ['s1', 's2']) - apply(executor, (self), {}) + executor(self) def get_env_scanner(self, env, kw): return MyScanner('dep-') def get_implicit_deps(self, env, scanner, path): @@ -184,8 +183,8 @@ class ExecutorTestCase(unittest.TestCase): class LocalScanner: def path(self, env, dir, target, source): - target = map(str, target) - source = map(str, source) + target = list(map(str, target)) + source = list(map(str, source)) return "scanner: %s, %s, %s, %s" % (env['SCANNERVAL'], dir, target, source) s = LocalScanner() @@ -440,13 +439,13 @@ class ExecutorTestCase(unittest.TestCase): x = SCons.Executor.Executor('b', env, [{}], [], [s1, s2, s3]) r = x.get_unignored_sources(None, []) - assert r == [s1, s2, s3], map(str, r) + assert r == [s1, s2, s3], list(map(str, r)) r = x.get_unignored_sources(None, [s2]) - assert r == [s1, s3], map(str, r) + assert r == [s1, s3], list(map(str, r)) r = x.get_unignored_sources(None, [s1, s3]) - assert r == [s2], map(str, r) + assert r == [s2], list(map(str, r)) @@ -455,7 +454,7 @@ if __name__ == "__main__": tclasses = [ ExecutorTestCase ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Job.py b/src/engine/SCons/Job.py index e2375f8..5d6befe 100644 --- a/src/engine/SCons/Job.py +++ b/src/engine/SCons/Job.py @@ -31,6 +31,8 @@ stop, and wait on jobs. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" +import SCons.compat + import os import signal @@ -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. @@ -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 @@ -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) diff --git a/src/engine/SCons/JobTests.py b/src/engine/SCons/JobTests.py index 793a8b7..afa00fb 100644 --- a/src/engine/SCons/JobTests.py +++ b/src/engine/SCons/JobTests.py @@ -20,6 +20,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -491,7 +492,7 @@ class _SConsTaskTest(unittest.TestCase): self.failUnless(state in [SCons.Node.no_state, N.expect_to_be], "Node %s got unexpected result: %s" % (N, state)) - self.failUnless(filter(lambda N: N.get_state(), testnodes), + self.failUnless([N for N in testnodes if N.get_state()], "no nodes ran at all.") diff --git a/src/engine/SCons/Memoize.py b/src/engine/SCons/Memoize.py index 966a618..4566d31 100644 --- a/src/engine/SCons/Memoize.py +++ b/src/engine/SCons/Memoize.py @@ -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,12 +199,12 @@ 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: """Object which performs caching of method calls for its 'primary' diff --git a/src/engine/SCons/MemoizeTests.py b/src/engine/SCons/MemoizeTests.py index 1452052..b3edf01 100644 --- a/src/engine/SCons/MemoizeTests.py +++ b/src/engine/SCons/MemoizeTests.py @@ -187,7 +187,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Node/Alias.py b/src/engine/SCons/Node/Alias.py index d599335..521488e 100644 --- a/src/engine/SCons/Node/Alias.py +++ b/src/engine/SCons/Node/Alias.py @@ -32,7 +32,6 @@ This creates a hash of global Aliases (dummy targets). __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" -import string import UserDict import SCons.Errors @@ -46,7 +45,7 @@ class AliasNameSpace(UserDict.UserDict): 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/src/engine/SCons/Node/AliasTests.py b/src/engine/SCons/Node/AliasTests.py index 82322e3..6931072 100644 --- a/src/engine/SCons/Node/AliasTests.py +++ b/src/engine/SCons/Node/AliasTests.py @@ -119,7 +119,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Node/FS.py b/src/engine/SCons/Node/FS.py index 88248d7..705e0bc 100644 --- a/src/engine/SCons/Node/FS.py +++ b/src/engine/SCons/Node/FS.py @@ -32,6 +32,7 @@ that can be used by scripts or modules looking for the canonical default. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -43,7 +44,6 @@ import os.path import re import shutil import stat -import string import sys import time @@ -260,7 +260,7 @@ def set_duplicate(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]) @@ -373,7 +373,7 @@ 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() @@ -459,7 +459,7 @@ def set_diskcheck(list): dc.set(list) def diskcheck_types(): - return map(lambda dc: dc.type, diskcheckers) + return [dc.type for dc in diskcheckers] @@ -497,7 +497,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 +507,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): @@ -753,8 +753,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.""" @@ -1249,7 +1249,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): @@ -1327,12 +1327,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 +1574,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 +1622,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) # # @@ -1687,7 +1687,7 @@ class Dir(Base): sorted_children.sort(name_cmp) for node in sorted_children: 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 +1783,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')) @@ -1915,8 +1915,7 @@ class Dir(Base): 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): @@ -1964,7 +1963,7 @@ 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 @@ -1990,9 +1989,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 +2013,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 +2029,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. @@ -2200,7 +2198,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 +2206,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 @@ -2249,9 +2247,9 @@ class FileBuildInfo(SCons.Node.BuildInfoBase): bkidsigs = self.bsourcesigs + self.bdependsigs + self.bimplicitsigs for bkid, bkidsig in izip(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. @@ -2288,7 +2286,7 @@ class File(Base): 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 @@ -2603,7 +2601,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 = [] @@ -3019,7 +3017,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) @@ -3117,8 +3115,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 = ' %s: ' % verbose + verbose = lambda s: sys.stdout.write(_verbose + s) filedir, filename = os.path.split(filename) if filedir: @@ -3153,7 +3151,7 @@ class FileFinder: #paths = filter(None, map(filedir_lookup, paths)) 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/src/engine/SCons/Node/FSTests.py b/src/engine/SCons/Node/FSTests.py index 9582a97..af7638d 100644 --- a/src/engine/SCons/Node/FSTests.py +++ b/src/engine/SCons/Node/FSTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import sys import time import unittest @@ -40,13 +39,6 @@ import SCons.Warnings built_it = None -# This will be built-in in 2.3. For now fake it. -try : - True , False -except NameError : - True = 1 ; False = 0 - - scanner_count = 0 class Scanner: @@ -341,7 +333,7 @@ class VariantDirTestCase(unittest.TestCase): f11 = fs.File('src/file11') t, m = f11.alter_targets() - bdt = map(lambda n: n.path, t) + bdt = [n.path for n in t] var1_file11 = os.path.normpath('build/var1/file11') var2_file11 = os.path.normpath('build/var2/file11') assert bdt == [var1_file11, var2_file11], bdt @@ -349,11 +341,11 @@ class VariantDirTestCase(unittest.TestCase): f12 = fs.File('src/file12') f12.builder = 1 bdt, m = f12.alter_targets() - assert bdt == [], map(lambda n: n.path, bdt) + assert bdt == [], [n.path for n in bdt] d13 = fs.Dir('src/new_dir') t, m = d13.alter_targets() - bdt = map(lambda n: n.path, t) + bdt = [n.path for n in t] var1_new_dir = os.path.normpath('build/var1/new_dir') var2_new_dir = os.path.normpath('build/var2/new_dir') assert bdt == [var1_new_dir, var2_new_dir], bdt @@ -445,7 +437,7 @@ class VariantDirTestCase(unittest.TestCase): self.have['copy'] = copy self.links_to_be_called = [] - for link in string.split(self.duplicate, '-'): + for link in self.duplicate.split('-'): if self.have[link]: self.links_to_be_called.append(link) @@ -817,7 +809,7 @@ class FileBuildInfoTestCase(_tempdirTestCase): 'actionsig [action]', ] - expect = string.join(expect_lines, '\n') + expect = '\n'.join(expect_lines) format = bi1.format() assert format == expect, (repr(expect), repr(format)) @@ -921,12 +913,12 @@ class FSTestCase(_tempdirTestCase): drive, path = os.path.splitdrive(os.getcwd()) def _do_Dir_test(lpath, path_, abspath_, up_path_, sep, fileSys=fs, drive=drive): - dir = fileSys.Dir(string.replace(lpath, '/', sep)) + dir = fileSys.Dir(lpath.replace('/', sep)) if os.sep != '/': - path_ = string.replace(path_, '/', os.sep) - abspath_ = string.replace(abspath_, '/', os.sep) - up_path_ = string.replace(up_path_, '/', os.sep) + path_ = path_.replace('/', os.sep) + abspath_ = abspath_.replace('/', os.sep) + up_path_ = up_path_.replace('/', os.sep) def strip_slash(p, drive=drive): if p[-1] == os.sep and len(p) > 1: @@ -937,7 +929,7 @@ class FSTestCase(_tempdirTestCase): path = strip_slash(path_) abspath = strip_slash(abspath_) up_path = strip_slash(up_path_) - name = string.split(abspath, os.sep)[-1] + name = abspath.split(os.sep)[-1] assert dir.name == name, \ "dir.name %s != expected name %s" % \ @@ -978,7 +970,7 @@ class FSTestCase(_tempdirTestCase): Dir_test('#', './', sub_dir, sub) try: - f2 = fs.File(string.join(['f1', 'f2'], sep), directory = d1) + f2 = fs.File(sep.join(['f1', 'f2']), directory = d1) except TypeError, x: assert str(x) == ("Tried to lookup File '%s' as a Dir." % d1_f1), x @@ -986,7 +978,7 @@ class FSTestCase(_tempdirTestCase): raise try: - dir = fs.Dir(string.join(['d1', 'f1'], sep)) + dir = fs.Dir(sep.join(['d1', 'f1'])) except TypeError, x: assert str(x) == ("Tried to lookup File '%s' as a Dir." % d1_f1), x @@ -1051,7 +1043,7 @@ class FSTestCase(_tempdirTestCase): assert built_it def match(path, expect): - expect = string.replace(expect, '/', os.sep) + expect = expect.replace('/', os.sep) assert path == expect, "path %s != expected %s" % (path, expect) e1 = fs.Entry("d1") @@ -1434,7 +1426,7 @@ class FSTestCase(_tempdirTestCase): test.subdir('sub', ['sub', 'dir']) def drive_workpath(drive, dirs, test=test): - x = apply(test.workpath, dirs) + x = test.workpath(*dirs) drive, path = os.path.splitdrive(x) return 'X:' + path @@ -1466,11 +1458,11 @@ class FSTestCase(_tempdirTestCase): seps = seps + ['/'] def _do_Dir_test(lpath, path_, up_path_, sep, fileSys=fs): - dir = fileSys.Dir(string.replace(lpath, '/', sep)) + dir = fileSys.Dir(lpath.replace('/', sep)) if os.sep != '/': - path_ = string.replace(path_, '/', os.sep) - up_path_ = string.replace(up_path_, '/', os.sep) + path_ = path_.replace('/', os.sep) + up_path_ = up_path_.replace('/', os.sep) def strip_slash(p): if p[-1] == os.sep and len(p) > 3: @@ -1478,7 +1470,7 @@ class FSTestCase(_tempdirTestCase): return p path = strip_slash(path_) up_path = strip_slash(up_path_) - name = string.split(path, os.sep)[-1] + name = path.split(os.sep)[-1] assert dir.name == name, \ "dir.name %s != expected name %s" % \ @@ -1577,8 +1569,8 @@ class FSTestCase(_tempdirTestCase): d1 = fs.Dir('d1') d2 = d1.Dir('d2') - dirs = string.split(os.path.normpath(d2.abspath), os.sep) - above_path = apply(os.path.join, ['..']*len(dirs) + ['above']) + dirs = os.path.normpath(d2.abspath).split(os.sep) + above_path = os.path.join(*['..']*len(dirs) + ['above']) above = d2.Dir(above_path) def test_rel_path(self): @@ -1730,7 +1722,7 @@ class DirTestCase(_tempdirTestCase): fs.Dir(os.path.join('ddd', 'd1', 'f4')) fs.Dir(os.path.join('ddd', 'd1', 'f5')) dir.scan() - kids = map(lambda x: x.path, dir.children(None)) + kids = [x.path for x in dir.children(None)] kids.sort() assert kids == [os.path.join('ddd', 'd1'), os.path.join('ddd', 'f1'), @@ -1757,7 +1749,7 @@ class DirTestCase(_tempdirTestCase): s = self.fs.Dir(os.path.join('d', 'sub')) #TODO(1.5) files = d.get_contents().split('\n') - files = string.split(d.get_contents(), '\n') + files = d.get_contents().split('\n') assert e.get_contents() == '', e.get_contents() assert e.get_text_contents() == '', e.get_text_contents() @@ -1776,13 +1768,13 @@ class DirTestCase(_tempdirTestCase): fs.File(os.path.join('ddd', 'f1')) dir.scan() - kids = map(lambda x: x.path, dir.children()) + kids = [x.path for x in dir.children()] kids.sort() assert kids == [os.path.join('ddd', 'f1')], kids fs.File(os.path.join('ddd', 'f2')) dir.scan() - kids = map(lambda x: x.path, dir.children()) + kids = [x.path for x in dir.children()] kids.sort() assert kids == [os.path.join('ddd', 'f1'), os.path.join('ddd', 'f2')], kids @@ -1818,8 +1810,8 @@ class DirTestCase(_tempdirTestCase): self.fs.VariantDir(sub2, src, duplicate=0) def check(result, expect): - result = map(str, result) - expect = map(os.path.normpath, expect) + result = list(map(str, result)) + expect = list(map(os.path.normpath, expect)) assert result == expect, result s = src.srcdir_list() @@ -1922,8 +1914,8 @@ class DirTestCase(_tempdirTestCase): exists_e.exists = return_true def check(result, expect): - result = map(str, result) - expect = map(os.path.normpath, expect) + result = list(map(str, result)) + expect = list(map(os.path.normpath, expect)) assert result == expect, result # First check from the source directory. @@ -2135,7 +2127,7 @@ class FileTestCase(_tempdirTestCase): d1 = self.fs.Dir('subdir/d1') d2 = self.fs.Dir('subdir/d2') dirs = fff.Dirs(['d1', 'd2']) - assert dirs == [d1, d2], map(str, dirs) + assert dirs == [d1, d2], list(map(str, dirs)) def test_exists(self): """Test the File.exists() method""" @@ -2248,7 +2240,7 @@ class GlobTestCase(_tempdirTestCase): strings_kwargs = copy.copy(kwargs) strings_kwargs['strings'] = True for input, string_expect, node_expect in cases: - r = apply(self.fs.Glob, (input,), strings_kwargs) + r = self.fs.Glob(input, **strings_kwargs) r.sort() assert r == string_expect, "Glob(%s, strings=True) expected %s, got %s" % (input, string_expect, r) @@ -2259,7 +2251,7 @@ class GlobTestCase(_tempdirTestCase): # Verify those by running the list through str() before comparing # them with the expected list of strings. for input, string_expect, node_expect in cases: - r = apply(self.fs.Glob, (input,), kwargs) + r = self.fs.Glob(input, **kwargs) if node_expect: r.sort(lambda a,b: cmp(a.path, b.path)) result = [] @@ -2269,16 +2261,16 @@ class GlobTestCase(_tempdirTestCase): result.append(n) fmt = lambda n: "%s %s" % (repr(n), repr(str(n))) else: - r = map(str, r) + r = list(map(str, r)) r.sort() result = string_expect fmt = lambda n: n if r != result: import pprint print "Glob(%s) expected:" % repr(input) - pprint.pprint(map(fmt, result)) + pprint.pprint(list(map(fmt, result))) print "Glob(%s) got:" % repr(input) - pprint.pprint(map(fmt, r)) + pprint.pprint(list(map(fmt, r))) self.fail() def test_exact_match(self): @@ -2538,7 +2530,7 @@ class RepositoryTestCase(_tempdirTestCase): ] rep = self.fs.Dir('#').getRepositories() - r = map(lambda x, np=os.path.normpath: np(str(x)), rep) + r = [os.path.normpath(str(x)) for x in rep] assert r == expect, r def test_get_all_rdirs(self): @@ -2560,7 +2552,7 @@ class RepositoryTestCase(_tempdirTestCase): ] rep = self.fs.Dir('#').get_all_rdirs() - r = map(lambda x, np=os.path.normpath: np(str(x)), rep) + r = [os.path.normpath(str(x)) for x in rep] assert r == expect, r def test_rentry(self): @@ -2742,25 +2734,25 @@ class RepositoryTestCase(_tempdirTestCase): rep3_sub_d1 = fs.Dir(test.workpath('rep3', 'sub', 'd1')) r = fs.Top.Rfindalldirs((d1,)) - assert r == [d1], map(str, r) + assert r == [d1], list(map(str, r)) r = fs.Top.Rfindalldirs((d1, d2)) - assert r == [d1, d2], map(str, r) + assert r == [d1, d2], list(map(str, r)) r = fs.Top.Rfindalldirs(('d1',)) - assert r == [d1, rep1_d1, rep2_d1, rep3_d1], map(str, r) + assert r == [d1, rep1_d1, rep2_d1, rep3_d1], list(map(str, r)) r = fs.Top.Rfindalldirs(('#d1',)) - assert r == [d1, rep1_d1, rep2_d1, rep3_d1], map(str, r) + assert r == [d1, rep1_d1, rep2_d1, rep3_d1], list(map(str, r)) r = sub.Rfindalldirs(('d1',)) - assert r == [sub_d1, rep1_sub_d1, rep2_sub_d1, rep3_sub_d1], map(str, r) + assert r == [sub_d1, rep1_sub_d1, rep2_sub_d1, rep3_sub_d1], list(map(str, r)) r = sub.Rfindalldirs(('#d1',)) - assert r == [d1, rep1_d1, rep2_d1, rep3_d1], map(str, r) + assert r == [d1, rep1_d1, rep2_d1, rep3_d1], list(map(str, r)) r = fs.Top.Rfindalldirs(('d1', d2)) - assert r == [d1, rep1_d1, rep2_d1, rep3_d1, d2], map(str, r) + assert r == [d1, rep1_d1, rep2_d1, rep3_d1, d2], list(map(str, r)) def test_rexists(self): """Test the Entry.rexists() method""" @@ -2892,10 +2884,10 @@ class find_fileTestCase(unittest.TestCase): nodes.append(SCons.Node.FS.find_file('pseudo', paths)) nodes.append(SCons.Node.FS.find_file('same', paths)) - file_names = map(str, nodes) - file_names = map(os.path.normpath, file_names) + file_names = list(map(str, nodes)) + file_names = list(map(os.path.normpath, file_names)) expect = ['./foo', './bar/baz', './pseudo', './bar/same'] - expect = map(os.path.normpath, expect) + expect = list(map(os.path.normpath, expect)) assert file_names == expect, file_names # Make sure we don't blow up if there's already a File in place @@ -3433,14 +3425,14 @@ class SaveStringsTestCase(unittest.TestCase): fs1.VariantDir('d0', 'src', duplicate=0) fs1.VariantDir('d1', 'src', duplicate=1) - s = map(str, nodes) - expect = map(os.path.normpath, ['src/f', 'd1/f', 'd0/b', 'd1/b']) + s = list(map(str, nodes)) + expect = list(map(os.path.normpath, ['src/f', 'd1/f', 'd0/b', 'd1/b'])) assert s == expect, s modify(nodes) - s = map(str, nodes) - expect = map(os.path.normpath, ['src/f', 'src/f', 'd0/b', 'd1/b']) + s = list(map(str, nodes)) + expect = list(map(os.path.normpath, ['src/f', 'src/f', 'd0/b', 'd1/b'])) assert s == expect, s SCons.Node.FS.save_strings(1) @@ -3449,14 +3441,14 @@ class SaveStringsTestCase(unittest.TestCase): fs2.VariantDir('d0', 'src', duplicate=0) fs2.VariantDir('d1', 'src', duplicate=1) - s = map(str, nodes) - expect = map(os.path.normpath, ['src/f', 'd1/f', 'd0/b', 'd1/b']) + s = list(map(str, nodes)) + expect = list(map(os.path.normpath, ['src/f', 'd1/f', 'd0/b', 'd1/b'])) assert s == expect, s modify(nodes) - s = map(str, nodes) - expect = map(os.path.normpath, ['src/f', 'd1/f', 'd0/b', 'd1/b']) + s = list(map(str, nodes)) + expect = list(map(os.path.normpath, ['src/f', 'd1/f', 'd0/b', 'd1/b'])) assert s == expect, 'node str() not cached: %s'%s @@ -3509,7 +3501,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Node/NodeTests.py b/src/engine/SCons/Node/NodeTests.py index 643e218..0784237 100644 --- a/src/engine/SCons/Node/NodeTests.py +++ b/src/engine/SCons/Node/NodeTests.py @@ -20,12 +20,12 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import re -import string import sys import types import unittest @@ -125,7 +125,7 @@ class Environment: def Override(self, overrides): d = self._dict.copy() d.update(overrides) - return apply(Environment, (), d) + return Environment(**d) def _update(self, dict): self._dict.update(dict) def get_factory(self, factory): @@ -889,24 +889,24 @@ class NodeTestCase(unittest.TestCase): d2.found_includes = [e, f] f.found_includes = [g] deps = node.get_implicit_deps(env, s, target) - assert deps == [d1, d2, e, f, g], map(str, deps) + assert deps == [d1, d2, e, f, g], list(map(str, deps)) # Recursive scanning eliminates duplicates e.found_includes = [f] deps = node.get_implicit_deps(env, s, target) - assert deps == [d1, d2, e, f, g], map(str, deps) + assert deps == [d1, d2, e, f, g], list(map(str, deps)) # Scanner method can select specific nodes to recurse def no_fff(nodes): - return filter(lambda n: str(n)[0] != 'f', nodes) + return [n for n in nodes if str(n)[0] != 'f'] s.recurse_nodes = no_fff deps = node.get_implicit_deps(env, s, target) - assert deps == [d1, d2, e, f], map(str, deps) + assert deps == [d1, d2, e, f], list(map(str, deps)) # Scanner method can short-circuit recursing entirely s.recurse_nodes = lambda nodes: [] deps = node.get_implicit_deps(env, s, target) - assert deps == [d1, d2], map(str, deps) + assert deps == [d1, d2], list(map(str, deps)) def test_get_env_scanner(self): """Test fetching the environment scanner for a Node @@ -1130,13 +1130,13 @@ class NodeTestCase(unittest.TestCase): nw = SCons.Node.Walker(n1) assert nw.next().name == "n4" assert nw.next().name == "n5" - assert nw.history.has_key(n2) + assert n2 in nw.history assert nw.next().name == "n2" assert nw.next().name == "n6" assert nw.next().name == "n7" - assert nw.history.has_key(n3) + assert n3 in nw.history assert nw.next().name == "n3" - assert nw.history.has_key(n1) + assert n1 in nw.history assert nw.next().name == "n1" assert nw.next() is None @@ -1293,7 +1293,7 @@ class NodeListTestCase(unittest.TestCase): # New-style classes report as "object"; classic classes report # as "instance"... r = re.sub("object", "instance", r) - l = string.join(["<MyNode instance at 0x>"]*3, ", ") + l = ", ".join(["<MyNode instance at 0x>"]*3) assert r == '[%s]' % l, r @@ -1306,7 +1306,7 @@ if __name__ == "__main__": NodeListTestCase ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Node/Python.py b/src/engine/SCons/Node/Python.py index eba008b..3d8bdaa 100644 --- a/src/engine/SCons/Node/Python.py +++ b/src/engine/SCons/Node/Python.py @@ -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/src/engine/SCons/Node/PythonTests.py b/src/engine/SCons/Node/PythonTests.py index 1dc2bb7..74a9c99 100644 --- a/src/engine/SCons/Node/PythonTests.py +++ b/src/engine/SCons/Node/PythonTests.py @@ -119,7 +119,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Node/__init__.py b/src/engine/SCons/Node/__init__.py index c4f36cc..c25c955 100644 --- a/src/engine/SCons/Node/__init__.py +++ b/src/engine/SCons/Node/__init__.py @@ -41,12 +41,12 @@ be able to depend on any other type of "thing." # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import copy from itertools import chain, izip -import string import UserList from SCons.Debug import logInstanceCreation @@ -57,7 +57,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 # @@ -372,7 +372,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 +548,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 +831,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 +848,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 +862,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))) @@ -1215,11 +1214,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 +1228,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,7 +1253,7 @@ class Node: return "%s %s" % (preamble, lines[0]) else: lines = ["%s:\n" % preamble] + lines - return string.join(lines, ' '*11) + return ( ' '*11).join(lines) try: [].extend(UserList.UserList([])) @@ -1267,7 +1266,7 @@ except TypeError: else: class NodeList(UserList.UserList): def __str__(self): - return str(map(str, self.data)) + return str(list(map(str, self.data))) def get_children(node, parent): return node.children() def ignore_cycle(node, stack): pass @@ -1310,7 +1309,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/src/engine/SCons/Options/BoolOption.py b/src/engine/SCons/Options/BoolOption.py index 652cf5e..452fdd3 100644 --- a/src/engine/SCons/Options/BoolOption.py +++ b/src/engine/SCons/Options/BoolOption.py @@ -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/src/engine/SCons/Options/EnumOption.py b/src/engine/SCons/Options/EnumOption.py index e89b5b9..2db158d 100644 --- a/src/engine/SCons/Options/EnumOption.py +++ b/src/engine/SCons/Options/EnumOption.py @@ -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/src/engine/SCons/Options/ListOption.py b/src/engine/SCons/Options/ListOption.py index a660924..4167d8e 100644 --- a/src/engine/SCons/Options/ListOption.py +++ b/src/engine/SCons/Options/ListOption.py @@ -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/src/engine/SCons/Options/PackageOption.py b/src/engine/SCons/Options/PackageOption.py index 51f9f9b..ba0608a 100644 --- a/src/engine/SCons/Options/PackageOption.py +++ b/src/engine/SCons/Options/PackageOption.py @@ -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/src/engine/SCons/Options/PathOption.py b/src/engine/SCons/Options/PathOption.py index fd1130b..5d460a0 100644 --- a/src/engine/SCons/Options/PathOption.py +++ b/src/engine/SCons/Options/PathOption.py @@ -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/src/engine/SCons/Options/__init__.py b/src/engine/SCons/Options/__init__.py index 104aa82..f6c8483 100644 --- a/src/engine/SCons/Options/__init__.py +++ b/src/engine/SCons/Options/__init__.py @@ -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/src/engine/SCons/PathList.py b/src/engine/SCons/PathList.py index 9da0f31..7b12865 100644 --- a/src/engine/SCons/PathList.py +++ b/src/engine/SCons/PathList.py @@ -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 @@ -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: diff --git a/src/engine/SCons/PathListTests.py b/src/engine/SCons/PathListTests.py index faecc4d..31a9ec6 100644 --- a/src/engine/SCons/PathListTests.py +++ b/src/engine/SCons/PathListTests.py @@ -159,7 +159,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Platform/__init__.py b/src/engine/SCons/Platform/__init__.py index 5bcd91c..2ae1e97 100644 --- a/src/engine/SCons/Platform/__init__.py +++ b/src/engine/SCons/Platform/__init__.py @@ -48,7 +48,6 @@ 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: @@ -184,7 +183,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 +197,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,7 +217,7 @@ 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()): diff --git a/src/engine/SCons/Platform/aix.py b/src/engine/SCons/Platform/aix.py index a5f9573..0229112 100644 --- a/src/engine/SCons/Platform/aix.py +++ b/src/engine/SCons/Platform/aix.py @@ -33,7 +33,6 @@ selection method. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Platform/os2.py b/src/engine/SCons/Platform/os2.py index aa348d4..0fa4553 100644 --- a/src/engine/SCons/Platform/os2.py +++ b/src/engine/SCons/Platform/os2.py @@ -34,7 +34,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Platform/posix.py b/src/engine/SCons/Platform/posix.py index d1102b3..ece48d7 100644 --- a/src/engine/SCons/Platform/posix.py +++ b/src/engine/SCons/Platform/posix.py @@ -35,7 +35,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Platform/win32.py b/src/engine/SCons/Platform/win32.py index a50a6ae..52255ba 100644 --- a/src/engine/SCons/Platform/win32.py +++ b/src/engine/SCons/Platform/win32.py @@ -34,7 +34,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import sys import tempfile @@ -67,14 +66,14 @@ else: _builtin_open = __builtin__.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) @@ -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 @@ -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/src/engine/SCons/SConf.py b/src/engine/SCons/SConf.py index 133dab5..bd67ab2 100644 --- a/src/engine/SCons/SConf.py +++ b/src/engine/SCons/SConf.py @@ -30,7 +30,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import re -import string import StringIO import sys import traceback @@ -96,7 +95,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,8 +152,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 |" ) ) + source[0].get_contents().replace( '\n', "\n |" ) ) # python 2.2 introduces types.BooleanType BooleanTypes = [types.IntType] @@ -222,8 +220,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 +243,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): @@ -465,7 +462,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): """ @@ -645,7 +642,7 @@ class SConfBase: raise (SCons.Errors.UserError, "Test called after sconf.Finish()") 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 +686,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 @@ -804,19 +801,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' ): @@ -889,7 +886,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 +898,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 +930,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/src/engine/SCons/SConfTests.py b/src/engine/SCons/SConfTests.py index 45b6eef..d0da84a 100644 --- a/src/engine/SCons/SConfTests.py +++ b/src/engine/SCons/SConfTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import re -import string import StringIO import sys from types import * @@ -60,7 +59,7 @@ class SConfTestCase(unittest.TestCase): import SCons.SConsign SCons.SConsign.write() # simulate normal scons-finish for n in sys.modules.keys(): - if string.split(n, '.')[0] == 'SCons' and n[:12] != 'SCons.compat': + if n.split('.')[0] == 'SCons' and n[:12] != 'SCons.compat': m = sys.modules[n] if type(m) is ModuleType: # if this is really a scons module, clear its namespace diff --git a/src/engine/SCons/SConsignTests.py b/src/engine/SCons/SConsignTests.py index 9a02044..7ae584a 100644 --- a/src/engine/SCons/SConsignTests.py +++ b/src/engine/SCons/SConsignTests.py @@ -386,7 +386,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Scanner/C.py b/src/engine/SCons/Scanner/C.py index 622ac67..fd8d2f2 100644 --- a/src/engine/SCons/Scanner/C.py +++ b/src/engine/SCons/Scanner/C.py @@ -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]) diff --git a/src/engine/SCons/Scanner/CTests.py b/src/engine/SCons/Scanner/CTests.py index a62f4c1..e92af24 100644 --- a/src/engine/SCons/Scanner/CTests.py +++ b/src/engine/SCons/Scanner/CTests.py @@ -192,7 +192,7 @@ class DummyEnvironment(UserDict.UserDict): def subst_path(self, path, target=None, source=None, conv=None): if type(path) != type([]): path = [path] - return map(self.subst, path) + return list(map(self.subst, path)) def get_calculator(self): return None @@ -213,8 +213,8 @@ else: def deps_match(self, deps, headers): global my_normpath - scanned = map(my_normpath, map(str, deps)) - expect = map(my_normpath, headers) + scanned = list(map(my_normpath, list(map(str, deps)))) + expect = list(map(my_normpath, headers)) self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned)) # define some tests: @@ -310,7 +310,7 @@ class CScannerTestCase8(unittest.TestCase): env.fs.chdir(env.Dir('')) path = s.path(env, dir) deps2 = s(env.File('#fa.cpp'), env, path) - headers1 = map(test.workpath, ['include/fa.h', 'include/fb.h']) + headers1 = list(map(test.workpath, ['include/fa.h', 'include/fb.h'])) headers2 = ['include/fa.h', 'include/fb.h'] deps_match(self, deps1, headers1) deps_match(self, deps2, headers2) diff --git a/src/engine/SCons/Scanner/D.py b/src/engine/SCons/Scanner/D.py index 4134337..9402ed1 100644 --- a/src/engine/SCons/Scanner/D.py +++ b/src/engine/SCons/Scanner/D.py @@ -33,7 +33,6 @@ Coded by Andy Friesen __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Scanner/Dir.py b/src/engine/SCons/Scanner/Dir.py index a623c99..6b7f05b 100644 --- a/src/engine/SCons/Scanner/Dir.py +++ b/src/engine/SCons/Scanner/Dir.py @@ -20,6 +20,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -28,21 +29,21 @@ 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 +68,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 +101,9 @@ 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 = list(filter(do_not_scan, entries.keys())) entry_list.sort() - return map(lambda n, e=entries: e[n], entry_list) + return [entries[n] for n in entry_list] # Local Variables: # tab-width:4 diff --git a/src/engine/SCons/Scanner/DirTests.py b/src/engine/SCons/Scanner/DirTests.py index 5d59bd5..0ad1cfe 100644 --- a/src/engine/SCons/Scanner/DirTests.py +++ b/src/engine/SCons/Scanner/DirTests.py @@ -24,7 +24,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path -import string import sys import types import unittest @@ -91,7 +90,7 @@ class DirScannerTestCase(DirScannerTestBase): os.path.join('dir', 'sub'), ] deps = s(env.Dir('dir'), env, ()) - sss = map(str, deps) + sss = list(map(str, deps)) assert sss == expect, sss expect = [ @@ -99,7 +98,7 @@ class DirScannerTestCase(DirScannerTestBase): os.path.join('dir', 'sub', 'f4'), ] deps = s(env.Dir('dir/sub'), env, ()) - sss = map(str, deps) + sss = list(map(str, deps)) assert sss == expect, sss class DirEntryScannerTestCase(DirScannerTestBase): @@ -109,16 +108,16 @@ class DirEntryScannerTestCase(DirScannerTestBase): s = SCons.Scanner.Dir.DirEntryScanner() deps = s(env.Dir('dir'), env, ()) - sss = map(str, deps) + sss = list(map(str, deps)) assert sss == [], sss deps = s(env.Dir('dir/sub'), env, ()) - sss = map(str, deps) + sss = list(map(str, deps)) assert sss == [], sss # Make sure we don't blow up if handed a non-Dir node. deps = s(env.File('dir/f1'), env, ()) - sss = map(str, deps) + sss = list(map(str, deps)) assert sss == [], sss def suite(): diff --git a/src/engine/SCons/Scanner/Fortran.py b/src/engine/SCons/Scanner/Fortran.py index 2aed653..fd6a014 100644 --- a/src/engine/SCons/Scanner/Fortran.py +++ b/src/engine/SCons/Scanner/Fortran.py @@ -26,11 +26,11 @@ This module implements the dependency scanner for Fortran code. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import re -import string import SCons.Node import SCons.Node.FS @@ -75,7 +75,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 +94,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 @@ -124,7 +124,7 @@ class F90Scanner(SCons.Scanner.Classic): nodes.append((sortkey, n)) nodes.sort() - nodes = map(lambda pair: pair[1], nodes) + nodes = [pair[1] for pair in nodes] return nodes def FortranScan(path_variable="FORTRANPATH"): diff --git a/src/engine/SCons/Scanner/FortranTests.py b/src/engine/SCons/Scanner/FortranTests.py index 570b565..0380e87 100644 --- a/src/engine/SCons/Scanner/FortranTests.py +++ b/src/engine/SCons/Scanner/FortranTests.py @@ -221,7 +221,7 @@ class DummyEnvironment: raise KeyError, "Dummy environment only has FORTRANPATH attribute." def has_key(self, key): - return self.Dictionary().has_key(key) + return key in self.Dictionary() def __getitem__(self,key): return self.Dictionary()[key] @@ -240,7 +240,7 @@ class DummyEnvironment: def subst_path(self, path, target=None, source=None, conv=None): if type(path) != type([]): path = [path] - return map(self.subst, path) + return list(map(self.subst, path)) def get_calculator(self): return None @@ -255,8 +255,8 @@ class DummyEnvironment: return self.fs.File(filename) def deps_match(self, deps, headers): - scanned = map(os.path.normpath, map(str, deps)) - expect = map(os.path.normpath, headers) + scanned = list(map(os.path.normpath, list(map(str, deps)))) + expect = list(map(os.path.normpath, headers)) self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned)) # define some tests: @@ -382,7 +382,7 @@ class FortranScannerTestCase10(unittest.TestCase): env.fs.chdir(env.Dir('')) path = s.path(env, dir) deps2 = s(env.File('#fff4.f'), env, path) - headers1 = map(test.workpath, ['include/f4.f']) + headers1 = list(map(test.workpath, ['include/f4.f'])) headers2 = ['include/f4.f'] deps_match(self, deps1, headers1) deps_match(self, deps2, headers2) diff --git a/src/engine/SCons/Scanner/IDLTests.py b/src/engine/SCons/Scanner/IDLTests.py index a454b31..26b3956 100644 --- a/src/engine/SCons/Scanner/IDLTests.py +++ b/src/engine/SCons/Scanner/IDLTests.py @@ -205,10 +205,10 @@ class DummyEnvironment: def subst_path(self, path, target=None, source=None, conv=None): if type(path) != type([]): path = [path] - return map(self.subst, path) + return list(map(self.subst, path)) def has_key(self, key): - return self.Dictionary().has_key(key) + return key in self.Dictionary() def __getitem__(self,key): return self.Dictionary()[key] @@ -238,8 +238,8 @@ if os.path.normcase('foo') == os.path.normcase('FOO'): my_normpath = os.path.normcase def deps_match(self, deps, headers): - scanned = map(my_normpath, map(str, deps)) - expect = map(my_normpath, headers) + scanned = list(map(my_normpath, list(map(str, deps)))) + expect = list(map(my_normpath, headers)) self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned)) # define some tests: @@ -329,7 +329,7 @@ class IDLScannerTestCase7(unittest.TestCase): env.fs.chdir(env.Dir('')) path = s.path(env, dir) deps2 = s(env.File('#t4.idl'), env, path) - headers1 = map(test.workpath, ['include/fa.idl', 'include/fb.idl']) + headers1 = list(map(test.workpath, ['include/fa.idl', 'include/fb.idl'])) headers2 = ['include/fa.idl', 'include/fb.idl'] deps_match(self, deps1, headers1) deps_match(self, deps2, headers2) diff --git a/src/engine/SCons/Scanner/LaTeX.py b/src/engine/SCons/Scanner/LaTeX.py index 17000a2..f3085d1 100644 --- a/src/engine/SCons/Scanner/LaTeX.py +++ b/src/engine/SCons/Scanner/LaTeX.py @@ -30,7 +30,6 @@ This module implements the dependency scanner for LaTeX code. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path -import string import re import SCons.Scanner @@ -60,11 +59,11 @@ def modify_env_var(env, var, abspath): 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 @@ -75,7 +74,7 @@ def modify_env_var(env, var, abspath): 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 @@ -231,7 +230,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] @@ -253,10 +252,10 @@ class LaTeX(SCons.Scanner.Base): 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) + #return map(lambda e: filename+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] return [filename] def sort_key(self, include): @@ -303,7 +302,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]) ) # @@ -368,7 +367,7 @@ class LaTeX(SCons.Scanner.Base): # nodes.sort() - nodes = map(lambda pair: pair[1], nodes) + nodes = [pair[1] for pair in nodes] return nodes # Local Variables: diff --git a/src/engine/SCons/Scanner/LaTeXTests.py b/src/engine/SCons/Scanner/LaTeXTests.py index e87a1aa..ac978cf 100644 --- a/src/engine/SCons/Scanner/LaTeXTests.py +++ b/src/engine/SCons/Scanner/LaTeXTests.py @@ -24,7 +24,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path -import string import sys import types import unittest @@ -88,7 +87,7 @@ class DummyEnvironment(UserDict.UserDict): def subst_path(self, path, target=None, source=None, conv=None): if type(path) != type([]): path = [path] - return map(self.subst, path) + return list(map(self.subst, path)) def get_calculator(self): return None @@ -109,8 +108,8 @@ else: def deps_match(self, deps, headers): global my_normpath - scanned = map(my_normpath, map(str, deps)) - expect = map(my_normpath, headers) + scanned = list(map(my_normpath, list(map(str, deps)))) + expect = list(map(my_normpath, headers)) self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned)) diff --git a/src/engine/SCons/Scanner/Prog.py b/src/engine/SCons/Scanner/Prog.py index bd7bffe..49e93a5 100644 --- a/src/engine/SCons/Scanner/Prog.py +++ b/src/engine/SCons/Scanner/Prog.py @@ -23,8 +23,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" -import string - import SCons.Node import SCons.Node.FS import SCons.Scanner @@ -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/src/engine/SCons/Scanner/ProgTests.py b/src/engine/SCons/Scanner/ProgTests.py index 7eaafcc..ee62ca7 100644 --- a/src/engine/SCons/Scanner/ProgTests.py +++ b/src/engine/SCons/Scanner/ProgTests.py @@ -24,7 +24,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path -import string import sys import types import unittest @@ -57,10 +56,10 @@ class DummyEnvironment: elif len(args) == 1: return self._dict[args[0]] else: - return map(lambda x, s=self: s._dict[x], args) + return [self._dict[x] for x in args] def has_key(self, key): - return self.Dictionary().has_key(key) + return key in self.Dictionary() def __getitem__(self,key): return self.Dictionary()[key] @@ -82,7 +81,7 @@ class DummyEnvironment: def subst_path(self, path, target=None, source=None, conv=None): if type(path) != type([]): path = [path] - return map(self.subst, path) + return list(map(self.subst, path)) def get_factory(self, factory): return factory or self.fs.File @@ -102,10 +101,10 @@ class DummyNode: return self.name def deps_match(deps, libs): - deps=map(str, deps) + deps=list(map(str, deps)) deps.sort() libs.sort() - return map(os.path.normpath, deps) == map(os.path.normpath, libs) + return list(map(os.path.normpath, deps)) == list(map(os.path.normpath, libs)) # define some tests: @@ -116,14 +115,14 @@ class ProgramScannerTestCase1(unittest.TestCase): s = SCons.Scanner.Prog.ProgramScanner() path = s.path(env) deps = s(DummyNode('dummy'), env, path) - assert deps_match(deps, ['l1.lib']), map(str, deps) + assert deps_match(deps, ['l1.lib']), list(map(str, deps)) env = DummyEnvironment(LIBPATH=[ test.workpath("") ], LIBS='l1') s = SCons.Scanner.Prog.ProgramScanner() path = s.path(env) deps = s(DummyNode('dummy'), env, path) - assert deps_match(deps, ['l1.lib']), map(str, deps) + assert deps_match(deps, ['l1.lib']), list(map(str, deps)) f1 = env.fs.File(test.workpath('f1')) env = DummyEnvironment(LIBPATH=[ test.workpath("") ], @@ -144,23 +143,23 @@ class ProgramScannerTestCase1(unittest.TestCase): class ProgramScannerTestCase2(unittest.TestCase): def runTest(self): - env = DummyEnvironment(LIBPATH=map(test.workpath, - ["", "d1", "d1/d2" ]), + env = DummyEnvironment(LIBPATH=list(map(test.workpath, + ["", "d1", "d1/d2" ])), LIBS=[ 'l1', 'l2', 'l3' ]) s = SCons.Scanner.Prog.ProgramScanner() path = s.path(env) deps = s(DummyNode('dummy'), env, path) - assert deps_match(deps, ['l1.lib', 'd1/l2.lib', 'd1/d2/l3.lib' ]), map(str, deps) + assert deps_match(deps, ['l1.lib', 'd1/l2.lib', 'd1/d2/l3.lib' ]), list(map(str, deps)) class ProgramScannerTestCase3(unittest.TestCase): def runTest(self): env = DummyEnvironment(LIBPATH=[test.workpath("d1/d2"), test.workpath("d1")], - LIBS=string.split('l2 l3')) + LIBS='l2 l3'.split()) s = SCons.Scanner.Prog.ProgramScanner() path = s.path(env) deps = s(DummyNode('dummy'), env, path) - assert deps_match(deps, ['d1/l2.lib', 'd1/d2/l3.lib']), map(str, deps) + assert deps_match(deps, ['d1/l2.lib', 'd1/d2/l3.lib']), list(map(str, deps)) class ProgramScannerTestCase5(unittest.TestCase): def runTest(self): @@ -171,11 +170,11 @@ class ProgramScannerTestCase5(unittest.TestCase): else: return arg env = SubstEnvironment(LIBPATH=[ "$blah" ], - LIBS=string.split('l2 l3')) + LIBS='l2 l3'.split()) s = SCons.Scanner.Prog.ProgramScanner() path = s.path(env) deps = s(DummyNode('dummy'), env, path) - assert deps_match(deps, [ 'd1/l2.lib' ]), map(str, deps) + assert deps_match(deps, [ 'd1/l2.lib' ]), list(map(str, deps)) class ProgramScannerTestCase6(unittest.TestCase): def runTest(self): @@ -186,7 +185,7 @@ class ProgramScannerTestCase6(unittest.TestCase): s = SCons.Scanner.Prog.ProgramScanner() path = s.path(env) deps = s(DummyNode('dummy'), env, path) - assert deps_match(deps, ['dir/libfoo.a', 'dir/sub/libbar.a', 'dir/libxyz.other']), map(str, deps) + assert deps_match(deps, ['dir/libfoo.a', 'dir/sub/libbar.a', 'dir/libxyz.other']), list(map(str, deps)) class ProgramScannerTestCase7(unittest.TestCase): def runTest(self): @@ -199,7 +198,7 @@ class ProgramScannerTestCase7(unittest.TestCase): s = SCons.Scanner.Prog.ProgramScanner() path = s.path(env) deps = s(DummyNode('dummy'), env, path) - assert deps_match(deps, ['dir/libfoo.a', 'dir/sub/libbar.a', 'dir/libxyz.other']), map(str, deps) + assert deps_match(deps, ['dir/libfoo.a', 'dir/sub/libbar.a', 'dir/libxyz.other']), list(map(str, deps)) class ProgramScannerTestCase8(unittest.TestCase): def runTest(self): @@ -239,7 +238,7 @@ def suite(): def runTest(self): env = DummyEnvironment(LIBPATH=[test.workpath("d1/d2"), test.workpath("d1")], - LIBS=string.split(u'l2 l3')) + LIBS=u'l2 l3'.split()) s = SCons.Scanner.Prog.ProgramScanner() path = s.path(env) deps = s(DummyNode('dummy'), env, path) diff --git a/src/engine/SCons/Scanner/RCTests.py b/src/engine/SCons/Scanner/RCTests.py index bf1048d..a20c919 100644 --- a/src/engine/SCons/Scanner/RCTests.py +++ b/src/engine/SCons/Scanner/RCTests.py @@ -88,10 +88,10 @@ class DummyEnvironment(UserDict.UserDict): def subst_path(self, path, target=None, source=None, conv=None): if type(path) != type([]): path = [path] - return map(self.subst, path) + return list(map(self.subst, path)) def has_key(self, key): - return self.Dictionary().has_key(key) + return key in self.Dictionary() def get_calculator(self): return None @@ -112,8 +112,8 @@ if os.path.normcase('foo') == os.path.normcase('FOO'): my_normpath = os.path.normcase def deps_match(self, deps, headers): - scanned = map(my_normpath, map(str, deps)) - expect = map(my_normpath, headers) + scanned = list(map(my_normpath, list(map(str, deps)))) + expect = list(map(my_normpath, headers)) scanned.sort() expect.sort() self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned)) diff --git a/src/engine/SCons/Scanner/ScannerTests.py b/src/engine/SCons/Scanner/ScannerTests.py index 518e0ed..d89fb14 100644 --- a/src/engine/SCons/Scanner/ScannerTests.py +++ b/src/engine/SCons/Scanner/ScannerTests.py @@ -20,6 +20,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -49,7 +50,7 @@ class DummyEnvironment(UserDict.UserDict): def subst_path(self, path, target=None, source=None, conv=None): if type(path) != type([]): path = [path] - return map(self.subst, path) + return list(map(self.subst, path)) def get_factory(self, factory): return factory or self.fs.File @@ -127,7 +128,7 @@ class BaseTestCase(unittest.TestCase): self.deps = deps path = scanner.path(env) scanned = scanner(filename, env, path) - scanned_strs = map(lambda x: str(x), scanned) + scanned_strs = [str(x) for x in scanned] self.failUnless(self.filename == filename, "the filename was passed incorrectly") self.failUnless(self.env == env, "the environment was passed incorrectly") @@ -280,7 +281,7 @@ class BaseTestCase(unittest.TestCase): "recursive = 1 didn't return all nodes: %s" % n) def odd_only(nodes): - return filter(lambda n: n % 2, nodes) + return [n for n in nodes if n % 2] s = SCons.Scanner.Base(function = self.func, recursive = odd_only) n = s.recurse_nodes(nodes) self.failUnless(n == [1, 3], @@ -595,7 +596,7 @@ def suite(): ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) return suite if __name__ == "__main__": diff --git a/src/engine/SCons/Scanner/__init__.py b/src/engine/SCons/Scanner/__init__.py index da82060..be08256 100644 --- a/src/engine/SCons/Scanner/__init__.py +++ b/src/engine/SCons/Scanner/__init__.py @@ -30,7 +30,6 @@ The Scanner package for the SCons software construction utility. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import re -import string import SCons.Node.FS import SCons.Util @@ -56,9 +55,9 @@ 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) @@ -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,7 +279,7 @@ 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() @@ -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 @@ -383,7 +382,7 @@ class Classic(Current): nodes.append((sortkey, n)) nodes.sort() - nodes = map(lambda pair: pair[1], nodes) + nodes = [pair[1] for pair in nodes] return nodes class ClassicCPP(Classic): @@ -408,7 +407,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/src/engine/SCons/Script/Interactive.py b/src/engine/SCons/Script/Interactive.py index 206f941..c546fc9 100644 --- a/src/engine/SCons/Script/Interactive.py +++ b/src/engine/SCons/Script/Interactive.py @@ -20,6 +20,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -90,7 +91,6 @@ import copy import os import re import shlex -import string import sys try: @@ -134,7 +134,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 +144,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 +222,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 @@ -307,7 +307,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 +318,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/src/engine/SCons/Script/Main.py b/src/engine/SCons/Script/Main.py index 082de34..7173f1b 100644 --- a/src/engine/SCons/Script/Main.py +++ b/src/engine/SCons/Script/Main.py @@ -33,12 +33,12 @@ it goes here. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import sys import time import traceback @@ -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. # @@ -208,7 +208,7 @@ class BuildTask(SCons.Taskmaster.OutOfDateTask): 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] + return str(obj.__class__).split('.')[-1] if classname(t) in ('File', 'Dir', 'Entry'): errstr="Do not know how to make %s target `%s' (%s)." % (classname(t), t, t.abspath) else: # Alias or Python or ... @@ -262,7 +262,7 @@ 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)) @@ -345,7 +345,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 +366,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)) @@ -414,7 +414,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,7 +425,7 @@ 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) @@ -469,9 +469,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): @@ -501,7 +501,7 @@ 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: @@ -514,12 +514,12 @@ class CountStats(Stats): 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))) + 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 keys: r = stats_table[k][:l] + [k] self.outfp.write(fmt2 % tuple(r)) @@ -563,7 +563,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] @@ -1087,7 +1087,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 +1122,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 ..." @@ -1224,7 +1224,7 @@ 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) @@ -1285,7 +1285,7 @@ def main(): pass parts.append(version_string("engine", SCons)) parts.append("__COPYRIGHT__") - version = string.join(parts, '') + version = ''.join(parts) import SConsOptions parser = SConsOptions.Parser(version) diff --git a/src/engine/SCons/Script/MainTests.py b/src/engine/SCons/Script/MainTests.py index 4fe760c..c44c426 100644 --- a/src/engine/SCons/Script/MainTests.py +++ b/src/engine/SCons/Script/MainTests.py @@ -42,7 +42,7 @@ if __name__ == "__main__": tclasses = [] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Script/SConsOptions.py b/src/engine/SCons/Script/SConsOptions.py index 1ffcc83..0f364d6 100644 --- a/src/engine/SCons/Script/SConsOptions.py +++ b/src/engine/SCons/Script/SConsOptions.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import optparse import re -import string import sys import textwrap @@ -55,9 +54,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': @@ -168,7 +168,7 @@ class SConsValues(optparse.Values): 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'): + 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. @@ -197,7 +197,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): @@ -292,7 +292,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 +356,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 +461,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 +473,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 +489,7 @@ class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter): else: opts = long_opts + short_opts - return string.join(opts, ", ") + return ", ".join(opts) def Parser(version): """ @@ -580,7 +580,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", @@ -623,7 +623,7 @@ def Parser(version): 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 +654,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 +802,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 +816,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 +846,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/src/engine/SCons/Script/SConscript.py b/src/engine/SCons/Script/SConscript.py index a34278a..1021921 100644 --- a/src/engine/SCons/Script/SConscript.py +++ b/src/engine/SCons/Script/SConscript.py @@ -27,6 +27,7 @@ files. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -48,7 +49,6 @@ import SCons.Util import os import os.path import re -import string import sys import traceback import types @@ -145,7 +145,7 @@ 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 @@ -312,7 +312,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,7 +334,7 @@ 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?! @@ -369,7 +369,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: @@ -396,11 +396,11 @@ class SConsEnvironment(SCons.Environment.Base): 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: @@ -459,7 +459,7 @@ class SConsEnvironment(SCons.Environment.Base): if not SCons.Script.sconscript_reading: raise SCons.Errors.UserError, "Calling Configure from Builders is not supported." kw['_depth'] = kw.get('_depth', 0) + 1 - return 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 +484,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,7 +520,7 @@ 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] @@ -530,11 +530,11 @@ class SConsEnvironment(SCons.Environment.Base): def SConscript(self, *ls, **kw): 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 +550,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 @@ -569,7 +569,7 @@ def Configure(*args, **kw): if not SCons.Script.sconscript_reading: raise SCons.Errors.UserError, "Calling Configure from Builders is not supported." kw['_depth'] = 1 - return 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() @@ -613,7 +613,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(): diff --git a/src/engine/SCons/Script/__init__.py b/src/engine/SCons/Script/__init__.py index 18ef114..7763210 100644 --- a/src/engine/SCons/Script/__init__.py +++ b/src/engine/SCons/Script/__init__.py @@ -40,7 +40,6 @@ import time start_time = time.time() import os -import string import sys import UserList @@ -58,7 +57,7 @@ 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 @@ -211,7 +210,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/src/engine/SCons/Subst.py b/src/engine/SCons/Subst.py index f3b4168..936348a 100644 --- a/src/engine/SCons/Subst.py +++ b/src/engine/SCons/Subst.py @@ -26,11 +26,11 @@ SCons string substitution. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import re -import string import types import UserList import UserString @@ -50,7 +50,7 @@ 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__ @@ -152,7 +152,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,7 +162,7 @@ def escape_list(list, escape_func): return obj else: return e(escape_func) - return map(escape, list) + return list(map(escape, mylist)) class NLWrapper: """A wrapper class that delays turning a list of sources or targets @@ -183,14 +183,14 @@ 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 @@ -344,7 +344,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,7 +399,7 @@ 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 type(strSubst) == types.StringType and strSubst.find('$') < 0: return strSubst class StringSubber: @@ -438,7 +438,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 +450,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 +472,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'], @@ -523,7 +523,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 +540,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 +571,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: @@ -619,9 +619,9 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv 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 +653,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 +665,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 +680,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() @@ -834,7 +834,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 +870,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 type(strSubst) == types.StringType and strSubst.find('$') < 0: return strSubst matchlist = ['$' + key, '${' + key + '}'] @@ -880,7 +880,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/src/engine/SCons/SubstTests.py b/src/engine/SCons/SubstTests.py index 0dda3a2..6ef15cf 100644 --- a/src/engine/SCons/SubstTests.py +++ b/src/engine/SCons/SubstTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import StringIO import sys import types @@ -101,7 +100,7 @@ if os.sep == '/': return str else: def cvt(str): - return string.replace(str, '/', os.sep) + return str.replace('/', os.sep) class SubstTestCase(unittest.TestCase): class MyNode(DummyNode): @@ -242,7 +241,7 @@ class SubstTestCase(unittest.TestCase): input, expect = cases[:2] expect = convert(expect) try: - result = apply(function, (input, env), kwargs) + result = function(input, env, **kwargs) except Exception, e: fmt = " input %s generated %s (%s)" print fmt % (repr(input), e.__class__.__name__, repr(e)) @@ -798,7 +797,7 @@ class scons_subst_list_TestCase(SubstTestCase): def test_scons_subst_list(self): """Test scons_subst_list(): basic substitution""" def convert_lists(expect): - return map(lambda l: map(cvt, l), expect) + return [list(map(cvt, l)) for l in expect] return self.basic_comparisons(scons_subst_list, convert_lists) subst_list_cases = [ @@ -1181,11 +1180,11 @@ class subst_dict_TestCase(unittest.TestCase): s1 = DummyNode('s1') s2 = DummyNode('s2') d = subst_dict(target=[t1, t2], source=[s1, s2]) - TARGETS = map(lambda x: str(x), d['TARGETS']) + TARGETS = [str(x) for x in d['TARGETS']] TARGETS.sort() assert TARGETS == ['t1', 't2'], d['TARGETS'] assert str(d['TARGET']) == 't1', d['TARGET'] - SOURCES = map(lambda x: str(x), d['SOURCES']) + SOURCES = [str(x) for x in d['SOURCES']] SOURCES.sort() assert SOURCES == ['s1', 's2'], d['SOURCES'] assert str(d['SOURCE']) == 's1', d['SOURCE'] @@ -1210,10 +1209,10 @@ class subst_dict_TestCase(unittest.TestCase): s4 = N('s4') s5 = V('s5') d = subst_dict(target=[t3, t4, t5], source=[s3, s4, s5]) - TARGETS = map(lambda x: str(x), d['TARGETS']) + TARGETS = [str(x) for x in d['TARGETS']] TARGETS.sort() assert TARGETS == ['t4', 'v-t3', 'v-t5'], TARGETS - SOURCES = map(lambda x: str(x), d['SOURCES']) + SOURCES = [str(x) for x in d['SOURCES']] SOURCES.sort() assert SOURCES == ['s3', 'v-rstr-s4', 'v-s5'], SOURCES @@ -1231,7 +1230,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Taskmaster.py b/src/engine/SCons/Taskmaster.py index c123ca5..66bcdfa 100644 --- a/src/engine/SCons/Taskmaster.py +++ b/src/engine/SCons/Taskmaster.py @@ -20,6 +20,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __doc__ = """ Generic Taskmaster module for the SCons build engine. @@ -52,7 +53,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" from itertools import chain import operator -import string import sys import traceback @@ -1001,14 +1001,14 @@ class Taskmaster: # 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 = [t for t in nclist if t[1] or t[0].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,7 +1017,7 @@ 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" % \ diff --git a/src/engine/SCons/TaskmasterTests.py b/src/engine/SCons/TaskmasterTests.py index 7137967..4a0e13a 100644 --- a/src/engine/SCons/TaskmasterTests.py +++ b/src/engine/SCons/TaskmasterTests.py @@ -660,7 +660,7 @@ class TaskmasterTestCase(unittest.TestCase): t = tm.next_task() assert t.targets == [n1], t.targets t.fail_stop() - assert t.targets == [n3], map(str, t.targets) + assert t.targets == [n3], list(map(str, t.targets)) assert t.top == 1, t.top def test_stop(self): diff --git a/src/engine/SCons/Tool/FortranCommon.py b/src/engine/SCons/Tool/FortranCommon.py index 2863f18..f2c828c 100644 --- a/src/engine/SCons/Tool/FortranCommon.py +++ b/src/engine/SCons/Tool/FortranCommon.py @@ -30,7 +30,6 @@ Stuff for processing Fortran, common to all fortran dialects. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Tool/JavaCommon.py b/src/engine/SCons/Tool/JavaCommon.py index cc2c536..1dfeefb 100644 --- a/src/engine/SCons/Tool/JavaCommon.py +++ b/src/engine/SCons/Tool/JavaCommon.py @@ -32,7 +32,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path import re -import string java_parsing = 1 @@ -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) @@ -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/src/engine/SCons/Tool/JavaCommonTests.py b/src/engine/SCons/Tool/JavaCommonTests.py index 92649b2..76944c1 100644 --- a/src/engine/SCons/Tool/JavaCommonTests.py +++ b/src/engine/SCons/Tool/JavaCommonTests.py @@ -569,7 +569,7 @@ if __name__ == "__main__": tclasses = [ parse_javaTestCase ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Tool/MSCommon/common.py b/src/engine/SCons/Tool/MSCommon/common.py index bb13e9b..3e9f62c 100644 --- a/src/engine/SCons/Tool/MSCommon/common.py +++ b/src/engine/SCons/Tool/MSCommon/common.py @@ -113,7 +113,7 @@ def normalize_env(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: normenv[k] = os.environ[k].encode('mbcs') return normenv @@ -149,7 +149,7 @@ def parse_output(output, keep = ("INCLUDE", "LIB", "LIBPATH", "PATH")): # 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/src/engine/SCons/Tool/MSCommon/netframework.py b/src/engine/SCons/Tool/MSCommon/netframework.py index 8fee916..c5f2880 100644 --- a/src/engine/SCons/Tool/MSCommon/netframework.py +++ b/src/engine/SCons/Tool/MSCommon/netframework.py @@ -20,6 +20,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -28,7 +29,6 @@ __doc__ = """ import os import re -import string from common import read_reg, debug @@ -58,14 +58,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/src/engine/SCons/Tool/MSCommon/sdk.py b/src/engine/SCons/Tool/MSCommon/sdk.py index fcf07a0..dc07192 100644 --- a/src/engine/SCons/Tool/MSCommon/sdk.py +++ b/src/engine/SCons/Tool/MSCommon/sdk.py @@ -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,7 +310,7 @@ 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 get_installed_sdks() @@ -328,13 +328,13 @@ 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) @@ -343,7 +343,7 @@ def mssdk_setup_env(env): 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/src/engine/SCons/Tool/MSCommon/vs.py b/src/engine/SCons/Tool/MSCommon/vs.py index b113340..264166f 100644 --- a/src/engine/SCons/Tool/MSCommon/vs.py +++ b/src/engine/SCons/Tool/MSCommon/vs.py @@ -385,7 +385,7 @@ 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 get_installed_visual_studios() @@ -415,15 +415,15 @@ def get_default_version(env): version: str the default version. """ - if not env.has_key('MSVS') or not SCons.Util.is_Dict(env['MSVS']): + if 'MSVS' not in env 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()) + 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: @@ -475,7 +475,7 @@ def msvs_setup_env(env): 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) + vscommonvarnames = [vs.common_tools_var for vs in msvs_list] nenv = normalize_env(env['ENV'], vscommonvarnames + ['COMSPEC']) output = get_output(batfilename, arch, env=nenv) vars = parse_output(output, vars) @@ -489,7 +489,7 @@ def query_versions(): 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/src/engine/SCons/Tool/PharLapCommon.py b/src/engine/SCons/Tool/PharLapCommon.py index ca19b8a..dc124b5 100644 --- a/src/engine/SCons/Tool/PharLapCommon.py +++ b/src/engine/SCons/Tool/PharLapCommon.py @@ -36,7 +36,6 @@ 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 @@ -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/src/engine/SCons/Tool/ToolTests.py b/src/engine/SCons/Tool/ToolTests.py index adcd40a..723ae56 100644 --- a/src/engine/SCons/Tool/ToolTests.py +++ b/src/engine/SCons/Tool/ToolTests.py @@ -45,8 +45,10 @@ class ToolTestCase(unittest.TestCase): return self.dict[key] def __setitem__(self, key, val): self.dict[key] = val + def __contains__(self, key): + return self.dict.__contains__(key) def has_key(self, key): - return self.dict.has_key(key) + return key in self.dict env = Environment() env['BUILDERS'] = {} env['ENV'] = {} diff --git a/src/engine/SCons/Tool/__init__.py b/src/engine/SCons/Tool/__init__.py index 910e6a1..b22fb59 100644 --- a/src/engine/SCons/Tool/__init__.py +++ b/src/engine/SCons/Tool/__init__.py @@ -35,6 +35,7 @@ tool definition. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -170,7 +171,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 +179,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 @@ -474,7 +475,7 @@ class ToolInitializerMethod: builder = self.get_builder(env) if builder is None: return [], [] - return apply(builder, args, kw) + return builder(*args, **kw) class ToolInitializer: """ @@ -530,9 +531,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 +547,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): @@ -666,7 +667,7 @@ def tool_list(platform, env): 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/src/engine/SCons/Tool/bcc32.py b/src/engine/SCons/Tool/bcc32.py index 023ad22..55f871b 100644 --- a/src/engine/SCons/Tool/bcc32.py +++ b/src/engine/SCons/Tool/bcc32.py @@ -31,7 +31,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import SCons.Defaults import SCons.Tool diff --git a/src/engine/SCons/Tool/cc.py b/src/engine/SCons/Tool/cc.py index da169fe..9b404b2 100644 --- a/src/engine/SCons/Tool/cc.py +++ b/src/engine/SCons/Tool/cc.py @@ -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/src/engine/SCons/Tool/dmd.py b/src/engine/SCons/Tool/dmd.py index 4429d4a..d7156dd 100644 --- a/src/engine/SCons/Tool/dmd.py +++ b/src/engine/SCons/Tool/dmd.py @@ -57,7 +57,6 @@ Lib tool variables: __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Tool/dvipdf.py b/src/engine/SCons/Tool/dvipdf.py index 80a4b07..ef4d1ee 100644 --- a/src/engine/SCons/Tool/dvipdf.py +++ b/src/engine/SCons/Tool/dvipdf.py @@ -30,6 +30,7 @@ selection method. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -88,7 +89,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/src/engine/SCons/Tool/filesystem.py b/src/engine/SCons/Tool/filesystem.py index 4cecb12..31c8abc 100644 --- a/src/engine/SCons/Tool/filesystem.py +++ b/src/engine/SCons/Tool/filesystem.py @@ -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/src/engine/SCons/Tool/fortran.py b/src/engine/SCons/Tool/fortran.py index b944ca2..26c6ff5 100644 --- a/src/engine/SCons/Tool/fortran.py +++ b/src/engine/SCons/Tool/fortran.py @@ -34,7 +34,6 @@ selection method. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import re -import string import SCons.Action import SCons.Defaults diff --git a/src/engine/SCons/Tool/gs.py b/src/engine/SCons/Tool/gs.py index 591eef0..ada169a 100644 --- a/src/engine/SCons/Tool/gs.py +++ b/src/engine/SCons/Tool/gs.py @@ -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/src/engine/SCons/Tool/hpc++.py b/src/engine/SCons/Tool/hpc++.py index e1a0040..2b8ed3f 100644 --- a/src/engine/SCons/Tool/hpc++.py +++ b/src/engine/SCons/Tool/hpc++.py @@ -34,7 +34,6 @@ selection method. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Tool/icl.py b/src/engine/SCons/Tool/icl.py index 2d1636e..caa2281 100644 --- a/src/engine/SCons/Tool/icl.py +++ b/src/engine/SCons/Tool/icl.py @@ -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/src/engine/SCons/Tool/ifl.py b/src/engine/SCons/Tool/ifl.py index 88dcf59..30b3672 100644 --- a/src/engine/SCons/Tool/ifl.py +++ b/src/engine/SCons/Tool/ifl.py @@ -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/src/engine/SCons/Tool/ifort.py b/src/engine/SCons/Tool/ifort.py index e4165de..4b2fd65 100644 --- a/src/engine/SCons/Tool/ifort.py +++ b/src/engine/SCons/Tool/ifort.py @@ -34,8 +34,6 @@ selection method. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" -import string - import SCons.Defaults from SCons.Scanner.Fortran import FortranScan from FortranCommon import add_all_to_env @@ -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/src/engine/SCons/Tool/install.py b/src/engine/SCons/Tool/install.py index 06bcfdd..abdd479 100644 --- a/src/engine/SCons/Tool/install.py +++ b/src/engine/SCons/Tool/install.py @@ -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 @@ -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/src/engine/SCons/Tool/intelc.py b/src/engine/SCons/Tool/intelc.py index 2cd38bb..e193695 100644 --- a/src/engine/SCons/Tool/intelc.py +++ b/src/engine/SCons/Tool/intelc.py @@ -38,7 +38,7 @@ 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' @@ -406,7 +406,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 +445,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/src/engine/SCons/Tool/ipkg.py b/src/engine/SCons/Tool/ipkg.py index 10fbc98..8e0940a 100644 --- a/src/engine/SCons/Tool/ipkg.py +++ b/src/engine/SCons/Tool/ipkg.py @@ -36,7 +36,6 @@ packages fake_root. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os -import string import SCons.Builder @@ -56,8 +55,8 @@ def generate(env): # 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/src/engine/SCons/Tool/javac.py b/src/engine/SCons/Tool/javac.py index 78d641a..d080af5 100644 --- a/src/engine/SCons/Tool/javac.py +++ b/src/engine/SCons/Tool/javac.py @@ -30,12 +30,12 @@ selection method. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import SCons.Action import SCons.Builder @@ -45,7 +45,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,20 +67,19 @@ 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) + def visit(arg, dirname, names, dirnode=entry.rdir()): + java_files = [n for n in names if _my_normcase(n[-len(js):]) == js] # 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) + java_paths = [mydir.File(f) for f in java_files] for jp in java_paths: arg[jp] = True @@ -156,8 +155,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 +193,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/src/engine/SCons/Tool/javah.py b/src/engine/SCons/Tool/javah.py index dda5ebb..c092273 100644 --- a/src/engine/SCons/Tool/javah.py +++ b/src/engine/SCons/Tool/javah.py @@ -34,7 +34,6 @@ selection method. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Tool/lex.py b/src/engine/SCons/Tool/lex.py index dd7fe25..280c768 100644 --- a/src/engine/SCons/Tool/lex.py +++ b/src/engine/SCons/Tool/lex.py @@ -35,8 +35,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" 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/src/engine/SCons/Tool/midl.py b/src/engine/SCons/Tool/midl.py index bf1f2ac..64b927a 100644 --- a/src/engine/SCons/Tool/midl.py +++ b/src/engine/SCons/Tool/midl.py @@ -33,8 +33,6 @@ selection method. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" -import string - import SCons.Action import SCons.Builder import SCons.Defaults @@ -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/src/engine/SCons/Tool/mingw.py b/src/engine/SCons/Tool/mingw.py index da8a59e..8d40a0b 100644 --- a/src/engine/SCons/Tool/mingw.py +++ b/src/engine/SCons/Tool/mingw.py @@ -35,7 +35,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import SCons.Action import SCons.Builder diff --git a/src/engine/SCons/Tool/mslink.py b/src/engine/SCons/Tool/mslink.py index 5daae51..b1ba1df 100644 --- a/src/engine/SCons/Tool/mslink.py +++ b/src/engine/SCons/Tool/mslink.py @@ -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 @@ -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,7 +179,7 @@ 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] diff --git a/src/engine/SCons/Tool/msvc.py b/src/engine/SCons/Tool/msvc.py index 920ac7c..fde93ea 100644 --- a/src/engine/SCons/Tool/msvc.py +++ b/src/engine/SCons/Tool/msvc.py @@ -35,7 +35,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path import re -import string import sys import SCons.Action @@ -55,8 +54,8 @@ 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'): + 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'] @@ -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/src/engine/SCons/Tool/msvs.py b/src/engine/SCons/Tool/msvs.py index f43dd94..57098a8 100644 --- a/src/engine/SCons/Tool/msvs.py +++ b/src/engine/SCons/Tool/msvs.py @@ -30,6 +30,7 @@ selection method. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -39,7 +40,6 @@ import ntpath import os import pickle import re -import string import sys import SCons.Builder @@ -57,23 +57,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 +75,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 +101,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 @@ -161,7 +146,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 @@ -188,7 +173,7 @@ class _DSPGenerator: else: self.dspabs = get_abspath() - if not env.has_key('variant'): + if 'variant' not in env: raise SCons.Errors.InternalError, \ "You must specify a 'variant' argument (i.e. 'Debug' or " +\ "'Release') to create an MSVSProject." @@ -197,7 +182,7 @@ class _DSPGenerator: 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']] @@ -219,7 +204,7 @@ 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']] @@ -241,7 +226,7 @@ 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']] @@ -269,7 +254,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 +274,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]]: @@ -308,7 +293,7 @@ class _DSPGenerator: 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))) + self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower())) def AddConfig(self, variant, buildtarget, outdir, runfile, cmdargs, dspfile=dspfile): config = Config() @@ -399,7 +384,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 @@ -409,7 +394,7 @@ class _GenerateV6DSP(_DSPGenerator): '# 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') @@ -462,7 +447,7 @@ class _GenerateV6DSP(_DSPGenerator): 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.sort(lambda a, b: cmp(a.lower(), b.lower())) for kind in cats: if not self.sources[kind]: continue # skip empty groups @@ -470,7 +455,7 @@ class _GenerateV6DSP(_DSPGenerator): 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]: @@ -495,7 +480,7 @@ class _GenerateV6DSP(_DSPGenerator): 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() @@ -674,7 +659,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 @@ -690,8 +675,8 @@ class _GenerateV7DSP(_DSPGenerator): # 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'] @@ -721,7 +706,7 @@ class _GenerateV7DSP(_DSPGenerator): 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.sort(lambda a, b: cmp(a[0].lower(), b[0].lower())) # First folders, then files for key, value in sorteditems: @@ -754,8 +739,8 @@ class _GenerateV7DSP(_DSPGenerator): 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.sort(lambda a, b: cmp(a.lower(), b.lower())) + cats = [k for k in cats if self.sources[k]] for kind in cats: if len(cats) > 1: self.file.write('\t\t<Filter\n' @@ -767,14 +752,14 @@ class _GenerateV7DSP(_DSPGenerator): # First remove any common prefix commonprefix = None if len(sources) > 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] ) @@ -805,7 +790,7 @@ class _GenerateV7DSP(_DSPGenerator): while line: # TODO(1.5) #if line.find('<!-- SCons Data:') > -1: - if string.find(line, '<!-- SCons Data:') > -1: + if line.find('<!-- SCons Data:') > -1: break line = dspfile.readline() @@ -860,7 +845,7 @@ class _DSWGenerator: self.dswfile = os.path.normpath(str(dswfile)) self.env = env - if not env.has_key('projects'): + if 'projects' not in env: raise SCons.Errors.UserError, \ "You must specify a 'projects' argument to create an MSVSSolution." projects = env['projects'] @@ -871,9 +856,9 @@ class _DSWGenerator: if len(projects) < 1: raise SCons.Errors.UserError, \ "You must specify at least one project to create an MSVSSolution." - self.dspfiles = map(str, projects) + self.dspfiles = list(map(str, projects)) - 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.dswfile)[0]) @@ -898,7 +883,7 @@ class _GenerateV7DSW(_DSWGenerator): if self.version_num >= 8.0: self.versionstr = '9.00' - if env.has_key('slnguid') and env['slnguid']: + if 'slnguid' in env and env['slnguid']: self.slnguid = env['slnguid'] else: self.slnguid = _generateGUID(dswfile, self.name) @@ -906,7 +891,7 @@ class _GenerateV7DSW(_DSWGenerator): 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.dswfile): @@ -926,7 +911,7 @@ class _GenerateV7DSW(_DSWGenerator): self.configs[variant] = config print "Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dswfile) + "'" - if not env.has_key('variant'): + if 'variant' not in env: raise SCons.Errors.InternalError, \ "You must specify a 'variant' argument (i.e. 'Debug' or " +\ "'Release') to create an MSVS Solution File." @@ -992,11 +977,11 @@ class _GenerateV7DSW(_DSWGenerator): self.file.write('Global\n') env = self.env - if env.has_key('MSVS_SCC_PROVIDER'): + if 'MSVS_SCC_PROVIDER' in env: dspfile_base = os.path.basename(self.dspfile) slnguid = self.slnguid scc_provider = env.get('MSVS_SCC_PROVIDER', '') - scc_provider = string.replace(scc_provider, ' ', r'\u0020') + scc_provider = scc_provider.replace(' ', r'\u0020') scc_project_name = env.get('MSVS_SCC_PROJECT_NAME', '') # scc_aux_path = env.get('MSVS_SCC_AUX_PATH', '') scc_local_path = env.get('MSVS_SCC_LOCAL_PATH', '') @@ -1136,7 +1121,7 @@ def GenerateDSP(dspfile, source, env): """Generates a Project file based on the version of MSVS that is being used""" version_num = 6.0 - if env.has_key('MSVS_VERSION'): + if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) if version_num >= 7.0: g = _GenerateV7DSP(dspfile, source, env) @@ -1149,7 +1134,7 @@ def GenerateDSW(dswfile, source, env): """Generates a Solution/Workspace file based on the version of MSVS that is being used""" version_num = 6.0 - if env.has_key('MSVS_VERSION'): + if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) if version_num >= 7.0: g = _GenerateV7DSW(dswfile, source, env) @@ -1225,7 +1210,7 @@ def projectEmitter(target, source, env): source = source + env.subst('$MSVSSCONSCOM', 1) source = source + env.subst('$MSVSENCODING', 1) - if env.has_key('buildtarget') and env['buildtarget'] != None: + if 'buildtarget' in env and env['buildtarget'] != None: if SCons.Util.is_String(env['buildtarget']): source = source + ' "%s"' % env['buildtarget'] elif SCons.Util.is_List(env['buildtarget']): @@ -1241,7 +1226,7 @@ def projectEmitter(target, source, env): except AttributeError: raise SCons.Errors.InternalError, \ "buildtarget can be a string, a node, a list of strings or nodes, or None" - if env.has_key('outdir') and env['outdir'] != None: + if 'outdir' in env and env['outdir'] != None: if SCons.Util.is_String(env['outdir']): source = source + ' "%s"' % env['outdir'] elif SCons.Util.is_List(env['outdir']): @@ -1257,13 +1242,13 @@ def projectEmitter(target, source, env): except AttributeError: raise SCons.Errors.InternalError, \ "outdir can be a string, a node, a list of strings or nodes, or None" - if env.has_key('name'): + if 'name' in env: if SCons.Util.is_String(env['name']): source = source + ' "%s"' % env['name'] else: raise SCons.Errors.InternalError, "name must be a string" - if env.has_key('variant'): + if 'variant' in env: if SCons.Util.is_String(env['variant']): source = source + ' "%s"' % env['variant'] elif SCons.Util.is_List(env['variant']): @@ -1278,7 +1263,7 @@ def projectEmitter(target, source, env): raise SCons.Errors.InternalError, "variant must be specified" for s in _DSPGenerator.srcargs: - if env.has_key(s): + if s in env: if SCons.Util.is_String(env[s]): source = source + ' "%s' % env[s] elif SCons.Util.is_List(env[s]): @@ -1320,13 +1305,13 @@ def solutionEmitter(target, source, env): if not source: source = 'sln_inputs:' - if env.has_key('name'): + if 'name' in env: if SCons.Util.is_String(env['name']): source = source + ' "%s"' % env['name'] else: raise SCons.Errors.InternalError, "name must be a string" - if env.has_key('variant'): + if 'variant' in env: if SCons.Util.is_String(env['variant']): source = source + ' "%s"' % env['variant'] elif SCons.Util.is_List(env['variant']): @@ -1340,13 +1325,13 @@ def solutionEmitter(target, source, env): else: raise SCons.Errors.InternalError, "variant must be specified" - if env.has_key('slnguid'): + if 'slnguid' in env: if SCons.Util.is_String(env['slnguid']): source = source + ' "%s"' % env['slnguid'] else: raise SCons.Errors.InternalError, "slnguid must be a string" - if env.has_key('projects'): + if 'projects' in env: if SCons.Util.is_String(env['projects']): source = source + ' "%s"' % env['projects'] elif SCons.Util.is_List(env['projects']): @@ -1410,11 +1395,11 @@ def generate(env): # Set-up ms tools paths for default version msvc_setup_env_once(env) - if env.has_key('MSVS_VERSION'): + if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) else: (version_num, suite) = (7.0, None) # guess at a default - if not env.has_key('MSVS'): + if 'MSVS' not in env: env['MSVS'] = {} if (version_num < 7.0): env['MSVS']['PROJECTSUFFIX'] = '.dsp' diff --git a/src/engine/SCons/Tool/msvsTests.py b/src/engine/SCons/Tool/msvsTests.py index 0f88ad3..00d4754 100644 --- a/src/engine/SCons/Tool/msvsTests.py +++ b/src/engine/SCons/Tool/msvsTests.py @@ -24,7 +24,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os -import string import sys import TestCmd import unittest @@ -39,7 +38,7 @@ from SCons.Tool.MSCommon.common import debug from SCons.Tool.MSCommon import get_default_version, \ query_versions -regdata_6a = string.split(r'''[HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio] +regdata_6a = r'''[HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio] [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\6.0] [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\6.0\ServicePacks] "sp3"="" @@ -49,9 +48,9 @@ regdata_6a = string.split(r'''[HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudi "ProductDir"="C:\Program Files\Microsoft Visual Studio\MSDN98\98VSa\1033" [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++] "ProductDir"="C:\Program Files\Microsoft Visual Studio\VC98" -''','\n') +'''.split('\n') -regdata_6b = string.split(r'''[HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio] +regdata_6b = r'''[HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio] [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\6.0] "InstallDir"="C:\VS6\Common\IDE\IDE98" [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\6.0\ServicePacks] @@ -68,9 +67,9 @@ regdata_6b = string.split(r'''[HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudi [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\6.0\Setup\Microsoft VSEE Client] "ProductDir"="C:\VS6\Common\Tools" [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\6.0\Setup\Visual Studio 98] -''','\n') +'''.split('\n') -regdata_7 = string.split(r''' +regdata_7 = r''' [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\7.0] "InstallDir"="C:\Program Files\Microsoft Visual Studio .NET\Common7\IDE\" "Source Directories"="C:\Program Files\Microsoft Visual Studio .NET\Vc7\crt\;C:\Program Files\Microsoft Visual Studio .NET\Vc7\atlmfc\src\mfc\;C:\Program Files\Microsoft Visual Studio .NET\Vc7\atlmfc\src\atl\" @@ -134,9 +133,9 @@ regdata_7 = string.split(r''' "Include Dirs"="$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(VCInstallDir)PlatformSDK\include\prerelease;$(VCInstallDir)PlatformSDK\include;$(FrameworkSDKDir)include" "Source Dirs"="$(VCInstallDir)atlmfc\src\mfc;$(VCInstallDir)atlmfc\src\atl;$(VCInstallDir)crt\src" "Reference Dirs"="" -''','\n') +'''.split('\n') -regdata_7_1 = string.split(r''' +regdata_7_1 = r''' [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\7.1] @="" "Source Directories"="C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\crt\src\;C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\atlmfc\src\mfc\;C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\atlmfc\src\atl\" @@ -240,9 +239,9 @@ regdata_7_1 = string.split(r''' "VCManagedWrapperGeneratorTool"="" "VCAuxiliaryManagedWrapperGeneratorTool"="" "VCPrimaryInteropTool"="" -''','\n') +'''.split('\n') -regdata_8exp = string.split(r''' +regdata_8exp = r''' [HKEY_LOCAL_MACHINE\Software\Microsoft\VCExpress\8.0] "CLR Version"="v2.0.50727" "ApplicationID"="VCExpress" @@ -284,9 +283,9 @@ regdata_8exp = string.split(r''' "VCXMLDataGeneratorTool"="*.xsd" "VCManifestTool"="*.manifest" "VCXDCMakeTool"="*.xdc" -''','\n') +'''.split('\n') -regdata_80 = string.split(r''' +regdata_80 = r''' [HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\8.0] "CLR Version"="v2.0.50727" "ApplicationID"="VisualStudio" @@ -346,13 +345,13 @@ regdata_80 = string.split(r''' "VCXMLDataGeneratorTool"="*.xsd" "VCManifestTool"="*.manifest" "VCXDCMakeTool"="*.xdc" -''','\n') +'''.split('\n') -regdata_cv = string.split(r'''[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion] +regdata_cv = r'''[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion] "ProgramFilesDir"="C:\Program Files" "CommonFilesDir"="C:\Program Files\Common Files" "MediaPath"="C:\WINDOWS\Media" -''','\n') +'''.split('\n') regdata_none = [] @@ -376,7 +375,7 @@ class DummyEnv: return self.dict[key] def has_key(self,name): - return self.dict.has_key(name) + return name in self.dict class RegKey: """key class for storing an 'open' registry key""" @@ -395,7 +394,7 @@ class RegNode: self.name = name def value(self,val): - if self.valdict.has_key(val): + if val in self.valdict: return (self.valdict[val],1) else: raise SCons.Util.RegError @@ -428,13 +427,13 @@ class RegNode: raise SCons.Util.RegError def addKey(self,name,sep = '\\'): - if string.find(name, sep) != -1: - keyname, subkeys = string.split(name, sep, 1) + if name.find(sep) != -1: + keyname, subkeys = name.split(sep, 1) else: keyname = name subkeys = "" - if not self.keydict.has_key(keyname): + if keyname not in self.keydict: self.keydict[keyname] = RegNode(keyname) self.keyarray.append(keyname) @@ -739,7 +738,7 @@ if __name__ == "__main__": for k in ['VS71COMNTOOLS', 'VS80COMNTOOLS', 'VS90COMNTOOLS']: - if os.environ.has_key(k): + if k in os.environ: del os.environ[k] suite = unittest.makeSuite(test_class, 'test_') diff --git a/src/engine/SCons/Tool/mwcc.py b/src/engine/SCons/Tool/mwcc.py index e83043f..c720956 100644 --- a/src/engine/SCons/Tool/mwcc.py +++ b/src/engine/SCons/Tool/mwcc.py @@ -34,7 +34,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import SCons.Util @@ -80,8 +79,8 @@ def set_vars(env): ENV['CWFolder'] = version.path ENV['LM_LICENSE_FILE'] = version.license plus = lambda x: '+%s' % x - ENV['MWCIncludes'] = string.join(map(plus, version.includes), os.pathsep) - ENV['MWLibraries'] = string.join(map(plus, version.libs), os.pathsep) + ENV['MWCIncludes'] = os.pathsep.join(map(plus, version.includes)) + ENV['MWLibraries'] = os.pathsep.join(map(plus, version.libs)) return 1 diff --git a/src/engine/SCons/Tool/packaging/__init__.py b/src/engine/SCons/Tool/packaging/__init__.py index c4ae170..b80f128 100644 --- a/src/engine/SCons/Tool/packaging/__init__.py +++ b/src/engine/SCons/Tool/packaging/__init__.py @@ -25,6 +25,7 @@ SCons Packaging Tool. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -105,16 +106,16 @@ def Package(env, target=None, source=None, **kw): kw['PACKAGETYPE'] = GetOption('package_type') if kw['PACKAGETYPE'] == None: - if env['BUILDERS'].has_key('Tar'): + if 'Tar' in env['BUILDERS']: kw['PACKAGETYPE']='targz' - elif env['BUILDERS'].has_key('Zip'): + elif 'Zip' in env['BUILDERS']: kw['PACKAGETYPE']='zip' else: raise UserError, "No type for Package() given" PACKAGETYPE=kw['PACKAGETYPE'] if not is_List(PACKAGETYPE): - PACKAGETYPE=string.split(PACKAGETYPE, ',') + PACKAGETYPE=PACKAGETYPE.split(',') # load the needed packagers. def load_packager(type): @@ -124,7 +125,7 @@ def Package(env, target=None, source=None, **kw): except ImportError, e: raise EnvironmentError("packager %s not available: %s"%(type,str(e))) - packagers=map(load_packager, PACKAGETYPE) + packagers=list(map(load_packager, PACKAGETYPE)) # set up targets and the PACKAGEROOT try: @@ -139,7 +140,7 @@ def Package(env, target=None, source=None, **kw): default_target = default_name%kw target.extend( [default_target]*size_diff ) - if not kw.has_key('PACKAGEROOT'): + if 'PACKAGEROOT' not in kw: kw['PACKAGEROOT'] = default_name%kw except KeyError, e: @@ -153,7 +154,7 @@ def Package(env, target=None, source=None, **kw): try: for packager in packagers: t=[target.pop(0)] - t=apply(packager.package, [env,t,source], kw) + t=packager.package(env,t,source, **kw) targets.extend(t) assert( len(target) == 0 ) @@ -173,8 +174,7 @@ def Package(env, target=None, source=None, **kw): args.remove('target') args.remove('source') # now remove any args for which we have a value in kw. - #args=[x for x in args if not kw.has_key(x)] - args=filter(lambda x, kw=kw: not kw.has_key(x), args) + args=[x for x in args if x not in kw] if len(args)==0: raise # must be a different error, so reraise @@ -222,7 +222,7 @@ def options(opts): opts.AddVariables( EnumVariable( 'PACKAGETYPE', 'the type of package to create.', - None, allowed_values=map( str, __all__ ), + None, allowed_values=list(map( str, __all__ )), ignorecase=2 ) ) @@ -236,8 +236,8 @@ def copy_attr(f1, f2): """ #pattrs = [x for x in dir(f1) if not hasattr(f2, x) and\ # x.startswith('PACKAGING_')] - copyit = lambda x, f2=f2: not hasattr(f2, x) and x[:10] == 'PACKAGING_' - pattrs = filter(copyit, dir(f1)) + copyit = lambda x: not hasattr(f2, x) and x[:10] == 'PACKAGING_' + pattrs = list(filter(copyit, dir(f1))) for attr in pattrs: setattr(f2, attr, getattr(f1, attr)) def putintopackageroot(target, source, env, pkgroot, honor_install_location=1): @@ -291,7 +291,7 @@ def stripinstallbuilder(target, source, env): (file.builder.name=="InstallBuilder" or\ file.builder.name=="InstallAsBuilder")) - if len(filter(has_no_install_location, source)): + if len(list(filter(has_no_install_location, source))): warn(Warning, "there are files to package which have no\ InstallBuilder attached, this might lead to irreproducible packages") diff --git a/src/engine/SCons/Tool/packaging/ipk.py b/src/engine/SCons/Tool/packaging/ipk.py index 8575de6..6549445 100644 --- a/src/engine/SCons/Tool/packaging/ipk.py +++ b/src/engine/SCons/Tool/packaging/ipk.py @@ -58,7 +58,7 @@ def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION, buildarchitecture = os.uname()[4] buildarchitecture = archmap.get(buildarchitecture, buildarchitecture) - if kw.has_key('ARCHITECTURE'): + if 'ARCHITECTURE' in kw: buildarchitecture = kw['ARCHITECTURE'] # setup the kw to contain the mandatory arguments to this fucntion. @@ -76,7 +76,7 @@ def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION, target=[ "%s_%s_%s.ipk"%(NAME, VERSION, buildarchitecture) ] # now apply the Ipkg builder - return apply(bld, [env, target, specfile], kw) + return bld(env, target, specfile, **kw) def gen_ipk_dir(proot, source, env, kw): # make sure the packageroot is a Dir object. @@ -98,7 +98,7 @@ def gen_ipk_dir(proot, source, env, kw): spec_target.append(control.File('preinst')) # apply the builder to the specfile targets - apply(s_bld, [env, spec_target, source], kw) + s_bld(env, spec_target, source, **kw) # the packageroot directory does now contain the specfiles. return proot @@ -125,7 +125,7 @@ def build_specfiles(source, target, env): control_file=open_file('control', target) - if not env.has_key('X_IPK_DESCRIPTION'): + if 'X_IPK_DESCRIPTION' not in env: env['X_IPK_DESCRIPTION']="%s\n %s"%(env['SUMMARY'], env['DESCRIPTION'].replace('\n', '\n ')) @@ -173,7 +173,7 @@ Description: $X_IPK_DESCRIPTION f.close() # call a user specified function - if env.has_key('CHANGE_SPECFILE'): + if 'CHANGE_SPECFILE' in env: content += env['CHANGE_SPECFILE'](target) return 0 diff --git a/src/engine/SCons/Tool/packaging/msi.py b/src/engine/SCons/Tool/packaging/msi.py index 41ea0b3..95adbed 100644 --- a/src/engine/SCons/Tool/packaging/msi.py +++ b/src/engine/SCons/Tool/packaging/msi.py @@ -25,6 +25,7 @@ The msi packager. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -65,14 +66,14 @@ def convert_to_id(s, id_set): charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.' if s[0] in '0123456789.': s += '_'+s - id = filter( lambda c : c in charset, s ) + id = [c for c in s if c in charset] # did we already generate an id for this file? try: return id_set[id][s] except KeyError: # no we did not so initialize with the id - if not id_set.has_key(id): id_set[id] = { s : id } + if id not in id_set: id_set[id] = { s : id } # there is a collision, generate an id which is unique by appending # the collision number else: id_set[id][s] = id + str(len(id_set[id])) @@ -109,7 +110,7 @@ def gen_dos_short_file_name(file, filename_set): # strip forbidden characters. forbidden = '."/[]:;=, ' - fname = filter( lambda c : c not in forbidden, fname ) + fname = [c for c in fname if c not in forbidden] # check if we already generated a filename with the same number: # thisis1.txt, thisis2.txt etc. @@ -137,7 +138,7 @@ def create_feature_dict(files): feature = [ feature ] for f in feature: - if not dict.has_key( f ): + if f not in dict: dict[ f ] = [ file ] else: dict[ f ].append( file ) @@ -214,7 +215,7 @@ def build_wxsfile(target, source, env): file.write( doc.toprettyxml() ) # call a user specified function - if env.has_key('CHANGE_SPECFILE'): + if 'CHANGE_SPECFILE' in env: env['CHANGE_SPECFILE'](target, source) except KeyError, e: @@ -296,9 +297,11 @@ def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, upper_dir = '' # walk down the xml tree finding parts of the directory - dir_parts = filter( lambda d: d != '', dir_parts ) + dir_parts = [d for d in dir_parts if d != ''] for d in dir_parts[:]: - already_created = filter( lambda c: c.nodeName == 'Directory' and c.attributes['LongName'].value == escape(d), Directory.childNodes ) + already_created = [c for c in Directory.childNodes + if c.nodeName == 'Directory' + and c.attributes['LongName'].value == escape(d)] if already_created != []: Directory = already_created[0] @@ -464,7 +467,7 @@ def build_wxsfile_header_section(root, spec): Product.childNodes.append( Package ) # set "mandatory" default values - if not spec.has_key('X_MSI_LANGUAGE'): + if 'X_MSI_LANGUAGE' not in spec: spec['X_MSI_LANGUAGE'] = '1033' # select english # mandatory sections, will throw a KeyError if the tag is not available @@ -475,10 +478,10 @@ def build_wxsfile_header_section(root, spec): Package.attributes['Description'] = escape( spec['SUMMARY'] ) # now the optional tags, for which we avoid the KeyErrror exception - if spec.has_key( 'DESCRIPTION' ): + if 'DESCRIPTION' in spec: Package.attributes['Comments'] = escape( spec['DESCRIPTION'] ) - if spec.has_key( 'X_MSI_UPGRADE_CODE' ): + if 'X_MSI_UPGRADE_CODE' in spec: Package.attributes['X_MSI_UPGRADE_CODE'] = escape( spec['X_MSI_UPGRADE_CODE'] ) # We hardcode the media tag as our current model cannot handle it. @@ -511,7 +514,7 @@ def package(env, target, source, PACKAGEROOT, NAME, VERSION, # put the arguments into the env and call the specfile builder. env['msi_spec'] = kw - specfile = apply( wxs_builder, [env, target, source], kw ) + specfile = wxs_builder(* [env, target, source], **kw) # now call the WiX Tool with the built specfile added as a source. msifile = env.WiX(target, specfile) diff --git a/src/engine/SCons/Tool/packaging/rpm.py b/src/engine/SCons/Tool/packaging/rpm.py index c2a532c..7480542 100644 --- a/src/engine/SCons/Tool/packaging/rpm.py +++ b/src/engine/SCons/Tool/packaging/rpm.py @@ -25,11 +25,11 @@ The rpm packager. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os -import string import SCons.Builder @@ -65,7 +65,7 @@ def package(env, target, source, PACKAGEROOT, NAME, VERSION, buildarchitecture = os.uname()[4] buildarchitecture = archmap.get(buildarchitecture, buildarchitecture) - if kw.has_key('ARCHITECTURE'): + if 'ARCHITECTURE' in kw: buildarchitecture = kw['ARCHITECTURE'] fmt = '%s-%s-%s.%s.rpm' @@ -81,9 +81,9 @@ def package(env, target, source, PACKAGEROOT, NAME, VERSION, del kw['source'], kw['target'], kw['env'] # if no "SOURCE_URL" tag is given add a default one. - if not kw.has_key('SOURCE_URL'): + if 'SOURCE_URL' not in kw: #kw['SOURCE_URL']=(str(target[0])+".tar.gz").replace('.rpm', '') - kw['SOURCE_URL']=string.replace(str(target[0])+".tar.gz", '.rpm', '') + kw['SOURCE_URL']=(str(target[0])+".tar.gz").replace('.rpm', '') # mangle the source and target list for the rpmbuild env = OverrideEnvironment(env, kw) @@ -92,7 +92,7 @@ def package(env, target, source, PACKAGEROOT, NAME, VERSION, target, source = collectintargz(target, source, env) # now call the rpm builder to actually build the packet. - return apply(bld, [env, target, source], kw) + return bld(env, target, source, **kw) def collectintargz(target, source, env): """ Puts all source files into a tar.gz file. """ @@ -102,21 +102,21 @@ def collectintargz(target, source, env): # filter out the target we are building the source list for. #sources = [s for s in sources if not (s in target)] - sources = filter(lambda s, t=target: not (s in t), sources) + sources = [s for s in sources if s not in target] # find the .spec file for rpm and add it since it is not necessarily found # by the FindSourceFiles function. #sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] ) - spec_file = lambda s: string.rfind(str(s), '.spec') != -1 - sources.extend( filter(spec_file, source) ) + spec_file = lambda s: str(s).rfind('.spec') != -1 + sources.extend( list(filter(spec_file, source)) ) # as the source contains the url of the source package this rpm package # is built from, we extract the target name #tarball = (str(target[0])+".tar.gz").replace('.rpm', '') - tarball = string.replace(str(target[0])+".tar.gz", '.rpm', '') + tarball = (str(target[0])+".tar.gz").replace('.rpm', '') try: #tarball = env['SOURCE_URL'].split('/')[-1] - tarball = string.split(env['SOURCE_URL'], '/')[-1] + tarball = env['SOURCE_URL'].split('/')[-1] except KeyError, e: raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] ) @@ -150,7 +150,7 @@ def build_specfile(target, source, env): file.close() # call a user specified function - if env.has_key('CHANGE_SPECFILE'): + if 'CHANGE_SPECFILE' in env: env['CHANGE_SPECFILE'](target, source) except KeyError, e: @@ -188,16 +188,16 @@ def build_specfile_sections(spec): # Default prep, build, install and clean rules # TODO: optimize those build steps, to not compile the project a second time - if not spec.has_key('X_RPM_PREP'): + if 'X_RPM_PREP' not in spec: spec['X_RPM_PREP'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' + '\n%setup -q' - if not spec.has_key('X_RPM_BUILD'): + if 'X_RPM_BUILD' not in spec: spec['X_RPM_BUILD'] = 'mkdir "$RPM_BUILD_ROOT"' - if not spec.has_key('X_RPM_INSTALL'): + if 'X_RPM_INSTALL' not in spec: spec['X_RPM_INSTALL'] = 'scons --install-sandbox="$RPM_BUILD_ROOT" "$RPM_BUILD_ROOT"' - if not spec.has_key('X_RPM_CLEAN'): + if 'X_RPM_CLEAN' not in spec: spec['X_RPM_CLEAN'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' str = str + SimpleTagCompiler(optional_sections, mandatory=0).compile( spec ) @@ -254,7 +254,7 @@ def build_specfile_header(spec): # if not s.has_key('x_rpm_BuildRequires'): # s['x_rpm_BuildRequires'] = 'scons' - if not spec.has_key('X_RPM_BUILDROOT'): + if 'X_RPM_BUILDROOT' not in spec: spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}' str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec ) @@ -268,7 +268,7 @@ def build_specfile_filesection(spec, files): """ str = '%files\n' - if not spec.has_key('X_RPM_DEFATTR'): + if 'X_RPM_DEFATTR' not in spec: spec['X_RPM_DEFATTR'] = '(-,root,root)' str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR'] @@ -337,7 +337,7 @@ class SimpleTagCompiler: str = "" #domestic = [ (k,v) for k,v in replacements if not is_international(k) ] - domestic = filter(lambda t, i=is_international: not i(t[0]), replacements) + domestic = [t for t in replacements if not is_international(t[0])] for key, replacement in domestic: try: str = str + replacement % values[key] @@ -346,12 +346,12 @@ class SimpleTagCompiler: raise e #international = [ (k,v) for k,v in replacements if is_international(k) ] - international = filter(lambda t, i=is_international: i(t[0]), replacements) + international = [t for t in replacements if is_international(t[0])] for key, replacement in international: try: #int_values_for_key = [ (get_country_code(k),v) for k,v in values.items() if strip_country_code(k) == key ] - x = filter(lambda t,key=key,s=strip_country_code: s(t[0]) == key, values.items()) - int_values_for_key = map(lambda t,g=get_country_code: (g(t[0]),t[1]), x) + x = [t for t in values.items() if strip_country_code(t[0]) == key] + int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x] for v in int_values_for_key: str = str + replacement % v except KeyError, e: diff --git a/src/engine/SCons/Tool/rmic.py b/src/engine/SCons/Tool/rmic.py index 8720d3d..7509672 100644 --- a/src/engine/SCons/Tool/rmic.py +++ b/src/engine/SCons/Tool/rmic.py @@ -34,7 +34,6 @@ selection method. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path -import string import SCons.Action import SCons.Builder @@ -86,7 +85,7 @@ def emit_rmic_classes(target, source, env): tlist = [] for s in source: for suff in stub_suffixes: - fname = string.replace(s.attributes.java_classname, '.', os.sep) + \ + fname = s.attributes.java_classname.replace('.', os.sep) + \ suff + class_suffix t = target[0].File(fname) t.attributes.java_lookupdir = target[0] diff --git a/src/engine/SCons/Tool/swig.py b/src/engine/SCons/Tool/swig.py index c473b10..c6815f7 100644 --- a/src/engine/SCons/Tool/swig.py +++ b/src/engine/SCons/Tool/swig.py @@ -35,7 +35,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path import re -import string import subprocess import SCons.Action @@ -72,7 +71,7 @@ def _find_modules(src): for m in matches: mnames.append(m[2]) - directors = directors or string.find(m[0], 'directors') >= 0 + directors = directors or m[0].find('directors') >= 0 return mnames, directors def _add_director_header_targets(target, env): @@ -97,29 +96,26 @@ def _swigEmitter(target, source, env): mnames, directors = _find_modules(src) if directors: _add_director_header_targets(target, env) - python_files = map(lambda m: m + ".py", mnames) + python_files = [m + ".py" for m in mnames] outdir = env.subst('$SWIGOUTDIR', target=target, source=source) # .py files should be generated in SWIGOUTDIR if specified, # otherwise in the same directory as the target if outdir: - python_files = map(lambda j, o=outdir, e=env: - e.fs.File(os.path.join(o, j)), - python_files) + python_files = [env.fs.File(os.path.join(outdir, j)) for j in python_files] else: - python_files = map(lambda m, d=target[0].dir: - d.File(m), python_files) + python_files = [target[0].dir.File(m) for m in python_files] target.extend(python_files) if "-java" in flags: if mnames is None: mnames, directors = _find_modules(src) if directors: _add_director_header_targets(target, env) - java_files = map(lambda m: [m + ".java", m + "JNI.java"], mnames) + java_files = [[m + ".java", m + "JNI.java"] for m in mnames] java_files = SCons.Util.flatten(java_files) outdir = env.subst('$SWIGOUTDIR', target=target, source=source) if outdir: - java_files = map(lambda j, o=outdir: os.path.join(o, j), java_files) - java_files = map(env.fs.File, java_files) + java_files = [os.path.join(outdir, j) for j in java_files] + java_files = list(map(env.fs.File, java_files)) for jf in java_files: t_from_s = lambda t, p, s, x: t.dir SCons.Util.AddMethod(jf, t_from_s, 'target_from_source') diff --git a/src/engine/SCons/Tool/tex.py b/src/engine/SCons/Tool/tex.py index 11e06bf..4960c5d 100644 --- a/src/engine/SCons/Tool/tex.py +++ b/src/engine/SCons/Tool/tex.py @@ -36,7 +36,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path import re -import string import shutil import SCons.Action @@ -292,7 +291,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None target_aux = os.path.join(targetdir, auxfilename) if os.path.exists(target_aux): content = open(target_aux, "rb").read() - if string.find(content, "bibdata") != -1: + if content.find("bibdata") != -1: if Verbose: print "Need to run bibtex" bibfile = env.fs.File(targetbase) @@ -422,7 +421,7 @@ def is_LaTeX(flist,env,abspath): # Split at os.pathsep to convert into absolute path # TODO(1.5) #paths = paths.split(os.pathsep) - paths = string.split(paths, os.pathsep) + paths = paths.split(os.pathsep) # now that we have the path list restore the env if savedpath is _null: @@ -648,7 +647,7 @@ def tex_emitter_core(target, source, env, graphics_extensions): # Split at os.pathsep to convert into absolute path # TODO(1.5) #paths = paths.split(os.pathsep) - paths = string.split(paths, os.pathsep) + paths = paths.split(os.pathsep) # now that we have the path list restore the env if savedpath is _null: diff --git a/src/engine/SCons/Tool/textfile.py b/src/engine/SCons/Tool/textfile.py index 67b61f4..5733014 100644 --- a/src/engine/SCons/Tool/textfile.py +++ b/src/engine/SCons/Tool/textfile.py @@ -84,7 +84,7 @@ def _action(target, source, env): % repr(linesep), None) # create a dictionary to use for the substitutions - if not env.has_key('SUBST_DICT'): + if 'SUBST_DICT' not in env: subs = None # no substitutions else: d = env['SUBST_DICT'] diff --git a/src/engine/SCons/Tool/wix.py b/src/engine/SCons/Tool/wix.py index 5737df2..32cc1f1 100644 --- a/src/engine/SCons/Tool/wix.py +++ b/src/engine/SCons/Tool/wix.py @@ -35,7 +35,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import SCons.Builder import SCons.Action import os -import string def generate(env): """Add Builders and construction variables for WiX to an Environment.""" @@ -68,7 +67,7 @@ def exists(env): # try to find the candle.exe and light.exe tools and # add the install directory to light libpath. #for path in os.environ['PATH'].split(os.pathsep): - for path in string.split(os.environ['PATH'], os.pathsep): + for path in os.environ['PATH'].split(os.pathsep): if not path: continue diff --git a/src/engine/SCons/Tool/yacc.py b/src/engine/SCons/Tool/yacc.py index 4d551e6..ca5e2fc 100644 --- a/src/engine/SCons/Tool/yacc.py +++ b/src/engine/SCons/Tool/yacc.py @@ -34,7 +34,6 @@ selection method. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path -import string import SCons.Defaults import SCons.Tool @@ -71,7 +70,7 @@ def _yaccEmitter(target, source, env, ysuf, hsuf): if option[:l] == fileGenOption: # A file generating option is present, so add the file # name to the list of targets. - fileName = string.strip(option[l:]) + fileName = option[l:].strip() target.append(fileName) return (target, source) diff --git a/src/engine/SCons/Util.py b/src/engine/SCons/Util.py index 9e5fe38..709cf1f 100644 --- a/src/engine/SCons/Util.py +++ b/src/engine/SCons/Util.py @@ -33,7 +33,6 @@ import copy import os import os.path import re -import string import sys import types @@ -59,11 +58,11 @@ if _altsep is None and sys.platform == 'win32': # My ActivePython 2.0.1 doesn't set os.altsep! What gives? _altsep = '/' if _altsep: - def rightmost_separator(path, sep, _altsep=_altsep): - rfind = string.rfind - return max(rfind(path, sep), rfind(path, _altsep)) + def rightmost_separator(path, sep): + return max(path.rfind(sep), path.rfind(_altsep)) else: - rightmost_separator = string.rfind + def rightmost_separator(path, sep): + return path.rfind(sep) # First two from the Python Cookbook, just for completeness. # (Yeah, yeah, YAGNI...) @@ -88,7 +87,7 @@ def containsOnly(str, set): def splitext(path): "Same as os.path.splitext() but faster." sep = rightmost_separator(path, os.sep) - dot = string.rfind(path, '.') + dot = path.rfind('.') # An ext is only real if it has at least one non-digit char if dot > sep and not containsOnly(path[dot:], "0123456789."): return path[:dot],path[dot:] @@ -104,7 +103,7 @@ def updrive(path): """ drive, rest = os.path.splitdrive(path) if drive: - path = string.upper(drive) + rest + path = drive.upper() + rest return path class NodeList(UserList): @@ -121,20 +120,17 @@ class NodeList(UserList): return len(self.data) != 0 def __str__(self): - return string.join(map(str, self.data)) + return ' '.join(map(str, self.data)) def __iter__(self): return iter(self.data) def __call__(self, *args, **kwargs): - result = map(lambda x, args=args, kwargs=kwargs: apply(x, - args, - kwargs), - self.data) + result = [x(*args, **kwargs) for x in self.data] return self.__class__(result) def __getattr__(self, name): - result = map(lambda x, n=name: getattr(x, n), self.data) + result = [getattr(x, name) for x in self.data] return self.__class__(result) @@ -204,7 +200,7 @@ def render_tree(root, child_func, prune=0, margin=[0], visited={}): else: retval = retval + " " - if visited.has_key(rname): + if rname in visited: return retval + "+-[" + rname + "]\n" retval = retval + "+-" + rname + "\n" @@ -273,15 +269,15 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}): def MMM(m): return [" ","| "][m] - margins = map(MMM, margin[:-1]) + margins = list(map(MMM, margin[:-1])) children = child_func(root) - if prune and visited.has_key(rname) and children: - print string.join(tags + margins + ['+-[', rname, ']'], '') + if prune and rname in visited and children: + print ''.join(tags + margins + ['+-[', rname, ']']) return - print string.join(tags + margins + ['+-', rname], '') + print ''.join(tags + margins + ['+-', rname]) visited[rname] = 1 @@ -426,7 +422,7 @@ except TypeError: def to_String_for_subst(s): if is_Sequence( s ): - return string.join( map(to_String_for_subst, s) ) + return ' '.join( map(to_String_for_subst, s) ) return to_String( s ) @@ -543,7 +539,7 @@ else: return str(s) def to_String_for_subst(s, - isinstance=isinstance, join=string.join, str=str, to_String=to_String, + isinstance=isinstance, str=str, to_String=to_String, BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes, UserString=UserString): @@ -554,7 +550,7 @@ else: l = [] for e in s: l.append(to_String_for_subst(e)) - return join( s ) + return ' '.join( s ) elif isinstance(s, UserString): # s.data can only be either a unicode or a regular # string. Please see the UserString initializer. @@ -602,7 +598,7 @@ def _semi_deepcopy_dict(x): d[types.DictionaryType] = _semi_deepcopy_dict def _semi_deepcopy_list(x): - return map(semi_deepcopy, x) + return list(map(semi_deepcopy, x)) d[types.ListType] = _semi_deepcopy_list def _semi_deepcopy_tuple(x): @@ -766,16 +762,16 @@ if sys.platform == 'win32': except KeyError: return None if is_String(path): - path = string.split(path, os.pathsep) + path = path.split(os.pathsep) if pathext is None: try: pathext = os.environ['PATHEXT'] except KeyError: pathext = '.COM;.EXE;.BAT;.CMD' if is_String(pathext): - pathext = string.split(pathext, os.pathsep) + pathext = pathext.split(os.pathsep) for ext in pathext: - if string.lower(ext) == string.lower(file[-len(ext):]): + if ext.lower() == file[-len(ext):].lower(): pathext = [''] break if not is_List(reject) and not is_Tuple(reject): @@ -801,11 +797,11 @@ elif os.name == 'os2': except KeyError: return None if is_String(path): - path = string.split(path, os.pathsep) + path = path.split(os.pathsep) if pathext is None: pathext = ['.exe', '.cmd'] for ext in pathext: - if string.lower(ext) == string.lower(file[-len(ext):]): + if ext.lower() == file[-len(ext):].lower(): pathext = [''] break if not is_List(reject) and not is_Tuple(reject): @@ -832,7 +828,7 @@ else: except KeyError: return None if is_String(path): - path = string.split(path, os.pathsep) + path = path.split(os.pathsep) if not is_List(reject) and not is_Tuple(reject): reject = [reject] for d in path: @@ -881,18 +877,18 @@ def PrependPath(oldpath, newpath, sep = os.pathsep, is_list = 1 paths = orig if not is_List(orig) and not is_Tuple(orig): - paths = string.split(paths, sep) + paths = paths.split(sep) is_list = 0 if is_String(newpath): - newpaths = string.split(newpath, sep) + newpaths = newpath.split(sep) elif not is_List(newpath) and not is_Tuple(newpath): newpaths = [ newpath ] # might be a Dir else: newpaths = newpath if canonicalize: - newpaths=map(canonicalize, newpaths) + newpaths=list(map(canonicalize, newpaths)) if not delete_existing: # First uniquify the old paths, making sure to @@ -934,7 +930,7 @@ def PrependPath(oldpath, newpath, sep = os.pathsep, if is_list: return paths else: - return string.join(paths, sep) + return sep.join(paths) def AppendPath(oldpath, newpath, sep = os.pathsep, delete_existing=1, canonicalize=None): @@ -962,18 +958,18 @@ def AppendPath(oldpath, newpath, sep = os.pathsep, is_list = 1 paths = orig if not is_List(orig) and not is_Tuple(orig): - paths = string.split(paths, sep) + paths = paths.split(sep) is_list = 0 if is_String(newpath): - newpaths = string.split(newpath, sep) + newpaths = newpath.split(sep) elif not is_List(newpath) and not is_Tuple(newpath): newpaths = [ newpath ] # might be a Dir else: newpaths = newpath if canonicalize: - newpaths=map(canonicalize, newpaths) + newpaths=list(map(canonicalize, newpaths)) if not delete_existing: # add old paths to result, then @@ -1015,13 +1011,13 @@ def AppendPath(oldpath, newpath, sep = os.pathsep, if is_list: return paths else: - return string.join(paths, sep) + return sep.join(paths) if sys.platform == 'cygwin': def get_native_path(path): """Transforms an absolute path into a native path for the system. In Cygwin, this converts from a Cygwin path to a Windows one.""" - return string.replace(os.popen('cygpath -w ' + path).read(), '\n', '') + return os.popen('cygpath -w ' + path).read().replace('\n', '') else: def get_native_path(path): """Transforms an absolute path into a native path for the system. @@ -1034,7 +1030,7 @@ def Split(arg): if is_List(arg) or is_Tuple(arg): return arg elif is_String(arg): - return string.split(arg) + return arg.split() else: return [arg] @@ -1057,7 +1053,7 @@ class CLVar(UserList): def __coerce__(self, other): return (self, CLVar(other)) def __str__(self): - return string.join(self.data) + return ' '.join(self.data) # A dictionary that preserves the order in which items are added. # Submitted by David Benjamin to ActiveState's Python Cookbook web site: @@ -1111,7 +1107,7 @@ class OrderedDict(UserDict): self.__setitem__(key, val) def values(self): - return map(self.get, self._keys) + return list(map(self.get, self._keys)) class Selector(OrderedDict): """A callable ordered dictionary that maps file suffixes to @@ -1132,7 +1128,7 @@ class Selector(OrderedDict): for (k,v) in self.items(): if k is not None: s_k = env.subst(k) - if s_dict.has_key(s_k): + if s_k in s_dict: # We only raise an error when variables point # to the same suffix. If one suffix is literal # and a variable suffix contains this literal, @@ -1279,7 +1275,7 @@ def uniquer_hashables(seq): result = [] for item in seq: #if not item in seen: - if not seen.has_key(item): + if item not in seen: seen[item] = 1 result.append(item) return result @@ -1304,7 +1300,7 @@ class LogicalLines: else: result.append(line) break - return string.join(result, '') + return ''.join(result) def readlines(self): result = [] @@ -1402,8 +1398,7 @@ class UniqueList(UserList): UserList.reverse(self) def sort(self, *args, **kwds): self.__make_unique() - #return UserList.sort(self, *args, **kwds) - return apply(UserList.sort, (self,)+args, kwds) + return UserList.sort(self, *args, **kwds) def extend(self, other): UserList.extend(self, other) self.unique = False @@ -1568,7 +1563,7 @@ def MD5collect(signatures): if len(signatures) == 1: return signatures[0] else: - return MD5signature(string.join(signatures, ', ')) + return MD5signature(', '.join(signatures)) @@ -1605,8 +1600,7 @@ class Null: """ Null objects always and reliably "do nothing." """ def __new__(cls, *args, **kwargs): if not '_inst' in vars(cls): - #cls._inst = type.__new__(cls, *args, **kwargs) - cls._inst = apply(type.__new__, (cls,) + args, kwargs) + cls._inst = type.__new__(cls, *args, **kwargs) return cls._inst def __init__(self, *args, **kwargs): pass diff --git a/src/engine/SCons/UtilTests.py b/src/engine/SCons/UtilTests.py index 9d013ca..670fc83 100644 --- a/src/engine/SCons/UtilTests.py +++ b/src/engine/SCons/UtilTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path -import string import StringIO import sys import types @@ -112,9 +111,9 @@ class UtilTestCase(unittest.TestCase): +-windows.h """ - lines = string.split(expect, '\n')[:-1] - lines = map(lambda l: '[E BSPACN ]'+l, lines) - withtags = string.join(lines, '\n') + '\n' + lines = expect.split('\n')[:-1] + lines = ['[E BSPACN ]'+l for l in lines] + withtags = '\n'.join(lines) + '\n' return foo, expect, withtags @@ -137,12 +136,12 @@ class UtilTestCase(unittest.TestCase): """ if not prune: - expect = string.replace(expect, '[', '') - expect = string.replace(expect, ']', '') + expect = expect.replace('[', '') + expect = expect.replace(']', '') - lines = string.split(expect, '\n')[:-1] - lines = map(lambda l: '[E BSPACN ]'+l, lines) - withtags = string.join(lines, '\n') + '\n' + lines = expect.split('\n')[:-1] + lines = ['[E BSPACN ]'+l for l in lines] + withtags = '\n'.join(lines) + '\n' return blat_o, expect, withtags @@ -333,20 +332,20 @@ class UtilTestCase(unittest.TestCase): test.workpath('sub2'), test.workpath('sub3'), test.workpath('sub4'), - ] + string.split(env_path, os.pathsep) + ] + env_path.split(os.pathsep) pathdirs_1243 = [ test.workpath('sub1'), test.workpath('sub2'), test.workpath('sub4'), test.workpath('sub3'), - ] + string.split(env_path, os.pathsep) + ] + env_path.split(os.pathsep) - os.environ['PATH'] = string.join(pathdirs_1234, os.pathsep) + os.environ['PATH'] = os.pathsep.join(pathdirs_1234) wi = WhereIs('xxx.exe') assert wi == test.workpath(sub3_xxx_exe), wi wi = WhereIs('xxx.exe', pathdirs_1243) assert wi == test.workpath(sub4_xxx_exe), wi - wi = WhereIs('xxx.exe', string.join(pathdirs_1243, os.pathsep)) + wi = WhereIs('xxx.exe', os.pathsep.join(pathdirs_1243)) assert wi == test.workpath(sub4_xxx_exe), wi wi = WhereIs('xxx.exe',reject = sub3_xxx_exe) @@ -354,12 +353,12 @@ class UtilTestCase(unittest.TestCase): wi = WhereIs('xxx.exe', pathdirs_1243, reject = sub3_xxx_exe) assert wi == test.workpath(sub4_xxx_exe), wi - os.environ['PATH'] = string.join(pathdirs_1243, os.pathsep) + os.environ['PATH'] = os.pathsep.join(pathdirs_1243) wi = WhereIs('xxx.exe') assert wi == test.workpath(sub4_xxx_exe), wi wi = WhereIs('xxx.exe', pathdirs_1234) assert wi == test.workpath(sub3_xxx_exe), wi - wi = WhereIs('xxx.exe', string.join(pathdirs_1234, os.pathsep)) + wi = WhereIs('xxx.exe', os.pathsep.join(pathdirs_1234)) assert wi == test.workpath(sub3_xxx_exe), wi if sys.platform == 'win32': @@ -370,13 +369,13 @@ class UtilTestCase(unittest.TestCase): assert wi == test.workpath(sub4_xxx_exe), wi wi = WhereIs('xxx', path = pathdirs_1234, pathext = '.BAT;.EXE') - assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi + assert wi.lower() == test.workpath(sub3_xxx_exe).lower(), wi # Test that we return a normalized path even when # the path contains forward slashes. forward_slash = test.workpath('') + '/sub3' wi = WhereIs('xxx', path = forward_slash, pathext = '.EXE') - assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi + assert wi.lower() == test.workpath(sub3_xxx_exe).lower(), wi del os.environ['PATH'] wi = WhereIs('xxx.exe') @@ -710,7 +709,7 @@ class MD5TestCase(unittest.TestCase): def test_collect(self): """Test collecting a list of signatures into a new signature value """ - s = map(MD5signature, ('111', '222', '333')) + s = list(map(MD5signature, ('111', '222', '333'))) assert '698d51a19d8a121ce581499d7b701668' == MD5collect(s[0:1]) assert '8980c988edc2c78cc43ccb718c06efd5' == MD5collect(s[0:2]) @@ -791,7 +790,7 @@ if __name__ == "__main__": ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Variables/BoolVariable.py b/src/engine/SCons/Variables/BoolVariable.py index c1a20e3..6bc66bb 100644 --- a/src/engine/SCons/Variables/BoolVariable.py +++ b/src/engine/SCons/Variables/BoolVariable.py @@ -38,8 +38,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" __all__ = ['BoolVariable',] -import string - import SCons.Errors __true_strings = ('y', 'yes', 'true', 't', '1', 'on' , 'all' ) @@ -57,7 +55,7 @@ def _text2bool(val): This is usable as 'converter' for SCons' Variables. """ - lval = string.lower(val) + lval = val.lower() if lval in __true_strings: return True if lval in __false_strings: return False raise ValueError("Invalid value for boolean option: %s" % val) diff --git a/src/engine/SCons/Variables/EnumVariable.py b/src/engine/SCons/Variables/EnumVariable.py index b8f30bf..71302ee 100644 --- a/src/engine/SCons/Variables/EnumVariable.py +++ b/src/engine/SCons/Variables/EnumVariable.py @@ -41,7 +41,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" __all__ = ['EnumVariable',] -import string import SCons.Errors @@ -80,24 +79,21 @@ def EnumVariable(key, help, default, allowed_values, map={}, ignorecase=0): given 'map'-dictionary (unmapped input values are returned unchanged). """ - help = '%s (%s)' % (help, string.join(allowed_values, '|')) + help = '%s (%s)' % (help, '|'.join(allowed_values)) # define validator if ignorecase >= 1: - validator = lambda key, val, env, vals=allowed_values: \ - _validator(key, string.lower(val), env, vals) + validator = lambda key, val, env: \ + _validator(key, val.lower(), env, allowed_values) else: - validator = lambda key, val, env, vals=allowed_values: \ - _validator(key, val, env, vals) + validator = lambda key, val, env: \ + _validator(key, val, env, allowed_values) # define converter if ignorecase == 2: - converter = lambda val, map=map: \ - string.lower(map.get(string.lower(val), val)) + converter = lambda val: map.get(val.lower(), val).lower() elif ignorecase == 1: - converter = lambda val, map=map: \ - map.get(string.lower(val), val) + converter = lambda val: map.get(val.lower(), val) else: - converter = lambda val, map=map: \ - map.get(val, val) + converter = lambda val: map.get(val, val) return (key, help, default, validator, converter) # Local Variables: diff --git a/src/engine/SCons/Variables/ListVariable.py b/src/engine/SCons/Variables/ListVariable.py index 521fa4f..36b530a 100644 --- a/src/engine/SCons/Variables/ListVariable.py +++ b/src/engine/SCons/Variables/ListVariable.py @@ -46,6 +46,7 @@ Usage example: # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -54,7 +55,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" __all__ = ['ListVariable',] -import string import UserList import SCons.Util @@ -62,7 +62,7 @@ import SCons.Util class _ListVariable(UserList.UserList): def __init__(self, initlist=[], allowedElems=[]): - UserList.UserList.__init__(self, filter(None, initlist)) + UserList.UserList.__init__(self, [_f for _f in initlist if _f]) self.allowedElems = allowedElems[:] self.allowedElems.sort() @@ -85,7 +85,7 @@ class _ListVariable(UserList.UserList): if self.data == self.allowedElems: return 'all' else: - return string.join(self, ',') + return ','.join(self) def prepare_to_store(self): return self.__str__() @@ -97,12 +97,12 @@ def _converter(val, allowedElems, mapdict): elif val == 'all': val = allowedElems else: - val = filter(None, string.split(val, ',')) - val = map(lambda v, m=mapdict: m.get(v, v), val) - notAllowed = filter(lambda v, aE=allowedElems: not v in aE, val) + val = [_f for _f in val.split(',') if _f] + val = [mapdict.get(v, v) for v in val] + notAllowed = [v for v in val if not v in allowedElems] if notAllowed: raise ValueError("Invalid value(s) for option: %s" % - string.join(notAllowed, ',')) + ','.join(notAllowed)) return _ListVariable(val, allowedElems) @@ -122,15 +122,14 @@ def ListVariable(key, help, default, names, map={}): A 'package list' option may either be 'all', 'none' or a list of package names (separated by space). """ - names_str = 'allowed names: %s' % string.join(names, ' ') + names_str = 'allowed names: %s' % ' '.join(names) if SCons.Util.is_List(default): - default = string.join(default, ',') - help = string.join( - (help, '(all|none|comma-separated list of names)', names_str), - '\n ') + default = ','.join(default) + help = '\n '.join( + (help, '(all|none|comma-separated list of names)', names_str)) return (key, help, default, None, #_validator, - lambda val, elems=names, m=map: _converter(val, elems, m)) + lambda val: _converter(val, names, map)) # Local Variables: # tab-width:4 diff --git a/src/engine/SCons/Variables/PackageVariable.py b/src/engine/SCons/Variables/PackageVariable.py index 294a398..440d0f6 100644 --- a/src/engine/SCons/Variables/PackageVariable.py +++ b/src/engine/SCons/Variables/PackageVariable.py @@ -54,8 +54,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" __all__ = ['PackageVariable',] -import string - import SCons.Errors __enable_strings = ('1', 'yes', 'true', 'on', 'enable', 'search') @@ -64,7 +62,7 @@ __disable_strings = ('0', 'no', 'false', 'off', 'disable') def _converter(val): """ """ - lval = string.lower(val) + lval = val.lower() if lval in __enable_strings: return True if lval in __disable_strings: return False #raise ValueError("Invalid value for boolean option: %s" % val) @@ -95,11 +93,10 @@ def PackageVariable(key, help, default, searchfunc=None): A 'package list' option may either be 'all', 'none' or a list of package names (seperated by space). """ - help = string.join( - (help, '( yes | no | /path/to/%s )' % key), - '\n ') + help = '\n '.join( + (help, '( yes | no | /path/to/%s )' % key)) return (key, help, default, - lambda k, v, e, f=searchfunc: _validator(k,v,e,f), + lambda k, v, e: _validator(k,v,e,searchfunc), _converter) # Local Variables: diff --git a/src/engine/SCons/Variables/VariablesTests.py b/src/engine/SCons/Variables/VariablesTests.py index 493d69f..4fa0879 100644 --- a/src/engine/SCons/Variables/VariablesTests.py +++ b/src/engine/SCons/Variables/VariablesTests.py @@ -41,8 +41,10 @@ class Environment: self.dict[key] = value def __getitem__(self, key): return self.dict[key] + def __contains__(self, key): + return self.dict.__contains__(key) def has_key(self, key): - return self.dict.has_key(key) + return key in self.dict def check(key, value, env): @@ -253,7 +255,7 @@ class VariablesTestCase(unittest.TestCase): env = Environment() opts.Update(env, {}) - assert not env.has_key('ANSWER') + assert 'ANSWER' not in env # Test that a default value of None is all right. test = TestSCons.TestSCons() @@ -267,7 +269,7 @@ class VariablesTestCase(unittest.TestCase): env = Environment() opts.Update(env, {}) - assert not env.has_key('ANSWER') + assert 'ANSWER' not in env def test_args(self): """Test updating an Environment with arguments overridden""" @@ -527,12 +529,12 @@ B 42 54 b - alpha test ['B'] env = Environment() opts.Update(env, {'ANSWER' : 'answer'}) - assert env.has_key('ANSWER') + assert 'ANSWER' in env env = Environment() opts.Update(env, {'ANSWERALIAS' : 'answer'}) - assert env.has_key('ANSWER') and not env.has_key('ANSWERALIAS') + assert 'ANSWER' in env and 'ANSWERALIAS' not in env # test alias as a list opts = SCons.Variables.Variables() @@ -545,12 +547,12 @@ B 42 54 b - alpha test ['B'] env = Environment() opts.Update(env, {'ANSWER' : 'answer'}) - assert env.has_key('ANSWER') + assert 'ANSWER' in env env = Environment() opts.Update(env, {'ANSWERALIAS' : 'answer'}) - assert env.has_key('ANSWER') and not env.has_key('ANSWERALIAS') + assert 'ANSWER' in env and 'ANSWERALIAS' not in env @@ -652,7 +654,7 @@ if __name__ == "__main__": UnknownVariablesTestCase ] for tclass in tclasses: names = unittest.getTestCaseNames(tclass, 'test_') - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Variables/__init__.py b/src/engine/SCons/Variables/__init__.py index b1a2288..27f694f 100644 --- a/src/engine/SCons/Variables/__init__.py +++ b/src/engine/SCons/Variables/__init__.py @@ -26,11 +26,11 @@ customizable variables to an SCons build. # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path -import string import sys import SCons.Environment @@ -108,7 +108,7 @@ class Variables: """ Returns the keywords for the options """ - return map(lambda o: o.key, self.options) + return [o.key for o in self.options] def Add(self, key, help="", default=None, validator=None, converter=None, **kw): """ @@ -124,7 +124,7 @@ class Variables: """ if SCons.Util.is_List(key) or type(key) == type(()): - apply(self._do_add, key) + self._do_add(*key) return if not SCons.Util.is_String(key) or \ @@ -149,7 +149,7 @@ class Variables: ) """ for o in optlist: - apply(self._do_add, o) + self._do_add(*o) def Update(self, env, args=None): @@ -203,7 +203,7 @@ class Variables: # Call the convert functions: for option in self.options: - if option.converter and values.has_key(option.key): + if option.converter and option.key in values: value = env.subst('${%s}'%option.key) try: try: @@ -216,7 +216,7 @@ class Variables: # Finally validate the values: for option in self.options: - if option.validator and values.has_key(option.key): + if option.validator and option.key in values: option.validator(option.key, env.subst('${%s}'%option.key), env) def UnknownVariables(self): @@ -285,26 +285,26 @@ class Variables: if sort: options = self.options[:] - options.sort(lambda x,y,func=sort: func(x.key,y.key)) + options.sort(lambda x,y: sort(x.key,y.key)) else: options = self.options def format(opt, self=self, env=env): - if env.has_key(opt.key): + if opt.key in env: actual = env.subst('${%s}' % opt.key) else: actual = None return self.FormatVariableHelpText(env, opt.key, opt.help, opt.default, actual, opt.aliases) - lines = filter(None, map(format, options)) + lines = [_f for _f in map(format, options) if _f] - return string.join(lines, '') + return ''.join(lines) format = '\n%s: %s\n default: %s\n actual: %s\n' format_ = '\n%s: %s\n default: %s\n actual: %s\n aliases: %s\n' def FormatVariableHelpText(self, env, key, help, default, actual, aliases=[]): # Don't display the key name itself as an alias. - aliases = filter(lambda a, k=key: a != k, aliases) + aliases = [a for a in aliases if a != key] if len(aliases)==0: return self.format % (key, help, default, actual) else: diff --git a/src/engine/SCons/Warnings.py b/src/engine/SCons/Warnings.py index 797ff41..1fa6302 100644 --- a/src/engine/SCons/Warnings.py +++ b/src/engine/SCons/Warnings.py @@ -29,7 +29,6 @@ This file implements the warnings framework for SCons. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" -import string import sys import SCons.Errors @@ -194,11 +193,11 @@ def process_warn_strings(arguments): if s[:5] == "scons": return "SCons" + s[5:] else: - return string.capitalize(s) + return s.capitalize() for arg in arguments: - elems = string.split(string.lower(arg), '-') + elems = arg.lower().split('-') enable = 1 if elems[0] == 'no': enable = 0 @@ -207,7 +206,7 @@ def process_warn_strings(arguments): if len(elems) == 1 and elems[0] == 'all': class_name = "Warning" else: - class_name = string.join(map(_capitalize, elems), '') + "Warning" + class_name = ''.join(map(_capitalize, elems)) + "Warning" try: clazz = globals()[class_name] except KeyError: diff --git a/src/engine/SCons/compat/__init__.py b/src/engine/SCons/compat/__init__.py index 4d38617..d959518 100644 --- a/src/engine/SCons/compat/__init__.py +++ b/src/engine/SCons/compat/__init__.py @@ -183,6 +183,15 @@ except ImportError: import_as('_scons_platform', 'platform') +try: + import queue +except ImportError: + # Before Python 3.0, the 'queue' module was named 'Queue'. + import imp + file, filename, suffix_mode_type = imp.find_module('Queue') + imp.load_module('queue', file, filename, suffix_mode_type) + + import shlex try: shlex.split @@ -244,6 +253,24 @@ except ImportError: import sys try: + sys.intern +except AttributeError: + # Pre-2.6 Python has no sys.intern() function. + import __builtin__ + try: + sys.intern = __builtin__.intern + except AttributeError: + # Pre-2.x Python has no builtin intern() function. + def intern(x): + return x + sys.intern = intern + del intern +try: + sys.maxsize +except AttributeError: + # Pre-2.6 Python has no sys.maxsize attribute + sys.maxsize = sys.maxint +try: sys.version_info except AttributeError: # Pre-1.6 Python has no sys.version_info diff --git a/src/engine/SCons/compat/_scons_optparse.py b/src/engine/SCons/compat/_scons_optparse.py index 219adba..5db4c90 100644 --- a/src/engine/SCons/compat/_scons_optparse.py +++ b/src/engine/SCons/compat/_scons_optparse.py @@ -799,7 +799,7 @@ class Option: if self.nargs == 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(map(lambda v: self.check_value(opt, v), value)) def process(self, opt, value, values, parser): @@ -1700,7 +1700,7 @@ def _match_abbrev(s, wordmap): return s else: # Isolate all words with s as a prefix. - possibilities = filter(lambda w, s=s: w[:len(s)] == s, wordmap.keys()) + possibilities = filter(lambda w: w[:len(s)] == s, wordmap.keys()) # No exact match, so there had better be just one possibility. if len(possibilities) == 1: return possibilities[0] diff --git a/src/engine/SCons/compat/builtins.py b/src/engine/SCons/compat/builtins.py index 19329f6..d52ea4d 100644 --- a/src/engine/SCons/compat/builtins.py +++ b/src/engine/SCons/compat/builtins.py @@ -158,7 +158,7 @@ except NameError: """ result = [] for i in xrange(min(map(len, lists))): - result.append(tuple(map(lambda l, i=i: l[i], lists))) + result.append(tuple(map(lambda l: l[i], lists))) return result __builtin__.zip = zip diff --git a/src/engine/SCons/cpp.py b/src/engine/SCons/cpp.py index 47d664c..4a826ba 100644 --- a/src/engine/SCons/cpp.py +++ b/src/engine/SCons/cpp.py @@ -34,7 +34,6 @@ import SCons import os import re -import string # # First "subsystem" of regular expressions that we set up: @@ -91,7 +90,7 @@ del op_list override = { 'if' : 'if(?!def)', } -l = map(lambda x, o=override: o.get(x, x), Table.keys()) +l = [override.get(x, x) for x in Table.keys()] # Turn the list of expressions into one big honkin' regular expression @@ -99,7 +98,7 @@ l = map(lambda x, o=override: o.get(x, x), Table.keys()) # a list of tuples, one for each preprocessor line. The preprocessor # directive will be the first element in each tuple, and the rest of # the line will be the second element. -e = '^\s*#\s*(' + string.join(l, '|') + ')(.*)$' +e = '^\s*#\s*(' + '|'.join(l) + ')(.*)$' # And last but not least, compile the expression. CPP_Expression = re.compile(e, re.M) @@ -126,7 +125,7 @@ CPP_to_Python_Ops_Dict = { '\r' : '', } -CPP_to_Python_Ops_Sub = lambda m, d=CPP_to_Python_Ops_Dict: d[m.group(0)] +CPP_to_Python_Ops_Sub = lambda m: CPP_to_Python_Ops_Dict[m.group(0)] # We have to sort the keys by length so that longer expressions # come *before* shorter expressions--in particular, "!=" must @@ -139,7 +138,7 @@ l.sort(lambda a, b: cmp(len(b), len(a))) # Turn the list of keys into one regular expression that will allow us # to substitute all of the operators at once. -expr = string.join(map(re.escape, l), '|') +expr = '|'.join(map(re.escape, l)) # ...and compile the expression. CPP_to_Python_Ops_Expression = re.compile(expr) @@ -147,8 +146,8 @@ CPP_to_Python_Ops_Expression = re.compile(expr) # A separate list of expressions to be evaluated and substituted # sequentially, not all at once. CPP_to_Python_Eval_List = [ - ['defined\s+(\w+)', '__dict__.has_key("\\1")'], - ['defined\s*\((\w+)\)', '__dict__.has_key("\\1")'], + ['defined\s+(\w+)', '"\\1" in __dict__'], + ['defined\s*\((\w+)\)', '"\\1" in __dict__'], ['/\*.*\*/', ''], ['/\*.*', ''], ['//.*', ''], @@ -192,7 +191,7 @@ class FunctionEvaluator: self.name = name self.args = function_arg_separator.split(args) try: - expansion = string.split(expansion, '##') + expansion = expansion.split('##') except (AttributeError, TypeError): # Python 1.5 throws TypeError if "expansion" isn't a string, # later versions throw AttributeError. @@ -218,7 +217,7 @@ class FunctionEvaluator: if not s in self.args: s = repr(s) parts.append(s) - statement = string.join(parts, ' + ') + statement = ' + '.join(parts) return eval(statement, globals(), locals) @@ -292,9 +291,7 @@ class PreProcessor: global CPP_Expression, Table contents = line_continuations.sub('', contents) cpp_tuples = CPP_Expression.findall(contents) - return map(lambda m, t=Table: - (m[0],) + t[m[0]].match(m[1]).groups(), - cpp_tuples) + return [(m[0],) + Table[m[0]].match(m[1]).groups() for m in cpp_tuples] def __call__(self, file): """ @@ -363,7 +360,7 @@ class PreProcessor: eval()ing it in the C preprocessor namespace we use to track #define values. """ - t = CPP_to_Python(string.join(t[1:])) + t = CPP_to_Python(' '.join(t[1:])) try: return eval(t, self.cpp_namespace) except (NameError, TypeError): return 0 @@ -446,13 +443,13 @@ class PreProcessor: """ Default handling of a #ifdef line. """ - self._do_if_else_condition(self.cpp_namespace.has_key(t[1])) + self._do_if_else_condition(t[1] in self.cpp_namespace) def do_ifndef(self, t): """ Default handling of a #ifndef line. """ - self._do_if_else_condition(not self.cpp_namespace.has_key(t[1])) + self._do_if_else_condition(t[1] not in self.cpp_namespace) def do_if(self, t): """ @@ -563,7 +560,7 @@ class PreProcessor: s = self.cpp_namespace[m.group(1)] if callable(s): args = function_arg_separator.split(m.group(2)) - s = apply(s, args) + s = s(*args) if not s: return None return (t[0], s[0], s[1:-1]) @@ -584,7 +581,7 @@ class DumbPreProcessor(PreProcessor): to tailor its behavior. """ def __init__(self, *args, **kw): - apply(PreProcessor.__init__, (self,)+args, kw) + PreProcessor.__init__(self, *args, **kw) d = self.default_table for func in ['if', 'elif', 'else', 'endif', 'ifdef', 'ifndef']: d[func] = d[func] = self.do_nothing diff --git a/src/engine/SCons/cppTests.py b/src/engine/SCons/cppTests.py index 252a064..bfb0b46 100644 --- a/src/engine/SCons/cppTests.py +++ b/src/engine/SCons/cppTests.py @@ -23,7 +23,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" -import string import sys import unittest @@ -635,7 +634,7 @@ class fileTestCase(unittest.TestCase): 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, spaces=spaces): #if l.startswith(spaces): @@ -643,7 +642,7 @@ class fileTestCase(unittest.TestCase): l = l[len(spaces):] return l #return '\n'.join([ strip_spaces(l) for l in lines ]) - return string.join(map(strip_spaces, lines), '\n') + return '\n'.join(map(strip_spaces, lines)) def write(self, file, contents): open(file, 'w').write(self.strip_initial_spaces(contents)) @@ -675,7 +674,7 @@ class fileTestCase(unittest.TestCase): """) class MyPreProcessor(cpp.DumbPreProcessor): def __init__(self, *args, **kw): - apply(cpp.DumbPreProcessor.__init__, (self,) + args, kw) + cpp.DumbPreProcessor.__init__(self, *args, **kw) self.files = [] def __call__(self, file): self.files.append(file) @@ -704,7 +703,7 @@ if __name__ == '__main__': except NameError: pass names.sort() - suite.addTests(map(tclass, names)) + suite.addTests(list(map(tclass, names))) if not unittest.TextTestRunner().run(suite).wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/exitfuncs.py b/src/engine/SCons/exitfuncs.py index d911b52..250dd54 100644 --- a/src/engine/SCons/exitfuncs.py +++ b/src/engine/SCons/exitfuncs.py @@ -41,7 +41,7 @@ def _run_exitfuncs(): while _exithandlers: func, targs, kargs = _exithandlers.pop() - apply(func, targs, kargs) + func(*targs, **kargs) def register(func, *targs, **kargs): """register a function to be executed upon normal program termination diff --git a/src/script/scons-time.py b/src/script/scons-time.py index eeddd87..c75bc13 100644 --- a/src/script/scons-time.py +++ b/src/script/scons-time.py @@ -30,8 +30,8 @@ # 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 nested_scopes +from __future__ import generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -41,7 +41,6 @@ import os import os.path import re import shutil -import string import sys import tempfile import time @@ -177,13 +176,13 @@ class Gnuplotter(Plotter): result = [] for line in self.lines: result.extend(line.get_x_values()) - return filter(lambda r: not r is None, result) + return [r for r in result if not r is None] def get_all_y_values(self): result = [] for line in self.lines: result.extend(line.get_y_values()) - return filter(lambda r: not r is None, result) + return [r for r in result if not r is None] def get_min_x(self): try: @@ -539,7 +538,7 @@ class SConsTimer: for file in files: base = os.path.splitext(file)[0] - run, index = string.split(base, '-')[-2:] + run, index = base.split('-')[-2:] run = int(run) index = int(index) @@ -577,11 +576,11 @@ class SConsTimer: and returns the next run number after the largest it finds. """ x = re.compile(re.escape(prefix) + '-([0-9]+).*') - matches = map(lambda e, x=x: x.match(e), os.listdir(dir)) - matches = filter(None, matches) + matches = [x.match(e) for e in os.listdir(dir)] + matches = [_f for _f in matches if _f] if not matches: return 0 - run_numbers = map(lambda m: int(m.group(1)), matches) + run_numbers = [int(m.group(1)) for m in matches] return int(max(run_numbers)) + 1 def gnuplot_results(self, results, fmt='%s %.3f'): @@ -964,7 +963,7 @@ class SConsTimer: if self.chdir: os.chdir(self.chdir) - logfile_path = lambda x, c=self.chdir: os.path.join(c, x) + logfile_path = lambda x: os.path.join(self.chdir, x) if not args: @@ -1084,7 +1083,7 @@ class SConsTimer: if self.chdir: os.chdir(self.chdir) - logfile_path = lambda x, c=self.chdir: os.path.join(c, x) + logfile_path = lambda x: os.path.join(self.chdir, x) if not args: @@ -1462,7 +1461,7 @@ class SConsTimer: if self.chdir: os.chdir(self.chdir) - logfile_path = lambda x, c=self.chdir: os.path.join(c, x) + logfile_path = lambda x: os.path.join(self.chdir, x) if not args: diff --git a/src/script/scons.py b/src/script/scons.py index dec4222..010302f 100644 --- a/src/script/scons.py +++ b/src/script/scons.py @@ -76,7 +76,7 @@ if script_dir in sys.path: libs = [] -if os.environ.has_key("SCONS_LIB_DIR"): +if "SCONS_LIB_DIR" in os.environ: libs.append(os.environ["SCONS_LIB_DIR"]) local_version = 'scons-local-' + __version__ @@ -137,12 +137,11 @@ else: # check only /foo/lib/scons*. prefs.append(sys.prefix) - temp = map(lambda x: os.path.join(x, 'lib'), prefs) - temp.extend(map(lambda x: os.path.join(x, + temp = [os.path.join(x, 'lib') for x in prefs] + temp.extend([os.path.join(x, 'lib', 'python' + sys.version[:3], - 'site-packages'), - prefs)) + 'site-packages') for x in prefs]) prefs = temp # Add the parent directory of the current python's library to the @@ -175,8 +174,8 @@ else: # Look first for 'scons-__version__' in all of our preference libs, # then for 'scons'. -libs.extend(map(lambda x: os.path.join(x, scons_version), prefs)) -libs.extend(map(lambda x: os.path.join(x, 'scons'), prefs)) +libs.extend([os.path.join(x, scons_version) for x in prefs]) +libs.extend([os.path.join(x, 'scons') for x in prefs]) sys.path = libs + sys.path diff --git a/src/script/sconsign.py b/src/script/sconsign.py index 40c5daf..fb3bd5e 100644 --- a/src/script/sconsign.py +++ b/src/script/sconsign.py @@ -23,6 +23,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -64,7 +65,7 @@ if script_dir in sys.path: libs = [] -if os.environ.has_key("SCONS_LIB_DIR"): +if "SCONS_LIB_DIR" in os.environ: libs.append(os.environ["SCONS_LIB_DIR"]) local_version = 'scons-local-' + __version__ @@ -125,12 +126,11 @@ else: # check only /foo/lib/scons*. prefs.append(sys.prefix) - temp = map(lambda x: os.path.join(x, 'lib'), prefs) - temp.extend(map(lambda x: os.path.join(x, + temp = [os.path.join(x, 'lib') for x in prefs] + temp.extend([os.path.join(x, 'lib', 'python' + sys.version[:3], - 'site-packages'), - prefs)) + 'site-packages') for x in prefs]) prefs = temp # Add the parent directory of the current python's library to the @@ -163,8 +163,8 @@ else: # Look first for 'scons-__version__' in all of our preference libs, # then for 'scons'. -libs.extend(map(lambda x: os.path.join(x, scons_version), prefs)) -libs.extend(map(lambda x: os.path.join(x, 'scons'), prefs)) +libs.extend([os.path.join(x, scons_version) for x in prefs]) +libs.extend([os.path.join(x, 'scons') for x in prefs]) sys.path = libs + sys.path @@ -174,7 +174,6 @@ sys.path = libs + sys.path import cPickle import imp -import string import whichdb import SCons.SConsign @@ -195,7 +194,7 @@ whichdb.whichdb = my_whichdb def my_import(mname): if '.' in mname: - i = string.rfind(mname, '.') + i = mname.rfind('.') parent = my_import(mname[:i]) fp, pathname, description = imp.find_module(mname[i+1:], parent.__path__) @@ -254,7 +253,7 @@ def map_bkids(entry, name): result.append(nodeinfo_string(bkids[i], bkidsigs[i], " ")) if result == []: return None - return string.join(result, "\n ") + return "\n ".join(result) map_field = { 'action' : map_action, @@ -290,22 +289,21 @@ def nodeinfo_raw(name, ninfo, prefix=""): l.append('%s: %s' % (repr(k), repr(d.get(k)))) if '\n' in name: name = repr(name) - return name + ': {' + string.join(l, ', ') + '}' + return name + ': {' + ', '.join(l) + '}' def nodeinfo_cooked(name, ninfo, prefix=""): try: field_list = ninfo.field_list except AttributeError: field_list = [] - f = lambda x, ni=ninfo, v=Verbose: field(x, ni, v) if '\n' in name: name = repr(name) - outlist = [name+':'] + filter(None, map(f, field_list)) + outlist = [name+':'] + [_f for _f in [field(x, ninfo, Verbose) for x in field_list] if _f] if Verbose: sep = '\n ' + prefix else: sep = ' ' - return string.join(outlist, sep) + return sep.join(outlist) nodeinfo_string = nodeinfo_cooked diff --git a/src/setup.py b/src/setup.py index 9378770..0dbb012 100644 --- a/src/setup.py +++ b/src/setup.py @@ -20,13 +20,13 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import os.path import stat -import string import sys Version = "__VERSION__" @@ -198,7 +198,7 @@ def get_scons_prefix(libdir, is_win32): if head == os.sep: break head, tail = os.path.split(head) - if string.lower(tail)[:6] == "python": + if tail.lower()[:6] == "python": # Found the Python library directory... if is_win32: # ...on Win32 systems, "scons" goes in the directory: @@ -297,8 +297,8 @@ class install_scripts(_install_scripts): create_version_script = self.do_nothing inputs = self.get_inputs() - bat_scripts = filter(lambda x: x[-4:] == '.bat', inputs) - non_bat_scripts = filter(lambda x: x[-4:] != '.bat', inputs) + bat_scripts = [x for x in inputs if x[-4:] == '.bat'] + non_bat_scripts = [x for x in inputs if x[-4:] != '.bat'] self.outfiles = [] self.mkpath(self.install_dir) @@ -415,10 +415,10 @@ arguments = { 'build_scripts' : build_scripts} } -apply(distutils.core.setup, (), arguments) +distutils.core.setup(**arguments) if Installed: - print string.join(Installed, '\n') + print '\n'.join(Installed) # Local Variables: # tab-width:4 diff --git a/src/test_aegistests.py b/src/test_aegistests.py index af29083..744f141 100644 --- a/src/test_aegistests.py +++ b/src/test_aegistests.py @@ -21,6 +21,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -35,7 +36,6 @@ name of this script doesn't end in *Tests.py. import os import popen2 import re -import string import sys import TestSCons @@ -57,8 +57,8 @@ else: output = get_stdout('aegis -list -unformatted pf') +\ get_stdout('aegis -list -unformatted cf') -lines = string.split(output, '\n')[:-1] -sources = filter(lambda x: x[:7] == 'source ', lines) +lines = output.split('\n')[:-1] +sources = [x for x in lines if x[:7] == 'source '] re1 = re.compile(r' src/.*Tests\.py') re2 = re.compile(r' src/test_.*\.py') @@ -67,11 +67,11 @@ re3 = re.compile(r' test/.*\.py') def filename_is_a_test(x): return re1.search(x) or re2.search(x) or re3.search(x) -test_files = filter(filename_is_a_test, sources) +test_files = list(filter(filename_is_a_test, sources)) if test_files: sys.stderr.write("Found the following files with test names not marked as Aegis tests:\n") - sys.stderr.write('\t' + string.join(test_files, '\n\t') + '\n') + sys.stderr.write('\t' + '\n\t'.join(test_files) + '\n') test.fail_test(1) test.pass_test() diff --git a/src/test_files.py b/src/test_files.py index b413853..7d8e75e 100644 --- a/src/test_files.py +++ b/src/test_files.py @@ -35,7 +35,6 @@ name of this script doesn't end in *Tests.py. import os import os.path import re -import string import TestSCons @@ -47,7 +46,7 @@ except KeyError: cwd = os.getcwd() def build_path(*args): - return apply(os.path.join, (cwd, 'build',) + args) + return os.path.join(cwd, 'build', *args) build_scons_tar_gz = build_path('unpack-tar-gz', 'scons-'+test.scons_version) build_scons_zip = build_path('unpack-zip', 'scons-'+test.scons_version) @@ -89,12 +88,12 @@ for directory, check_list in check.items(): if missing: print "Missing the following files:\n" - print "\t" + string.join(missing, "\n\t") + print "\t" + "\n\t".join(missing) test.fail_test(1) if no_result: print "Cannot check files, the following have apparently not been built:" - print "\t" + string.join(no_result, "\n\t") + print "\t" + "\n\t".join(no_result) test.no_result(1) test.pass_test() diff --git a/src/test_interrupts.py b/src/test_interrupts.py index 0c7c4df..69e7a80 100644 --- a/src/test_interrupts.py +++ b/src/test_interrupts.py @@ -21,6 +21,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -32,7 +33,6 @@ keyboard interrupts (e.g. Ctrl-C). import os import os.path import re -import string import time import TestSCons @@ -76,8 +76,8 @@ try: except IOError: test.skip_test('%s does not exist; skipping test.\n' % MANIFEST) else: - files = string.split(fp.read()) - files = filter(lambda f: f[-3:] == '.py', files) + files = fp.read().split() + files = [f for f in files if f[-3:] == '.py'] # some regexps to parse the python files tryexc_pat = re.compile( @@ -100,7 +100,7 @@ for f in files: indent_list = try_except_lines[match.group('indent')] except: indent_list = [] - line_num = 1 + string.count(contents[:match.start()], '\n') + line_num = 1 + contents[:match.start()].count('\n') indent_list.append( (line_num, match.group('try_or_except') ) ) try_except_lines[match.group('indent')] = indent_list uncaught_this_file = [] @@ -111,7 +111,7 @@ for f in files: #print "%4d %s" % (l,statement), m1 = keyboardint_pat.match(statement) m2 = exceptall_pat.match(statement) - if string.find(statement, indent + 'try') == 0: + if statement.find(indent + 'try') == 0: if exc_all_seen and not exc_keyboardint_seen: uncaught_this_file.append(line) exc_keyboardint_seen = 0 diff --git a/src/test_pychecker.py b/src/test_pychecker.py index 20aae69..fb60646 100644 --- a/src/test_pychecker.py +++ b/src/test_pychecker.py @@ -21,6 +21,7 @@ # 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 generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -30,7 +31,6 @@ Use pychecker to catch various Python coding errors. import os import os.path -import string import sys import TestSCons @@ -64,9 +64,9 @@ else: src_engine_ = os.path.join(src_engine, '') MANIFEST = os.path.join(src_engine, 'MANIFEST.in') -files = string.split(open(MANIFEST).read()) +files = open(MANIFEST).read().split() -files = filter(lambda f: f[-3:] == '.py', files) +files = [f for f in files if f[-3:] == '.py'] ignore = [ 'SCons/compat/__init__.py', @@ -131,15 +131,15 @@ for file in files: test.run(program=program, arguments=args, status=None, stderr=None) stdout = test.stdout() - stdout = string.replace(stdout, src_engine_, '') + stdout = stdout.replace(src_engine_, '') stderr = test.stderr() - stderr = string.replace(stderr, src_engine_, '') - stderr = string.replace(stderr, pywintypes_warning, '') + stderr = stderr.replace(src_engine_, '') + stderr = stderr.replace(pywintypes_warning, '') if test.status or stdout or stderr: mismatches.append('\n') - mismatches.append(string.join([program] + args) + '\n') + mismatches.append(' '.join([program] + args) + '\n') mismatches.append('STDOUT =====================================\n') mismatches.append(stdout) @@ -149,7 +149,7 @@ for file in files: mismatches.append(stderr) if mismatches: - print string.join(mismatches[1:], '') + print ''.join(mismatches[1:]) test.fail_test() test.pass_test() diff --git a/src/test_setup.py b/src/test_setup.py index 7454b56..29d36bf 100644 --- a/src/test_setup.py +++ b/src/test_setup.py @@ -34,7 +34,6 @@ name of this script doesn't end in *Tests.py. import os import os.path import shutil -import string import sys try: WindowsError @@ -109,51 +108,50 @@ class MyTestSCons(TestSCons.TestSCons): self.version_lib = os.path.join(self.lib_dir, scons_version) self.man_dir = os.path.join(self.prefix, 'man', 'man1') - self.prepend_bin_dir = lambda p, d=self.bin_dir: os.path.join(d, p) - self.prepend_bat_dir = lambda p, d=self.bat_dir: os.path.join(d, p) - self.prepend_man_dir = lambda p, d=self.man_dir: os.path.join(d, p) + self.prepend_bin_dir = lambda p: os.path.join(self.bin_dir, p) + self.prepend_bat_dir = lambda p: os.path.join(self.bat_dir, p) + self.prepend_man_dir = lambda p: os.path.join(self.man_dir, p) def run(self, *args, **kw): kw['chdir'] = scons_version kw['program'] = python kw['stderr'] = None - return apply(TestSCons.TestSCons.run, (self,)+args, kw) + return TestSCons.TestSCons.run(self, *args, **kw) def remove(self, dir): try: shutil.rmtree(dir) except (OSError, WindowsError): pass def stdout_lines(self): - return string.split(self.stdout(), '\n') + return self.stdout().split('\n') def lib_line(self, lib): return 'Installed SCons library modules into %s' % lib def lib_paths(self, lib_dir): - prepend_lib_dir = lambda p, d=lib_dir: os.path.join(d, 'SCons', p) - return map(prepend_lib_dir, self._lib_modules) + return [os.path.join(lib_dir, 'SCons', p) for p in self._lib_modules] def scripts_line(self): return 'Installed SCons scripts into %s' % self.bin_dir def base_script_paths(self): scripts = self._base_scripts - return map(self.prepend_bin_dir, scripts) + return list(map(self.prepend_bin_dir, scripts)) def version_script_paths(self): scripts = self._version_scripts - return map(self.prepend_bin_dir, scripts) + return list(map(self.prepend_bin_dir, scripts)) def bat_script_paths(self): scripts = self._bat_scripts + self._bat_version_scripts - return map(self.prepend_bat_dir, scripts) + return list(map(self.prepend_bat_dir, scripts)) def man_page_line(self): return 'Installed SCons man pages into %s' % self.man_dir def man_page_paths(self): - return map(self.prepend_man_dir, self._man_pages) + return list(map(self.prepend_man_dir, self._man_pages)) def must_have_installed(self, paths): @@ -321,8 +319,7 @@ test.must_have_installed(test.man_page_paths()) other_prefix = test.workpath('other-prefix') test.subdir(other_prefix) test.run(arguments = 'setup.py install --prefix=%s' % other_prefix) -test.fail_test(string.find(test.stderr(), - "you'll have to change the search path yourself") +test.fail_test(test.stderr().find("you'll have to change the search path yourself") != -1) # All done. diff --git a/src/test_strings.py b/src/test_strings.py index 4ca2245..eed4234 100644 --- a/src/test_strings.py +++ b/src/test_strings.py @@ -36,7 +36,6 @@ import fnmatch import os import os.path import re -import string import TestCmd import TestSCons @@ -47,7 +46,7 @@ test = TestCmd.TestCmd() scons_version = TestSCons.SConsVersion def build_path(*args): - return apply(os.path.join, ('build',)+args) + return os.path.join('build', *args) build_scons = build_path('scons') build_local = build_path('scons-local', 'scons-local-'+scons_version) @@ -87,8 +86,7 @@ class Checker: return os.path.isfile(path) def visit(self, result, dirname, names): - make_path_tuple = lambda n, d=dirname: (n, os.path.join(d, n)) - for name, path in map(make_path_tuple, names): + for name, path in [(n, os.path.join(dirname, n)) for n in names]: if self.remove_this(name, path): names.remove(name) elif self.search_this(path): @@ -263,12 +261,12 @@ for collector in check_list: if missing_strings: print "Found the following files with missing strings:" - print "\t" + string.join(missing_strings, "\n\t") + print "\t" + "\n\t".join(missing_strings) test.fail_test(1) if not_built: print "Cannot check all strings, the following have apparently not been built:" - print "\t" + string.join(not_built, "\n\t") + print "\t" + "\n\t".join(not_built) test.no_result(1) test.pass_test() |