from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>


class Parser(object):
    def __init__(self, initial, contexts=()):
        # TODO: what should contexts be? name-based dict?
        self.initial = initial
        self.contexts = contexts

    def parse_argv(self, argv):
        # Assumes any program name has already been stripped out.
        context = self.initial
        context_index = 0
        flag_index = 0
        for index, arg in enumerate(argv):
            if context.has_arg(arg):
                flag_index = index
            # Otherwise, it's either a flag arg or a task name.
            else:
                flag = argv[flag_index]
                # If previous flag takes an arg, this is the arg
                if context.needs_value(flag):
                    context.set_value(flag, arg)
                # If not, it's the first task name
                else:
                    context = self.contexts[arg]
                    context_index = index
        return self.contexts

@@ -98,16 +98,41 @@
 ser.%3Cx%3E%0A
+from ..util import debug%0A
 %0A%0Aclass 
@@ -506,42 +506,207 @@
     
-for index, arg in enumerate(argv):
+debug(%22Parsing argv %25r%22 %25 (argv,))%0A        debug(%22Starting with context %25s%22 %25 context)%0A        for index, arg in enumerate(argv):%0A            debug(%22Testing string arg %25r at index %25r%22 %25 (arg, index))
 %0A   
@@ -766,32 +766,92 @@
 g_index = index%0A
+                debug(%22Current context has this as a flag%22)%0A
             # Ot
@@ -956,16 +956,86 @@
 _index%5D%0A
+                debug(%22Current context does not have this as a flag%22)%0A
         
@@ -1342,32 +1342,94 @@
 t_index = index%0A
+                    debug(%22That pevious flag needs no value%22)%0A
         return s

Make debug logging even more convenient.