Command: Variable replacement with errors or default in case of missing value

This commit is contained in:
Bela 2018-03-14 18:27:46 +01:00
parent e36784f424
commit 6f49b25ded

View file

@ -5,7 +5,7 @@ is automagically created. Both can be modelled by commands.
"""
from formfield import FormField
import formfield as ff
from readformdata import (SUBINFO_SEP, VARIABLE_BEGIN_SEP, VARIABLE_END_SEP,
VARIABLE_PARTS_SEP, ConfigError)
@ -112,40 +112,63 @@ class Command():
# one or the other has no priority
return "Priority" in self
def interpret(self, value):
def interpret(self, value, default=None):
"""Interpret variables in values.
Replace occurences of {FieldName} by the value saved in
field FieldName.
Replace occurences of {form|FieldName} by the value saved
in field FieldName in the data self.data[form].
Replace occurences of {REF|FieldName} by the value saved
in field FieldName in the data self.data[REF].
If nothing is saved replace with default.
Variables are replaced as long as there are any.
Hence if there are variables in the new strings they get replaced
as well. Hope no one uses this for recursion. ^^^
Attributes:
value (str): the string in which variables are replaced.
default (str): if some Field has no value saved, use default.
If default is None (default for this attribute),
raise a ConfigError.
Raises:
ConfigError:
if some FieldName does not exist or has no value and default
is None.
"""
while True:
start = value.find(VARIABLE_BEGIN_SEP)
end = value.find(VARIABLE_END_SEP, start)
if start == -1 or end == -1: # not found
break
return value
sep = value.find(VARIABLE_PARTS_SEP, start)
replaced = value[start:end + len(VARIABLE_END_SEP)]
# {FieldName}
if sep == -1:
# {FieldName}
value = value.replace(value[start:end + len(VARIABLE_END_SEP)],
FormField.findByFieldName(
self.fieldList,
value[start +
len(VARIABLE_BEGIN_SEP):
end])["Value"])
fieldList = self.fieldList
fieldname = value[start + len(VARIABLE_BEGIN_SEP):end]
else:
# {form|FieldName}
value = value.replace(
value[start:end + len(VARIABLE_END_SEP)],
FormField.findByFieldName(
self.data[value[start:sep]],
value[sep + len(VARIABLE_PARTS_SEP):end])["Value"])
fieldList = self.data[value[
start + len(VARIABLE_BEGIN_SEP):sep]]
fieldname = value[sep + len(VARIABLE_PARTS_SEP):end]
try:
field = ff.FormField.findByFieldName(fieldList, fieldname)
except KeyError as e:
raise ConfigError("Variable cannot be replaced due to " +
"missing FormField: " + fieldname
+ " (" + str(e) + ")")
else:
try:
value = value.replace(replaced, field["Value"])
except KeyError as e:
if default is None:
raise ConfigError("Variable cannot be replaced" +
" due to missing value: "
+ fieldname + " (" + str(e) + ")")
else:
value = value.replace(replaced, default)
def __call__(self):
"""Run the command.