view makeitso/cli.py @ 60:da0d8c5c5157

what i really meant to do with variables
author Jeff Hammel <jhammel@mozilla.com>
date Thu, 06 Jan 2011 17:12:36 -0800
parents 93f2b2c7f838
children 57f9b0349192
line wrap: on
line source

"""
command line parser for MakeItSo
"""

from optparse import OptionParser

class MakeItSoCLI(object):
  """command line interface to a makeitso template"""
  
  def __init__(self, template_class):
    self.template_class = template_class

  def parser(self):
    """
    return a command line parser for the template
    """
    usage = '%prog [options] output [var1=value1] [var2=value2] [...]'
    description = getattr(self.template_class, 'description', None)
    parser = OptionParser(usage=usage, description=description)

    # add the variables as options
    for variable in self.template_class.vars:
      parser.add_option('--%s' % variable.name, dest=variable.name,
                        default=variable.default,
                        help=variable.description)

    # add CLI-specific options
    # should start with '_' to indicate reserved
    parser.add_option('--variables', dest='_print_variables', 
                      action='store_true', default=False,
                      help="display variables in the template")
    return parser

  def parse(self):
    parser = self.parser()
    options, args = parser.parse_args()

    # print the variables for the templates
    if options._print_variables:

        # find all variables
        template = self.template()
        variables = template.variables()

        # print them
        for variable in sorted(variables):
            print variable
        return

    # ensure output is given
    if len(args) != 1:
      parser.error("Please specify one output")

    # template variables
    variables = dict([(key, value)
                      for key, value in options.__dict__.items()
                      if not key.startswith('_')])
    
    # instantiate the template
    template = self.template_class(output=args[0], variables=variables)

    return template