comparison 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
comparison
equal deleted inserted replaced
59:93f2b2c7f838 60:da0d8c5c5157
13 def parser(self): 13 def parser(self):
14 """ 14 """
15 return a command line parser for the template 15 return a command line parser for the template
16 """ 16 """
17 usage = '%prog [options] output [var1=value1] [var2=value2] [...]' 17 usage = '%prog [options] output [var1=value1] [var2=value2] [...]'
18 description = getattr(template, 'description', None) 18 description = getattr(self.template_class, 'description', None)
19 parser = OptionParser(usage=usage, description=description) 19 parser = OptionParser(usage=usage, description=description)
20 parser.add_options('--variables', dest='variables', 20
21 action='store_true', default=False, 21 # add the variables as options
22 help="display variables in the template") 22 for variable in self.template_class.vars:
23 parser.add_option('--%s' % variable.name, dest=variable.name,
24 default=variable.default,
25 help=variable.description)
26
27 # add CLI-specific options
28 # should start with '_' to indicate reserved
29 parser.add_option('--variables', dest='_print_variables',
30 action='store_true', default=False,
31 help="display variables in the template")
23 return parser 32 return parser
24 33
25 def parse(self): 34 def parse(self):
26 parser = self.parser() 35 parser = self.parser()
27 options, args = parser.parse_args() 36 options, args = parser.parse_args()
28 37
29 # print the variables for the templates 38 # print the variables for the templates
30 if options.variables: 39 if options._print_variables:
31
32 # makes no sense without a template
33 if not args:
34 parser.print_usage()
35 parser.exit()
36 40
37 # find all variables 41 # find all variables
38 template = self.template() 42 template = self.template()
39 variables = template.variables() 43 variables = template.variables()
40 44
41 # print them 45 # print them
42 for variable in sorted(variables): 46 for variable in sorted(variables):
43 print variable 47 print variable
44 return 48 return
45 49
50 # ensure output is given
51 if len(args) != 1:
52 parser.error("Please specify one output")
53
46 # template variables 54 # template variables
47 variables = {} 55 variables = dict([(key, value)
48 output = [] 56 for key, value in options.__dict__.items()
49 for arg in args: 57 if not key.startswith('_')])
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
58 # instantiate the template 59 # instantiate the template
59 template = self.template_class(output=output[0], variables=variables) 60 template = self.template_class(output=args[0], variables=variables)
60 61
61 return template 62 return template