import os
import pipes
import re
import string
import sys
import yaml
from rock.config import Config
from rock.exceptions import ConfigError
from rock.utils import Shell

NAME_RE = re.compile('^[a-zA-Z0-9_]+$')


class Project(object):

    def __init__(self, *args, **kwargs):
        self.config = Config(*args, **kwargs)

    def run(self, section, argv):
        argv, args, opts = argv or [], [], {}
        script = self.config.get(section, '')

        def check():
            if section not in self.config:
                raise ConfigError('section not found: %s' % section)

        if section == 'run':
            if not argv:
                check()
            else:
                script = ' '.join(argv)
        else:
            check()

        with Shell() as shell:
            # declare builtin functions
            shell.write('warn() { echo "$@" >&2; }')
            shell.write('die() { warn "$@"; exit 1; }')
            # print commands as they're run
            if self.config.get('verbose'):
                shell.write('set -o verbose')
            # don't execute commands, just print them
            if self.config.get('dry_run'):
                shell.write('set -o noexec')
            # exit with error if any one command fails
            shell.write('set -o errexit')
            # switch to project directory
            if section != 'run' or len(argv) == 0:
                shell.write('cd ' + pipes.quote(self.config['path']))
            # setup environment variables
            if self.config.get('env'):
                # blank line before exports
                shell.write('')
                for name, value in self.config['env'].items():
                    shell.write('export %s="%s"' % (name, value))
            # blank line before command
            shell.write('')
            # handle arguments
            if section != 'run':
                # raw arguments
                shell.write("export ROCK_ARGV='%s'" %
                            ' '.join(map(pipes.quote, argv)))
                # parse arguments
                skip_next = False
                for i, arg in enumerate(argv):
                    if skip_next:
                        skip_next = False
                        continue
                    if arg.startswith('--'):
                        name, value = arg[2:], '1'
                        if '=' in name:
                            name, value = name.split('=', 1)
                        elif (i + 1 < len(argv) and not argv[i+1].startswith('--')):
                            value = argv[i+1]
                            skip_next = True
                        name = name.upper().replace('-', '_')
                        if NAME_RE.match(name):
                            opts[name] = value
                    else:
                        args.append(arg)
                # parsed arguments
                shell.write("export ROCK_ARGS='%s'" %
                            ' '.join(map(pipes.quote, args)))
                # set zero argument to command
                args.insert(0, section)
                # positional arguments
                for i, arg in enumerate(args):
                    shell.write("export ROCK_ARG%s='%s'" %
                                (i, pipes.quote(arg)))
                # parsed argument options
                for name, value in opts.items():
                    shell.write('export ROCK_ARGS_%s="%s"' %
                                (name, pipes.quote(value)))
                # parsed options
                shell.write("export ROCK_OPTS='%s'" %
                            ' '.join(map(pipes.quote, opts.keys())))
                shell.write('')
                shell.write("export ROCK_CWD='%s'" % os.getcwd())
                shell.write('')
            # execute script
            shell.write(script)

@@ -2069,42 +2069,8 @@
 nts%0A
-                skip_next = False%0A
     
@@ -2116,117 +2116,8 @@
 v):%0A
-                    if skip_next:%0A                        skip_next = False%0A                        continue%0A
     
@@ -2205,17 +2205,20 @@
 g%5B2:%5D, '
-1
+true
 '%0A      
@@ -2316,184 +2316,8 @@
  1)%0A
-                        elif (i + 1 %3C len(argv) and not argv%5Bi+1%5D.startswith('--')):%0A                            value = argv%5Bi+1%5D%0A                            skip_next = True%0A
     

Options with = are now always true or empty string