changeset 3:8931be6d2c8a

stub for getting missing variables
author Jeff Hammel <jhammel@mozilla.com>
date Thu, 04 Nov 2010 19:12:56 -0700
parents 825922315ce6
children 08a50935e941
files makeitso/main.py
diffstat 1 files changed, 33 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/makeitso/main.py	Thu Nov 04 18:58:11 2010 -0700
+++ b/makeitso/main.py	Thu Nov 04 19:12:56 2010 -0700
@@ -19,19 +19,50 @@
             cmdstr = ' '.join(command)
         raise SystemExit("Command `%s` exited with code %d" % (cmdstr, code))
 
+def get_missing(name_error):
+    """
+    This is a horrible hack because python doesn't do the proper thing
+    via eval and return the name of the variable;  instead, it just gives
+    you a message:
+    >>> try:
+    ...   eval('2*foo')
+    ... except Exception, e:
+    ...   pass
+    """
+    message = name_error.args[0]
+    varname = message.split("'")[1]
+    return varname
+
+def missing_variables(template, variables):
+    """return additional variables needed"""
+    vars = variables.copy()
+    missing = set([])
+    while True:
+        try:
+            template.substitute(**missing)
+            return missing
+        except NameError, e:
+            missed = get_missing(e)
+            missing.add(missed)
+            vars[missed] = ''
+
 def template_variables(template):
     """return the variables needed for a template"""
-    raise NotImplementedError
+    return missing_variables(template, {})
 
 def main(args=sys.argv[1:]):
 
     # create option parser
     usage = '%prog [options]'
     parser = OptionParser(usage, description=__doc__)
-    parser.add_option('--variables', dest='variables',
+    parser.add_option('--variables', dest='variables', action='store_true',
                       help='print the variables in a template')
     options, args = parser.parse_args(args)
 
+    if options.variables:
+        variables = template_variables() # TODO: pass template
+        return
+
     # template variables
     variables = {}
     _vars = []
@@ -55,6 +86,5 @@
         template = Template(content)
         print template.substitute(**variables)
         
-
 if __name__ == '__main__':
     main()