Mercurial > hg > MakeItSo
comparison makeitso/cli.py @ 58:112bf081148c
make a full CLI class for a single API template
| author | Jeff Hammel <jhammel@mozilla.com> |
|---|---|
| date | Thu, 06 Jan 2011 15:54:55 -0800 |
| parents | 074a32920f7c |
| children | 93f2b2c7f838 |
comparison
equal
deleted
inserted
replaced
| 57:074a32920f7c | 58:112bf081148c |
|---|---|
| 2 command line parser for MakeItSo | 2 command line parser for MakeItSo |
| 3 """ | 3 """ |
| 4 | 4 |
| 5 from optparse import OptionParser | 5 from optparse import OptionParser |
| 6 | 6 |
| 7 def parser(template): | 7 class MakeItSoCLI(object): |
| 8 """ | 8 """command line interface to a makeitso template""" |
| 9 return a command line parser for the template | 9 |
| 10 """ | 10 def __init__(self, template_class): |
| 11 usage = '%prog [options]' | 11 self.template_class = template_class |
| 12 description = getattr(template, 'description', None) | |
| 13 parser = OptionParser(usage=usage, description=description) | |
| 14 return parser | |
| 15 | 12 |
| 13 def parser(self): | |
| 14 """ | |
| 15 return a command line parser for the template | |
| 16 """ | |
| 17 usage = '%prog [options] output [var1=value1] [var2=value2] [...]' | |
| 18 description = getattr(template, 'description', None) | |
| 19 parser = OptionParser(usage=usage, description=description) | |
| 20 parser.add_options('--variables', dest='variables', | |
| 21 action='store_true', default=False, | |
| 22 help="display variables in the template") | |
| 23 return parser | |
| 24 | |
| 25 def parse(self): | |
| 26 parser = self.parser() | |
| 27 options, args = parser.parse_args() | |
| 28 | |
| 29 # print the variables for the templates | |
| 30 if options.variables: | |
| 31 | |
| 32 # makes no sense without a template | |
| 33 if not args: | |
| 34 parser.print_usage() | |
| 35 parser.exit() | |
| 36 | |
| 37 # find all variables | |
| 38 template = self.template() | |
| 39 variables = template.variables() | |
| 40 | |
| 41 # print them | |
| 42 for variable in sorted(variables): | |
| 43 print variable | |
| 44 return | |
| 45 | |
| 46 # template variables | |
| 47 variables = {} | |
| 48 output = [] | |
| 49 for arg in args: | |
| 50 if '=' in arg: | |
| 51 key, value = arg.split('=') | |
| 52 variables[key] = value | |
| 53 else: | |
| 54 output.append(arg) | |
| 55 if len(output) != 1: | |
| 56 parser.error("Please specify one output") | |
| 57 | |
| 58 template = self.template_class(output=output[0], variables=variables) | |
| 59 | |
| 60 return template |
