#!/usr/bin/python

import logging
import optparse
import subprocess
import sys

import blueprint.cli
from blueprint import git

parser = optparse.OptionParser('Usage: %prog [-q] <name> [<dirname>][...]')
parser.add_option('-q', '--quiet',
                  dest='quiet',
                  default=False,
                  action='store_true',
                  help='operate quietly')
options, args = parser.parse_args()

if options.quiet:
    logging.root.setLevel(logging.CRITICAL)

if 1 > len(args):
    parser.print_usage()
    sys.exit(1)

b = blueprint.cli.read(options, args)

try:
    commit = git.rev_parse(args[0])
    tree = git.tree(commit)
    def source(dirname, filename, gen_content, url):
        if args[1:] and dirname not in args[1:]:
            return
        if url is not None:
            sys.stderr.write('{0} {1}\n'.format(dirname, url))
        elif gen_content is not None:
            sys.stderr.write('{0} {1}\n'.format(dirname, filename))
            blob = git.blob(tree, filename)
            p = subprocess.Popen(['tar', 'tv'],
                                 close_fds=True,
                                 stdin=git.cat_file(blob))
            p.communicate()
    b.walk(source=source)
except IOError:
    pass
