3 simple templating system for mavlink generator 5 Copyright Andrew Tridgell 2011 6 Released under GNU GPL version 3 or later 9 from builtins
import object
11 from .mavparse
import MAVParseError
14 '''simple templating system''' 18 start_rep_token=
"${{",
29 def find_end(self, text, start_token, end_token, ignore_end_token=None):
30 '''find the of a token. 31 Returns the offset in the string immediately after the matching end_token''' 32 if not text.startswith(start_token):
33 raise MAVParseError(
"invalid token start")
34 offset = len(start_token)
37 idx1 = text[offset:].find(start_token)
38 idx2 = text[offset:].find(end_token)
42 combined_token = ignore_end_token + end_token
43 if text[offset+idx2:offset+idx2+len(combined_token)] == combined_token:
44 idx2 += len(ignore_end_token)
45 if idx1 == -1
and idx2 == -1:
46 raise MAVParseError(
"token nesting error")
47 if idx1 == -1
or idx1 > idx2:
48 offset += idx2 + len(end_token)
51 offset += idx1 + len(start_token)
56 '''find the of a variable''' 60 '''find the of a repitition''' 64 trim_leading_lf=
None, checkmissing=
None):
65 '''substitute variables in a string''' 67 if trim_leading_lf
is None:
69 if checkmissing
is None:
79 raise MAVParseError(
"missing end macro in %s" % text[subidx:])
80 part1 = text[0:subidx]
82 part3 = text[subidx+endidx:]
85 rest =
':'.join(a[1:])
87 if isinstance(subvars, dict):
88 v = subvars.get(field_name,
None)
90 v = getattr(subvars, field_name,
None)
92 raise MAVParseError(
'unable to find field %s' % field_name)
95 t1 += self.
substitute(rest, f, trim_leading_lf=
False, checkmissing=
False)
96 if len(v) != 0
and t1[-1]
in [
"\n",
","]:
110 raise MAVParseError(
'missing end of variable: %s' % text[idx:idx+10])
111 varname = text[idx+2:idx+endidx]
112 if isinstance(subvars, dict):
113 if not varname
in subvars:
115 raise MAVParseError(
"unknown variable in '%s%s%s'" % (
117 return text[0:idx+endidx] + self.
substitute(text[idx+endidx:], subvars,
118 trim_leading_lf=
False, checkmissing=
False)
119 value = subvars[varname]
121 value = getattr(subvars, varname,
None)
124 raise MAVParseError(
"unknown variable in '%s%s%s'" % (
126 return text[0:idx+endidx] + self.
substitute(text[idx+endidx:], subvars,
127 trim_leading_lf=
False, checkmissing=
False)
131 def write(self, file, text, subvars={}, trim_leading_lf=True):
132 '''write to a file with variable substitution''' 133 file.write(self.
substitute(text, subvars=subvars, trim_leading_lf=trim_leading_lf))
def __init__(self, start_var_token="${", end_var_token="}", start_rep_token="${{", end_rep_token="}}", trim_leading_lf=True, checkmissing=True)
def write(self, file, text, subvars={}, trim_leading_lf=True)
def find_end(self, text, start_token, end_token, ignore_end_token=None)
def find_var_end(self, text)
def find_rep_end(self, text)
def substitute(self, text, subvars={}, trim_leading_lf=None, checkmissing=None)