From 89335098e4e0f16d4dfb6ea4d0f38a3f9fa5b260 Mon Sep 17 00:00:00 2001 From: Kristian Rumberg Date: Fri, 8 Aug 2008 21:15:12 +0200 Subject: [PATCH] improved OptionalSetting --- pyvconv.py | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 9 deletions(-) diff --git a/pyvconv.py b/pyvconv.py index b4078a4..ed8891a 100644 --- a/pyvconv.py +++ b/pyvconv.py @@ -2,15 +2,37 @@ import libxml2 import re class Variable: - def __init__(self, name, default, expr): - self.name = name - self.default = default - self.expr = expr + def __init__(self, namestr, defaultstr, exprstr): + self.namestr = namestr + self.defaultstr = defaultstr + self.exprstr = exprstr + + def __str__(self): + return self.namestr + + def has_value(self): + return self.defaultstr != None + + def evaluate(self): + return self.exprstr class OptionalSetting: - def __init__(self, name, expr): - self.name = name - self.expr = expr + def __init__(self, namestr, exprstr): + self.namestr = namestr + self.exprstr = exprstr + + def get_name(self): + return self.namestr + + def evaluate(self, var_list): + instr = self.exprstr + for var in var_list: + if var_list[var].has_value(): + p = re.compile( '\$\{' + var + '\}') + instr = p.sub( var_list[var].get_value(), instr) + if instr.find("$") != -1: + instr = "" # if not all variables were found, return empty option + return instr class RenderCommand: def __init__(self, namestr, callstr, var_list, optset_list): @@ -19,6 +41,26 @@ class RenderCommand: self.var_list = var_list self.optset_list = optset_list + def get_name(self): + return self.namestr + + def evaluate(self): + instr = self.callstr + + p = re.compile("\$\[(\w+)\]") + for o in p.findall(instr): + if o not in self.optset_list: + raise "Error: Optional variable not defined" + instr = p.sub(self.optset_list[o].evaluate(self.var_list), instr) + + p = re.compile("\$\{(\w+)\}") + for o in p.findall(instr): + instr = p.sub(self.var_list[o].evaluate(), instr) + + if instr.find("$") != -1: + raise "Error: all variables were not expanded" + return instr + class RenderCommands: def __init__(self): self.cmdcall_dict = {} @@ -62,11 +104,11 @@ class RenderCommands: defprop = None if "default" in props: defprop = props["default"] - var_list = Variable(props["name"], defprop, props["expr"]) + var_list[props["name"]] = Variable(props["name"], defprop, props["expr"]) elif varsetnode.type == "element" and varsetnode.name == "optionalsetting": props = self._read_properties(varsetnode.properties, ["name", "expr"]) - optset_list = OptionalSetting(props["name"], props["expr"]) + optset_list[props["name"]] = OptionalSetting(props["name"], props["expr"]) elif varsetnode.name != "text": raise "Error parsing XML: only variable and optionalsetting elements allowed in command" -- 2.11.4.GIT