Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(77)

Side by Side Diff: client/dom/scripts/templateloader.py

Issue 9706084: Add conditional feature to templates. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: merge Created 8 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « client/dom/scripts/idlrenderer_test.py ('k') | client/dom/scripts/templateloader_test.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 #!/usr/bin/python
2 # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
3 # for details. All rights reserved. Use of this source code is governed by a
4 # BSD-style license that can be found in the LICENSE file.
5
6 # Template loader and preprocessor.
7 #
8 # Preprocessor language:
9 #
10 # $if VAR
11 # $else
12 # $endif
13 #
14 # VAR must be defined in the conditions dictionary.
15
16 import os
17
18 class TemplateLoader(object):
19 """Loads template files from a path."""
20
21 def __init__(self, root, subpaths, conditions = {}):
22 """Initializes loader.
23
24 Args:
25 root - a string, the directory under which the templates are stored.
26 subpaths - a list of strings, subpaths of root in search order.
27 conditions - a dictionay from strings to booleans. Any conditional
28 expression must be a key in the map.
29 """
30 self._root = root
31 self._subpaths = subpaths
32 self._conditions = conditions
33 self._cache = {}
34
35 def TryLoad(self, name):
36 """Returns content of template file as a string, or None of not found."""
37 if name in self._cache:
38 return self._cache[name]
39
40 for subpath in self._subpaths:
41 template_file = os.path.join(self._root, subpath, name)
42 if os.path.exists(template_file):
43 template = ''.join(open(template_file).readlines())
44 template = self._Preprocess(template, template_file)
45 self._cache[name] = template
46 return template
47
48 return None
49
50 def Load(self, name):
51 """Returns contents of template file as a string, or raises an exception."""
52 template = self.TryLoad(name)
53 if template is not None: # Can be empty string
54 return template
55 raise Exception("Could not find template '%s' on %s / %s" % (
56 name, self._root, self._subpaths))
57
58 def _Preprocess(self, template, filename):
59 def error(lineno, message):
60 raise Exception('%s:%s: %s' % (filename, lineno, message))
61
62 lines = template.splitlines(True)
63 out = []
64
65 condition_stack = []
66 active = True
67 seen_else = False
68
69 for (lineno, full_line) in enumerate(lines):
70 line = full_line.strip()
71
72 if line.startswith('$'):
73 words = line.split()
74 directive = words[0]
75
76 if directive == '$if':
77 if len(words) != 2:
78 error(lineno, '$if does not have single variable')
79 variable = words[1]
80 if variable in self._conditions:
81 condition_stack.append((active, seen_else))
82 active = self._conditions[variable]
83 seen_else = False
84 else:
85 error(lineno, "Unknown $if variable '%s'" % variable)
86
87 elif directive == '$else':
88 if not condition_stack:
89 error(lineno, '$else without $if')
90 if seen_else:
91 raise error(lineno, 'Double $else')
92 seen_else = True
93 active = not active
94
95 elif directive == '$endif':
96 if not condition_stack:
97 error(lineno, '$endif without $if')
98 (active, seen_else) = condition_stack.pop()
99
100 else:
101 # Something else, like '$!MEMBERS'
102 if active:
103 out.append(full_line)
104
105 else:
106 if active:
107 out.append(full_line);
108 continue
109
110 if condition_stack:
111 error(len(lines), 'Unterminated $if')
112
113 return ''.join(out)
OLDNEW
« no previous file with comments | « client/dom/scripts/idlrenderer_test.py ('k') | client/dom/scripts/templateloader_test.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698