diff options
author | Luca Falavigna <dktrkranz@debian.org> | 2010-06-15 14:28:22 +0000 |
---|---|---|
committer | Luca Falavigna <dktrkranz@debian.org> | 2010-06-15 14:28:22 +0000 |
commit | 738149c9bfb9965d013d01ef99f9bb1c2819e7e8 (patch) | |
tree | 0397d9bf3b12c903dc73419585df231397ff343c /src/engine/SCons/Script | |
parent | e7885e3af440eaef38a9301fd92a105afc8ddebb (diff) |
Imported Upstream version 2.0.0upstream/2.0.0
Diffstat (limited to 'src/engine/SCons/Script')
-rw-r--r-- | src/engine/SCons/Script/Interactive.py | 22 | ||||
-rw-r--r-- | src/engine/SCons/Script/Main.py | 132 | ||||
-rw-r--r-- | src/engine/SCons/Script/MainTests.py | 4 | ||||
-rw-r--r-- | src/engine/SCons/Script/SConsOptions.py | 65 | ||||
-rw-r--r-- | src/engine/SCons/Script/SConscript.py | 70 | ||||
-rw-r--r-- | src/engine/SCons/Script/SConscriptTests.py | 2 | ||||
-rw-r--r-- | src/engine/SCons/Script/__init__.py | 16 |
7 files changed, 137 insertions, 174 deletions
diff --git a/src/engine/SCons/Script/Interactive.py b/src/engine/SCons/Script/Interactive.py index 6218021..52fc753 100644 --- a/src/engine/SCons/Script/Interactive.py +++ b/src/engine/SCons/Script/Interactive.py @@ -19,9 +19,8 @@ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -__revision__ = "src/engine/SCons/Script/Interactive.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/Interactive.py 5023 2010/06/14 22:05:46 scons" __doc__ = """ SCons interactive mode @@ -90,7 +89,6 @@ import copy import os import re import shlex -import string import sys try: @@ -134,7 +132,7 @@ class SConsInteractiveCmd(cmd.Cmd): print "*** Unknown command: %s" % argv[0] def onecmd(self, line): - line = string.strip(line) + line = line.strip() if not line: print self.lastcmd return self.emptyline() @@ -144,7 +142,7 @@ class SConsInteractiveCmd(cmd.Cmd): elif line[0] == '?': line = 'help ' + line[1:] if os.sep == '\\': - line = string.replace(line, '\\', '\\\\') + line = line.replace('\\', '\\\\') argv = shlex.split(line) argv[0] = self.synonyms.get(argv[0], argv[0]) if not argv[0]: @@ -222,8 +220,8 @@ class SConsInteractiveCmd(cmd.Cmd): def get_unseen_children(node, parent, seen_nodes=seen_nodes): def is_unseen(node, seen_nodes=seen_nodes): - return not seen_nodes.has_key(node) - return filter(is_unseen, node.children(scan=1)) + return node not in seen_nodes + return list(filter(is_unseen, node.children(scan=1))) def add_to_seen_nodes(node, parent, seen_nodes=seen_nodes): seen_nodes[node] = 1 @@ -247,9 +245,9 @@ class SConsInteractiveCmd(cmd.Cmd): walker = SCons.Node.Walker(node, kids_func=get_unseen_children, eval_func=add_to_seen_nodes) - n = walker.next() + n = walker.get_next() while n: - n = walker.next() + n = walker.get_next() for node in seen_nodes.keys(): # Call node.clear() to clear most of the state @@ -307,7 +305,7 @@ class SConsInteractiveCmd(cmd.Cmd): def _strip_initial_spaces(self, s): #lines = s.split('\n') - lines = string.split(s, '\n') + lines = s.split('\n') spaces = re.match(' *', lines[0]).group(0) #def strip_spaces(l): # if l.startswith(spaces): @@ -318,8 +316,8 @@ class SConsInteractiveCmd(cmd.Cmd): if l[:len(spaces)] == spaces: l = l[len(spaces):] return l - lines = map(strip_spaces, lines) - return string.join(lines, '\n') + lines = list(map(strip_spaces, lines)) + return '\n'.join(lines) def do_exit(self, argv): """\ diff --git a/src/engine/SCons/Script/Main.py b/src/engine/SCons/Script/Main.py index 74a28f2..2bd1560 100644 --- a/src/engine/SCons/Script/Main.py +++ b/src/engine/SCons/Script/Main.py @@ -8,10 +8,11 @@ should not be, or be considered, part of the build engine. If it's something that we expect other software to want to use, it should go in some other module. If it's specific to the "scons" script invocation, it goes here. - """ -# +unsupported_python_version = (2, 3, 0) +deprecated_python_version = (2, 4, 0) + # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining @@ -32,13 +33,12 @@ it goes here. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -__revision__ = "src/engine/SCons/Script/Main.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/Main.py 5023 2010/06/14 22:05:46 scons" + +import SCons.compat import os -import os.path -import string import sys import time import traceback @@ -89,7 +89,7 @@ progress_display = SCons.Util.DisplayEngine() first_command_start = None last_command_end = None -class Progressor: +class Progressor(object): prev = '' count = 0 target_string = '$TARGET' @@ -107,7 +107,7 @@ class Progressor: self.func = obj elif SCons.Util.is_List(obj): self.func = self.spinner - elif string.find(obj, self.target_string) != -1: + elif obj.find(self.target_string) != -1: self.func = self.replace_string else: self.func = self.string @@ -132,7 +132,7 @@ class Progressor: self.write(self.obj) def replace_string(self, node): - self.write(string.replace(self.obj, self.target_string, str(node))) + self.write(self.obj.replace(self.target_string, str(node))) def __call__(self, node): self.count = self.count + 1 @@ -145,7 +145,7 @@ ProgressObject = SCons.Util.Null() def Progress(*args, **kw): global ProgressObject - ProgressObject = apply(Progressor, args, kw) + ProgressObject = Progressor(*args, **kw) # Task control. # @@ -207,12 +207,10 @@ class BuildTask(SCons.Taskmaster.OutOfDateTask): t = self.targets[0] if self.top and not t.has_builder() and not t.side_effect: if not t.exists(): - def classname(obj): - return string.split(str(obj.__class__), '.')[-1] - if classname(t) in ('File', 'Dir', 'Entry'): - errstr="Do not know how to make %s target `%s' (%s)." % (classname(t), t, t.abspath) + if t.__class__.__name__ in ('File', 'Dir', 'Entry'): + errstr="Do not know how to make %s target `%s' (%s)." % (t.__class__.__name__, t, t.abspath) else: # Alias or Python or ... - errstr="Do not know how to make %s target `%s'." % (classname(t), t) + errstr="Do not know how to make %s target `%s'." % (t.__class__.__name__, t) sys.stderr.write("scons: *** " + errstr) if not self.options.keep_going: sys.stderr.write(" Stop.") @@ -262,19 +260,16 @@ class BuildTask(SCons.Taskmaster.OutOfDateTask): node = buildError.node if not SCons.Util.is_List(node): node = [ node ] - nodename = string.join(map(str, node), ', ') + nodename = ', '.join(map(str, node)) errfmt = "scons: *** [%s] %s\n" sys.stderr.write(errfmt % (nodename, buildError)) if (buildError.exc_info[2] and buildError.exc_info[1] and - # TODO(1.5) - #not isinstance( - # buildError.exc_info[1], - # (EnvironmentError, SCons.Errors.StopError, SCons.Errors.UserError))): - not isinstance(buildError.exc_info[1], EnvironmentError) and - not isinstance(buildError.exc_info[1], SCons.Errors.StopError) and - not isinstance(buildError.exc_info[1], SCons.Errors.UserError)): + not isinstance( + buildError.exc_info[1], + (EnvironmentError, SCons.Errors.StopError, + SCons.Errors.UserError))): type, value, trace = buildError.exc_info traceback.print_exception(type, value, trace) elif tb and print_stacktrace: @@ -316,11 +311,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask): display("Removed " + pathstr) elif os.path.isdir(path) and not os.path.islink(path): # delete everything in the dir - entries = os.listdir(path) - # Sort for deterministic output (os.listdir() Can - # return entries in a random order). - entries.sort() - for e in entries: + for e in sorted(os.listdir(path)): p = os.path.join(path, e) s = os.path.join(pathstr, e) if os.path.isfile(p): @@ -345,7 +336,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask): for t in self.targets: if not t.isdir(): display("Removed " + str(t)) - if SCons.Environment.CleanTargets.has_key(target): + if target in SCons.Environment.CleanTargets: files = SCons.Environment.CleanTargets[target] for f in files: self.fs_delete(f.abspath, str(f), 0) @@ -366,7 +357,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask): else: if removed: display("Removed " + str(t)) - if SCons.Environment.CleanTargets.has_key(target): + if target in SCons.Environment.CleanTargets: files = SCons.Environment.CleanTargets[target] for f in files: self.fs_delete(f.abspath, str(f)) @@ -405,7 +396,7 @@ class QuestionTask(SCons.Taskmaster.AlwaysTask): pass -class TreePrinter: +class TreePrinter(object): def __init__(self, derived=False, prune=False, status=False): self.derived = derived self.prune = prune @@ -414,7 +405,7 @@ class TreePrinter: return node.all_children() def get_derived_children(self, node): children = node.all_children(None) - return filter(lambda x: x.has_builder(), children) + return [x for x in children if x.has_builder()] def display(self, t): if self.derived: func = self.get_derived_children @@ -425,13 +416,13 @@ class TreePrinter: def python_version_string(): - return string.split(sys.version)[0] + return sys.version.split()[0] def python_version_unsupported(version=sys.version_info): - return version < (1, 5, 2) + return version < unsupported_python_version def python_version_deprecated(version=sys.version_info): - return version < (2, 4, 0) + return version < deprecated_python_version # Global variables @@ -447,7 +438,7 @@ this_build_status = 0 # "exit status" of an individual build num_jobs = None delayed_warnings = [] -class FakeOptionParser: +class FakeOptionParser(object): """ A do-nothing option parser, used for the initial OptionsParser variable. @@ -459,7 +450,7 @@ class FakeOptionParser: without blowing up. """ - class FakeOptionValues: + class FakeOptionValues(object): def __getattr__(self, attr): return None values = FakeOptionValues() @@ -469,9 +460,9 @@ class FakeOptionParser: OptionsParser = FakeOptionParser() def AddOption(*args, **kw): - if not kw.has_key('default'): + if 'default' not in kw: kw['default'] = None - result = apply(OptionsParser.add_local_option, args, kw) + result = OptionsParser.add_local_option(*args, **kw) return result def GetOption(name): @@ -481,7 +472,7 @@ def SetOption(name, value): return OptionsParser.values.set_option(name, value) # -class Stats: +class Stats(object): def __init__(self): self.stats = [] self.labels = [] @@ -501,26 +492,24 @@ class CountStats(Stats): def do_print(self): stats_table = {} for s in self.stats: - for n in map(lambda t: t[0], s): + for n in [t[0] for t in s]: stats_table[n] = [0, 0, 0, 0] i = 0 for s in self.stats: for n, c in s: stats_table[n][i] = c i = i + 1 - keys = stats_table.keys() - keys.sort() self.outfp.write("Object counts:\n") pre = [" "] post = [" %s\n"] l = len(self.stats) - fmt1 = string.join(pre + [' %7s']*l + post, '') - fmt2 = string.join(pre + [' %7d']*l + post, '') + fmt1 = ''.join(pre + [' %7s']*l + post) + fmt2 = ''.join(pre + [' %7d']*l + post) labels = self.labels[:l] labels.append(("", "Class")) - self.outfp.write(fmt1 % tuple(map(lambda x: x[0], labels))) - self.outfp.write(fmt1 % tuple(map(lambda x: x[1], labels))) - for k in keys: + self.outfp.write(fmt1 % tuple([x[0] for x in labels])) + self.outfp.write(fmt1 % tuple([x[1] for x in labels])) + for k in sorted(stats_table.keys()): r = stats_table[k][:l] + [k] self.outfp.write(fmt2 % tuple(r)) @@ -532,7 +521,7 @@ class MemStats(Stats): self.stats.append(SCons.Debug.memory()) def do_print(self): fmt = 'Memory %-32s %12d\n' - for label, stats in map(None, self.labels, self.stats): + for label, stats in zip(self.labels, self.stats): self.outfp.write(fmt % (label, stats)) memory_stats = MemStats() @@ -563,7 +552,7 @@ def find_deepest_user_frame(tb): # of SCons: for frame in tb: filename = frame[0] - if string.find(filename, os.sep+'SCons'+os.sep) == -1: + if filename.find(os.sep+'SCons'+os.sep) == -1: return frame return tb[0] @@ -598,7 +587,7 @@ def _scons_internal_warning(e): *current call stack* rather than sys.exc_info() to get our stack trace. This is used by the warnings framework to print warnings.""" filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_stack()) - sys.stderr.write("\nscons: warning: %s\n" % e[0]) + sys.stderr.write("\nscons: warning: %s\n" % e.args[0]) sys.stderr.write('File "%s", line %d, in %s\n' % (filename, lineno, routine)) def _scons_internal_error(): @@ -687,7 +676,7 @@ def _load_site_scons_dir(topdir, site_dir_name=None): site_dir = os.path.join(topdir.path, site_dir_name) if not os.path.exists(site_dir): if err_if_not_found: - raise SCons.Errors.UserError, "site dir %s not found."%site_dir + raise SCons.Errors.UserError("site dir %s not found."%site_dir) return site_init_filename = "site_init.py" @@ -714,7 +703,7 @@ def _load_site_scons_dir(topdir, site_dir_name=None): m = sys.modules['SCons.Script'] except Exception, e: fmt = 'cannot import site_init.py: missing SCons.Script module %s' - raise SCons.Errors.InternalError, fmt % repr(e) + raise SCons.Errors.InternalError(fmt % repr(e)) try: # This is the magic. exec fp in m.__dict__ @@ -763,21 +752,8 @@ def _main(parser): # suppress) appropriate warnings about anything that might happen, # as configured by the user. - default_warnings = [ SCons.Warnings.CorruptSConsignWarning, + default_warnings = [ SCons.Warnings.WarningOnByDefault, SCons.Warnings.DeprecatedWarning, - SCons.Warnings.DuplicateEnvironmentWarning, - SCons.Warnings.FutureReservedVariableWarning, - SCons.Warnings.LinkWarning, - SCons.Warnings.MissingSConscriptWarning, - SCons.Warnings.NoMD5ModuleWarning, - SCons.Warnings.NoMetaclassSupportWarning, - SCons.Warnings.NoObjectCountWarning, - SCons.Warnings.NoParallelSupportWarning, - SCons.Warnings.MisleadingKeywordsWarning, - SCons.Warnings.ReservedVariableWarning, - SCons.Warnings.StackSizeWarning, - SCons.Warnings.VisualVersionMismatch, - SCons.Warnings.VisualCMissingWarning, ] for warning in default_warnings: @@ -855,7 +831,7 @@ def _main(parser): # Give them the options usage now, before we fail # trying to read a non-existent SConstruct file. raise SConsPrintHelpException - raise SCons.Errors.UserError, "No SConstruct file found." + raise SCons.Errors.UserError("No SConstruct file found.") if scripts[0] == "-": d = fs.getcwd() @@ -955,7 +931,7 @@ def _main(parser): # $SCONSFLAGS, or in the SConscript file, then the search through # the list of deprecated warning classes will find that disabling # first and not issue the warning. - SCons.Warnings.enableWarningClass(SCons.Warnings.PythonVersionWarning) + #SCons.Warnings.enableWarningClass(SCons.Warnings.PythonVersionWarning) SCons.Warnings.process_warn_strings(options.warn) # Now that we've read the SConscript files, we can check for the @@ -1087,7 +1063,7 @@ def _build_targets(fs, options, targets, target_top): # or not a file, so go ahead and keep it as a default # target and let the engine sort it out: return 1 - d = filter(check_dir, SCons.Script.DEFAULT_TARGETS) + d = list(filter(check_dir, SCons.Script.DEFAULT_TARGETS)) SCons.Script.DEFAULT_TARGETS[:] = d target_top = None lookup_top = None @@ -1122,7 +1098,7 @@ def _build_targets(fs, options, targets, target_top): node = None return node - nodes = filter(None, map(Entry, targets)) + nodes = [_f for _f in map(Entry, targets) if _f] task_class = BuildTask # default action is to build targets opening_message = "Building targets ..." @@ -1154,7 +1130,7 @@ def _build_targets(fs, options, targets, target_top): # This is cribbed from the implementation of # random.shuffle() in Python 2.X. d = dependencies - for i in xrange(len(d)-1, 0, -1): + for i in range(len(d)-1, 0, -1): j = int(random.random() * (i+1)) d[i], d[j] = d[j], d[i] return d @@ -1224,18 +1200,16 @@ def _build_targets(fs, options, targets, target_top): def _exec_main(parser, values): sconsflags = os.environ.get('SCONSFLAGS', '') - all_args = string.split(sconsflags) + sys.argv[1:] + all_args = sconsflags.split() + sys.argv[1:] options, args = parser.parse_args(all_args, values) - if type(options.debug) == type([]) and "pdb" in options.debug: + if isinstance(options.debug, list) and "pdb" in options.debug: import pdb pdb.Pdb().runcall(_main, parser) elif options.profile_file: - try: - from cProfile import Profile - except ImportError, e: - from profile import Profile + # compat layer imports "cProfile" for us if it's available. + from profile import Profile # Some versions of Python 2.4 shipped a profiler that had the # wrong 'c_exception' entry in its dispatch table. Make sure @@ -1285,7 +1259,7 @@ def main(): pass parts.append(version_string("engine", SCons)) parts.append("Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation") - version = string.join(parts, '') + version = ''.join(parts) import SConsOptions parser = SConsOptions.Parser(version) diff --git a/src/engine/SCons/Script/MainTests.py b/src/engine/SCons/Script/MainTests.py index d41d9c1..1855afa 100644 --- a/src/engine/SCons/Script/MainTests.py +++ b/src/engine/SCons/Script/MainTests.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Script/MainTests.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/MainTests.py 5023 2010/06/14 22:05:46 scons" import unittest import SCons.Errors @@ -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 545162b..913a6ee 100644 --- a/src/engine/SCons/Script/SConsOptions.py +++ b/src/engine/SCons/Script/SConsOptions.py @@ -21,20 +21,14 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Script/SConsOptions.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/SConsOptions.py 5023 2010/06/14 22:05:46 scons" import optparse import re -import string import sys import textwrap -try: - no_hyphen_re = re.compile(r'(\s+|(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') -except re.error: - # Pre-2.0 Python versions don't have the (?<= negative - # look-behind assertion. - no_hyphen_re = re.compile(r'(\s+|-*\w{2,}-(?=\w{2,}))') +no_hyphen_re = re.compile(r'(\s+|(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') try: from gettext import gettext @@ -55,9 +49,10 @@ def diskcheck_convert(value): if value is None: return [] if not SCons.Util.is_List(value): - value = string.split(value, ',') + value = value.split(',') result = [] - for v in map(string.lower, value): + for v in value: + v = v.lower() if v == 'all': result = diskcheck_all elif v == 'none': @@ -65,7 +60,7 @@ def diskcheck_convert(value): elif v in diskcheck_all: result.append(v) else: - raise ValueError, v + raise ValueError(v) return result class SConsValues(optparse.Values): @@ -139,7 +134,7 @@ class SConsValues(optparse.Values): Sets an option from an SConscript file. """ if not name in self.settable: - raise SCons.Errors.UserError, "This option is not settable from a SConscript file: %s"%name + raise SCons.Errors.UserError("This option is not settable from a SConscript file: %s"%name) if name == 'num_jobs': try: @@ -147,19 +142,19 @@ class SConsValues(optparse.Values): if value < 1: raise ValueError except ValueError: - raise SCons.Errors.UserError, "A positive integer is required: %s"%repr(value) + raise SCons.Errors.UserError("A positive integer is required: %s"%repr(value)) elif name == 'max_drift': try: value = int(value) except ValueError: - raise SCons.Errors.UserError, "An integer is required: %s"%repr(value) + raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'duplicate': try: value = str(value) except ValueError: - raise SCons.Errors.UserError, "A string is required: %s"%repr(value) + raise SCons.Errors.UserError("A string is required: %s"%repr(value)) if not value in SCons.Node.FS.Valid_Duplicates: - raise SCons.Errors.UserError, "Not a valid duplication style: %s" % value + raise SCons.Errors.UserError("Not a valid duplication style: %s" % value) # Set the duplicate style right away so it can affect linking # of SConscript files. SCons.Node.FS.set_duplicate(value) @@ -167,8 +162,8 @@ class SConsValues(optparse.Values): try: value = diskcheck_convert(value) except ValueError, v: - raise SCons.Errors.UserError, "Not a valid diskcheck value: %s"%v - if not self.__dict__.has_key('diskcheck'): + raise SCons.Errors.UserError("Not a valid diskcheck value: %s"%v) + if 'diskcheck' not in self.__dict__: # No --diskcheck= option was specified on the command line. # Set this right away so it can affect the rest of the # file/Node lookups while processing the SConscript files. @@ -177,12 +172,12 @@ class SConsValues(optparse.Values): try: value = int(value) except ValueError: - raise SCons.Errors.UserError, "An integer is required: %s"%repr(value) + raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'md5_chunksize': try: value = int(value) except ValueError: - raise SCons.Errors.UserError, "An integer is required: %s"%repr(value) + raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'warn': if SCons.Util.is_String(value): value = [value] @@ -197,7 +192,7 @@ class SConsOption(optparse.Option): if self.nargs in (1, '?'): return self.check_value(opt, value) else: - return tuple(map(lambda v, o=opt, s=self: s.check_value(o, v), value)) + return tuple([self.check_value(opt, v) for v in value]) def process(self, opt, value, values, parser): @@ -214,7 +209,7 @@ class SConsOption(optparse.Option): def _check_nargs_optional(self): if self.nargs == '?' and self._short_opts: fmt = "option %s: nargs='?' is incompatible with short options" - raise SCons.Errors.UserError, fmt % self._short_opts[0] + raise SCons.Errors.UserError(fmt % self._short_opts[0]) try: _orig_CONST_ACTIONS = optparse.Option.CONST_ACTIONS @@ -292,7 +287,7 @@ class SConsOptionParser(optparse.OptionParser): # Value explicitly attached to arg? Pretend it's the next # argument. if "=" in arg: - (opt, next_arg) = string.split(arg, "=", 1) + (opt, next_arg) = arg.split("=", 1) rargs.insert(0, next_arg) had_explicit_value = True else: @@ -356,7 +351,7 @@ class SConsOptionParser(optparse.OptionParser): group = self.add_option_group(group) self.local_option_group = group - result = apply(group.add_option, args, kw) + result = group.add_option(*args, **kw) if result: # The option was added succesfully. We now have to add the @@ -461,7 +456,7 @@ class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter): result.append("%*s%s\n" % (self.help_position, "", line)) elif opts[-1] != "\n": result.append("\n") - return string.join(result, "") + return "".join(result) # For consistent help output across Python versions, we provide a # subclass copy of format_option_strings() and these two variables. @@ -473,7 +468,7 @@ class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter): def format_option_strings(self, option): """Return a comma-separated list of option strings & metavariables.""" if option.takes_value(): - metavar = option.metavar or string.upper(option.dest) + metavar = option.metavar or option.dest.upper() short_opts = [] for sopt in option._short_opts: short_opts.append(self._short_opt_fmt % (sopt, metavar)) @@ -489,7 +484,7 @@ class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter): else: opts = long_opts + short_opts - return string.join(opts, ", ") + return ", ".join(opts) def Parser(version): """ @@ -580,7 +575,7 @@ def Parser(version): raise OptionValueError("Warning: %s is not a valid config type" % value) setattr(parser.values, option.dest, value) opt_config_help = "Controls Configure subsystem: %s." \ - % string.join(config_options, ", ") + % ", ".join(config_options) op.add_option('--config', nargs=1, type="string", dest="config", default="auto", @@ -604,7 +599,7 @@ def Parser(version): debug_options = ["count", "explain", "findlibs", "includes", "memoizer", "memory", "objects", "pdb", "presub", "stacktrace", - "time"] + deprecated_debug_options.keys() + "time"] + list(deprecated_debug_options.keys()) def opt_debug(option, opt, value, parser, debug_options=debug_options, @@ -618,12 +613,12 @@ def Parser(version): parser.values.delayed_warnings = [] msg = deprecated_debug_options[value] w = "The --debug=%s option is deprecated%s." % (value, msg) - t = (SCons.Warnings.DeprecatedWarning, w) + t = (SCons.Warnings.DeprecatedDebugOptionsWarning, w) parser.values.delayed_warnings.append(t) else: raise OptionValueError("Warning: %s is not a valid debug type" % value) opt_debug_help = "Print various types of debugging information: %s." \ - % string.join(debug_options, ", ") + % ", ".join(debug_options) op.add_option('--debug', nargs=1, type="string", dest="debug", default=[], @@ -654,7 +649,7 @@ def Parser(version): SCons.Node.FS.set_duplicate(value) opt_duplicate_help = "Set the preferred duplication methods. Must be one of " \ - + string.join(SCons.Node.FS.Valid_Duplicates, ", ") + + ", ".join(SCons.Node.FS.Valid_Duplicates) op.add_option('--duplicate', nargs=1, type="string", @@ -802,7 +797,7 @@ def Parser(version): def opt_tree(option, opt, value, parser, tree_options=tree_options): import Main tp = Main.TreePrinter() - for o in string.split(value, ','): + for o in value.split(','): if o == 'all': tp.derived = False elif o == 'derived': @@ -816,7 +811,7 @@ def Parser(version): parser.values.tree_printers.append(tp) opt_tree_help = "Print a dependency tree in various formats: %s." \ - % string.join(tree_options, ", ") + % ", ".join(tree_options) op.add_option('--tree', nargs=1, type="string", @@ -846,7 +841,7 @@ def Parser(version): def opt_warn(option, opt, value, parser, tree_options=tree_options): if SCons.Util.is_String(value): - value = string.split(value, ',') + value = value.split(',') parser.values.warn.extend(value) op.add_option('--warn', '--warning', diff --git a/src/engine/SCons/Script/SConscript.py b/src/engine/SCons/Script/SConscript.py index 98a3126..5a22db7 100644 --- a/src/engine/SCons/Script/SConscript.py +++ b/src/engine/SCons/Script/SConscript.py @@ -26,9 +26,9 @@ files. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# +from __future__ import division -__revision__ = "src/engine/SCons/Script/SConscript.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/SConscript.py 5023 2010/06/14 22:05:46 scons" import SCons import SCons.Action @@ -45,14 +45,12 @@ import SCons.Script.Main import SCons.Tool import SCons.Util +import collections import os import os.path import re -import string import sys import traceback -import types -import UserList # The following variables used to live in this module. Some # SConscript files out there may have referred to them directly as @@ -80,7 +78,7 @@ sconscript_chdir = 1 def get_calling_namespaces(): """Return the locals and globals for the function that called into this module in the current call stack.""" - try: 1/0 + try: 1//0 except ZeroDivisionError: # Don't start iterating with the current stack-frame to # prevent creating reference cycles (f_back is safe). @@ -116,11 +114,11 @@ def compute_exports(exports): except KeyError: retval[export] = glob[export] except KeyError, x: - raise SCons.Errors.UserError, "Export of non-existent variable '%s'"%x + raise SCons.Errors.UserError("Export of non-existent variable '%s'"%x) return retval -class Frame: +class Frame(object): """A frame on the SConstruct/SConscript call stack""" def __init__(self, fs, exports, sconscript): self.globals = BuildDefaultGlobals() @@ -145,10 +143,10 @@ def Return(*vars, **kw): try: fvars = SCons.Util.flatten(vars) for var in fvars: - for v in string.split(var): + for v in var.split(): retval.append(call_stack[-1].globals[v]) except KeyError, x: - raise SCons.Errors.UserError, "Return of non-existent variable '%s'"%x + raise SCons.Errors.UserError("Return of non-existent variable '%s'"%x) if len(retval) == 1: call_stack[-1].retval = retval[0] @@ -312,7 +310,7 @@ def SConscript_exception(file=sys.stderr): up to where we exec the SConscript.""" exc_type, exc_value, exc_tb = sys.exc_info() tb = exc_tb - while tb and not tb.tb_frame.f_locals.has_key(stack_bottom): + while tb and stack_bottom not in tb.tb_frame.f_locals: tb = tb.tb_next if not tb: # We did not find our exec statement, so this was actually a bug @@ -334,11 +332,11 @@ def annotate(node): """Annotate a node with the stack frame describing the SConscript file and line number that created it.""" tb = sys.exc_info()[2] - while tb and not tb.tb_frame.f_locals.has_key(stack_bottom): + while tb and stack_bottom not in tb.tb_frame.f_locals: tb = tb.tb_next if not tb: # We did not find any exec of an SConscript file: what?! - raise SCons.Errors.InternalError, "could not find SConscript stack frame" + raise SCons.Errors.InternalError("could not find SConscript stack frame") node.creator = traceback.extract_stack(tb)[0] # The following line would cause each Node to be annotated using the @@ -369,7 +367,7 @@ class SConsEnvironment(SCons.Environment.Base): This is complicated by the fact that a version string can be something like 3.2b1.""" - version = string.split(string.split(version_string, ' ')[0], '.') + version = version_string.split(' ')[0].split('.') v_major = int(version[0]) v_minor = int(re.match('\d+', version[1]).group()) if len(version) >= 3: @@ -380,7 +378,7 @@ class SConsEnvironment(SCons.Environment.Base): def _get_SConscript_filenames(self, ls, kw): """ - Convert the parameters passed to # SConscript() calls into a list + Convert the parameters passed to SConscript() calls into a list of files and export variables. If the parameters are invalid, throws SCons.Errors.UserError. Returns a tuple (l, e) where l is a list of SConscript filenames and e is a list of exports. @@ -391,16 +389,15 @@ class SConsEnvironment(SCons.Environment.Base): try: dirs = kw["dirs"] except KeyError: - raise SCons.Errors.UserError, \ - "Invalid SConscript usage - no parameters" + raise SCons.Errors.UserError("Invalid SConscript usage - no parameters") if not SCons.Util.is_List(dirs): dirs = [ dirs ] - dirs = map(str, dirs) + dirs = list(map(str, dirs)) name = kw.get('name', 'SConscript') - files = map(lambda n, name = name: os.path.join(n, name), dirs) + files = [os.path.join(n, name) for n in dirs] elif len(ls) == 1: @@ -413,8 +410,7 @@ class SConsEnvironment(SCons.Environment.Base): else: - raise SCons.Errors.UserError, \ - "Invalid SConscript() usage - too many arguments" + raise SCons.Errors.UserError("Invalid SConscript() usage - too many arguments") if not SCons.Util.is_List(files): files = [ files ] @@ -425,8 +421,7 @@ class SConsEnvironment(SCons.Environment.Base): variant_dir = kw.get('variant_dir') or kw.get('build_dir') if variant_dir: if len(files) != 1: - raise SCons.Errors.UserError, \ - "Invalid SConscript() usage - can only specify one SConscript with a variant_dir" + raise SCons.Errors.UserError("Invalid SConscript() usage - can only specify one SConscript with a variant_dir") duplicate = kw.get('duplicate', 1) src_dir = kw.get('src_dir') if not src_dir: @@ -457,9 +452,9 @@ class SConsEnvironment(SCons.Environment.Base): def Configure(self, *args, **kw): if not SCons.Script.sconscript_reading: - raise SCons.Errors.UserError, "Calling Configure from Builders is not supported." + raise SCons.Errors.UserError("Calling Configure from Builders is not supported.") kw['_depth'] = kw.get('_depth', 0) + 1 - return apply(SCons.Environment.Base.Configure, (self,)+args, kw) + return SCons.Environment.Base.Configure(self, *args, **kw) def Default(self, *targets): SCons.Script._Set_Default_Targets(self, targets) @@ -484,7 +479,7 @@ class SConsEnvironment(SCons.Environment.Base): except AttributeError: python_ver = self._get_major_minor_revision(sys.version)[:2] if python_ver < (major, minor): - v = string.split(sys.version, " ", 1)[0] + v = sys.version.split(" ", 1)[0] print "Python %d.%d or greater required, but you have Python %s" %(major,minor,v) sys.exit(2) @@ -520,21 +515,24 @@ class SConsEnvironment(SCons.Environment.Base): globals.update(global_exports) globals.update(exports) else: - if exports.has_key(v): + if v in exports: globals[v] = exports[v] else: globals[v] = global_exports[v] except KeyError,x: - raise SCons.Errors.UserError, "Import of non-existent variable '%s'"%x + raise SCons.Errors.UserError("Import of non-existent variable '%s'"%x) def SConscript(self, *ls, **kw): + if 'build_dir' in kw: + msg = """The build_dir keyword has been deprecated; use the variant_dir keyword instead.""" + SCons.Warnings.warn(SCons.Warnings.DeprecatedBuildDirWarning, msg) def subst_element(x, subst=self.subst): if SCons.Util.is_List(x): - x = map(subst, x) + x = list(map(subst, x)) else: x = subst(x) return x - ls = map(subst_element, ls) + ls = list(map(subst_element, ls)) subst_kw = {} for key, val in kw.items(): if SCons.Util.is_String(val): @@ -550,7 +548,7 @@ class SConsEnvironment(SCons.Environment.Base): files, exports = self._get_SConscript_filenames(ls, subst_kw) subst_kw['exports'] = exports - return apply(_SConscript, [self.fs,] + files, subst_kw) + return _SConscript(self.fs, *files, **subst_kw) def SConscriptChdir(self, flag): global sconscript_chdir @@ -567,9 +565,9 @@ SCons.Environment.Environment = SConsEnvironment def Configure(*args, **kw): if not SCons.Script.sconscript_reading: - raise SCons.Errors.UserError, "Calling Configure from Builders is not supported." + raise SCons.Errors.UserError("Calling Configure from Builders is not supported.") kw['_depth'] = 1 - return apply(SCons.SConf.SConf, args, kw) + return SCons.SConf.SConf(*args, **kw) # It's very important that the DefaultEnvironmentCall() class stay in this # file, with the get_calling_namespaces() function, the compute_exports() @@ -595,7 +593,7 @@ def get_DefaultEnvironmentProxy(): _DefaultEnvironmentProxy = SCons.Environment.NoSubstitutionProxy(default_env) return _DefaultEnvironmentProxy -class DefaultEnvironmentCall: +class DefaultEnvironmentCall(object): """A class that implements "global function" calls of Environment methods by fetching the specified method from the DefaultEnvironment's class. Note that this uses an intermediate @@ -613,7 +611,7 @@ class DefaultEnvironmentCall: def __call__(self, *args, **kw): env = self.factory() method = getattr(env, self.method_name) - return apply(method, args, kw) + return method(*args, **kw) def BuildDefaultGlobals(): @@ -629,7 +627,7 @@ def BuildDefaultGlobals(): import SCons.Script d = SCons.Script.__dict__ def not_a_module(m, d=d, mtype=type(SCons.Script)): - return type(d[m]) != mtype + return not isinstance(d[m], mtype) for m in filter(not_a_module, dir(SCons.Script)): GlobalDict[m] = d[m] diff --git a/src/engine/SCons/Script/SConscriptTests.py b/src/engine/SCons/Script/SConscriptTests.py index 4bf9dab..4036dd4 100644 --- a/src/engine/SCons/Script/SConscriptTests.py +++ b/src/engine/SCons/Script/SConscriptTests.py @@ -21,7 +21,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Script/SConscriptTests.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/SConscriptTests.py 5023 2010/06/14 22:05:46 scons" import SCons.Script.SConscript diff --git a/src/engine/SCons/Script/__init__.py b/src/engine/SCons/Script/__init__.py index 97af6da..b5b5222 100644 --- a/src/engine/SCons/Script/__init__.py +++ b/src/engine/SCons/Script/__init__.py @@ -34,15 +34,14 @@ it goes here. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -__revision__ = "src/engine/SCons/Script/__init__.py 4720 2010/03/24 03:14:11 jars" +__revision__ = "src/engine/SCons/Script/__init__.py 5023 2010/06/14 22:05:46 scons" import time start_time = time.time() +import collections import os -import string import sys -import UserList # Special chicken-and-egg handling of the "--debug=memoizer" flag: # @@ -58,16 +57,15 @@ import UserList # the "--debug=memoizer" flag and enable Memoizer before we import any # of the other modules that use it. -_args = sys.argv + string.split(os.environ.get('SCONSFLAGS', '')) +_args = sys.argv + os.environ.get('SCONSFLAGS', '').split() if "--debug=memoizer" in _args: import SCons.Memoize import SCons.Warnings try: SCons.Memoize.EnableMemoization() except SCons.Warnings.Warning: - # Some warning was thrown (inability to --debug=memoizer on - # Python 1.5.2 because it doesn't have metaclasses). Arrange - # for it to be displayed or not after warnings are configured. + # Some warning was thrown. Arrange for it to be displayed + # or not after warnings are configured. import Main exc_type, exc_value, tb = sys.exc_info() Main.delayed_warnings.append((exc_type, exc_value)) @@ -184,7 +182,7 @@ CScan = SCons.Defaults.CScan DefaultEnvironment = SCons.Defaults.DefaultEnvironment # Other variables we provide. -class TargetList(UserList.UserList): +class TargetList(collections.UserList): def _do_nothing(self, *args, **kw): pass def _add_Default(self, list): @@ -211,7 +209,7 @@ _build_plus_default = TargetList() def _Add_Arguments(alist): for arg in alist: - a, b = string.split(arg, '=', 1) + a, b = arg.split('=', 1) ARGUMENTS[a] = b ARGLIST.append((a, b)) |