http://scons.tigris.org/issues/show_bug.cgi?id=2329
[scons.git] / src / engine / SCons / Util.py
index 982fdecec8caea5a023bc46854ab51018cc4e3c2..f8bac89cf547be07f001c5185ceeba0e2184b29e 100644 (file)
@@ -29,93 +29,43 @@ Various utility functions go here.
 
 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
-
 import copy
 import os
 import os.path
 import re
-import stat
-import string
 import sys
 import types
-from UserDict import UserDict
-import UserList
-
-import SCons.Errors
 
-try:
-    from UserString import UserString
-except ImportError:
-    # "Borrowed" from the Python 2.2 UserString module
-    # and modified slightly for use with SCons.
-    class UserString:
-        def __init__(self, seq):
-            if is_String(seq):
-                self.data = seq
-            elif isinstance(seq, UserString):
-                self.data = seq.data[:]
-            else:
-                self.data = str(seq)
-        def __str__(self): return str(self.data)
-        def __repr__(self): return repr(self.data)
-        def __int__(self): return int(self.data)
-        def __long__(self): return long(self.data)
-        def __float__(self): return float(self.data)
-        def __complex__(self): return complex(self.data)
-        def __hash__(self): return hash(self.data)
-
-        def __cmp__(self, string):
-            if isinstance(string, UserString):
-                return cmp(self.data, string.data)
-            else:
-                return cmp(self.data, string)
-        def __contains__(self, char):
-            return char in self.data
-
-        def __len__(self): return len(self.data)
-        def __getitem__(self, index): return self.__class__(self.data[index])
-        def __getslice__(self, start, end):
-            start = max(start, 0); end = max(end, 0)
-            return self.__class__(self.data[start:end])
-
-        def __add__(self, other):
-            if isinstance(other, UserString):
-                return self.__class__(self.data + other.data)
-            elif is_String(other):
-                return self.__class__(self.data + other)
-            else:
-                return self.__class__(self.data + str(other))
-        def __radd__(self, other):
-            if is_String(other):
-                return self.__class__(other + self.data)
-            else:
-                return self.__class__(str(other) + self.data)
-        def __mul__(self, n):
-            return self.__class__(self.data*n)
-        __rmul__ = __mul__
-
-#
-import __builtin__
-try:
-    __builtin__.zip
-except AttributeError:
-    def zip(*lists):
-        result = []
-        for i in xrange(len(lists[0])):
-            result.append(tuple(map(lambda l, i=i: l[i], lists)))
-        return result
-    __builtin__.zip = zip
+from UserDict import UserDict
+from UserList import UserList
+from UserString import UserString
+
+# Don't "from types import ..." these because we need to get at the
+# types module later to look for UnicodeType.
+DictType        = dict
+InstanceType    = types.InstanceType
+ListType        = list
+StringType      = str
+TupleType       = tuple
+try: unicode
+except NameError: UnicodeType = None
+else:             UnicodeType = unicode
+
+def dictify(keys, values, result={}):
+    for k, v in zip(keys, values):
+        result[k] = v
+    return result
 
 _altsep = os.altsep
 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...)
@@ -140,7 +90,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:]
@@ -156,103 +106,10 @@ def updrive(path):
     """
     drive, rest = os.path.splitdrive(path)
     if drive:
-        path = string.upper(drive) + rest
+        path = drive.upper() + rest
     return path
 
-#
-# Generic convert-to-string functions that abstract away whether or
-# not the Python we're executing has Unicode support.  The wrapper
-# to_String_for_signature() will use a for_signature() method if the
-# specified object has one.
-#
-if hasattr(types, 'UnicodeType'):
-    def to_String(s):
-        if isinstance(s, UserString):
-            t = type(s.data)
-        else:
-            t = type(s)
-        if t is types.UnicodeType:
-            return unicode(s)
-        else:
-            return str(s)
-else:
-    to_String = str
-
-def to_String_for_signature(obj):
-    try:
-        f = obj.for_signature
-    except AttributeError:
-        return to_String(obj)
-    else:
-        return f()
-
-# Indexed by the SUBST_* constants below.
-_strconv = [to_String, to_String, to_String_for_signature]
-
-class Literal:
-    """A wrapper for a string.  If you use this object wrapped
-    around a string, then it will be interpreted as literal.
-    When passed to the command interpreter, all special
-    characters will be escaped."""
-    def __init__(self, lstr):
-        self.lstr = lstr
-
-    def __str__(self):
-        return self.lstr
-
-    def escape(self, escape_func):
-        return escape_func(self.lstr)
-
-    def for_signature(self):
-        return self.lstr
-
-    def is_literal(self):
-        return 1
-
-class SpecialAttrWrapper:
-    """This is a wrapper for what we call a 'Node special attribute.'
-    This is any of the attributes of a Node that we can reference from
-    Environment variable substitution, such as $TARGET.abspath or
-    $SOURCES[1].filebase.  We implement the same methods as Literal
-    so we can handle special characters, plus a for_signature method,
-    such that we can return some canonical string during signature
-    calculation to avoid unnecessary rebuilds."""
-
-    def __init__(self, lstr, for_signature=None):
-        """The for_signature parameter, if supplied, will be the
-        canonical string we return from for_signature().  Else
-        we will simply return lstr."""
-        self.lstr = lstr
-        if for_signature:
-            self.forsig = for_signature
-        else:
-            self.forsig = lstr
-
-    def __str__(self):
-        return self.lstr
-
-    def escape(self, escape_func):
-        return escape_func(self.lstr)
-
-    def for_signature(self):
-        return self.forsig
-
-    def is_literal(self):
-        return 1
-
-class CallableComposite(UserList.UserList):
-    """A simple composite callable class that, when called, will invoke all
-    of its contained callables with the same arguments."""
-    def __call__(self, *args, **kwargs):
-        retvals = map(lambda x, args=args, kwargs=kwargs: apply(x,
-                                                                args,
-                                                                kwargs),
-                      self.data)
-        if self.data and (len(self.data) == len(filter(callable, retvals))):
-            return self.__class__(retvals)
-        return NodeList(retvals)
-
-class NodeList(UserList.UserList):
+class NodeList(UserList):
     """This class is almost exactly like a regular list of Nodes
     (actually it can hold any object), with one important difference.
     If you try to get an attribute from this list, it will return that
@@ -266,34 +123,21 @@ class NodeList(UserList.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 = [x(*args, **kwargs) for x in self.data]
+        return self.__class__(result)
 
     def __getattr__(self, name):
-        if not self.data:
-            # If there is nothing in the list, then we have no attributes to
-            # pass through, so raise AttributeError for everything.
-            raise AttributeError, "NodeList has no attribute: %s" % name
-
-        # Return a list of the attribute, gotten from every element
-        # in the list
-        attrList = map(lambda x, n=name: getattr(x, n), self.data)
-
-        # Special case.  If the attribute is callable, we do not want
-        # to return a list of callables.  Rather, we want to return a
-        # single callable that, when called, will invoke the function on
-        # all elements of this list.
-        if self.data and (len(self.data) == len(filter(callable, attrList))):
-            return CallableComposite(attrList)
-        return self.__class__(attrList)
-
-_valid_var = re.compile(r'[_a-zA-Z]\w*$')
-_get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')
+        result = [getattr(x, name) for x in self.data]
+        return self.__class__(result)
 
-def is_valid_construction_var(varstr):
-    """Return if the specified string is a legitimate construction
-    variable.
-    """
-    return _valid_var.match(varstr)
+
+_get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')
 
 def get_environment_var(varstr):
     """Given a string, first determine if it looks like a reference
@@ -310,54 +154,23 @@ def get_environment_var(varstr):
     else:
         return None
 
-def quote_spaces(arg):
-    """Generic function for putting double quotes around any string that
-    has white space in it."""
-    if ' ' in arg or '\t' in arg:
-        return '"%s"' % arg
-    else:
-        return str(arg)
-
-class CmdStringHolder(UserString):
-    """This is a special class used to hold strings generated by
-    scons_subst() and scons_subst_list().  It defines a special method
-    escape().  When passed a function with an escape algorithm for a
-    particular platform, it will return the contained string with the
-    proper escape sequences inserted.
-
-    This should really be a subclass of UserString, but that module
-    doesn't exist in Python 1.5.2."""
-    def __init__(self, cmd, literal=None):
-        UserString.__init__(self, cmd)
-        self.literal = literal
-
-    def is_literal(self):
-        return self.literal
-
-    def escape(self, escape_func, quote_func=quote_spaces):
-        """Escape the string with the supplied function.  The
-        function is expected to take an arbitrary string, then
-        return it with all special characters escaped and ready
-        for passing to the command interpreter.
-
-        After calling this function, the next call to str() will
-        return the escaped string.
-        """
-
-        if self.is_literal():
-            return escape_func(self.data)
-        elif ' ' in self.data or '\t' in self.data:
-            return quote_func(self.data)
-        else:
-            return self.data
-
 class DisplayEngine:
     def __init__(self):
         self.__call__ = self.print_it
 
     def print_it(self, text, append_newline=1):
         if append_newline: text = text + '\n'
-        sys.stdout.write(text)
+        try:
+            sys.stdout.write(text)
+        except IOError:
+            # Stdout might be connected to a pipe that has been closed
+            # by now. The most likely reason for the pipe being closed
+            # is that the user has press ctrl-c. It this is the case,
+            # then SCons is currently shutdown. We therefore ignore
+            # IOError's here so that SCons can continue and shutdown
+            # properly so that the .sconsign is correctly written
+            # before SCons exits.
+            pass
 
     def dont_print(self, text, append_newline=1):
         pass
@@ -368,652 +181,6 @@ class DisplayEngine:
         else:
             self.__call__ = self.dont_print
 
-def escape_list(list, escape_func):
-    """Escape a list of arguments by running the specified escape_func
-    on every object in the list that has an escape() method."""
-    def escape(obj, escape_func=escape_func):
-        try:
-            e = obj.escape
-        except AttributeError:
-            return obj
-        else:
-            return e(escape_func)
-    return map(escape, list)
-
-class NLWrapper:
-    """A wrapper class that delays turning a list of sources or targets
-    into a NodeList until it's needed.  The specified function supplied
-    when the object is initialized is responsible for turning raw nodes
-    into proxies that implement the special attributes like .abspath,
-    .source, etc.  This way, we avoid creating those proxies just
-    "in case" someone is going to use $TARGET or the like, and only
-    go through the trouble if we really have to.
-
-    In practice, this might be a wash performance-wise, but it's a little
-    cleaner conceptually...
-    """
-
-    def __init__(self, list, func):
-        self.list = list
-        self.func = func
-    def _create_nodelist(self):
-        try:
-            return self.nodelist
-        except AttributeError:
-            list = self.list
-            if list is None:
-                list = []
-            elif not is_List(list):
-                list = [list]
-            # The map(self.func) call is what actually turns
-            # a list into appropriate proxies.
-            self.nodelist = NodeList(map(self.func, list))
-        return self.nodelist
-
-class Targets_or_Sources(UserList.UserList):
-    """A class that implements $TARGETS or $SOURCES expansions by in turn
-    wrapping a NLWrapper.  This class handles the different methods used
-    to access the list, calling the NLWrapper to create proxies on demand.
-
-    Note that we subclass UserList.UserList purely so that the is_List()
-    function will identify an object of this class as a list during
-    variable expansion.  We're not really using any UserList.UserList
-    methods in practice.
-    """
-    def __init__(self, nl):
-        self.nl = nl
-    def __getattr__(self, attr):
-        nl = self.nl._create_nodelist()
-        return getattr(nl, attr)
-    def __getitem__(self, i):
-        nl = self.nl._create_nodelist()
-        return nl[i]
-    def __getslice__(self, i, j):
-        nl = self.nl._create_nodelist()
-        i = max(i, 0); j = max(j, 0)
-        return nl[i:j]
-    def __str__(self):
-        nl = self.nl._create_nodelist()
-        return str(nl)
-    def __repr__(self):
-        nl = self.nl._create_nodelist()
-        return repr(nl)
-
-class Target_or_Source:
-    """A class that implements $TARGET or $SOURCE expansions by in turn
-    wrapping a NLWrapper.  This class handles the different methods used
-    to access an individual proxy Node, calling the NLWrapper to create
-    a proxy on demand.
-    """
-    def __init__(self, nl):
-        self.nl = nl
-    def __getattr__(self, attr):
-        nl = self.nl._create_nodelist()
-        try:
-            nl0 = nl[0]
-        except IndexError:
-            # If there is nothing in the list, then we have no attributes to
-            # pass through, so raise AttributeError for everything.
-            raise AttributeError, "NodeList has no attribute: %s" % attr
-        return getattr(nl0, attr)
-    def __str__(self):
-        nl = self.nl._create_nodelist()
-        try:
-            nl0 = nl[0]
-        except IndexError:
-            return ''
-        return str(nl0)
-    def __repr__(self):
-        nl = self.nl._create_nodelist()
-        try:
-            nl0 = nl[0]
-        except IndexError:
-            return ''
-        return repr(nl0)
-
-def subst_dict(target, source):
-    """Create a dictionary for substitution of special
-    construction variables.
-
-    This translates the following special arguments:
-
-    target - the target (object or array of objects),
-             used to generate the TARGET and TARGETS
-             construction variables
-
-    source - the source (object or array of objects),
-             used to generate the SOURCES and SOURCE
-             construction variables
-    """
-    dict = {}
-
-    if target:
-        tnl = NLWrapper(target, lambda x: x.get_subst_proxy())
-        dict['TARGETS'] = Targets_or_Sources(tnl)
-        dict['TARGET'] = Target_or_Source(tnl)
-
-    if source:
-        def get_src_subst_proxy(node):
-            try:
-                rfile = node.rfile
-            except AttributeError:
-                pass
-            else:
-                node = rfile()
-            return node.get_subst_proxy()
-        snl = NLWrapper(source, get_src_subst_proxy)
-        dict['SOURCES'] = Targets_or_Sources(snl)
-        dict['SOURCE'] = Target_or_Source(snl)
-
-    return dict
-
-# Constants for the "mode" parameter to scons_subst_list() and
-# scons_subst().  SUBST_RAW gives the raw command line.  SUBST_CMD
-# gives a command line suitable for passing to a shell.  SUBST_SIG
-# gives a command line appropriate for calculating the signature
-# of a command line...if this changes, we should rebuild.
-SUBST_CMD = 0
-SUBST_RAW = 1
-SUBST_SIG = 2
-
-_rm = re.compile(r'\$[()]')
-_remove = re.compile(r'\$\([^\$]*(\$[^\)][^\$]*)*\$\)')
-
-# Indexed by the SUBST_* constants above.
-_regex_remove = [ _rm, None, _remove ]
-
-# Regular expressions for splitting strings and handling substitutions,
-# for use by the scons_subst() and scons_subst_list() functions:
-#
-# The first expression compiled matches all of the $-introduced tokens
-# that we need to process in some way, and is used for substitutions.
-# The expressions it matches are:
-#
-#       "$$"
-#       "$("
-#       "$)"
-#       "$variable"             [must begin with alphabetic or underscore]
-#       "${any stuff}"
-#
-# The second expression compiled is used for splitting strings into tokens
-# to be processed, and it matches all of the tokens listed above, plus
-# the following that affect how arguments do or don't get joined together:
-#
-#       "   "                   [white space]
-#       "non-white-space"       [without any dollar signs]
-#       "$"                     [single dollar sign]
-#
-_dollar_exps_str = r'\$[\$\(\)]|\$[_a-zA-Z][\.\w]*|\${[^}]*}'
-_dollar_exps = re.compile(r'(%s)' % _dollar_exps_str)
-_separate_args = re.compile(r'(%s|\s+|[^\s\$]+|\$)' % _dollar_exps_str)
-
-# This regular expression is used to replace strings of multiple white
-# space characters in the string result from the scons_subst() function.
-_space_sep = re.compile(r'[\t ]+(?![^{]*})')
-
-def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, dict=None, conv=None, gvars=None):
-    """Expand a string containing construction variable substitutions.
-
-    This is the work-horse function for substitutions in file names
-    and the like.  The companion scons_subst_list() function (below)
-    handles separating command lines into lists of arguments, so see
-    that function if that's what you're looking for.
-    """
-    if type(strSubst) == types.StringType and string.find(strSubst, '$') < 0:
-        return strSubst
-
-    class StringSubber:
-        """A class to construct the results of a scons_subst() call.
-
-        This binds a specific construction environment, mode, target and
-        source with two methods (substitute() and expand()) that handle
-        the expansion.
-        """
-        def __init__(self, env, mode, target, source, conv, gvars):
-            self.env = env
-            self.mode = mode
-            self.target = target
-            self.source = source
-            self.conv = conv
-            self.gvars = gvars
-
-        def expand_var_once(self, var, lvars):
-            try:
-                return lvars[var]
-            except KeyError:
-                try:
-                    return self.gvars[var]
-                except KeyError:
-                    return ''
-
-        def expand(self, s, lvars):
-            """Expand a single "token" as necessary, returning an
-            appropriate string containing the expansion.
-
-            This handles expanding different types of things (strings,
-            lists, callables) appropriately.  It calls the wrapper
-            substitute() method to re-expand things as necessary, so that
-            the results of expansions of side-by-side strings still get
-            re-evaluated separately, not smushed together.
-            """
-            if is_String(s):
-                try:
-                    s0, s1 = s[:2]
-                except (IndexError, ValueError):
-                    return s
-                if s0 == '$':
-                    if s1 == '$':
-                        return '$'
-                    elif s1 in '()':
-                        return s
-                    else:
-                        key = s[1:]
-                        if key[0] == '{' or string.find(key, '.') >= 0:
-                            if key[0] == '{':
-                                key = key[1:-1]
-                            try:
-                                s = eval(key, self.gvars, lvars)
-                            except (IndexError, NameError, TypeError):
-                                return ''
-                            except SyntaxError,e:
-                                if self.target:
-                                    raise SCons.Errors.BuildError, (self.target[0], "Syntax error `%s' trying to evaluate `%s'" % (e,s))
-                                else:
-                                    raise SCons.Errors.UserError, "Syntax error `%s' trying to evaluate `%s'" % (e,s)
-                        else:
-                            s = self.expand_var_once(key, lvars)
-
-                        # Before re-expanding the result, handle
-                        # recursive expansion by copying the local
-                        # variable dictionary and overwriting a null
-                        # string for the value of the variable name
-                        # we just expanded.
-                        #
-                        # This could potentially be optimized by only
-                        # copying lvars when s contains more expansions,
-                        # but lvars is usually supposed to be pretty
-                        # small, and deeply nested variable expansions
-                        # are probably more the exception than the norm,
-                        # so it should be tolerable for now.
-                        lv = lvars.copy()
-                        var = string.split(key, '.')[0]
-                        lv[var] = ''
-                        return self.substitute(s, lv)
-                else:
-                    return s
-            elif is_List(s):
-                def func(l, conv=self.conv, substitute=self.substitute, lvars=lvars):
-                    return conv(substitute(l, lvars))
-                r = map(func, s)
-                return string.join(r)
-            elif callable(s):
-                try:
-                    s = s(target=self.target,
-                         source=self.source,
-                         env=self.env,
-                         for_signature=(self.mode != SUBST_CMD))
-                except TypeError:
-                    # This probably indicates that it's a callable
-                    # object that doesn't match our calling arguments
-                    # (like an Action).
-                    s = str(s)
-                return self.substitute(s, lvars)
-            elif s is None:
-                return ''
-            else:
-                return s
-
-        def substitute(self, args, lvars):
-            """Substitute expansions in an argument or list of arguments.
-
-            This serves as a wrapper for splitting up a string into
-            separate tokens.
-            """
-            if is_String(args) and not isinstance(args, CmdStringHolder):
-                try:
-                    def sub_match(match, conv=self.conv, expand=self.expand, lvars=lvars):
-                        return conv(expand(match.group(1), lvars))
-                    result = _dollar_exps.sub(sub_match, args)
-                except TypeError:
-                    # If the internal conversion routine doesn't return
-                    # strings (it could be overridden to return Nodes, for
-                    # example), then the 1.5.2 re module will throw this
-                    # exception.  Back off to a slower, general-purpose
-                    # algorithm that works for all data types.
-                    args = _separate_args.findall(args)
-                    result = []
-                    for a in args:
-                        result.append(self.conv(self.expand(a, lvars)))
-                    try:
-                        result = string.join(result, '')
-                    except TypeError:
-                        if len(result) == 1:
-                            result = result[0]
-                return result
-            else:
-                return self.expand(args, lvars)
-
-    if dict is None:
-        dict = subst_dict(target, source)
-    if conv is None:
-        conv = _strconv[mode]
-    if gvars is None:
-        gvars = env.Dictionary()
-
-    # We're (most likely) going to eval() things.  If Python doesn't
-    # find a __builtin__ value in the global dictionary used for eval(),
-    # it copies the current __builtin__ values for you.  Avoid this by
-    # setting it explicitly and then deleting, so we don't pollute the
-    # construction environment Dictionary(ies) that are typically used
-    # for expansion.
-    gvars['__builtin__'] = __builtin__
-
-    ss = StringSubber(env, mode, target, source, conv, gvars)
-    result = ss.substitute(strSubst, dict)
-
-    try:
-        del gvars['__builtin__']
-    except KeyError:
-        pass
-
-    if is_String(result):
-        # Remove $(-$) pairs and any stuff in between,
-        # if that's appropriate.
-        remove = _regex_remove[mode]
-        if remove:
-            result = remove.sub('', result)
-        if mode != SUBST_RAW:
-            # Compress strings of white space characters into
-            # a single space.
-            result = string.strip(_space_sep.sub(' ', result))
-
-    return result
-
-def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, dict=None, conv=None, gvars=None):
-    """Substitute construction variables in a string (or list or other
-    object) and separate the arguments into a command list.
-
-    The companion scons_subst() function (above) handles basic
-    substitutions within strings, so see that function instead
-    if that's what you're looking for.
-    """
-    class ListSubber(UserList.UserList):
-        """A class to construct the results of a scons_subst_list() call.
-
-        Like StringSubber, this class binds a specific construction
-        environment, mode, target and source with two methods
-        (substitute() and expand()) that handle the expansion.
-
-        In addition, however, this class is used to track the state of
-        the result(s) we're gathering so we can do the appropriate thing
-        whenever we have to append another word to the result--start a new
-        line, start a new word, append to the current word, etc.  We do
-        this by setting the "append" attribute to the right method so
-        that our wrapper methods only need ever call ListSubber.append(),
-        and the rest of the object takes care of doing the right thing
-        internally.
-        """
-        def __init__(self, env, mode, target, source, conv, gvars):
-            UserList.UserList.__init__(self, [])
-            self.env = env
-            self.mode = mode
-            self.target = target
-            self.source = source
-            self.conv = conv
-            self.gvars = gvars
-
-            if self.mode == SUBST_RAW:
-                self.add_strip = lambda x, s=self: s.append(x)
-            else:
-                self.add_strip = lambda x, s=self: None
-            self.in_strip = None
-            self.next_line()
-
-        def expand(self, s, lvars, within_list):
-            """Expand a single "token" as necessary, appending the
-            expansion to the current result.
-
-            This handles expanding different types of things (strings,
-            lists, callables) appropriately.  It calls the wrapper
-            substitute() method to re-expand things as necessary, so that
-            the results of expansions of side-by-side strings still get
-            re-evaluated separately, not smushed together.
-            """
-
-            if is_String(s):
-                try:
-                    s0, s1 = s[:2]
-                except (IndexError, ValueError):
-                    self.append(s)
-                    return
-                if s0 == '$':
-                    if s1 == '$':
-                        self.append('$')
-                    elif s1 == '(':
-                        self.open_strip('$(')
-                    elif s1 == ')':
-                        self.close_strip('$)')
-                    else:
-                        key = s[1:]
-                        if key[0] == '{':
-                            key = key[1:-1]
-                        try:
-                            s = eval(key, self.gvars, lvars)
-                        except (IndexError, NameError, TypeError):
-                            return
-                        except SyntaxError,e:
-                            if self.target:
-                                raise SCons.Errors.BuildError, (self.target[0], "Syntax error `%s' trying to evaluate `%s'" % (e,s))
-                            else:
-                                raise SCons.Errors.UserError, "Syntax error `%s' trying to evaluate `%s'" % (e,s)
-                        else:
-                            # Before re-expanding the result, handle
-                            # recursive expansion by copying the local
-                            # variable dictionary and overwriting a null
-                            # string for the value of the variable name
-                            # we just expanded.
-                            lv = lvars.copy()
-                            var = string.split(key, '.')[0]
-                            lv[var] = ''
-                            self.substitute(s, lv, 0)
-                            self.this_word()
-                else:
-                    self.append(s)
-            elif is_List(s):
-                for a in s:
-                    self.substitute(a, lvars, 1)
-                    self.next_word()
-            elif callable(s):
-                try:
-                    s = s(target=self.target,
-                         source=self.source,
-                         env=self.env,
-                         for_signature=(self.mode != SUBST_CMD))
-                except TypeError:
-                    # This probably indicates that it's a callable
-                    # object that doesn't match our calling arguments
-                    # (like an Action).
-                    s = str(s)
-                self.substitute(s, lvars, within_list)
-            elif s is None:
-                self.this_word()
-            else:
-                self.append(s)
-
-        def substitute(self, args, lvars, within_list):
-            """Substitute expansions in an argument or list of arguments.
-
-            This serves as a wrapper for splitting up a string into
-            separate tokens.
-            """
-
-            if is_String(args) and not isinstance(args, CmdStringHolder):
-                args = _separate_args.findall(args)
-                for a in args:
-                    if a[0] in ' \t\n\r\f\v':
-                        if '\n' in a:
-                            self.next_line()
-                        elif within_list:
-                            self.append(a)
-                        else:
-                            self.next_word()
-                    else:
-                        self.expand(a, lvars, within_list)
-            else:
-                self.expand(args, lvars, within_list)
-
-        def next_line(self):
-            """Arrange for the next word to start a new line.  This
-            is like starting a new word, except that we have to append
-            another line to the result."""
-            UserList.UserList.append(self, [])
-            self.next_word()
-
-        def this_word(self):
-            """Arrange for the next word to append to the end of the
-            current last word in the result."""
-            self.append = self.add_to_current_word
-
-        def next_word(self):
-            """Arrange for the next word to start a new word."""
-            self.append = self.add_new_word
-
-        def add_to_current_word(self, x):
-            """Append the string x to the end of the current last word
-            in the result.  If that is not possible, then just add
-            it as a new word.  Make sure the entire concatenated string
-            inherits the object attributes of x (in particular, the
-            escape function) by wrapping it as CmdStringHolder."""
-
-            if not self.in_strip or self.mode != SUBST_SIG:
-                try:
-                    current_word = self[-1][-1]
-                except IndexError:
-                    self.add_new_word(x)
-                else:
-                    # All right, this is a hack and it should probably
-                    # be refactored out of existence in the future.
-                    # The issue is that we want to smoosh words together
-                    # and make one file name that gets escaped if
-                    # we're expanding something like foo$EXTENSION,
-                    # but we don't want to smoosh them together if
-                    # it's something like >$TARGET, because then we'll
-                    # treat the '>' like it's part of the file name.
-                    # So for now, just hard-code looking for the special
-                    # command-line redirection characters...
-                    try:
-                        last_char = str(current_word)[-1]
-                    except IndexError:
-                        last_char = '\0'
-                    if last_char in '<>|':
-                        self.add_new_word(x)
-                    else:
-                        y = current_word + x
-                        literal1 = self.literal(self[-1][-1])
-                        literal2 = self.literal(x)
-                        y = self.conv(y)
-                        if is_String(y):
-                            y = CmdStringHolder(y, literal1 or literal2)
-                        self[-1][-1] = y
-
-        def add_new_word(self, x):
-            if not self.in_strip or self.mode != SUBST_SIG:
-                literal = self.literal(x)
-                x = self.conv(x)
-                if is_String(x):
-                    x = CmdStringHolder(x, literal)
-                self[-1].append(x)
-            self.append = self.add_to_current_word
-
-        def literal(self, x):
-            try:
-                l = x.is_literal
-            except AttributeError:
-                return None
-            else:
-                return l()
-
-        def open_strip(self, x):
-            """Handle the "open strip" $( token."""
-            self.add_strip(x)
-            self.in_strip = 1
-
-        def close_strip(self, x):
-            """Handle the "close strip" $) token."""
-            self.add_strip(x)
-            self.in_strip = None
-
-    if dict is None:
-        dict = subst_dict(target, source)
-    if conv is None:
-        conv = _strconv[mode]
-    if gvars is None:
-        gvars = env.Dictionary()
-
-    # We're (most likely) going to eval() things.  If Python doesn't
-    # find a __builtin__ value in the global dictionary used for eval(),
-    # it copies the current __builtin__ values for you.  Avoid this by
-    # setting it explicitly and then deleting, so we don't pollute the
-    # construction environment Dictionary(ies) that are typically used
-    # for expansion.
-    gvars['__builtins__'] = __builtins__
-
-    ls = ListSubber(env, mode, target, source, conv, gvars)
-    ls.substitute(strSubst, dict, 0)
-
-    try:
-        del gvars['__builtins__']
-    except KeyError:
-        pass
-
-    return ls.data
-
-def scons_subst_once(strSubst, env, key):
-    """Perform single (non-recursive) substitution of a single
-    construction variable keyword.
-
-    This is used when setting a variable when copying or overriding values
-    in an Environment.  We want to capture (expand) the old value before
-    we override it, so people can do things like:
-
-        env2 = env.Copy(CCFLAGS = '$CCFLAGS -g')
-
-    We do this with some straightforward, brute-force code here...
-    """
-    if type(strSubst) == types.StringType and string.find(strSubst, '$') < 0:
-        return strSubst
-
-    matchlist = ['$' + key, '${' + key + '}']
-    val = env.get(key, '')
-    def sub_match(match, val=val, matchlist=matchlist):
-        a = match.group(1)
-        if a in matchlist:
-            a = val
-        if is_List(a):
-            return string.join(map(str, a))
-        else:
-            return str(a)
-
-    if is_List(strSubst):
-        result = []
-        for arg in strSubst:
-            if is_String(arg):
-                if arg in matchlist:
-                    arg = val
-                    if is_List(arg):
-                        result.extend(arg)
-                    else:
-                        result.append(arg)
-                else:
-                    result.append(_dollar_exps.sub(sub_match, arg))
-            else:
-                result.append(arg)
-        return result
-    elif is_String(strSubst):
-        return _dollar_exps.sub(sub_match, strSubst)
-    else:
-        return strSubst
-
 def render_tree(root, child_func, prune=0, margin=[0], visited={}):
     """
     Render a tree of nodes into an ASCII tree view.
@@ -1028,9 +195,6 @@ def render_tree(root, child_func, prune=0, margin=[0], visited={}):
 
     rname = str(root)
 
-    if visited.has_key(rname):
-        return ""
-
     children = child_func(root)
     retval = ""
     for pipe in margin[:-1]:
@@ -1039,6 +203,9 @@ def render_tree(root, child_func, prune=0, margin=[0], visited={}):
         else:
             retval = retval + "  "
 
+    if rname in visited:
+        return retval + "+-[" + rname + "]\n"
+
     retval = retval + "+-" + rname + "\n"
     if not prune:
         visited = copy.copy(visited)
@@ -1072,20 +239,19 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}):
 
     rname = str(root)
 
-    if visited.has_key(rname):
-        return
-
     if showtags:
 
         if showtags == 2:
-            print ' E       = exists'
-            print '  R      = exists in repository only'
-            print '   b     = implicit builder'
-            print '   B     = explicit builder'
-            print '    S    = side effect'
-            print '     P   = precious'
-            print '      A  = always build'
-            print '       C = current'
+            print ' E         = exists'
+            print '  R        = exists in repository only'
+            print '   b       = implicit builder'
+            print '   B       = explicit builder'
+            print '    S      = side effect'
+            print '     P     = precious'
+            print '      A    = always build'
+            print '       C   = current'
+            print '        N  = no clean'
+            print '         H = no cache'
             print ''
 
         tags = ['[']
@@ -1096,7 +262,9 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}):
         tags.append(' S'[IDX(root.side_effect)])
         tags.append(' P'[IDX(root.precious)])
         tags.append(' A'[IDX(root.always_build)])
-        tags.append(' C'[IDX(root.current())])
+        tags.append(' C'[IDX(root.is_up_to_date())])
+        tags.append(' N'[IDX(root.noclean)])
+        tags.append(' H'[IDX(root.nocache)])
         tags.append(']')
 
     else:
@@ -1104,50 +272,360 @@ 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]))
 
-    print string.join(tags + margins + ['+-', rname], '')
+    children = child_func(root)
 
-    if prune:
-        visited[rname] = 1
+    if prune and rname in visited and children:
+        print ''.join(tags + margins + ['+-[', rname, ']'])
+        return
+
+    print ''.join(tags + margins + ['+-', rname])
+
+    visited[rname] = 1
 
-    children = child_func(root)
     if children:
         margin.append(1)
-        map(lambda C, cf=child_func, p=prune, i=IDX(showtags), m=margin, v=visited:
-                   print_tree(C, cf, p, i, m, v),
-            children[:-1])
+        idx = IDX(showtags)
+        for C in children[:-1]:
+            print_tree(C, child_func, prune, idx, margin, visited)
         margin[-1] = 0
-        print_tree(children[-1], child_func, prune, IDX(showtags), margin, visited)
+        print_tree(children[-1], child_func, prune, idx, margin, visited)
         margin.pop()
 
-def is_Dict(e):
-    return type(e) is types.DictType or isinstance(e, UserDict)
 
-def is_List(e):
-    return type(e) is types.ListType or isinstance(e, UserList.UserList)
 
-if hasattr(types, 'UnicodeType'):
-    def is_String(e):
-        return type(e) is types.StringType \
-            or type(e) is types.UnicodeType \
-            or isinstance(e, UserString)
+# Functions for deciding if things are like various types, mainly to
+# handle UserDict, UserList and UserString like their underlying types.
+#
+# Yes, all of this manual testing breaks polymorphism, and the real
+# Pythonic way to do all of this would be to just try it and handle the
+# exception, but handling the exception when it's not the right type is
+# often too slow.
+
+try:
+    class mystr(str):
+        pass
+except TypeError:
+    # An older Python version without new-style classes.
+    #
+    # The actual implementations here have been selected after timings
+    # coded up in in bench/is_types.py (from the SCons source tree,
+    # see the scons-src distribution), mostly against Python 1.5.2.
+    # Key results from those timings:
+    #
+    #   --  Storing the type of the object in a variable (t = type(obj))
+    #       slows down the case where it's a native type and the first
+    #       comparison will match, but nicely speeds up the case where
+    #       it's a different native type.  Since that's going to be
+    #       common, it's a good tradeoff.
+    #
+    #   --  The data show that calling isinstance() on an object that's
+    #       a native type (dict, list or string) is expensive enough
+    #       that checking up front for whether the object is of type
+    #       InstanceType is a pretty big win, even though it does slow
+    #       down the case where it really *is* an object instance a
+    #       little bit.
+    def is_Dict(obj):
+        t = type(obj)
+        return t is DictType or \
+               (t is InstanceType and isinstance(obj, UserDict))
+
+    def is_List(obj):
+        t = type(obj)
+        return t is ListType \
+            or (t is InstanceType and isinstance(obj, UserList))
+
+    def is_Sequence(obj):
+        t = type(obj)
+        return t is ListType \
+            or t is TupleType \
+            or (t is InstanceType and isinstance(obj, UserList))
+
+    def is_Tuple(obj):
+        t = type(obj)
+        return t is TupleType
+
+    if UnicodeType is not None:
+        def is_String(obj):
+            t = type(obj)
+            return t is StringType \
+                or t is UnicodeType \
+                or (t is InstanceType and isinstance(obj, UserString))
+    else:
+        def is_String(obj):
+            t = type(obj)
+            return t is StringType \
+                or (t is InstanceType and isinstance(obj, UserString))
+
+    def is_Scalar(obj):
+        return is_String(obj) or not is_Sequence(obj)
+
+    def flatten(obj, result=None):
+        """Flatten a sequence to a non-nested list.
+
+        Flatten() converts either a single scalar or a nested sequence
+        to a non-nested list. Note that flatten() considers strings
+        to be scalars instead of sequences like Python would.
+        """
+        if is_Scalar(obj):
+            return [obj]
+        if result is None:
+            result = []
+        for item in obj:
+            if is_Scalar(item):
+                result.append(item)
+            else:
+                flatten_sequence(item, result)
+        return result
+
+    def flatten_sequence(sequence, result=None):
+        """Flatten a sequence to a non-nested list.
+
+        Same as flatten(), but it does not handle the single scalar
+        case. This is slightly more efficient when one knows that
+        the sequence to flatten can not be a scalar.
+        """
+        if result is None:
+            result = []
+        for item in sequence:
+            if is_Scalar(item):
+                result.append(item)
+            else:
+                flatten_sequence(item, result)
+        return result
+
+    #
+    # Generic convert-to-string functions that abstract away whether or
+    # not the Python we're executing has Unicode support.  The wrapper
+    # to_String_for_signature() will use a for_signature() method if the
+    # specified object has one.
+    #
+    if UnicodeType is not None:
+        def to_String(s):
+            if isinstance(s, UserString):
+                t = type(s.data)
+            else:
+                t = type(s)
+            if t is UnicodeType:
+                return unicode(s)
+            else:
+                return str(s)
+    else:
+        to_String = str
+
+    def to_String_for_signature(obj):
+        try:
+            f = obj.for_signature
+        except AttributeError:
+            return to_String_for_subst(obj)
+        else:
+            return f()
+
+    def to_String_for_subst(s):
+        if is_Sequence( s ):
+            return ' '.join( map(to_String_for_subst, s) )
+
+        return to_String( s )
+
 else:
-    def is_String(e):
-        return type(e) is types.StringType or isinstance(e, UserString)
+    # A modern Python version with new-style classes, so we can just use
+    # isinstance().
+    #
+    # We are using the following trick to speed-up these
+    # functions. Default arguments are used to take a snapshot of the
+    # the global functions and constants used by these functions. This
+    # transforms accesses to global variable into local variables
+    # accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL).
+
+    DictTypes = (dict, UserDict)
+    ListTypes = (list, UserList)
+    SequenceTypes = (list, tuple, UserList)
+
+    # Empirically, Python versions with new-style classes all have
+    # unicode.
+    #
+    # Note that profiling data shows a speed-up when comparing
+    # explicitely with str and unicode instead of simply comparing
+    # with basestring. (at least on Python 2.5.1)
+    StringTypes = (str, unicode, UserString)
+
+    # Empirically, it is faster to check explicitely for str and
+    # unicode than for basestring.
+    BaseStringTypes = (str, unicode)
+
+    def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes):
+        return isinstance(obj, DictTypes)
+
+    def is_List(obj, isinstance=isinstance, ListTypes=ListTypes):
+        return isinstance(obj, ListTypes)
+
+    def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes):
+        return isinstance(obj, SequenceTypes)
+
+    def is_Tuple(obj, isinstance=isinstance, tuple=tuple):
+        return isinstance(obj, tuple)
+
+    def is_String(obj, isinstance=isinstance, StringTypes=StringTypes):
+        return isinstance(obj, StringTypes)
+
+    def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes):
+        # Profiling shows that there is an impressive speed-up of 2x
+        # when explicitely checking for strings instead of just not
+        # sequence when the argument (i.e. obj) is already a string.
+        # But, if obj is a not string than it is twice as fast to
+        # check only for 'not sequence'. The following code therefore
+        # assumes that the obj argument is a string must of the time.
+        return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes)
+
+    def do_flatten(sequence, result, isinstance=isinstance, 
+                   StringTypes=StringTypes, SequenceTypes=SequenceTypes):
+        for item in sequence:
+            if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
+                result.append(item)
+            else:
+                do_flatten(item, result)
 
-def is_Scalar(e):
-    return is_String(e) or not is_List(e)
+    def flatten(obj, isinstance=isinstance, StringTypes=StringTypes, 
+                SequenceTypes=SequenceTypes, do_flatten=do_flatten):
+        """Flatten a sequence to a non-nested list.
 
-def flatten(sequence, scalarp=is_Scalar, result=None):
-    if result is None:
+        Flatten() converts either a single scalar or a nested sequence
+        to a non-nested list. Note that flatten() considers strings
+        to be scalars instead of sequences like Python would.
+        """
+        if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
+            return [obj]
         result = []
-    for item in sequence:
-        if scalarp(item):
-            result.append(item)
+        for item in obj:
+            if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
+                result.append(item)
+            else:
+                do_flatten(item, result)
+        return result
+
+    def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes, 
+                         SequenceTypes=SequenceTypes, do_flatten=do_flatten):
+        """Flatten a sequence to a non-nested list.
+
+        Same as flatten(), but it does not handle the single scalar
+        case. This is slightly more efficient when one knows that
+        the sequence to flatten can not be a scalar.
+        """
+        result = []
+        for item in sequence:
+            if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
+                result.append(item)
+            else:
+                do_flatten(item, result)
+        return result
+
+
+    #
+    # Generic convert-to-string functions that abstract away whether or
+    # not the Python we're executing has Unicode support.  The wrapper
+    # to_String_for_signature() will use a for_signature() method if the
+    # specified object has one.
+    #
+    def to_String(s, 
+                  isinstance=isinstance, str=str,
+                  UserString=UserString, BaseStringTypes=BaseStringTypes):
+        if isinstance(s,BaseStringTypes):
+            # Early out when already a string!
+            return s
+        elif isinstance(s, UserString):
+            # s.data can only be either a unicode or a regular
+            # string. Please see the UserString initializer.
+            return s.data
         else:
-            flatten(item, scalarp, result)
-    return result
+            return str(s)
+
+    def to_String_for_subst(s, 
+                            isinstance=isinstance, str=str, to_String=to_String,
+                            BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes,
+                            UserString=UserString):
+                            
+        # Note that the test cases are sorted by order of probability.
+        if isinstance(s, BaseStringTypes):
+            return s
+        elif isinstance(s, SequenceTypes):
+            l = []
+            for e in s:
+                l.append(to_String_for_subst(e))
+            return ' '.join( s )
+        elif isinstance(s, UserString):
+            # s.data can only be either a unicode or a regular
+            # string. Please see the UserString initializer.
+            return s.data
+        else:
+            return str(s)
+
+    def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst, 
+                                AttributeError=AttributeError):
+        try:
+            f = obj.for_signature
+        except AttributeError:
+            return to_String_for_subst(obj)
+        else:
+            return f()
+
+
+
+# The SCons "semi-deep" copy.
+#
+# This makes separate copies of lists (including UserList objects)
+# dictionaries (including UserDict objects) and tuples, but just copies
+# references to anything else it finds.
+#
+# A special case is any object that has a __semi_deepcopy__() method,
+# which we invoke to create the copy, which is used by the BuilderDict
+# class because of its extra initialization argument.
+#
+# The dispatch table approach used here is a direct rip-off from the
+# normal Python copy module.
+
+_semi_deepcopy_dispatch = d = {}
+
+def _semi_deepcopy_dict(x):
+    copy = {}
+    for key, val in x.items():
+        # The regular Python copy.deepcopy() also deepcopies the key,
+        # as follows:
+        #
+        #    copy[semi_deepcopy(key)] = semi_deepcopy(val)
+        #
+        # Doesn't seem like we need to, but we'll comment it just in case.
+        copy[key] = semi_deepcopy(val)
+    return copy
+d[dict] = _semi_deepcopy_dict
+
+def _semi_deepcopy_list(x):
+    return list(map(semi_deepcopy, x))
+d[list] = _semi_deepcopy_list
+
+def _semi_deepcopy_tuple(x):
+    return tuple(map(semi_deepcopy, x))
+d[tuple] = _semi_deepcopy_tuple
+
+def _semi_deepcopy_inst(x):
+    if hasattr(x, '__semi_deepcopy__'):
+        return x.__semi_deepcopy__()
+    elif isinstance(x, UserDict):
+        return x.__class__(_semi_deepcopy_dict(x))
+    elif isinstance(x, UserList):
+        return x.__class__(_semi_deepcopy_list(x))
+    else:
+        return x
+d[types.InstanceType] = _semi_deepcopy_inst
+
+def semi_deepcopy(x):
+    copier = _semi_deepcopy_dispatch.get(type(x))
+    if copier:
+        return copier(x)
+    else:
+        return x
+
+
 
 class Proxy:
     """A simple generic Proxy class, forwarding all calls to
@@ -1195,11 +673,11 @@ try:
     can_read_reg = 1
     hkey_mod = _winreg
 
-    RegOpenKeyEx = _winreg.OpenKeyEx
-    RegEnumKey = _winreg.EnumKey
-    RegEnumValue = _winreg.EnumValue
+    RegOpenKeyEx    = _winreg.OpenKeyEx
+    RegEnumKey      = _winreg.EnumKey
+    RegEnumValue    = _winreg.EnumValue
     RegQueryValueEx = _winreg.QueryValueEx
-    RegError = _winreg.error
+    RegError        = _winreg.error
 
 except ImportError:
     try:
@@ -1208,11 +686,11 @@ except ImportError:
         can_read_reg = 1
         hkey_mod = win32con
 
-        RegOpenKeyEx = win32api.RegOpenKeyEx
-        RegEnumKey = win32api.RegEnumKey
-        RegEnumValue = win32api.RegEnumValue
+        RegOpenKeyEx    = win32api.RegOpenKeyEx
+        RegEnumKey      = win32api.RegEnumKey
+        RegEnumValue    = win32api.RegEnumValue
         RegQueryValueEx = win32api.RegQueryValueEx
-        RegError = win32api.error
+        RegError        = win32api.error
 
     except ImportError:
         class _NoError(Exception):
@@ -1220,10 +698,10 @@ except ImportError:
         RegError = _NoError
 
 if can_read_reg:
-    HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
+    HKEY_CLASSES_ROOT  = hkey_mod.HKEY_CLASSES_ROOT
     HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
-    HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
-    HKEY_USERS = hkey_mod.HKEY_USERS
+    HKEY_CURRENT_USER  = hkey_mod.HKEY_CURRENT_USER
+    HKEY_USERS         = hkey_mod.HKEY_USERS
 
     def RegGetValue(root, key):
         """This utility function returns a value in the registry
@@ -1247,10 +725,35 @@ if can_read_reg:
         # I would use os.path.split here, but it's not a filesystem
         # path...
         p = key.rfind('\\') + 1
-        keyp = key[:p]
+        keyp = key[:p-1]          # -1 to omit trailing slash
         val = key[p:]
-        k = SCons.Util.RegOpenKeyEx(root, keyp)
-        return SCons.Util.RegQueryValueEx(k,val)
+        k = RegOpenKeyEx(root, keyp)
+        return RegQueryValueEx(k,val)
+else:
+    try:
+        e = WindowsError
+    except NameError:
+        # Make sure we have a definition of WindowsError so we can
+        # run platform-independent tests of Windows functionality on
+        # platforms other than Windows.  (WindowsError is, in fact, an
+        # OSError subclass on Windows.)
+        class WindowsError(OSError):
+            pass
+        import __builtin__
+        __builtin__.WindowsError = WindowsError
+    else:
+        del e
+        
+    HKEY_CLASSES_ROOT = None
+    HKEY_LOCAL_MACHINE = None
+    HKEY_CURRENT_USER = None
+    HKEY_USERS = None
+
+    def RegGetValue(root, key):
+        raise WindowsError
+
+    def RegOpenKeyEx(root, key):
+        raise WindowsError
 
 if sys.platform == 'win32':
 
@@ -1261,19 +764,19 @@ 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):
+        if not is_List(reject) and not is_Tuple(reject):
             reject = [reject]
         for dir in path:
             f = os.path.join(dir, file)
@@ -1296,14 +799,14 @@ 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):
+        if not is_List(reject) and not is_Tuple(reject):
             reject = [reject]
         for dir in path:
             f = os.path.join(dir, file)
@@ -1320,14 +823,15 @@ elif os.name == 'os2':
 else:
 
     def WhereIs(file, path=None, pathext=None, reject=[]):
+        import stat
         if path is None:
             try:
                 path = os.environ['PATH']
             except KeyError:
                 return None
         if is_String(path):
-            path = string.split(path, os.pathsep)
-        if not is_List(reject):
+            path = path.split(os.pathsep)
+        if not is_List(reject) and not is_Tuple(reject):
             reject = [reject]
         for d in path:
             f = os.path.join(d, file)
@@ -1335,6 +839,10 @@ else:
                 try:
                     st = os.stat(f)
                 except OSError:
+                    # os.stat() raises OSError, not IOError if the file
+                    # doesn't exist, so in this case we let IOError get
+                    # raised so as to not mask possibly serious disk or
+                    # network issues.
                     continue
                 if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
                     try:
@@ -1344,7 +852,8 @@ else:
                     continue
         return None
 
-def PrependPath(oldpath, newpath, sep = os.pathsep):
+def PrependPath(oldpath, newpath, sep = os.pathsep, 
+                delete_existing=1, canonicalize=None):
     """This prepends newpath elements to the given oldpath.  Will only
     add any particular path once (leaving the first one it encounters
     and ignoring the rest, to preserve path order), and will
@@ -1357,37 +866,76 @@ def PrependPath(oldpath, newpath, sep = os.pathsep):
       Old Path: "/foo/bar:/foo"
       New Path: "/biz/boom:/foo"
       Result:   "/biz/boom:/foo:/foo/bar"
+
+    If delete_existing is 0, then adding a path that exists will
+    not move it to the beginning; it will stay where it is in the
+    list.
+
+    If canonicalize is not None, it is applied to each element of 
+    newpath before use.
     """
 
     orig = oldpath
     is_list = 1
     paths = orig
-    if not is_List(orig):
-        paths = string.split(paths, sep)
+    if not is_List(orig) and not is_Tuple(orig):
+        paths = paths.split(sep)
         is_list = 0
 
-    if is_List(newpath):
-        newpaths = newpath
+    if is_String(newpath):
+        newpaths = newpath.split(sep)
+    elif not is_List(newpath) and not is_Tuple(newpath):
+        newpaths = [ newpath ]  # might be a Dir
     else:
-        newpaths = string.split(newpath, sep)
+        newpaths = newpath
+
+    if canonicalize:
+        newpaths=list(map(canonicalize, newpaths))
+
+    if not delete_existing:
+        # First uniquify the old paths, making sure to 
+        # preserve the first instance (in Unix/Linux,
+        # the first one wins), and remembering them in normpaths.
+        # Then insert the new paths at the head of the list
+        # if they're not already in the normpaths list.
+        result = []
+        normpaths = []
+        for path in paths:
+            if not path:
+                continue
+            normpath = os.path.normpath(os.path.normcase(path))
+            if normpath not in normpaths:
+                result.append(path)
+                normpaths.append(normpath)
+        newpaths.reverse()      # since we're inserting at the head
+        for path in newpaths:
+            if not path:
+                continue
+            normpath = os.path.normpath(os.path.normcase(path))
+            if normpath not in normpaths:
+                result.insert(0, path)
+                normpaths.append(normpath)
+        paths = result
 
-    newpaths = newpaths + paths # prepend new paths
+    else:
+        newpaths = newpaths + paths # prepend new paths
 
-    normpaths = []
-    paths = []
-    # now we add them only if they are unique
-    for path in newpaths:
-        normpath = os.path.normpath(os.path.normcase(path))
-        if path and not normpath in normpaths:
-            paths.append(path)
-            normpaths.append(normpath)
+        normpaths = []
+        paths = []
+        # now we add them only if they are unique
+        for path in newpaths:
+            normpath = os.path.normpath(os.path.normcase(path))
+            if path and not normpath in normpaths:
+                paths.append(path)
+                normpaths.append(normpath)
 
     if is_list:
         return paths
     else:
-        return string.join(paths, sep)
+        return sep.join(paths)
 
-def AppendPath(oldpath, newpath, sep = os.pathsep):
+def AppendPath(oldpath, newpath, sep = os.pathsep, 
+               delete_existing=1, canonicalize=None):
     """This appends new path elements to the given old path.  Will
     only add any particular path once (leaving the last one it
     encounters and ignoring the rest, to preserve path order), and
@@ -1400,76 +948,78 @@ def AppendPath(oldpath, newpath, sep = os.pathsep):
       Old Path: "/foo/bar:/foo"
       New Path: "/biz/boom:/foo"
       Result:   "/foo/bar:/biz/boom:/foo"
+
+    If delete_existing is 0, then adding a path that exists
+    will not move it to the end; it will stay where it is in the list.
+
+    If canonicalize is not None, it is applied to each element of 
+    newpath before use.
     """
 
     orig = oldpath
     is_list = 1
     paths = orig
-    if not is_List(orig):
-        paths = string.split(paths, sep)
+    if not is_List(orig) and not is_Tuple(orig):
+        paths = paths.split(sep)
         is_list = 0
 
-    if is_List(newpath):
-        newpaths = newpath
+    if is_String(newpath):
+        newpaths = newpath.split(sep)
+    elif not is_List(newpath) and not is_Tuple(newpath):
+        newpaths = [ newpath ]  # might be a Dir
     else:
-        newpaths = string.split(newpath, sep)
-
-    newpaths = paths + newpaths # append new paths
-    newpaths.reverse()
+        newpaths = newpath
 
-    normpaths = []
-    paths = []
-    # now we add them only of they are unique
-    for path in newpaths:
-        normpath = os.path.normpath(os.path.normcase(path))
-        if path and not normpath in normpaths:
-            paths.append(path)
-            normpaths.append(normpath)
+    if canonicalize:
+        newpaths=list(map(canonicalize, newpaths))
 
-    paths.reverse()
+    if not delete_existing:
+        # add old paths to result, then
+        # add new paths if not already present
+        # (I thought about using a dict for normpaths for speed,
+        # but it's not clear hashing the strings would be faster
+        # than linear searching these typically short lists.)
+        result = []
+        normpaths = []
+        for path in paths:
+            if not path:
+                continue
+            result.append(path)
+            normpaths.append(os.path.normpath(os.path.normcase(path)))
+        for path in newpaths:
+            if not path:
+                continue
+            normpath = os.path.normpath(os.path.normcase(path))
+            if normpath not in normpaths:
+                result.append(path)
+                normpaths.append(normpath)
+        paths = result
+    else:
+        # start w/ new paths, add old ones if not present,
+        # then reverse.
+        newpaths = paths + newpaths # append new paths
+        newpaths.reverse()
+
+        normpaths = []
+        paths = []
+        # now we add them only if they are unique
+        for path in newpaths:
+            normpath = os.path.normpath(os.path.normcase(path))
+            if path and not normpath in normpaths:
+                paths.append(path)
+                normpaths.append(normpath)
+        paths.reverse()
 
     if is_list:
         return paths
     else:
-        return string.join(paths, sep)
-
-
-def dir_index(directory):
-    files = []
-    for f in os.listdir(directory):
-        fullname = os.path.join(directory, f)
-        files.append(fullname)
-
-    # os.listdir() isn't guaranteed to return files in any specific order,
-    # but some of the test code expects sorted output.
-    files.sort()
-    return files
-
-def fs_delete(path, remove=1):
-    try:
-        if os.path.exists(path):
-            if os.path.isfile(path):
-                if remove: os.unlink(path)
-                display("Removed " + path)
-            elif os.path.isdir(path) and not os.path.islink(path):
-                # delete everything in the dir
-                for p in dir_index(path):
-                    if os.path.isfile(p):
-                        if remove: os.unlink(p)
-                        display("Removed " + p)
-                    else:
-                        fs_delete(p, remove)
-                # then delete dir itself
-                if remove: os.rmdir(path)
-                display("Removed directory " + path)
-    except OSError, e:
-        print "scons: Could not remove '%s':" % str(path), e.strerror
+        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 Win32 one."""
-        return string.replace(os.popen('cygpath -w ' + path).read(), '\n', '')
+        Cygwin, this converts from a Cygwin path to a Windows one."""
+        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.
@@ -1479,14 +1029,14 @@ else:
 display = DisplayEngine()
 
 def Split(arg):
-    if is_List(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]
 
-class CLVar(UserList.UserList):
+class CLVar(UserList):
     """A class for command-line construction variables.
 
     This is a list that uses Split() to split an initial string along
@@ -1497,11 +1047,15 @@ class CLVar(UserList.UserList):
     command-line construction variable.
     """
     def __init__(self, seq = []):
-        UserList.UserList.__init__(self, Split(seq))
+        UserList.__init__(self, Split(seq))
+    def __add__(self, other):
+        return UserList.__add__(self, CLVar(other))
+    def __radd__(self, other):
+        return UserList.__radd__(self, CLVar(other))
     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:
@@ -1530,7 +1084,7 @@ class OrderedDict(UserDict):
         return dict
 
     def items(self):
-        return zip(self._keys, self.values())
+        return list(zip(self._keys, self.values()))
 
     def keys(self):
         return self._keys[:]
@@ -1555,17 +1109,18 @@ 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
     dictionary values.  We preserve the order in which items are added
     so that get_suffix() calls always return the first suffix added."""
-    def __call__(self, env, source):
-        try:
-            ext = splitext(str(source[0]))[1]
-        except IndexError:
-            ext = ""
+    def __call__(self, env, source, ext=None):
+        if ext is None:
+            try:
+                ext = source[0].suffix
+            except IndexError:
+                ext = ""
         try:
             return self[ext]
         except KeyError:
@@ -1573,9 +1128,9 @@ class Selector(OrderedDict):
             # the dictionary before giving up.
             s_dict = {}
             for (k,v) in self.items():
-                if not k is None:
+                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,
@@ -1593,24 +1148,33 @@ class Selector(OrderedDict):
 
 if sys.platform == 'cygwin':
     # On Cygwin, os.path.normcase() lies, so just report back the
-    # fact that the underlying Win32 OS is case-insensitive.
+    # fact that the underlying Windows OS is case-insensitive.
     def case_sensitive_suffixes(s1, s2):
         return 0
 else:
     def case_sensitive_suffixes(s1, s2):
         return (os.path.normcase(s1) != os.path.normcase(s2))
 
-def adjustixes(fname, pre, suf):
+def adjustixes(fname, pre, suf, ensure_suffix=False):
     if pre:
         path, fn = os.path.split(os.path.normpath(fname))
         if fn[:len(pre)] != pre:
             fname = os.path.join(path, pre + fn)
-    # Only append a suffix if the file does not have one.
-    if suf and not splitext(fname)[1] and fname[-len(suf):] != suf:
+    # Only append a suffix if the suffix we're going to add isn't already
+    # there, and if either we've been asked to ensure the specific suffix
+    # is present or there's no suffix on it at all.
+    if suf and fname[-len(suf):] != suf and \
+       (ensure_suffix or not splitext(fname)[1]):
             fname = fname + suf
     return fname
 
 
+
+# From Tim Peters,
+# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
+# ASPN: Python Cookbook: Remove duplicates from a sequence
+# (Also in the printed Python Cookbook.)
+
 def unique(s):
     """Return a list of the elements in s, but without duplicates.
 
@@ -1645,9 +1209,10 @@ def unique(s):
         for x in s:
             u[x] = 1
     except TypeError:
-        del u  # move on to the next method
+        pass    # move on to the next method
     else:
         return u.keys()
+    del u
 
     # We can't hash all the elements.  Second fastest is to sort,
     # which brings the equal elements together; then duplicates are
@@ -1657,10 +1222,9 @@ def unique(s):
     # sort functions in all languages or libraries, so this approach
     # is more effective in Python than it may be elsewhere.
     try:
-        t = list(s)
-        t.sort()
+        t = sorted(s)
     except TypeError:
-        del t  # move on to the next method
+        pass    # move on to the next method
     else:
         assert n > 0
         last = t[0]
@@ -1671,6 +1235,7 @@ def unique(s):
                 lasti = lasti + 1
             i = i + 1
         return t[:lasti]
+    del t
 
     # Brute force is all that's left.
     u = []
@@ -1679,6 +1244,45 @@ def unique(s):
             u.append(x)
     return u
 
+
+
+# From Alex Martelli,
+# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
+# ASPN: Python Cookbook: Remove duplicates from a sequence
+# First comment, dated 2001/10/13.
+# (Also in the printed Python Cookbook.)
+
+def uniquer(seq, idfun=None):
+    if idfun is None:
+        def idfun(x): return x
+    seen = {}
+    result = []
+    for item in seq:
+        marker = idfun(item)
+        # in old Python versions:
+        # if seen.has_key(marker)
+        # but in new ones:
+        if marker in seen: continue
+        seen[marker] = 1
+        result.append(item)
+    return result
+
+# A more efficient implementation of Alex's uniquer(), this avoids the
+# idfun() argument and function-call overhead by assuming that all
+# items in the sequence are hashable.
+
+def uniquer_hashables(seq):
+    seen = {}
+    result = []
+    for item in seq:
+        #if not item in seen:
+        if item not in seen:
+            seen[item] = 1
+            result.append(item)
+    return result
+
+
+
 # Much of the logic here was originally based on recipe 4.9 from the
 # Python CookBook, but we had to dumb it way down for Python 1.5.2.
 class LogicalLines:
@@ -1688,7 +1292,7 @@ class LogicalLines:
 
     def readline(self):
         result = []
-        while 1:
+        while True:
             line = self.fileobj.readline()
             if not line:
                 break
@@ -1697,13 +1301,340 @@ class LogicalLines:
             else:
                 result.append(line)
                 break
-        return string.join(result, '')
+        return ''.join(result)
 
     def readlines(self):
         result = []
-        while 1:
+        while True:
             line = self.readline()
             if not line:
                 break
             result.append(line)
         return result
+
+
+
+class UniqueList(UserList):
+    def __init__(self, seq = []):
+        UserList.__init__(self, seq)
+        self.unique = True
+    def __make_unique(self):
+        if not self.unique:
+            self.data = uniquer_hashables(self.data)
+            self.unique = True
+    def __lt__(self, other):
+        self.__make_unique()
+        return UserList.__lt__(self, other)
+    def __le__(self, other):
+        self.__make_unique()
+        return UserList.__le__(self, other)
+    def __eq__(self, other):
+        self.__make_unique()
+        return UserList.__eq__(self, other)
+    def __ne__(self, other):
+        self.__make_unique()
+        return UserList.__ne__(self, other)
+    def __gt__(self, other):
+        self.__make_unique()
+        return UserList.__gt__(self, other)
+    def __ge__(self, other):
+        self.__make_unique()
+        return UserList.__ge__(self, other)
+    def __cmp__(self, other):
+        self.__make_unique()
+        return UserList.__cmp__(self, other)
+    def __len__(self):
+        self.__make_unique()
+        return UserList.__len__(self)
+    def __getitem__(self, i):
+        self.__make_unique()
+        return UserList.__getitem__(self, i)
+    def __setitem__(self, i, item):
+        UserList.__setitem__(self, i, item)
+        self.unique = False
+    def __getslice__(self, i, j):
+        self.__make_unique()
+        return UserList.__getslice__(self, i, j)
+    def __setslice__(self, i, j, other):
+        UserList.__setslice__(self, i, j, other)
+        self.unique = False
+    def __add__(self, other):
+        result = UserList.__add__(self, other)
+        result.unique = False
+        return result
+    def __radd__(self, other):
+        result = UserList.__radd__(self, other)
+        result.unique = False
+        return result
+    def __iadd__(self, other):
+        result = UserList.__iadd__(self, other)
+        result.unique = False
+        return result
+    def __mul__(self, other):
+        result = UserList.__mul__(self, other)
+        result.unique = False
+        return result
+    def __rmul__(self, other):
+        result = UserList.__rmul__(self, other)
+        result.unique = False
+        return result
+    def __imul__(self, other):
+        result = UserList.__imul__(self, other)
+        result.unique = False
+        return result
+    def append(self, item):
+        UserList.append(self, item)
+        self.unique = False
+    def insert(self, i):
+        UserList.insert(self, i)
+        self.unique = False
+    def count(self, item):
+        self.__make_unique()
+        return UserList.count(self, item)
+    def index(self, item):
+        self.__make_unique()
+        return UserList.index(self, item)
+    def reverse(self):
+        self.__make_unique()
+        UserList.reverse(self)
+    def sort(self, *args, **kwds):
+        self.__make_unique()
+        return UserList.sort(self, *args, **kwds)
+    def extend(self, other):
+        UserList.extend(self, other)
+        self.unique = False
+
+
+
+class Unbuffered:
+    """
+    A proxy class that wraps a file object, flushing after every write,
+    and delegating everything else to the wrapped object.
+    """
+    def __init__(self, file):
+        self.file = file
+    def write(self, arg):
+        try:
+            self.file.write(arg)
+            self.file.flush()
+        except IOError:
+            # Stdout might be connected to a pipe that has been closed
+            # by now. The most likely reason for the pipe being closed
+            # is that the user has press ctrl-c. It this is the case,
+            # then SCons is currently shutdown. We therefore ignore
+            # IOError's here so that SCons can continue and shutdown
+            # properly so that the .sconsign is correctly written
+            # before SCons exits.
+            pass
+    def __getattr__(self, attr):
+        return getattr(self.file, attr)
+
+def make_path_relative(path):
+    """ makes an absolute path name to a relative pathname.
+    """
+    if os.path.isabs(path):
+        drive_s,path = os.path.splitdrive(path)
+
+        import re
+        if not drive_s:
+            path=re.compile("/*(.*)").findall(path)[0]
+        else:
+            path=path[1:]
+
+    assert( not os.path.isabs( path ) ), path
+    return path
+
+
+
+# The original idea for AddMethod() and RenameFunction() come from the
+# following post to the ActiveState Python Cookbook:
+#
+#      ASPN: Python Cookbook : Install bound methods in an instance
+#      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223613
+#
+# That code was a little fragile, though, so the following changes
+# have been wrung on it:
+#
+# * Switched the installmethod() "object" and "function" arguments,
+#   so the order reflects that the left-hand side is the thing being
+#   "assigned to" and the right-hand side is the value being assigned.
+#
+# * Changed explicit type-checking to the "try: klass = object.__class__"
+#   block in installmethod() below so that it still works with the
+#   old-style classes that SCons uses.
+#
+# * Replaced the by-hand creation of methods and functions with use of
+#   the "new" module, as alluded to in Alex Martelli's response to the
+#   following Cookbook post:
+#
+#      ASPN: Python Cookbook : Dynamically added methods to a class
+#      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732
+
+def AddMethod(object, function, name = None):
+    """
+    Adds either a bound method to an instance or an unbound method to
+    a class. If name is ommited the name of the specified function
+    is used by default.
+    Example:
+      a = A()
+      def f(self, x, y):
+        self.z = x + y
+      AddMethod(f, A, "add")
+      a.add(2, 4)
+      print a.z
+      AddMethod(lambda self, i: self.l[i], a, "listIndex")
+      print a.listIndex(5)
+    """
+    import new
+
+    if name is None:
+        name = function.func_name
+    else:
+        function = RenameFunction(function, name)
+
+    try:
+        klass = object.__class__
+    except AttributeError:
+        # "object" is really a class, so it gets an unbound method.
+        object.__dict__[name] = new.instancemethod(function, None, object)
+    else:
+        # "object" is really an instance, so it gets a bound method.
+        object.__dict__[name] = new.instancemethod(function, object, klass)
+
+def RenameFunction(function, name):
+    """
+    Returns a function identical to the specified function, but with
+    the specified name.
+    """
+    import new
+
+    # Compatibility for Python 1.5 and 2.1.  Can be removed in favor of
+    # passing function.func_defaults directly to new.function() once
+    # we base on Python 2.2 or later.
+    func_defaults = function.func_defaults
+    if func_defaults is None:
+        func_defaults = ()
+
+    return new.function(function.func_code,
+                        function.func_globals,
+                        name,
+                        func_defaults)
+
+
+md5 = False
+def MD5signature(s):
+    return str(s)
+
+def MD5filesignature(fname, chunksize=65536):
+    f = open(fname, "rb")
+    result = f.read()
+    f.close()
+    return result
+
+try:
+    import hashlib
+except ImportError:
+    pass
+else:
+    if hasattr(hashlib, 'md5'):
+        md5 = True
+        def MD5signature(s):
+            m = hashlib.md5()
+            m.update(str(s))
+            return m.hexdigest()
+
+        def MD5filesignature(fname, chunksize=65536):
+            m = hashlib.md5()
+            f = open(fname, "rb")
+            while True:
+                blck = f.read(chunksize)
+                if not blck:
+                    break
+                m.update(str(blck))
+            f.close()
+            return m.hexdigest()
+            
+def MD5collect(signatures):
+    """
+    Collects a list of signatures into an aggregate signature.
+
+    signatures - a list of signatures
+    returns - the aggregate signature
+    """
+    if len(signatures) == 1:
+        return signatures[0]
+    else:
+        return MD5signature(', '.join(signatures))
+
+
+
+# Wrap the intern() function so it doesn't throw exceptions if ineligible
+# arguments are passed. The intern() function was moved into the sys module in
+# Python 3.
+try:
+    intern
+except NameError:
+    from sys import intern
+
+def silent_intern(x):
+    """
+    Perform intern() on the passed argument and return the result.
+    If the input is ineligible (e.g. a unicode string) the original argument is
+    returned and no exception is thrown.
+    """
+    try:
+        return intern(x)
+    except TypeError:
+        return x
+
+
+
+# From Dinu C. Gherman,
+# Python Cookbook, second edition, recipe 6.17, p. 277.
+# Also:
+# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205
+# ASPN: Python Cookbook: Null Object Design Pattern
+
+# TODO(1.5):
+#class Null(object):
+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)
+        return cls._inst
+    def __init__(self, *args, **kwargs):
+        pass
+    def __call__(self, *args, **kwargs):
+        return self
+    def __repr__(self):
+        return "Null(0x%08X)" % id(self)
+    def __nonzero__(self):
+        return False
+    def __getattr__(self, name):
+        return self
+    def __setattr__(self, name, value):
+        return self
+    def __delattr__(self, name):
+        return self
+
+class NullSeq(Null):
+    def __len__(self):
+        return 0
+    def __iter__(self):
+        return iter(())
+    def __getitem__(self, i):
+        return self
+    def __delitem__(self, i):
+        return self
+    def __setitem__(self, i, v):
+        return self
+
+
+del __revision__
+
+# Local Variables:
+# tab-width:4
+# indent-tabs-mode:nil
+# End:
+# vim: set expandtab tabstop=4 shiftwidth=4: