view makeitso/cli.py @ 90:26b9c3bba04e

make the api for substitute() variables, output
author Jeff Hammel <jhammel@mozilla.com>
date Mon, 10 Jan 2011 21:33:03 -0800
parents cb6c54b1adf3
children e74baa8e6df4
line wrap: on
line source

"""
command line parser for MakeItSo
"""

from template import Undefined
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'
    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:
      description = variable.description
      if (variable.default is not None) and (variable.default is not Undefined) and description is not None:
        description += ' [DEFAULT: %s]' % variable.default
      parser.add_option('--%s' % variable.name, dest=variable.name,
                        default=variable.default,
                        help=description)
    return parser

  def parse(self, parser=None, options=None, args=None):

    # parse the command line
    if not parser or not options or not args:
      parser = self.parser()
      options, args = parser.parse_args()

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

    # 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