"""SCons integration for nestly."""
from collections import OrderedDict
import os

def name_targets(func):
    """
    Wrap a function such that returning ``'a', 'b', 'c', [1, 2, 3]`` transforms
    the value into ``dict(a=1, b=2, c=3)``.

    This is useful in the case where the last parameter is an SCons command.
    """
    def wrap(*a, **kw):
        ret = func(*a, **kw)
        return dict(zip(ret[:-1], ret[-1]))
    return wrap

class SConsWrap(object):
    """A Nest wrapper to add SCons integration.

    This class wraps a Nest in order to provide methods which are useful for
    using nestly with SCons.

    A Nest passed to SConsWrap must have been created with include_outdir=True,
    which is the default.
    """

    def __init__(self, nest, dest_dir='.'):
        """Initialize an SConsWrap.

        Takes the Nest to operate on and the base directory for all output
        directories.
        """
        self.nest = nest
        self.dest_dir = dest_dir
        self.aggregates = OrderedDict()

    def __iter__(self):
        "Iterate over the current controls."
        return self.nest.iter(self.dest_dir)

    def add(self, *a, **kw):
        "Call .add on the wrapped Nest."
        return self.nest.add(*a, **kw)

    def add_nest(self, name=None, **kw):
        "A simple decorator which wraps nest.add."
        def deco(func):
            self.nest.add(name or func.__name__, func, **kw)
            return func
        return deco

    def add_target(self, name=None):
        """Add an SCons target to this nest.

        The function decorated will be immediately called with each of the
        output directories and current control dictionaries. Each result will
        be added to the respective control dictionary for later nests to
        access.
        """
        def deco(func):
            def nestfunc(control):
                destdir = os.path.join(self.dest_dir, control['OUTDIR'])
                return [func(destdir, control)]
            self.nest.add(name or func.__name__, nestfunc, create_dir=False)
            return func
        return deco

    def add_aggregate(self, data_fac, name=None):
        """Add an aggregate target to this nest.

        The first argument is a nullary factory function which will be called
        immediately for each of the current control dictionaries and stored in
        each dictionary with the given name like in ``add_target``. After
        ``finalize_aggregate`` or ``finalize_all_aggregates`` are called, the
        decorated function will then be called in the same way as
        ``add_target``, except with an additional argument: the value which was
        returned by the factory function.

        Since nests added after the aggregate can access the factory function's
        value, it can be mutated to provide additional values for use when the
        decorated function is called.
        """
        def deco(func):
            agg_name = name or func.__name__
            finalizers = self.aggregates[agg_name] = []
            @self.add_target(agg_name)
            def wrap(outdir, c):
                data = data_fac()
                def finalize():
                    return func(outdir, c, data)
                finalizers.append(finalize)
                return data
            return wrap
        return deco

    def finalize_aggregate(self, aggregate):
        """Call the finalizers for one particular aggregate.

        Finalizing an aggregate this way means that it will not be finalized by
        any future calls to ``finalize_all_aggregates``.
        """
        for finalizer in self.aggregates.pop(aggregate):
            finalizer()

    def finalize_all_aggregates(self):
        """Call the finalizers for all defined aggregates.

        If any aggregates have been specifically finalized by
        ``finalize_aggregate``, they will not be finalized again. This function
        itself calls ``finalize_aggregate``; if ``finalize_all_aggregates`` is
        called twice, aggregates will not be finalized twice.

        Aggregates will be finalized in the same order in which they were
        defined.
        """
        for aggregate in list(self.aggregates):
            self.finalize_aggregate(aggregate)

@@ -72,18 +72,77 @@
 %0Aimport 
-os
+logging%0Aimport os%0A%0Alogger = logging.getLogger('nestly.scons')
 %0A%0Adef na
@@ -491,16 +491,17 @@
 n wrap%0A%0A
+%0A
 class SC
@@ -2133,32 +2133,32 @@
     return func%0A
-
         return d
@@ -2154,32 +2154,1332 @@
    return deco%0A%0A
+    def add_target_with_env(self, environment, name=None):%0A        %22%22%22Add an SCons target to this nest, with an SCons Environment%0A%0A        The function decorated will be immediately called with three arguments:%0A%0A        * %60%60environment%60%60: A clone of the SCons environment, with variables%0A          populated for all values in the control dictionary, plus a variable%0A          %60%60OUTDIR%60%60.%0A        * %60%60outdir%60%60: The output directory%0A        * %60%60control%60%60: The control dictionary%0A%0A        Each result will be added to the respective control dictionary for%0A        later nests to access.%0A%0A        Differs from :meth:%60SConsWrap.add_target%60 only by the addition of the%0A        %60%60Environment%60%60 clone.%0A        %22%22%22%0A        def deco(func):%0A            def nestfunc(control):%0A                env = environment.Clone()%0A                for k, v in control.iteritems():%0A                    if k in env:%0A                        logger.warn(%22Overwriting previously bound value %25s=%25s%22, k, env%5Bk%5D)%0A                    env%5Bk%5D = v%0A                destdir = os.path.join(self.dest_dir, control%5B'OUTDIR'%5D)%0A                env%5B'OUTDIR'%5D = destdir%0A                return %5Bfunc(env, destdir, control)%5D%0A            self.nest.add(name or func.__name__, nestfunc, create_dir=False)%0A            return func%0A        return deco%0A%0A%0A
     def add_aggr

Add SConsWrap.add_target_with_env