##// END OF EJS Templates
templater: make a template a string-only iterator
Dirkjan Ochtman -
r6783:6d824dc8 default
parent child Browse files
Show More
@@ -1,150 +1,171 b''
1 1 # templater.py - template expansion for output
2 2 #
3 3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from i18n import _
9 9 import re, sys, os
10 10 from mercurial import util
11 11
12 12 def parsestring(s, quoted=True):
13 13 '''parse a string using simple c-like syntax.
14 14 string must be in quotes if quoted is True.'''
15 15 if quoted:
16 16 if len(s) < 2 or s[0] != s[-1]:
17 17 raise SyntaxError(_('unmatched quotes'))
18 18 return s[1:-1].decode('string_escape')
19 19
20 20 return s.decode('string_escape')
21 21
22 22 class templater(object):
23 23 '''template expansion engine.
24 24
25 25 template expansion works like this. a map file contains key=value
26 26 pairs. if value is quoted, it is treated as string. otherwise, it
27 27 is treated as name of template file.
28 28
29 29 templater is asked to expand a key in map. it looks up key, and
30 30 looks for strings like this: {foo}. it expands {foo} by looking up
31 31 foo in map, and substituting it. expansion is recursive: it stops
32 32 when there is no more {foo} to replace.
33 33
34 34 expansion also allows formatting and filtering.
35 35
36 36 format uses key to expand each item in list. syntax is
37 37 {key%format}.
38 38
39 39 filter uses function to transform value. syntax is
40 40 {key|filter1|filter2|...}.'''
41 41
42 42 template_re = re.compile(r"(?:(?:#(?=[\w\|%]+#))|(?:{(?=[\w\|%]+})))"
43 43 r"(\w+)(?:(?:%(\w+))|((?:\|\w+)*))[#}]")
44 44
45 45 def __init__(self, mapfile, filters={}, defaults={}, cache={}):
46 46 '''set up template engine.
47 47 mapfile is name of file to read map definitions from.
48 48 filters is dict of functions. each transforms a value into another.
49 49 defaults is dict of default map definitions.'''
50 50 self.mapfile = mapfile or 'template'
51 51 self.cache = cache.copy()
52 52 self.map = {}
53 53 self.base = (mapfile and os.path.dirname(mapfile)) or ''
54 54 self.filters = filters
55 55 self.defaults = defaults
56 56
57 57 if not mapfile:
58 58 return
59 59 if not os.path.exists(mapfile):
60 60 raise util.Abort(_('style not found: %s') % mapfile)
61 61
62 62 i = 0
63 63 for l in file(mapfile):
64 64 l = l.strip()
65 65 i += 1
66 66 if not l or l[0] in '#;': continue
67 67 m = re.match(r'([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.+)$', l)
68 68 if m:
69 69 key, val = m.groups()
70 70 if val[0] in "'\"":
71 71 try:
72 72 self.cache[key] = parsestring(val)
73 73 except SyntaxError, inst:
74 74 raise SyntaxError('%s:%s: %s' %
75 75 (mapfile, i, inst.args[0]))
76 76 else:
77 77 self.map[key] = os.path.join(self.base, val)
78 78 else:
79 79 raise SyntaxError(_("%s:%s: parse error") % (mapfile, i))
80 80
81 81 def __contains__(self, key):
82 82 return key in self.cache or key in self.map
83 83
84 def __call__(self, t, **map):
85 '''perform expansion.
86 t is name of map element to expand.
87 map is added elements to use during expansion.'''
84 def _template(self, t):
85 '''Get the template for the given template name. Use a local cache.'''
88 86 if not t in self.cache:
89 87 try:
90 88 self.cache[t] = file(self.map[t]).read()
91 89 except IOError, inst:
92 90 raise IOError(inst.args[0], _('template file %s: %s') %
93 91 (self.map[t], inst.args[1]))
94 tmpl = self.cache[t]
92 return self.cache[t]
95 93
94 def _process(self, tmpl, map):
95 '''Render a template. Returns a generator.'''
96 96 while tmpl:
97 97 m = self.template_re.search(tmpl)
98 98 if not m:
99 99 yield tmpl
100 100 break
101 101
102 102 start, end = m.span(0)
103 103 key, format, fl = m.groups()
104 104
105 105 if start:
106 106 yield tmpl[:start]
107 107 tmpl = tmpl[end:]
108 108
109 109 if key in map:
110 110 v = map[key]
111 111 else:
112 112 v = self.defaults.get(key, "")
113 113 if callable(v):
114 114 v = v(**map)
115 115 if format:
116 116 if not hasattr(v, '__iter__'):
117 117 raise SyntaxError(_("Error expanding '%s%%%s'")
118 118 % (key, format))
119 119 lm = map.copy()
120 120 for i in v:
121 121 lm.update(i)
122 yield self(format, **lm)
122 t = self._template(format)
123 yield self._process(t, lm)
123 124 else:
124 125 if fl:
125 126 for f in fl.split("|")[1:]:
126 127 v = self.filters[f](v)
127 128 yield v
128 129
130 def __call__(self, t, **map):
131 '''Perform expansion. t is name of map element to expand. map contains
132 added elements for use during expansion. Is a generator.'''
133 tmpl = self._template(t)
134 iters = [self._process(tmpl, map)]
135 while iters:
136 try:
137 item = iters[0].next()
138 except StopIteration:
139 iters.pop(0)
140 continue
141 if isinstance(item, str):
142 yield item
143 elif item is None:
144 yield ''
145 elif hasattr(item, '__iter__'):
146 iters.insert(0, iter(item))
147 else:
148 yield str(item)
149
129 150 def templatepath(name=None):
130 151 '''return location of template file or directory (if no name).
131 152 returns None if not found.'''
132 153
133 154 # executable version (py2exe) doesn't support __file__
134 155 if hasattr(sys, 'frozen'):
135 156 module = sys.executable
136 157 else:
137 158 module = __file__
138 159 for f in 'templates', '../templates':
139 160 fl = f.split('/')
140 161 if name: fl.append(name)
141 162 p = os.path.join(os.path.dirname(module), *fl)
142 163 if (name and os.path.exists(p)) or os.path.isdir(p):
143 164 return os.path.normpath(p)
144 165
145 166 def stringify(thing):
146 167 '''turn nested template iterator into string.'''
147 168 if hasattr(thing, '__iter__'):
148 169 return "".join([stringify(t) for t in thing if t is not None])
149 170 return str(thing)
150 171
General Comments 0
You need to be logged in to leave comments. Login now