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

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

Issue 10913125: Remove lib/dom directory! (Closed) Base URL: http://dart.googlecode.com/svn/branches/bleeding_edge/dart/
Patch Set: Created 8 years, 3 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
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 # //$ Comment line removed by preprocessor
11 # $if VAR
12 # $else
13 # $endif
14 #
15 # VAR must be defined in the conditions dictionary.
16
17 import os
18
19 class TemplateLoader(object):
20 """Loads template files from a path."""
21
22 def __init__(self, root, subpaths, conditions = {}):
23 """Initializes loader.
24
25 Args:
26 root - a string, the directory under which the templates are stored.
27 subpaths - a list of strings, subpaths of root in search order.
28 conditions - a dictionay from strings to booleans. Any conditional
29 expression must be a key in the map.
30 """
31 self._root = root
32 self._subpaths = subpaths
33 self._conditions = conditions
34 self._cache = {}
35
36 def TryLoad(self, name):
37 """Returns content of template file as a string, or None of not found."""
38 if name in self._cache:
39 return self._cache[name]
40
41 for subpath in self._subpaths:
42 template_file = os.path.join(self._root, subpath, name)
43 if os.path.exists(template_file):
44 template = ''.join(open(template_file).readlines())
45 template = self._Preprocess(template, template_file)
46 self._cache[name] = template
47 return template
48
49 return None
50
51 def Load(self, name):
52 """Returns contents of template file as a string, or raises an exception."""
53 template = self.TryLoad(name)
54 if template is not None: # Can be empty string
55 return template
56 raise Exception("Could not find template '%s' on %s / %s" % (
57 name, self._root, self._subpaths))
58
59 def _Preprocess(self, template, filename):
60 def error(lineno, message):
61 raise Exception('%s:%s: %s' % (filename, lineno, message))
62
63 lines = template.splitlines(True)
64 out = []
65
66 condition_stack = []
67 active = True
68 seen_else = False
69
70 for (lineno, full_line) in enumerate(lines):
71 line = full_line.strip()
72
73 if line.startswith('$'):
74 words = line.split()
75 directive = words[0]
76
77 if directive == '$if':
78 if len(words) != 2:
79 error(lineno, '$if does not have single variable')
80 variable = words[1]
81 if variable in self._conditions:
82 condition_stack.append((active, seen_else))
83 active = self._conditions[variable]
84 seen_else = False
85 else:
86 error(lineno, "Unknown $if variable '%s'" % variable)
87
88 elif directive == '$else':
89 if not condition_stack:
90 error(lineno, '$else without $if')
91 if seen_else:
92 raise error(lineno, 'Double $else')
93 seen_else = True
94 active = not active
95
96 elif directive == '$endif':
97 if not condition_stack:
98 error(lineno, '$endif without $if')
99 (active, seen_else) = condition_stack.pop()
100
101 else:
102 # Something else, like '$!MEMBERS'
103 if active:
104 out.append(full_line)
105 elif line.startswith('//$'):
106 pass # Ignore pre-processor comment.
107
108 else:
109 if active:
110 out.append(full_line)
111 continue
112
113 if condition_stack:
114 error(len(lines), 'Unterminated $if')
115
116 return ''.join(out)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698