#!/usr/bin/env python
"""
Parse a test Python file and create a bigbuts script with the tests found in it.
"""

import re
from StringIO import StringIO
from subprocess import Popen, PIPE


def parse_args(parser, args, *names):
    class Args(object): pass
    if len(args) < len(names):
        parser.error("Required arguments: %s" % ','.join(names))
    for n, arg in zip(names, args):
        setattr(Args, n, arg)
    return Args


_cmd_collect = 'py.test --collectonly %(fn)s'
_cmd_run = 'py.test -s -k %(test)s %(fn)s'

def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())
    opts, args = parser.parse_args()

    rex = re.compile("<Function '(test_([a-zA-Z0-9_]+))'>")
    tests = []
    for fn in (x for x in args if x.endswith('.py')):
        print fn
        p = Popen(_cmd_collect % locals(), stdout=PIPE, stderr=PIPE, shell=True)
        out, _ = p.communicate()
        tests.extend((fn,) + mo.groups() for mo in rex.finditer(out, re.M))
    
    s = StringIO()
    print >> s, '#!/usr/bin/env python'
    for fn, test, label in sorted(tests):
        print >> s, '%s: %s' % (label, _cmd_run % locals())

    p = Popen('bigbuts', stdin=PIPE)
    p.stdin.write(s.getvalue())
    p.stdin.close()
    p.wait()

if __name__ == '__main__':
    main()
