Commits

Steven Knight  committed 6661c9e

Merged revisions 1968-2115 via svnmerge from
http://scons.tigris.org/svn/scons/branches/core

........
r1970 | stevenknight | 2007-06-01 18:22:37 -0500 (Fri, 01 Jun 2007) | 4 lines

Import a vanilla Python 2.3 version of textwrap.py into the compatibility
library, so we can track the changes we'll make to it. (This isn't
actually used yet.)
........
r1971 | stevenknight | 2007-06-02 00:38:20 -0500 (Sat, 02 Jun 2007) | 2 lines

Add a compatibility module for the textwrap.py module introduced in Python 2.3.
........
r1972 | stevenknight | 2007-06-02 00:39:26 -0500 (Sat, 02 Jun 2007) | 2 lines

Remove spurious <para> tags.
........
r1973 | stevenknight | 2007-06-03 08:57:05 -0500 (Sun, 03 Jun 2007) | 2 lines

Improved help-text generation using a textwrap.TextWrapper object.
........
r1991 | stevenknight | 2007-06-10 16:03:18 -0500 (Sun, 10 Jun 2007) | 3 lines

Add compatibility versions of the all() and any() functions introduced
in Python 2.5.
........
r1992 | stevenknight | 2007-06-10 17:02:18 -0500 (Sun, 10 Jun 2007) | 8 lines

SCons-time portability fixes for Python 2.[12]:

-- Use "from __future__ import nested_scopes".
-- Create "False" and "True" builtins
-- Work around the lack of a "prefix =" keyword argument to the
Python 2.[12] version of the mktemp module.
-- Accomodate pickier single-element tuple syntax.
........
r1993 | stevenknight | 2007-06-10 17:27:43 -0500 (Sun, 10 Jun 2007) | 3 lines

Delay instantiation of pstat.Stats objects until after we override
sys.stdout, which as of Python 2.5 is captured when the object is created.
........
r1994 | stevenknight | 2007-06-10 21:22:42 -0500 (Sun, 10 Jun 2007) | 6 lines

Update various tests to handle the

File "SConstruct", line 1, in <module>

Messages in Python 2.5.
........
r1995 | stevenknight | 2007-06-10 21:32:16 -0500 (Sun, 10 Jun 2007) | 3 lines

Update tests to not raise strings as exceptions, which has been
deprecated in Python 2.5.
........
r1996 | stevenknight | 2007-06-10 21:41:57 -0500 (Sun, 10 Jun 2007) | 3 lines

Fix the Scanner hash unit test for Python 2.5. (Yes, it still works
on previous versions, too.)
........
r1997 | stevenknight | 2007-06-10 21:55:46 -0500 (Sun, 10 Jun 2007) | 3 lines

Make the mock Node object's side_effect attribute a list, so it's
iterable in Python 2.1 as well.
........
r1998 | stevenknight | 2007-06-10 22:04:26 -0500 (Sun, 10 Jun 2007) | 3 lines

Append an explicit tuple to the delayed_warnings list if there are
problems interpreting --debug=memoizer.
........
r1999 | stevenknight | 2007-06-11 11:09:07 -0500 (Mon, 11 Jun 2007) | 2 lines

Fix --debug=time with -j when no arguments are rebuilt (all up-to-date).
........
r2007 | stevenknight | 2007-06-14 13:56:35 -0500 (Thu, 14 Jun 2007) | 4 lines

Performance improvement when looking up Nodes: don't use is_String(),
just check for the initial '#' that specifies a top-relative lookup,
and handle the exceptions.
........
r2008 | stevenknight | 2007-06-14 16:57:47 -0500 (Thu, 14 Jun 2007) | 11 lines

First step in refactoring command-line flag processing: Split out the
current processing into its own module, with minimal additional changes.
Among the minimal changes:
-- Store delayed warnings (for deprecated --debug= keywords)
in the option parser object, not in a global variable.
-- Remove the OptParser variable itself from the SCons.Script globals.
It's going to change significantly (and no one's probably using
it anyway).
-- Don't move definition of the --version output with the OptParser,
keep it in Main.py.
........
r2009 | stevenknight | 2007-06-15 08:15:25 -0500 (Fri, 15 Jun 2007) | 3 lines

Refactor the test/explain.py script into three individual scripts
so it's easier to deal with.
........
r2010 | stevenknight | 2007-06-15 09:49:07 -0500 (Fri, 15 Jun 2007) | 3 lines

Handle Aliases in --debug=explain. This is kind of hard-coded for the
normal lookup, and should be better handled by the signature refactoring.
........
r2011 | stevenknight | 2007-06-15 17:25:37 -0500 (Fri, 15 Jun 2007) | 5 lines

Refactor use of the command-line parser object so it's localized to the
top-level main() function, and not passed down through _exec_main() or
to _main() itself. Replace its functionality with use of an exception to
signal that the top-level main() function should print its help message.
........
r2012 | stevenknight | 2007-06-17 23:34:26 -0500 (Sun, 17 Jun 2007) | 2 lines

Remove unnecessary import of __main__.
........
r2013 | stevenknight | 2007-06-17 23:48:06 -0500 (Sun, 17 Jun 2007) | 2 lines

Pass the options object to _main(), don't use a global.
........
r2014 | stevenknight | 2007-06-18 00:12:09 -0500 (Mon, 18 Jun 2007) | 6 lines

Qt test fixes for Windows:
Link against a static library created by the test infrastructure,
not a shared library.
Escape backslashes in Windows path names.
Skip test/QT/Tool.py if Qt isn't installed.
........
r2015 | stevenknight | 2007-06-18 10:46:17 -0500 (Mon, 18 Jun 2007) | 3 lines

Support GetOption('no_exec'), and update test/NodeOps.py to use it
instead of reaching into the SCons.Script.Main internals.
........
r2016 | stevenknight | 2007-06-18 11:04:39 -0500 (Mon, 18 Jun 2007) | 4 lines

Restore use of a global delayed_warnings variable so the chicken-and-egg
warning from trying to use --debug=memoizer on Python versions without
metaclasses has somewhere to go.
........
r2017 | stevenknight | 2007-06-18 11:37:59 -0500 (Mon, 18 Jun 2007) | 3 lines

Have the test infrastructure create a mock Qt shared library on UNIX,
static library on Windows.
........
r2018 | stevenknight | 2007-06-18 11:48:10 -0500 (Mon, 18 Jun 2007) | 2 lines

Pull more globals into the command-line parser options object.
........
r2023 | stevenknight | 2007-06-19 16:46:02 -0500 (Tue, 19 Jun 2007) | 3 lines

Refactor the __checkClass() and must_be_a_Dir() methods into a more
general and more efficient must_be_same() method.
........
r2025 | stevenknight | 2007-06-19 20:56:10 -0500 (Tue, 19 Jun 2007) | 3 lines

More clean up: change various self.fs.Entry() calls to calls through
the bound directory.Entry() method.
........
r2033 | stevenknight | 2007-06-20 20:03:23 -0500 (Wed, 20 Jun 2007) | 5 lines

The --debug=count option doesn't work when run with Python - O, or
from optimized compiled Python modules (*.pyo files), because the
counting is all within "#if __debug__:" blocks that get stripped.
Print a warning so it doesn't look like --debug=count is broken.
........
r2037 | stevenknight | 2007-06-21 10:42:40 -0500 (Thu, 21 Jun 2007) | 3 lines

Replace the _stripixes() function with a more efficient/readable version
that was checked in, but commented out, prior to 0.96.96.
........
r2040 | stevenknight | 2007-06-21 12:18:57 -0500 (Thu, 21 Jun 2007) | 2 lines

Ignore *.pyo files, too, since one of the tests now generates them.
........
r2051 | stevenknight | 2007-06-26 15:11:57 -0500 (Tue, 26 Jun 2007) | 5 lines

Arrange for graceful shutdown of the worker threads by writing None to
the requestQueue and having the worker threads terminate their processing
loops when they read it. We can then .join() the threads, to wait for
their termination, avoiding exceptions in the threading library module.
........
r2052 | stevenknight | 2007-06-26 15:12:53 -0500 (Tue, 26 Jun 2007) | 3 lines

Have the SWIG tests that use the Python.h header skip gracefully if
the Python development environment isn't installed.
........
r2053 | stevenknight | 2007-06-26 15:23:55 -0500 (Tue, 26 Jun 2007) | 3 lines

Massage the datestamp and IDs in the generated PDF so we can compare
before-and-after output reliably regardless of when generated.
........
r2054 | stevenknight | 2007-06-26 15:25:56 -0500 (Tue, 26 Jun 2007) | 3 lines

Fix the regular expression that matches the Qt warning message when
the moc executable is used as a hint.
........
r2055 | stevenknight | 2007-06-26 15:48:21 -0500 (Tue, 26 Jun 2007) | 2 lines

Fix 2.5.1 string exception warnings.
........
r2056 | stevenknight | 2007-06-26 19:23:22 -0500 (Tue, 26 Jun 2007) | 2 lines

Skip the scons-time tests if the Python version can't import __future__.
........
r2057 | stevenknight | 2007-06-26 22:11:04 -0500 (Tue, 26 Jun 2007) | 3 lines

Normalize PDF output in the bibtex rerun test as well. Commonize the
PDF normalization logic by putting it in QMTest/TestSCons.py.
........
r2058 | stevenknight | 2007-06-26 22:50:39 -0500 (Tue, 26 Jun 2007) | 3 lines

Duplicate a function declaration to suppress compiler warnings about a cast,
when using certain systems/compilers.
........
r2059 | stevenknight | 2007-06-26 22:53:12 -0500 (Tue, 26 Jun 2007) | 2 lines

Use the frtbegin when compiling Fortran programs using GCC 4.
........
r2060 | stevenknight | 2007-06-26 23:13:35 -0500 (Tue, 26 Jun 2007) | 2 lines

Make the object that goes into the shared library a shared object file.
........
r2061 | stevenknight | 2007-06-26 23:53:49 -0500 (Tue, 26 Jun 2007) | 4 lines

Split test/AS/AS.py into sub-tests for the live assemblers it tests.
Only test nasm for the known configuration of version 0.98* on a
32-bit x86 system.
........
r2063 | stevenknight | 2007-06-27 09:51:43 -0500 (Wed, 27 Jun 2007) | 2 lines

Fix searching for the rmic utility.
........
r2064 | stevenknight | 2007-06-27 10:26:42 -0500 (Wed, 27 Jun 2007) | 3 lines

Improved worker-thread termination in a separate Job.cleanup() method.
(Adam Simpkins)
........
r2087 | stevenknight | 2007-07-03 12:22:10 -0500 (Tue, 03 Jul 2007) | 7 lines

Get rid of unnecessary subclassing and complicating overriding of
__init__() and parse_args() methods in favor of more straightforward
initialization of the OptionParser object.

We may need to restore subclassing in the future, but if so we'll do it
in a more OO way.
........
r2088 | stevenknight | 2007-07-03 16:12:30 -0500 (Tue, 03 Jul 2007) | 2 lines

Fix a cleanup error (no self.p4d attribute) when Perforce isn't installed.
........
r2090 | stevenknight | 2007-07-04 03:23:57 -0500 (Wed, 04 Jul 2007) | 2 lines

Import the vanilla Python 2.5 optparse.py for use as a compatibility module.
........
r2091 | stevenknight | 2007-07-04 03:35:17 -0500 (Wed, 04 Jul 2007) | 5 lines

Use the new optparse compatibility module for command-line processing,
and remove the SCons/Optik/*.py modules, with appropriate subclassing
in Script/SConsOptions.py to preserve the way we print help text and
SCons error messages.
........
r2108 | stevenknight | 2007-07-08 22:57:08 -0500 (Sun, 08 Jul 2007) | 3 lines

Make all of the optparse.add_options calls more-or-less consistent in
how they call the keyword arguments.
........
r2109 | stevenknight | 2007-07-09 12:31:01 -0500 (Mon, 09 Jul 2007) | 6 lines

Consolidate command-line and {Get,Set}Option() processing and access
in a single subclass of the optparse.Values() class.

Allow all options, not just those that aren't SConscript-settable,
to set their default values when calling op.add_option().
........
r2110 | stevenknight | 2007-07-09 13:17:58 -0500 (Mon, 09 Jul 2007) | 4 lines

Handle initialization of command-line repository options by passing the
option arguments directly to the _SConstruct_exists() utility function,
not by setting a global variable.
........
r2111 | stevenknight | 2007-07-09 13:42:41 -0500 (Mon, 09 Jul 2007) | 2 lines

Remove the unused _varargs() utility function.
........
r2112 | stevenknight | 2007-07-09 15:21:51 -0500 (Mon, 09 Jul 2007) | 2 lines

Clean up how we use optparse (mainly for readability).
........
r2113 | stevenknight | 2007-07-10 15:50:08 -0500 (Tue, 10 Jul 2007) | 2 lines

More old-Python-version compatibility changes in optparse.py.
........
r2114 | stevenknight | 2007-07-10 16:46:42 -0500 (Tue, 10 Jul 2007) | 3 lines

Add support for a new AddOption() function to allow the SConscript
file(s) to define new command-line flags.
........

  • Participants
  • Parent commits e4b07e2

Comments (0)

Files changed (72)

File QMTest/TestSCons.py

     for l in stderr.readlines():
         list = string.split(l)
         if len(list) > 3 and list[:2] == ['gcc', 'version']:
-            if list[2][:2] == '3.':
+            if list[2][:2] in ('3.', '4.'):
                 libs = ['frtbegin'] + libs
                 break
     return libs
             # we call test.no_result().
             self.no_result(skip=1)
 
-    def diff_substr(self, expect, actual):
+    def diff_substr(self, expect, actual, prelen=20, postlen=40):
         i = 0
         for x, y in zip(expect, actual):
             if x != y:
                 return "Actual did not match expect at char %d:\n" \
                        "    Expect:  %s\n" \
                        "    Actual:  %s\n" \
-                       % (i, repr(expect[i-20:i+40]), repr(actual[i-20:i+40]))
+                       % (i, repr(expect[i-prelen:i+postlen]),
+                             repr(actual[i-prelen:i+postlen]))
             i = i + 1
         return "Actual matched the expected output???"
 
         x = string.replace(x, 'line 1,', 'line %s,' % line)
         return x
 
+    def normalize_pdf(self, s):
+        s = re.sub(r'/CreationDate \(D:[^)]*\)',
+                   r'/CreationDate (D:XXXX)', s)
+        s = re.sub(r'/ID \[<[0-9a-fA-F]*> <[0-9a-fA-F]*>\]',
+                   r'/ID [<XXXX> <XXXX>]', s)
+        return s
+
     def java_ENV(self):
         """
         Return a default external environment that uses a local Java SDK
     else: opt_string = opt_string + ' ' + opt
 for a in args:
     contents = open(a, 'rb').read()
+    a = string.replace(a, '\\\\', '\\\\\\\\')
     subst = r'{ my_qt_symbol( "' + a + '\\\\n" ); }'
     if impl:
         contents = re.sub( r'#include.*', '', contents )
 
         self.write([dir, 'lib', 'SConstruct'], r"""
 env = Environment()
-env.SharedLibrary( 'myqt', 'my_qobject.cpp' )
+import sys
+if sys.platform == 'win32':
+    env.StaticLibrary( 'myqt', 'my_qobject.cpp' )
+else:
+    env.SharedLibrary( 'myqt', 'my_qobject.cpp' )
 """)
 
         self.run(chdir = self.workpath(dir, 'lib'),

File QMTest/TestSCons_time.py

 
         apply(TestCommon.__init__, [self], kw)
 
+        # Now that the testing object has been set up, check if we should
+        # skip the test due to the Python version.  We need to be able to
+        # import __future__ (which scons-time.py uses for nested scopes)
+        # and to handle list comprehensions (just because we're avoiding
+        # the old map() and filter() idioms).
+
+        try:
+            import __future__
+        except ImportError:
+            version = string.split(sys.version)[0]
+            msg = 'scons-time does not work on Python version %s\n' % version
+            self.skip_test(msg)
+
         try:
             eval('[x for x in [1, 2]]')
         except SyntaxError:

File doc/man/scons.1

 of the various classes used internally by SCons
 before and after reading the SConscript files
 and before and after building targets.
-This only works when run under Python 2.1 or later.
+This is not supported when run under Python versions earlier than 2.1,
+when SCons is executed with the Python
+.B -O
+(optimized) option,
+or when the SCons modules
+have been compiled with optimization
+(that is, when executing from
+.B *.pyo
+files).
 
 .TP
 --debug=dtree
 .EE
 
 '\"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+.TP
+.RI AddOption( arguments )
+This function adds a new command-line option to be recognized.
+The specified
+.I arguments
+are the same as supported by the standard Python
+.B optparse.add_option
+method;
+see the documentation for
+.B optparse
+for a thorough discussion of its option-processing capabities.
+(Note that although the
+.B optparse
+module was not a standard module until Python 2.3,
+.B scons
+contains a compatible version of the module
+that is used to provide identical functionality
+when run by earlier Python versions.)
+
+If no
+.B default=
+keyword argument is supplied when calling
+.BR AddOption (),
+the option will have a default value of
+.BR None .
+
+Once a new command-line option has been added with
+.BR AddOption (),
+the option value may be accessed using
+.BR GetOption ()
+or
+.BR env.GetOption ().
+The value may also be set, using
+.BR SetOption ()
+or
+.BR env.SetOption (),
+if conditions in a
+.B SConscript
+require overriding any default value.
+Note, however, that a
+value specified on the command line will
+.I always
+override a value set by any SConscript file.
+
+Any specified
+.B help=
+strings for the new option(s)
+will be displayed by the
+.B -H
+or
+.B -h
+options
+(the latter only if no other help text is
+specified in the SConscript files).
+The help text for the local options specified by
+.BR AddOption ()
+will appear below the SCons options themselves,
+under a separate
+.B "Local Options"
+heading.
+The options will appear in the help text
+in the order in which the
+.BR AddOption ()
+calls occur.
+
+Example:
+
+.ES
+AddOption('--prefix',
+          dest='prefix',
+          nargs=1, type='string',
+          action='store',
+          metavar='DIR',
+          help='installation prefix')
+env = Environment(PREFIX = GetOption('prefix'))
+.EE
+
+'\"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
 .TP 
 .RI AddPostAction( target ", " action )
 .TP
 which corresponds to --implicit-cache;
 .B max_drift
 which corresponds to --max-drift;
+.B no_exec
+which corresponds to -n, --no-exec, --just-print, --dry-run and --recon;
 .B num_jobs
 which corresponds to -j and --jobs.
 .B random

File doc/user/libraries.in

 
       </para>
 
-      <para>
-
       <scons_example name="objects" printme="1">
         <file name="SConstruct" printme="1">
         Library('foo', ['f1.c', 'f2.o', 'f3.c', 'f4.o'])

File doc/user/libraries.sgml

 
       </para>
 
-      <para>
-
       <programlisting>
         Library('foo', ['f1.c', 'f2.o', 'f3.c', 'f4.o'])
       </programlisting>

File src/CHANGES.txt

   - Support {Get,Set}Option('random') so random-dependency interaction
     with CacheDir() is controllable from SConscript files.
 
+  - Add a new AddOption() function to support user-defined command-
+    line flags (like --prefix=, --force, etc.).
+
   - Push and retrieve built symlinks to/from a CacheDir() as actual
     symlinks, not by copying the file contents.
 
     for adding a new method, respectively, to a construction environment
     or an arbitrary object (such as a class).
 
+  - Fix the --debug=time option when the -j option is specified and all
+    files are up to date.
+
   From Leanid Nazdrynau:
 
   - When applying Tool modules after a construction environment has
   - Find Java anonymous classes when the next token after the name is
     an open parenthesis.
 
+  From Adam Simpkins:
+
+  - Allow worker threads to terminate gracefully when all jobs are
+    finished.
+
   From Sohail Somani:
 
   - Add LaTeX scanner support for finding dependencies specified with

File src/engine/MANIFEST.in

 SCons/Action.py
 SCons/Builder.py
 SCons/compat/__init__.py
+SCons/compat/_scons_optparse.py
 SCons/compat/_scons_sets.py
 SCons/compat/_scons_sets15.py
 SCons/compat/_scons_subprocess.py
+SCons/compat/_scons_textwrap.py
 SCons/compat/_scons_UserString.py
 SCons/compat/builtins.py
 SCons/Conftest.py
 SCons/Node/Alias.py
 SCons/Node/FS.py
 SCons/Node/Python.py
-SCons/Optik/__init__.py
-SCons/Optik/errors.py
-SCons/Optik/option.py
-SCons/Optik/option_parser.py
 SCons/Options/__init__.py
 SCons/Options/BoolOption.py
 SCons/Options/EnumOption.py
 SCons/SConsign.py
 SCons/Script/Main.py
 SCons/Script/SConscript.py
+SCons/Script/SConsOptions.py
 SCons/Script/__init__.py
 SCons/Sig/__init__.py
 SCons/Sig/MD5.py

File src/engine/SCons/Defaults.py

     return result
 
 def _stripixes(prefix, list, suffix, stripprefix, stripsuffix, env, c=None):
-    """This is a wrapper around _concat() that checks for the existence
-    of prefixes or suffixes on list elements and strips them where it
-    finds them.  This is used by tools (like the GNU linker) that need
-    to turn something like 'libfoo.a' into '-lfoo'."""
+    """
+    This is a wrapper around _concat()/_concat_ixes() that checks for the
+    existence of prefixes or suffixes on list elements and strips them
+    where it finds them.  This is used by tools (like the GNU linker)
+    that need to turn something like 'libfoo.a' into '-lfoo'.
+    """
     
+    if not list:
+        return list
+
     if not callable(c):
-        if callable(env["_concat"]):
-            c = env["_concat"]
+        env_c = env['_concat']
+        if env_c != _concat and callable(env_c):
+            # There's a custom _concat() method in the construction
+            # environment, and we've allowed people to set that in
+            # the past (see test/custom-concat.py), so preserve the
+            # backwards compatibility.
+            c = env_c
         else:
-            c = _concat
-    def f(list, sp=stripprefix, ss=stripsuffix):
-        result = []
-        for l in list:
-            if isinstance(l, SCons.Node.FS.File):
-                result.append(l)
-                continue
-            if not SCons.Util.is_String(l):
-                l = str(l)
-            if l[:len(sp)] == sp:
-                l = l[len(sp):]
-            if l[-len(ss):] == ss:
-                l = l[:-len(ss)]
-            result.append(l)
-        return result
-    return c(prefix, list, suffix, env, f)
+            c = _concat_ixes
+    
+    if SCons.Util.is_List(list):
+        list = SCons.Util.flatten(list)
 
-# This is an alternate _stripixes() function that passes all of our tests
-# (as of 21 February 2007), like the current version above.  It's more
-# straightforward because it does its manipulation directly, not using
-# the funky f call-back function to _concat().  (In this respect it's
-# like the updated _defines() function below.)
-#
-# The most convoluted thing is that it still uses a custom _concat()
-# function if one was placed in the construction environment; there's
-# a specific test for that functionality, but it might be worth getting
-# rid of.
-#
-# Since this work was done while trying to get 0.97 out the door
-# (just prior to 0.96.96), I decided to be cautious and leave the old
-# function as is, to minimize the chance of other corner-case regressions.
-# The updated version is captured here so we can uncomment it and start
-# using it at a less sensitive time in the development cycle (or when
-# it's clearly required to fix something).
-#
-#def _stripixes(prefix, list, suffix, stripprefix, stripsuffix, env, c=None):
-#    """
-#    This is a wrapper around _concat()/_concat_ixes() that checks for the
-#    existence of prefixes or suffixes on list elements and strips them
-#    where it finds them.  This is used by tools (like the GNU linker)
-#    that need to turn something like 'libfoo.a' into '-lfoo'.
-#    """
-#    
-#    if not list:
-#        return list
-#
-#    if not callable(c):
-#        env_c = env['_concat']
-#        if env_c != _concat and callable(env_c):
-#            # There's a custom _concat() method in the construction
-#            # environment, and we've allowed people to set that in
-#            # the past (see test/custom-concat.py), so preserve the
-#            # backwards compatibility.
-#            c = env_c
-#        else:
-#            c = _concat_ixes
-#    
-#    if SCons.Util.is_List(list):
-#        list = SCons.Util.flatten(list)
-#
-#    lsp = len(stripprefix)
-#    lss = len(stripsuffix)
-#    stripped = []
-#    for l in SCons.PathList.PathList(list).subst_path(env, None, None):
-#        if isinstance(l, SCons.Node.FS.File):
-#            stripped.append(l)
-#            continue
-#        if not SCons.Util.is_String(l):
-#            l = str(l)
-#        if l[:lsp] == stripprefix:
-#            l = l[lsp:]
-#        if l[-lss:] == stripsuffix:
-#            l = l[:-lss]
-#        stripped.append(l)
-#
-#    return c(prefix, stripped, suffix, env)
+    lsp = len(stripprefix)
+    lss = len(stripsuffix)
+    stripped = []
+    for l in SCons.PathList.PathList(list).subst_path(env, None, None):
+        if isinstance(l, SCons.Node.FS.File):
+            stripped.append(l)
+            continue
+        if not SCons.Util.is_String(l):
+            l = str(l)
+        if l[:lsp] == stripprefix:
+            l = l[lsp:]
+        if l[-lss:] == stripsuffix:
+            l = l[:-lss]
+        stripped.append(l)
+
+    return c(prefix, stripped, suffix, env)
 
 def _defines(prefix, defs, suffix, env, c=_concat_ixes):
     """A wrapper around _concat_ixes that turns a list or string

File src/engine/SCons/Environment.py

                 # Prepend './' so the lookup doesn't interpret an initial
                 # '#' on the file name portion as meaning the Node should
                 # be relative to the top-level SConstruct directory.
-                target = self.fs.Entry('.'+os.sep+src.name, dnode)
+                target = dnode.Entry('.'+os.sep+src.name)
                 tgt.extend(InstallBuilder(self, target, src))
         return tgt
 

File src/engine/SCons/Job.py

             signal.signal(signal.SIGINT, signal.SIG_IGN)
             raise
 
+    def cleanup(self):
+        self.job.cleanup()
+
 class Serial:
     """This class is used to execute tasks in series, and is more efficient
     than Parallel, but is only appropriate for non-parallel builds. Only
 
             task.postprocess()
 
+    def cleanup(self):
+        pass
 
 # Trap import failure so that everything in the Job module but the
 # Parallel class (and its dependent classes) will work if the interpreter
             while 1:
                 task = self.requestQueue.get()
 
+                if not task:
+                    # The "None" value is used as a sentinel by
+                    # ThreadPool.cleanup().  This indicates that there
+                    # are no more tasks, so we should quit.
+                    break
+
                 try:
                     task.execute()
                 except KeyboardInterrupt:
             self.resultsQueue = Queue.Queue(0)
 
             # Create worker threads
+            self.workers = []
             for _ in range(num):
-                Worker(self.requestQueue, self.resultsQueue)
+                worker = Worker(self.requestQueue, self.resultsQueue)
+                self.workers.append(worker)
 
         def put(self, obj):
             """Put task into request queue."""
             return self.resultsQueue.get(block)
 
         def preparation_failed(self, obj):
-            self.resultsQueue.put((obj, 0))
+            self.resultsQueue.put((obj, False))
+
+        def cleanup(self):
+            """
+            Shuts down the thread pool, giving each worker thread a
+            chance to shut down gracefully.
+            """
+            # For each worker thread, put a sentinel "None" value
+            # on the requestQueue (indicating that there's no work
+            # to be done) so that each worker thread will get one and
+            # terminate gracefully.
+            for _ in self.workers:
+                self.requestQueue.put(None)
+
+            # Wait for all of the workers to terminate.
+            # 
+            # If we don't do this, later Python versions (2.4, 2.5) often
+            # seem to raise exceptions during shutdown.  This happens
+            # in requestQueue.get(), as an assertion failure that
+            # requestQueue.not_full is notified while not acquired,
+            # seemingly because the main thread has shut down (or is
+            # in the process of doing so) while the workers are still
+            # trying to pull sentinels off the requestQueue.
+            #
+            # Normally these terminations should happen fairly quickly,
+            # but we'll stick a one-second timeout on here just in case
+            # someone gets hung.
+            for worker in self.workers:
+                worker.join(1.0)
+            self.workers = []
 
     class Parallel:
         """This class is used to execute tasks in parallel, and is somewhat 
 
                     if self.tp.resultsQueue.empty():
                         break
+
+        def cleanup(self):
+            self.tp.cleanup()

File src/engine/SCons/JobTests.py

         self.was_prepared = 1
 
     def execute(self):
-        raise "exception"
+        raise Exception
 
     def executed(self):
         self.taskmaster.num_executed = self.taskmaster.num_executed + 1
         goodnode.__init__(self)
         self.expect_to_be = SCons.Node.failed
     def build(self, **kw):
-        raise 'badnode exception'
+        raise Exception, 'badnode exception'
 
 class slowbadnode (badnode):
     def build(self, **kw):
         # it is faster than slowgoodnode then these could complete
         # while the scheduler is sleeping.
         time.sleep(0.05)
-        raise 'slowbadnode exception'
+        raise Exception, 'slowbadnode exception'
 
 class badpreparenode (badnode):
     def prepare(self):
-        raise 'badpreparenode exception'
+        raise Exception, 'badpreparenode exception'
 
 class _SConsTaskTest(unittest.TestCase):
 

File src/engine/SCons/Node/FS.py

         self.cwd = None # will hold the SConscript directory for target nodes
         self.duplicate = directory.duplicate
 
+    def must_be_same(self, klass):
+        """
+        This node, which already existed, is being looked up as the
+        specified klass.  Raise an exception if it isn't.
+        """
+        if self.__class__ is klass or klass is Entry:
+            return
+        raise TypeError, "Tried to lookup %s '%s' as a %s." %\
+              (self.__class__.__name__, self.path, klass.__name__)
+
     def get_dir(self):
         return self.dir
 
         name=self.name
         while dir:
             if dir.srcdir:
-                srcnode = self.fs.Entry(name, dir.srcdir,
-                                        klass=self.__class__)
+                srcnode = dir.srcdir.Entry(name)
+                srcnode.must_be_same(self.__class__)
                 return srcnode
             name = dir.name + os.sep + name
             dir = dir.up()
         else:
             return self.get_contents()
 
-    def must_be_a_Dir(self):
+    def must_be_same(self, klass):
         """Called to make sure a Node is a Dir.  Since we're an
         Entry, we can morph into one."""
-        self.__class__ = Dir
-        self._morph()
-        return self
+        if not self.__class__ is klass:
+            self.__class__ = klass
+            self._morph()
+            self.clear
 
     # The following methods can get called before the Taskmaster has
     # had a chance to call disambiguate() directly to see if this Entry
     def getcwd(self):
         return self._cwd
 
-    def __checkClass(self, node, klass):
-        if isinstance(node, klass) or klass == Entry:
-            return node
-        if node.__class__ == Entry:
-            node.__class__ = klass
-            node._morph()
-            return node
-        raise TypeError, "Tried to lookup %s '%s' as a %s." % \
-              (node.__class__.__name__, node.path, klass.__name__)
-        
     def _doLookup_key(self, fsclass, name, directory = None, create = 1):
         return (fsclass, name, directory)
 
                 # We tried to look up the entry in either an Entry or
                 # a File.  Give whatever it is a chance to do what's
                 # appropriate: morph into a Dir or raise an exception.
-                directory.must_be_a_Dir()
+                directory.must_be_same(Dir)
                 entries = directory.entries
             try:
                 directory = entries[norm]
                 directory.add_wkid(d)
                 directory = d
 
-        directory.must_be_a_Dir()
+        directory.must_be_same(Dir)
 
         try:
             e = directory.entries[last_norm]
             directory.entries[last_norm] = result 
             directory.add_wkid(result)
         else:
-            result = self.__checkClass(e, fsclass)
+            e.must_be_same(fsclass)
+            result = e
 
         memo_dict[memo_key] = result
 
         If directory is None, and name is a relative path,
         then the same applies.
         """
-        if not SCons.Util.is_String(name):
-            # This handles cases where the object is a Proxy wrapping
-            # a Node.FS.File object (e.g.).  It would be good to handle
-            # this more directly some day by having the callers of this
-            # function recognize that a Proxy can be treated like the
-            # underlying object (that is, get rid of the isinstance()
-            # calls that explicitly look for a Node.FS.Base object).
+        try:
+            # Decide if this is a top-relative look up.  The normal case
+            # (by far) is handed a non-zero-length string to look up,
+            # so just (try to) check for the initial '#'.
+            top_relative = (name[0] == '#')
+        except (AttributeError, IndexError):
+            # The exceptions we may encounter in unusual cases:
+            #   AttributeError: a proxy without a __getitem__() method.
+            #   IndexError: a null string.
+            top_relative = False
             name = str(name)
-        if name and name[0] == '#':
+        if top_relative:
             directory = self.Top
             name = name[1:]
             if name and (name[0] == os.sep or name[0] == '/'):
             klass = Entry
 
         if isinstance(name, Base):
-            return self.__checkClass(name, klass)
+            name.must_be_same(klass)
+            return name
         else:
             if directory and not isinstance(directory, Dir):
                 directory = self.Dir(directory)
     def entry_tpath(self, name):
         return self.tpath + os.sep + name
 
-    def must_be_a_Dir(self):
-        """Called to make sure a Node is a Dir.  Since we're already
-        one, this is a no-op for us."""
-        return self
-
     def entry_exists_on_disk(self, name):
         try:
             d = self.on_disk_entries
         self.tpath = name + os.sep
         self._morph()
 
+    def must_be_same(self, klass):
+        if klass is Dir:
+            return
+        Base.must_be_same(self, klass)
+
     def __str__(self):
         return self.abspath
 
         as dependency info.  Convert the strings to actual Nodes (for
         use by the --debug=explain code and --implicit-cache).
         """
-        Entry_func = self.node.dir.Entry
+        def str_to_node(s, entry=self.node.dir.Entry):
+            # This is a little bogus; we're going to mimic the lookup
+            # order of env.arg2nodes() by hard-coding an Alias lookup
+            # before we assume it's an Entry.  This should be able to
+            # go away once the Big Signature Refactoring pickles the
+            # actual NodeInfo object, which will let us know precisely
+            # what type of Node to turn it into.
+            import SCons.Node.Alias
+            n = SCons.Node.Alias.default_ans.lookup(s)
+            if not n:
+                n = entry(s)
+            return n
         for attr in ['bsources', 'bdepends', 'bimplicit']:
             try:
                 val = getattr(self, attr)
             except AttributeError:
                 pass
             else:
-                setattr(self, attr, map(Entry_func, val))
+                setattr(self, attr, map(str_to_node, val))
     def format(self):
         result = [ self.ninfo.format() ]
         bkids = self.bsources + self.bdepends + self.bimplicit
     def Entry(self, name):
         """Create an entry node named 'name' relative to
         the SConscript directory of this file."""
-        return self.fs.Entry(name, self.cwd)
+        return self.cwd.Entry(name)
 
     def Dir(self, name):
         """Create a directory node named 'name' relative to
         the SConscript directory of this file."""
-        return self.fs.Dir(name, self.cwd)
+        return self.cwd.Dir(name)
 
     def Dirs(self, pathlist):
         """Create a list of directories relative to the SConscript
     def File(self, name):
         """Create a file node named 'name' relative to
         the SConscript directory of this file."""
-        return self.fs.File(name, self.cwd)
+        return self.cwd.File(name)
 
     #def generate_build_dict(self):
     #    """Return an appropriate dictionary of values for building
 
         Note that there's a special trick here with the execute flag
         (one that's not normally done for other actions).  Basically
-        if the user requested a noexec (-n) build, then
+        if the user requested a no_exec (-n) build, then
         SCons.Action.execute_actions is set to 0 and when any action
         is called, it does its showing but then just returns zero
         instead of actually calling the action execution operation.
         dir = os.path.join(self.fs.CachePath, subdir)
         return dir, os.path.join(dir, cache_sig)
 
-    def must_be_a_Dir(self):
-        """Called to make sure a Node is a Dir.  Since we're already a
-        File, this is a TypeError..."""
-        raise TypeError, "Tried to lookup File '%s' as a Dir." % self.path
-
 default_fs = None
 
 class FileFinder:

File src/engine/SCons/Node/FSTests.py

         x = e.get_executor()
         x.add_pre_action('pre')
         x.add_post_action('post')
-        e.must_be_a_Dir()
+        e.must_be_same(SCons.Node.FS.Dir)
         a = x.get_action_list()
         assert a[0] == 'pre', a
         assert a[2] == 'post', a

File src/engine/SCons/Optik/__init__.py

-"""optik
-
-A powerful, extensible, and easy-to-use command-line parser for Python.
-
-By Greg Ward <gward@python.net>
-
-See http://optik.sourceforge.net/
-"""
-
-# Copyright (c) 2001 Gregory P. Ward.  All rights reserved.
-# See the README.txt distributed with Optik for licensing terms.
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-
-# Original Optik revision this is based on:
-__Optik_revision__ = "__init__.py,v 1.11 2002/04/11 19:17:34 gward Exp"
-
-__version__ = "1.3"
-
-
-# Re-import these for convenience
-from SCons.Optik.option import Option
-from SCons.Optik.option_parser import \
-     OptionParser, SUPPRESS_HELP, SUPPRESS_USAGE
-from SCons.Optik.errors import OptionValueError
-
-
-# Some day, there might be many Option classes.  As of Optik 1.3, the
-# preferred way to instantiate Options is indirectly, via make_option(),
-# which will become a factory function when there are many Option
-# classes.
-make_option = Option

File src/engine/SCons/Optik/errors.py

-"""optik.errors
-
-Exception classes used by Optik.
-"""
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-
-# Original Optik revision this is based on:
-__Optik_revision__ = "errors.py,v 1.5 2002/02/13 23:29:47 gward Exp"
-
-# Copyright (c) 2001 Gregory P. Ward.  All rights reserved.
-# See the README.txt distributed with Optik for licensing terms.
-
-# created 2001/10/17 GPW (from optik.py)
-
-
-class OptikError (Exception):
-    def __init__ (self, msg):
-        self.msg = msg
-
-    def __str__ (self):
-        return self.msg
-
-
-class OptionError (OptikError):
-    """
-    Raised if an Option instance is created with invalid or
-    inconsistent arguments.
-    """
-
-    def __init__ (self, msg, option):
-        self.msg = msg
-        self.option_id = str(option)
-
-    def __str__ (self):
-        if self.option_id:
-            return "option %s: %s" % (self.option_id, self.msg)
-        else:
-            return self.msg
-
-class OptionConflictError (OptionError):
-    """
-    Raised if conflicting options are added to an OptionParser.
-    """
-
-class OptionValueError (OptikError):
-    """
-    Raised if an invalid option value is encountered on the command
-    line.
-    """
-
-class BadOptionError (OptikError):
-    """
-    Raised if an invalid or ambiguous option is seen on the command-line.
-    """

File src/engine/SCons/Optik/option.py

-"""optik.option
-
-Defines the Option class and some standard value-checking functions.
-"""
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-
-# Original Optik revision this is based on:
-__Optik_revision__ = "option.py,v 1.19.2.1 2002/07/23 01:51:14 gward Exp" 
-
-# Copyright (c) 2001 Gregory P. Ward.  All rights reserved.
-# See the README.txt distributed with Optik for licensing terms.
-
-# created 2001/10/17, GPW (from optik.py)
-
-import sys
-import string
-from types import TupleType, ListType, DictType
-from SCons.Optik.errors import OptionError, OptionValueError
-
-_builtin_cvt = { "int" : (int, "integer"),
-                 "long" : (long, "long integer"),
-                 "float" : (float, "floating-point"),
-                 "complex" : (complex, "complex") }
-
-def check_builtin (option, opt, value):
-    (cvt, what) = _builtin_cvt[option.type]
-    try:
-        return cvt(value)
-    except ValueError:
-        raise OptionValueError(
-            #"%s: invalid %s argument %s" % (opt, what, repr(value)))
-            "option %s: invalid %s value: %s" % (opt, what, repr(value)))
-
-def check_choice(option, opt, value):
-    if value in option.choices:
-        return value
-    else:
-        choices = string.join(map(repr, option.choices),", ")
-        raise OptionValueError(
-            "option %s: invalid choice: %s (choose from %s)"
-            % (opt, repr(value), choices))
-
-# Not supplying a default is different from a default of None,
-# so we need an explicit "not supplied" value.
-NO_DEFAULT = "NO"+"DEFAULT"
-
-
-class Option:
-    """
-    Instance attributes:
-      _short_opts : [string]
-      _long_opts : [string]
-
-      action : string
-      type : string
-      dest : string
-      default : any
-      nargs : int
-      const : any
-      choices : [string]
-      callback : function
-      callback_args : (any*)
-      callback_kwargs : { string : any }
-      help : string
-      metavar : string
-    """
-
-    # The list of instance attributes that may be set through
-    # keyword args to the constructor.
-    ATTRS = ['action',
-             'type',
-             'dest',
-             'default',
-             'nargs',
-             'const',
-             'choices',
-             'callback',
-             'callback_args',
-             'callback_kwargs',
-             'help',
-             'metavar']
-
-    # The set of actions allowed by option parsers.  Explicitly listed
-    # here so the constructor can validate its arguments.
-    ACTIONS = ("store",
-               "store_const",
-               "store_true",
-               "store_false",
-               "append",
-               "count",
-               "callback",
-               "help",
-               "version")
-
-    # The set of actions that involve storing a value somewhere;
-    # also listed just for constructor argument validation.  (If
-    # the action is one of these, there must be a destination.)
-    STORE_ACTIONS = ("store",
-                     "store_const",
-                     "store_true",
-                     "store_false",
-                     "append",
-                     "count")
-
-    # The set of actions for which it makes sense to supply a value
-    # type, ie. where we expect an argument to this option.
-    TYPED_ACTIONS = ("store",
-                     "append",
-                     "callback")
-
-    # The set of known types for option parsers.  Again, listed here for
-    # constructor argument validation.
-    TYPES = ("string", "int", "long", "float", "complex", "choice")
-
-    # Dictionary of argument checking functions, which convert and
-    # validate option arguments according to the option type.
-    # 
-    # Signature of checking functions is:
-    #   check(option : Option, opt : string, value : string) -> any
-    # where
-    #   option is the Option instance calling the checker
-    #   opt is the actual option seen on the command-line
-    #     (eg. "-a", "--file")
-    #   value is the option argument seen on the command-line
-    #
-    # The return value should be in the appropriate Python type
-    # for option.type -- eg. an integer if option.type == "int".
-    # 
-    # If no checker is defined for a type, arguments will be
-    # unchecked and remain strings.
-    TYPE_CHECKER = { "int"    : check_builtin,
-                     "long"   : check_builtin,
-                     "float"  : check_builtin,
-                     "complex"  : check_builtin,
-                     "choice" : check_choice,
-                   }
-
-
-    # CHECK_METHODS is a list of unbound method objects; they are called
-    # by the constructor, in order, after all attributes are
-    # initialized.  The list is created and filled in later, after all
-    # the methods are actually defined.  (I just put it here because I
-    # like to define and document all class attributes in the same
-    # place.)  Subclasses that add another _check_*() method should
-    # define their own CHECK_METHODS list that adds their check method
-    # to those from this class.
-    CHECK_METHODS = None
-                    
-
-    # -- Constructor/initialization methods ----------------------------
-
-    def __init__ (self, *opts, **attrs):
-        # Set _short_opts, _long_opts attrs from 'opts' tuple
-        opts = self._check_opt_strings(opts)
-        self._set_opt_strings(opts)
-
-        # Set all other attrs (action, type, etc.) from 'attrs' dict
-        self._set_attrs(attrs)
-
-        # Check all the attributes we just set.  There are lots of
-        # complicated interdependencies, but luckily they can be farmed
-        # out to the _check_*() methods listed in CHECK_METHODS -- which
-        # could be handy for subclasses!  The one thing these all share
-        # is that they raise OptionError if they discover a problem.
-        for checker in self.CHECK_METHODS:
-            checker(self)
-
-    def _check_opt_strings (self, opts):
-        # Filter out None because early versions of Optik had exactly
-        # one short option and one long option, either of which
-        # could be None.
-        opts = filter(None, opts)
-        if not opts:
-            raise OptionError("at least one option string must be supplied",
-                              self)
-        return opts
-
-    def _set_opt_strings (self, opts):
-        self._short_opts = []
-        self._long_opts = []
-        for opt in opts:
-            if len(opt) < 2:
-                raise OptionError(
-                    "invalid option string %s: "
-                    "must be at least two characters long" % (`opt`,), self)
-            elif len(opt) == 2:
-                if not (opt[0] == "-" and opt[1] != "-"):
-                    raise OptionError(
-                        "invalid short option string %s: "
-                        "must be of the form -x, (x any non-dash char)" % (`opt`,),
-                        self)
-                self._short_opts.append(opt)
-            else:
-                if not (opt[0:2] == "--" and opt[2] != "-"):
-                    raise OptionError(
-                        "invalid long option string %s: "
-                        "must start with --, followed by non-dash" % (`opt`,),
-                        self)
-                self._long_opts.append(opt)
-
-    def _set_attrs (self, attrs):
-        for attr in self.ATTRS:
-            if attrs.has_key(attr):
-                setattr(self, attr, attrs[attr])
-                del attrs[attr]
-            else:
-                if attr == 'default':
-                    setattr(self, attr, NO_DEFAULT)
-                else:
-                    setattr(self, attr, None)
-        if attrs:
-            raise OptionError(
-                "invalid keyword arguments: %s" % string.join(attrs.keys(),", "),
-                self)
-
-
-    # -- Constructor validation methods --------------------------------
-
-    def _check_action (self):
-        if self.action is None:
-            self.action = "store"
-        elif self.action not in self.ACTIONS:
-            raise OptionError("invalid action: %s" % (`self.action`,), self)
-
-    def _check_type (self):
-        if self.type is None:
-            # XXX should factor out another class attr here: list of
-            # actions that *require* a type
-            if self.action in ("store", "append"):
-                if self.choices is not None:
-                    # The "choices" attribute implies "choice" type.
-                    self.type = "choice"
-                else:
-                    # No type given?  "string" is the most sensible default.
-                    self.type = "string"
-        else:
-            if self.type not in self.TYPES:
-                raise OptionError("invalid option type: %s" % (`self.type`,), self)
-            if self.action not in self.TYPED_ACTIONS:
-                raise OptionError(
-                    "must not supply a type for action %s" % (`self.action`,), self)
-
-    def _check_choice(self):
-        if self.type == "choice":
-            if self.choices is None:
-                raise OptionError(
-                    "must supply a list of choices for type 'choice'", self)
-            elif type(self.choices) not in (TupleType, ListType):
-                raise OptionError(
-                    "choices must be a list of strings ('%s' supplied)"
-                    % string.split(str(type(self.choices)),"'")[1], self)
-        elif self.choices is not None:
-            raise OptionError(
-                "must not supply choices for type %s" % (repr(self.type),), self)
-
-    def _check_dest (self):
-        if self.action in self.STORE_ACTIONS and self.dest is None:
-            # No destination given, and we need one for this action.
-            # Glean a destination from the first long option string,
-            # or from the first short option string if no long options.
-            if self._long_opts:
-                # eg. "--foo-bar" -> "foo_bar"
-                self.dest = string.replace(self._long_opts[0][2:],'-', '_')
-            else:
-                self.dest = self._short_opts[0][1]
-
-    def _check_const (self):
-        if self.action != "store_const" and self.const is not None:
-            raise OptionError(
-                "'const' must not be supplied for action %s" % (repr(self.action),),
-                self)
-        
-    def _check_nargs (self):
-        if self.action in self.TYPED_ACTIONS:
-            if self.nargs is None:
-                self.nargs = 1
-        elif self.nargs is not None:
-            raise OptionError(
-                "'nargs' must not be supplied for action %s" % (repr(self.action),),
-                self)
-
-    def _check_callback (self):
-        if self.action == "callback":
-            if not callable(self.callback):
-                raise OptionError(
-                    "callback not callable: %s" % (repr(self.callback),), self)
-            if (self.callback_args is not None and
-                type(self.callback_args) is not TupleType):
-                raise OptionError(
-                    "callback_args, if supplied, must be a tuple: not %s"
-                    % (repr(self.callback_args),), self)
-            if (self.callback_kwargs is not None and
-                type(self.callback_kwargs) is not DictType):
-                raise OptionError(
-                    "callback_kwargs, if supplied, must be a dict: not %s"
-                    % (repr(self.callback_kwargs),), self)
-        else:
-            if self.callback is not None:
-                raise OptionError(
-                    "callback supplied (%s) for non-callback option"
-                    % (repr(self.callback),), self)
-            if self.callback_args is not None:
-                raise OptionError(
-                    "callback_args supplied for non-callback option", self)
-            if self.callback_kwargs is not None:
-                raise OptionError(
-                    "callback_kwargs supplied for non-callback option", self)
-
-
-    CHECK_METHODS = [_check_action,
-                     _check_type,
-                     _check_choice,
-                     _check_dest,
-                     _check_const,
-                     _check_nargs,
-                     _check_callback]
-        
-
-    # -- Miscellaneous methods -----------------------------------------
-
-    def __str__ (self):
-        if self._short_opts or self._long_opts:
-            return string.join(self._short_opts + self._long_opts,"/")
-        else:
-            raise RuntimeError, "short_opts and long_opts both empty!"
-
-    def takes_value (self):
-        return self.type is not None
-
-
-    # -- Processing methods --------------------------------------------
-
-    def check_value (self, opt, value):
-        checker = self.TYPE_CHECKER.get(self.type)
-        if checker is None:
-            return value
-        else:
-            return checker(self, opt, value)
-
-    def process (self, opt, value, values, parser):
-
-        # First, convert the value(s) to the right type.  Howl if any
-        # value(s) are bogus.
-        if value is not None:
-            if self.nargs == 1:
-                value = self.check_value(opt, value)
-            else:
-                def cv(v,check=self.check_value,o=opt):
-                    return check(o,v)
-
-                value = tuple(map(cv,value))
-
-        # And then take whatever action is expected of us.
-        # This is a separate method to make life easier for
-        # subclasses to add new actions.
-        return self.take_action(
-            self.action, self.dest, opt, value, values, parser)
-
-    def take_action (self, action, dest, opt, value, values, parser):
-        if action == "store":
-            setattr(values, dest, value)
-        elif action == "store_const":
-            setattr(values, dest, self.const)
-        elif action == "store_true":
-            setattr(values, dest, 1)
-        elif action == "store_false":
-            setattr(values, dest, 0)
-        elif action == "append":
-            values.ensure_value(dest, []).append(value)
-        elif action == "count":
-            setattr(values, dest, values.ensure_value(dest, 0) + 1)
-        elif action == "callback":
-            args = self.callback_args or ()
-            kwargs = self.callback_kwargs or {}
-            apply( self.callback, (self, opt, value, parser,)+ args, kwargs)
-        elif action == "help":
-            parser.print_help()
-            sys.exit(0)
-        elif action == "version":
-            parser.print_version()
-            sys.exit(0)
-        else:
-            raise RuntimeError, "unknown action %s" % (repr(self.action),)
-
-        return 1
-
-# class Option

File src/engine/SCons/Optik/option_parser.py

-"""optik.option_parser
-
-Provides the OptionParser and Values classes.
-"""
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-
-# Original Optik revision this is based on:
-__Optik_revision__ = "option_parser.py,v 1.38.2.1 2002/07/23 01:51:14 gward Exp"
-
-# Copyright (c) 2001 Gregory P. Ward.  All rights reserved.
-# See the README.txt distributed with Optik for licensing terms.
-
-# created 2001/10/17, GPW (from optik.py)
-
-import sys, os
-import string
-import types
-from SCons.Optik.option import Option, NO_DEFAULT
-from SCons.Optik.errors import OptionConflictError, OptionValueError, BadOptionError
-
-def get_prog_name ():
-    return os.path.basename(sys.argv[0])
-
-
-SUPPRESS_HELP = "SUPPRESS"+"HELP"
-SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
-
-class Values:
-
-    def __init__ (self, defaults=None):
-        if defaults:
-            for (attr, val) in defaults.items():
-                setattr(self, attr, val)
-
-
-    def _update_careful (self, dict):
-        """
-        Update the option values from an arbitrary dictionary, but only
-        use keys from dict that already have a corresponding attribute
-        in self.  Any keys in dict without a corresponding attribute
-        are silently ignored.
-        """
-        for attr in dir(self):
-            if dict.has_key(attr):
-                dval = dict[attr]
-                if dval is not None:
-                    setattr(self, attr, dval)
-
-    def _update_loose (self, dict):
-        """
-        Update the option values from an arbitrary dictionary,
-        using all keys from the dictionary regardless of whether
-        they have a corresponding attribute in self or not.
-        """
-        self.__dict__.update(dict)
-
-    def _update (self, dict, mode):
-        if mode == "careful":
-            self._update_careful(dict)
-        elif mode == "loose":
-            self._update_loose(dict)
-        else:
-            raise ValueError, "invalid update mode: %s" % (repr(mode),)
-
-    def read_module (self, modname, mode="careful"):
-        __import__(modname)
-        mod = sys.modules[modname]
-        self._update(vars(mod), mode)
-
-    def read_file (self, filename, mode="careful"):
-        vars = {}
-        execfile(filename, vars)
-        self._update(vars, mode)
-
-    def ensure_value (self, attr, value):
-        if not hasattr(self, attr) or getattr(self, attr) is None:
-            setattr(self, attr, value)
-        return getattr(self, attr)
-
-
-class OptionParser:
-    """
-    Class attributes:
-      standard_option_list : [Option]
-        list of standard options that will be accepted by all instances
-        of this parser class (intended to be overridden by subclasses).
-
-    Instance attributes:
-      usage : string
-        a usage string for your program.  Before it is displayed
-        to the user, "%prog" will be expanded to the name of
-        your program (os.path.basename(sys.argv[0])).
-      option_list : [Option]
-        the list of all options accepted on the command-line of
-        this program
-      _short_opt : { string : Option }
-        dictionary mapping short option strings, eg. "-f" or "-X",
-        to the Option instances that implement them.  If an Option
-        has multiple short option strings, it will appears in this
-        dictionary multiple times.
-      _long_opt : { string : Option }
-        dictionary mapping long option strings, eg. "--file" or
-        "--exclude", to the Option instances that implement them.
-        Again, a given Option can occur multiple times in this
-        dictionary.
-      defaults : { string : any }
-        dictionary mapping option destination names to default
-        values for each destination.
-
-      allow_interspersed_args : boolean = true
-        if true, positional arguments may be interspersed with options.
-        Assuming -a and -b each take a single argument, the command-line
-          -ablah foo bar -bboo baz
-        will be interpreted the same as
-          -ablah -bboo -- foo bar baz
-        If this flag were false, that command line would be interpreted as
-          -ablah -- foo bar -bboo baz
-        -- ie. we stop processing options as soon as we see the first
-        non-option argument.  (This is the tradition followed by
-        Python's getopt module, Perl's Getopt::Std, and other argument-
-        parsing libraries, but it is generally annoying to users.)
-
-      rargs : [string]
-        the argument list currently being parsed.  Only set when
-        parse_args() is active, and continually trimmed down as
-        we consume arguments.  Mainly there for the benefit of
-        callback options.
-      largs : [string]
-        the list of leftover arguments that we have skipped while
-        parsing options.  If allow_interspersed_args is false, this
-        list is always empty.
-      values : Values
-        the set of option values currently being accumulated.  Only
-        set when parse_args() is active.  Also mainly for callbacks.
-
-    Because of the 'rargs', 'largs', and 'values' attributes,
-    OptionParser is not thread-safe.  If, for some perverse reason, you
-    need to parse command-line arguments simultaneously in different
-    threads, use different OptionParser instances.
-    
-    """ 
-
-    standard_option_list = []
-
-
-    def __init__ (self,
-                  usage=None,
-                  option_list=None,
-                  option_class=Option,
-                  version=None,
-                  conflict_handler="error"):
-        self.set_usage(usage)
-        self.option_class = option_class
-        self.version = version
-        self.set_conflict_handler(conflict_handler)
-        self.allow_interspersed_args = 1
-
-        # Create the various lists and dicts that constitute the
-        # "option list".  See class docstring for details about
-        # each attribute.
-        self._create_option_list()
-
-        # Populate the option list; initial sources are the
-        # standard_option_list class attribute, the 'option_list'
-        # argument, and the STD_VERSION_OPTION global (if 'version'
-        # supplied).
-        self._populate_option_list(option_list)
-
-        self._init_parsing_state()
-
-    # -- Private methods -----------------------------------------------
-    # (used by the constructor)
-
-    def _create_option_list (self):
-        self.option_list = []
-        self._short_opt = {}            # single letter -> Option instance
-        self._long_opt = {}             # long option -> Option instance
-        self.defaults = {}              # maps option dest -> default value
-
-    def _populate_option_list (self, option_list):
-        if self.standard_option_list:
-            self.add_options(self.standard_option_list)
-        if option_list:
-            self.add_options(option_list)
-        
-    def _init_parsing_state (self):
-        # These are set in parse_args() for the convenience of callbacks.
-        self.rargs = None
-        self.largs = None
-        self.values = None
-
-
-    # -- Simple modifier methods ---------------------------------------
-
-    def set_usage (self, usage):
-        if usage is None:
-            self.usage = "usage: %prog [options]"
-        elif usage is SUPPRESS_USAGE:
-            self.usage = None
-        else:
-            self.usage = usage
-
-    def enable_interspersed_args (self):
-        self.allow_interspersed_args = 1
-
-    def disable_interspersed_args (self):
-        self.allow_interspersed_args = 0
-
-    def set_conflict_handler (self, handler):
-        if handler not in ("ignore", "error", "resolve"):
-            raise ValueError, "invalid conflict_resolution value %s" % (repr(handler),)
-        self.conflict_handler = handler
-
-    def set_default (self, dest, value):
-        self.defaults[dest] = value
-
-    def set_defaults (self, **kwargs):
-        self.defaults.update(kwargs)
-
-    def get_default_values(self):
-        return Values(self.defaults)
-
-
-    # -- Option-adding methods -----------------------------------------
-
-    def _check_conflict (self, option):
-        conflict_opts = []
-        for opt in option._short_opts:
-            if self._short_opt.has_key(opt):
-                conflict_opts.append((opt, self._short_opt[opt]))
-        for opt in option._long_opts:
-            if self._long_opt.has_key(opt):
-                conflict_opts.append((opt, self._long_opt[opt]))
-
-        if conflict_opts:
-            handler = self.conflict_handler
-            if handler == "ignore":     # behaviour for Optik 1.0, 1.1
-                pass
-            elif handler == "error":    # new in 1.2
-                raise OptionConflictError(
-                    "conflicting option string(s): %s"
-                    % string.join( map( lambda x: x[0], conflict_opts),", "),
-                    option)
-            elif handler == "resolve":  # new in 1.2
-                for (opt, c_option) in conflict_opts:
-                    if len(opt)>2 and opt[:2]=="--":
-                        c_option._long_opts.remove(opt)
-                        del self._long_opt[opt]
-                    else:
-                        c_option._short_opts.remove(opt)
-                        del self._short_opt[opt]
-                    if not (c_option._short_opts or c_option._long_opts):
-                        self.option_list.remove(c_option)
-
-
-    def add_option (self, *args, **kwargs):
-        """add_option(Option)
-           add_option(opt_str, ..., kwarg=val, ...)
-        """
-        if type(args[0]) is types.StringType:
-            option = apply(self.option_class,args, kwargs)
-        elif len(args) == 1 and not kwargs:
-            option = args[0]
-            if not isinstance(option, Option):
-                raise TypeError, "not an Option instance: %s" % (repr(option),)
-        else:
-            raise TypeError, "invalid arguments"
-
-        self._check_conflict(option)
-
-        self.option_list.append(option)
-        for opt in option._short_opts:
-            self._short_opt[opt] = option
-        for opt in option._long_opts:
-            self._long_opt[opt] = option
-
-        if option.dest is not None:     # option has a dest, we need a default
-            if option.default is not NO_DEFAULT:
-                self.defaults[option.dest] = option.default
-            elif not self.defaults.has_key(option.dest):
-                self.defaults[option.dest] = None
-
-    def add_options (self, option_list):
-        for option in option_list:
-            self.add_option(option)
-
-
-    # -- Option query/removal methods ----------------------------------
-
-    def get_option (self, opt_str):
-        return (self._short_opt.get(opt_str) or
-                self._long_opt.get(opt_str))
-
-    def has_option (self, opt_str):
-        return (self._short_opt.has_key(opt_str) or
-                self._long_opt.has_key(opt_str))
-
-
-    def remove_option (self, opt_str):
-        option = self._short_opt.get(opt_str)
-        if option is None:
-            option = self._long_opt.get(opt_str)
-        if option is None:
-            raise ValueError("no such option %s" % (repr(opt_str),))
-
-        for opt in option._short_opts:
-            del self._short_opt[opt]
-        for opt in option._long_opts:
-            del self._long_opt[opt]
-        self.option_list.remove(option)
-
-
-    # -- Option-parsing methods ----------------------------------------
-
-    def _get_args (self, args):
-        if args is None:
-            return sys.argv[1:]
-        else:
-            return args[:]              # don't modify caller's list
-
-    def parse_args (self, args=None, values=None):
-        """
-        parse_args(args : [string] = sys.argv[1:],
-                   values : Values = None)
-        -> (values : Values, args : [string])
-
-        Parse the command-line options found in 'args' (default:
-        sys.argv[1:]).  Any errors result in a call to 'error()', which
-        by default prints the usage message to stderr and calls
-        sys.exit() with an error message.  On success returns a pair
-        (values, args) where 'values' is an Values instance (with all
-        your option values) and 'args' is the list of arguments left
-        over after parsing options.
-        """
-        rargs = self._get_args(args)
-        if values is None:
-            values = self.get_default_values()
-
-        # Store the halves of the argument list as attributes for the
-        # convenience of callbacks:
-        #   rargs
-        #     the rest of the command-line (the "r" stands for
-        #     "remaining" or "right-hand")
-        #   largs
-        #     the leftover arguments -- ie. what's left after removing
-        #     options and their arguments (the "l" stands for "leftover"
-        #     or "left-hand")
-        self.rargs = rargs
-        self.largs = largs = []
-        self.values = values
-
-        try:
-            stop = self._process_args(largs, rargs, values)
-        except (BadOptionError, OptionValueError), err:
-            self.error(err.msg)
-
-        args = largs + rargs
-        return self.check_values(values, args)
-
-    def check_values (self, values, args):
-        """
-        check_values(values : Values, args : [string])
-        -> (values : Values, args : [string])
-
-        Check that the supplied option values and leftover arguments are
-        valid.  Returns the option values and leftover arguments
-        (possibly adjusted, possibly completely new -- whatever you
-        like).  Default implementation just returns the passed-in
-        values; subclasses may override as desired.
-        """
-        return (values, args)
-
-    def _process_args (self, largs, rargs, values):
-        """_process_args(largs : [string],
-                         rargs : [string],
-                         values : Values)
-
-        Process command-line arguments and populate 'values', consuming
-        options and arguments from 'rargs'.  If 'allow_interspersed_args' is
-        false, stop at the first non-option argument.  If true, accumulate any
-        interspersed non-option arguments in 'largs'.
-        """
-        while rargs:
-            arg = rargs[0]
-            # We handle bare "--" explicitly, and bare "-" is handled by the
-            # standard arg handler since the short arg case ensures that the
-            # len of the opt string is greater than 1.
-            if arg == "--":
-                del rargs[0]
-                return
-            elif arg[0:2] == "--":
-                # process a single long option (possibly with value(s))
-                self._process_long_opt(rargs, values)
-            elif arg[:1] == "-" and len(arg) > 1:
-                # process a cluster of short options (possibly with
-                # value(s) for the last one only)
-                self._process_short_opts(rargs, values)
-            elif self.allow_interspersed_args:
-                largs.append(arg)
-                del rargs[0]
-            else:
-                return                  # stop now, leave this arg in rargs
-
-        # Say this is the original argument list:
-        # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
-        #                            ^
-        # (we are about to process arg(i)).
-        #
-        # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
-        # [arg0, ..., arg(i-1)] (any options and their arguments will have
-        # been removed from largs).
-        #
-        # The while loop will usually consume 1 or more arguments per pass.
-        # If it consumes 1 (eg. arg is an option that takes no arguments),
-        # then after _process_arg() is done the situation is:
-        #
-        #   largs = subset of [arg0, ..., arg(i)]
-        #   rargs = [arg(i+1), ..., arg(N-1)]
-        #
-        # If allow_interspersed_args is false, largs will always be
-        # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
-        # not a very interesting subset!
-        
-    def _match_long_opt (self, opt):
-        """_match_long_opt(opt : string) -> string
-
-        Determine which long option string 'opt' matches, ie. which one
-        it is an unambiguous abbrevation for.  Raises BadOptionError if
-        'opt' doesn't unambiguously match any long option string.
-        """
-        return _match_abbrev(opt, self._long_opt)
-
-    def _process_long_opt (self, rargs, values):
-        arg = rargs.pop(0)
-
-        # Value explicitly attached to arg?  Pretend it's the next
-        # argument.
-        if "=" in arg:
-            (opt, next_arg) = string.split(arg,"=", 1)
-            rargs.insert(0, next_arg)
-            had_explicit_value = 1
-        else:
-            opt = arg
-            had_explicit_value = 0
-
-        opt = self._match_long_opt(opt)
-        option = self._long_opt[opt]
-        if option.takes_value():
-            nargs = option.nargs
-            if len(rargs) < nargs:
-                if nargs == 1:
-                    self.error("%s option requires a value" % opt)
-                else:
-                    self.error("%s option requires %d values"
-                               % (opt, nargs))
-            elif nargs == 1:
-                value = rargs.pop(0)
-            else:
-                value = tuple(rargs[0:nargs])
-                del rargs[0:nargs]
-
-        elif had_explicit_value:
-            self.error("%s option does not take a value" % opt)
-
-        else:
-            value = None
-
-        option.process(opt, value, values, self)
-
-    def _process_short_opts (self, rargs, values):
-        arg = rargs.pop(0)
-        stop = 0
-        i = 1
-        for ch in arg[1:]:
-            opt = "-" + ch
-            option = self._short_opt.get(opt)
-            i = i+1                      # we have consumed a character
-
-            if not option:
-                self.error("no such option: %s" % opt)
-            if option.takes_value():
-                # Any characters left in arg?  Pretend they're the
-                # next arg, and stop consuming characters of arg.
-                if i < len(arg):
-                    rargs.insert(0, arg[i:])
-                    stop = 1
-
-                nargs = option.nargs
-                if len(rargs) < nargs:
-                    if nargs == 1:
-                        self.error("%s option requires a value" % opt)
-                    else:
-                        self.error("%s option requires %s values"
-                                   % (opt, nargs))
-                elif nargs == 1:
-                    value = rargs.pop(0)
-                else:
-                    value = tuple(rargs[0:nargs])
-                    del rargs[0:nargs]
-
-            else:                       # option doesn't take a value
-                value = None
-
-            option.process(opt, value, values, self)
-
-            if stop:
-                break
-
-
-    # -- Output/error methods ------------------------------------------
-
-    def error (self, msg):
-        """error(msg : string)
-
-        Print a usage message incorporating 'msg' to stderr and exit.
-        If you override this in a subclass, it should not return -- it
-        should either exit or raise an exception.
-        """
-        self.print_usage(sys.stderr)
-        sys.stderr.write("\nSCons error: %s\n" % msg)
-        sys.exit(2)
-
-    def print_usage (self, file=None):
-        """print_usage(file : file = stdout)
-
-        Print the usage message for the current program (self.usage) to
-        'file' (default stdout).  Any occurence of the string "%prog" in
-        self.usage is replaced with the name of the current program
-        (basename of sys.argv[0]).  Does nothing if self.usage is empty
-        or not defined.
-        """
-        if file is None:
-            file = sys.stdout
-        if self.usage:
-            usage = string.replace(self.usage,"%prog", get_prog_name())
-            file.write(usage + "\n")
-
-    def print_version (self, file=None):
-        """print_version(file : file = stdout)
-
-        Print the version message for this program (self.version) to
-        'file' (default stdout).  As with print_usage(), any occurence
-        of "%prog" in self.version is replaced by the current program's
-        name.  Does nothing if self.version is empty or undefined.
-        """
-        if file is None:
-            file = sys.stdout
-        if self.version:
-            version = string.replace(self.version,"%prog", get_prog_name())
-            file.write(version+"\n")
-
-    def print_help (self, file=None):
-        """print_help(file : file = stdout)
-
-        Print an extended help message, listing all options and any
-        help text provided with them, to 'file' (default stdout).
-        """
-        # SCons:  don't import wrap_text from distutils, use the
-        # copy we've included below, so we can avoid being dependent
-        # on having the right version of distutils installed.
-        #from distutils.fancy_getopt import wrap_text
-        
-        if file is None:
-            file = sys.stdout
-
-        self.print_usage(file)
-
-        # The help for each option consists of two parts:
-        #   * the opt strings and metavars
-        #     eg. ("-x", or "-fFILENAME, --file=FILENAME")
-        #   * the user-supplied help string
-        #     eg. ("turn on expert mode", "read data from FILENAME")
-        #
-        # If possible, we write both of these on the same line:
-        #   -x      turn on expert mode
-        # 
-        # But if the opt string list is too long, we put the help
-        # string on a second line, indented to the same column it would
-        # start in if it fit on the first line.
-        #   -fFILENAME, --file=FILENAME
-        #           read data from FILENAME
-
-        file.write("Options:\n")
-        width = 78                      # assume 80 cols for now
-
-        option_help = []                # list of (string, string) tuples
-        lengths = []
-
-        for option in self.option_list:
-            takes_value = option.takes_value()
-            if takes_value:
-                metavar = option.metavar or string.upper(option.dest)
-
-            opts = []               # list of "-a" or "--foo=FILE" strings
-            if option.help is SUPPRESS_HELP:
-                continue
-
-            if takes_value:
-                for sopt in option._short_opts:
-                    opts.append(sopt + ' ' + metavar)
-                for lopt in option._long_opts:
-                    opts.append(lopt + "=" + metavar)
-            else:
-                for opt in option._short_opts + option._long_opts:
-                    opts.append(opt)
-
-            opts = string.join(opts,", ")
-            option_help.append((opts, option.help))
-            lengths.append(len(opts))