21 """Loads template files from a path."""
23 def __init__(self, root, subpaths, conditions={}):
24 """Initializes loader.
27 root - a string, the directory under which the templates are stored.
28 subpaths - a list of strings, subpaths of root in search order.
29 conditions - a dictionary
from strings to booleans. Any conditional
30 expression must be a key
in the map.
37 def TryLoad(self, name, more_conditions={}):
38 """Returns content of template file as a string, or None of not found."""
39 conditions = dict(self.
_conditions, **more_conditions)
40 cache_key = (name, tuple(sorted(conditions.items())))
41 if cache_key
in self.
_cache:
42 return self.
_cache[cache_key]
45 template_file = os.path.join(self.
_root, subpath, name)
46 if os.path.exists(template_file):
48 template = self.
_Preprocess(template, template_file, conditions)
49 self.
_cache[cache_key] = template
54 def Load(self, name, more_conditions={}):
55 """Returns contents of template file as a string, or raises an exception."""
56 template = self.
TryLoad(name, more_conditions)
57 if template
is not None:
59 raise Exception(
"Could not find template '%s' on %s / %s" %
62 def _Preprocess(self, template, filename, conditions):
64 def error(lineno, message):
65 raise Exception(
'%s:%s: %s' % (filename, lineno, message))
67 lines = template.splitlines(
True)
74 for (lineno, full_line)
in enumerate(lines):
75 line = full_line.strip()
77 if line.startswith(
'$'):
81 if directive ==
'$if':
83 error(lineno,
'$if does not have single variable')
85 if variable
in conditions:
86 condition_stack.append((active, seen_else))
87 active = active
and conditions[variable]
90 error(lineno,
"Unknown $if variable '%s'" % variable)
92 elif directive ==
'$else':
93 if not condition_stack:
94 error(lineno,
'$else without $if')
96 raise error(lineno,
'Double $else')
99 _) = condition_stack[
len(condition_stack) - 1]
100 active =
not active
and parentactive
102 elif directive ==
'$endif':
103 if not condition_stack:
104 error(lineno,
'$endif without $if')
105 (active, seen_else) = condition_stack.pop()
110 out.append(full_line)
111 elif line.startswith(
'//$'):
116 out.append(full_line)
120 error(
len(lines),
'Unterminated $if')
def Load(self, name, more_conditions={})
def __init__(self, root, subpaths, conditions={})
def TryLoad(self, name, more_conditions={})
def _Preprocess(self, template, filename, conditions)
static void readlines(const void *data, size_t size, F f)
const uint8_t uint32_t uint32_t GError ** error
static SkString join(const CommandLineFlags::StringArray &)