##// END OF EJS Templates
templater: drop bool support from evalastype()...
Yuya Nishihara -
r37177:53e6b7e0 default
parent child Browse files
Show More
@@ -1,469 +1,468 b''
1 # templateutil.py - utility for template evaluation
1 # templateutil.py - utility for template evaluation
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import types
10 import types
11
11
12 from .i18n import _
12 from .i18n import _
13 from . import (
13 from . import (
14 error,
14 error,
15 pycompat,
15 pycompat,
16 util,
16 util,
17 )
17 )
18 from .utils import (
18 from .utils import (
19 stringutil,
19 stringutil,
20 )
20 )
21
21
22 class ResourceUnavailable(error.Abort):
22 class ResourceUnavailable(error.Abort):
23 pass
23 pass
24
24
25 class TemplateNotFound(error.Abort):
25 class TemplateNotFound(error.Abort):
26 pass
26 pass
27
27
28 class hybrid(object):
28 class hybrid(object):
29 """Wrapper for list or dict to support legacy template
29 """Wrapper for list or dict to support legacy template
30
30
31 This class allows us to handle both:
31 This class allows us to handle both:
32 - "{files}" (legacy command-line-specific list hack) and
32 - "{files}" (legacy command-line-specific list hack) and
33 - "{files % '{file}\n'}" (hgweb-style with inlining and function support)
33 - "{files % '{file}\n'}" (hgweb-style with inlining and function support)
34 and to access raw values:
34 and to access raw values:
35 - "{ifcontains(file, files, ...)}", "{ifcontains(key, extras, ...)}"
35 - "{ifcontains(file, files, ...)}", "{ifcontains(key, extras, ...)}"
36 - "{get(extras, key)}"
36 - "{get(extras, key)}"
37 - "{files|json}"
37 - "{files|json}"
38 """
38 """
39
39
40 def __init__(self, gen, values, makemap, joinfmt, keytype=None):
40 def __init__(self, gen, values, makemap, joinfmt, keytype=None):
41 if gen is not None:
41 if gen is not None:
42 self.gen = gen # generator or function returning generator
42 self.gen = gen # generator or function returning generator
43 self._values = values
43 self._values = values
44 self._makemap = makemap
44 self._makemap = makemap
45 self.joinfmt = joinfmt
45 self.joinfmt = joinfmt
46 self.keytype = keytype # hint for 'x in y' where type(x) is unresolved
46 self.keytype = keytype # hint for 'x in y' where type(x) is unresolved
47 def gen(self):
47 def gen(self):
48 """Default generator to stringify this as {join(self, ' ')}"""
48 """Default generator to stringify this as {join(self, ' ')}"""
49 for i, x in enumerate(self._values):
49 for i, x in enumerate(self._values):
50 if i > 0:
50 if i > 0:
51 yield ' '
51 yield ' '
52 yield self.joinfmt(x)
52 yield self.joinfmt(x)
53 def itermaps(self):
53 def itermaps(self):
54 makemap = self._makemap
54 makemap = self._makemap
55 for x in self._values:
55 for x in self._values:
56 yield makemap(x)
56 yield makemap(x)
57 def __contains__(self, x):
57 def __contains__(self, x):
58 return x in self._values
58 return x in self._values
59 def __getitem__(self, key):
59 def __getitem__(self, key):
60 return self._values[key]
60 return self._values[key]
61 def __len__(self):
61 def __len__(self):
62 return len(self._values)
62 return len(self._values)
63 def __iter__(self):
63 def __iter__(self):
64 return iter(self._values)
64 return iter(self._values)
65 def __getattr__(self, name):
65 def __getattr__(self, name):
66 if name not in (r'get', r'items', r'iteritems', r'iterkeys',
66 if name not in (r'get', r'items', r'iteritems', r'iterkeys',
67 r'itervalues', r'keys', r'values'):
67 r'itervalues', r'keys', r'values'):
68 raise AttributeError(name)
68 raise AttributeError(name)
69 return getattr(self._values, name)
69 return getattr(self._values, name)
70
70
71 class mappable(object):
71 class mappable(object):
72 """Wrapper for non-list/dict object to support map operation
72 """Wrapper for non-list/dict object to support map operation
73
73
74 This class allows us to handle both:
74 This class allows us to handle both:
75 - "{manifest}"
75 - "{manifest}"
76 - "{manifest % '{rev}:{node}'}"
76 - "{manifest % '{rev}:{node}'}"
77 - "{manifest.rev}"
77 - "{manifest.rev}"
78
78
79 Unlike a hybrid, this does not simulate the behavior of the underling
79 Unlike a hybrid, this does not simulate the behavior of the underling
80 value. Use unwrapvalue() or unwraphybrid() to obtain the inner object.
80 value. Use unwrapvalue() or unwraphybrid() to obtain the inner object.
81 """
81 """
82
82
83 def __init__(self, gen, key, value, makemap):
83 def __init__(self, gen, key, value, makemap):
84 if gen is not None:
84 if gen is not None:
85 self.gen = gen # generator or function returning generator
85 self.gen = gen # generator or function returning generator
86 self._key = key
86 self._key = key
87 self._value = value # may be generator of strings
87 self._value = value # may be generator of strings
88 self._makemap = makemap
88 self._makemap = makemap
89
89
90 def gen(self):
90 def gen(self):
91 yield pycompat.bytestr(self._value)
91 yield pycompat.bytestr(self._value)
92
92
93 def tomap(self):
93 def tomap(self):
94 return self._makemap(self._key)
94 return self._makemap(self._key)
95
95
96 def itermaps(self):
96 def itermaps(self):
97 yield self.tomap()
97 yield self.tomap()
98
98
99 def hybriddict(data, key='key', value='value', fmt=None, gen=None):
99 def hybriddict(data, key='key', value='value', fmt=None, gen=None):
100 """Wrap data to support both dict-like and string-like operations"""
100 """Wrap data to support both dict-like and string-like operations"""
101 prefmt = pycompat.identity
101 prefmt = pycompat.identity
102 if fmt is None:
102 if fmt is None:
103 fmt = '%s=%s'
103 fmt = '%s=%s'
104 prefmt = pycompat.bytestr
104 prefmt = pycompat.bytestr
105 return hybrid(gen, data, lambda k: {key: k, value: data[k]},
105 return hybrid(gen, data, lambda k: {key: k, value: data[k]},
106 lambda k: fmt % (prefmt(k), prefmt(data[k])))
106 lambda k: fmt % (prefmt(k), prefmt(data[k])))
107
107
108 def hybridlist(data, name, fmt=None, gen=None):
108 def hybridlist(data, name, fmt=None, gen=None):
109 """Wrap data to support both list-like and string-like operations"""
109 """Wrap data to support both list-like and string-like operations"""
110 prefmt = pycompat.identity
110 prefmt = pycompat.identity
111 if fmt is None:
111 if fmt is None:
112 fmt = '%s'
112 fmt = '%s'
113 prefmt = pycompat.bytestr
113 prefmt = pycompat.bytestr
114 return hybrid(gen, data, lambda x: {name: x}, lambda x: fmt % prefmt(x))
114 return hybrid(gen, data, lambda x: {name: x}, lambda x: fmt % prefmt(x))
115
115
116 def unwraphybrid(thing):
116 def unwraphybrid(thing):
117 """Return an object which can be stringified possibly by using a legacy
117 """Return an object which can be stringified possibly by using a legacy
118 template"""
118 template"""
119 gen = getattr(thing, 'gen', None)
119 gen = getattr(thing, 'gen', None)
120 if gen is None:
120 if gen is None:
121 return thing
121 return thing
122 if callable(gen):
122 if callable(gen):
123 return gen()
123 return gen()
124 return gen
124 return gen
125
125
126 def unwrapvalue(thing):
126 def unwrapvalue(thing):
127 """Move the inner value object out of the wrapper"""
127 """Move the inner value object out of the wrapper"""
128 if not util.safehasattr(thing, '_value'):
128 if not util.safehasattr(thing, '_value'):
129 return thing
129 return thing
130 return thing._value
130 return thing._value
131
131
132 def wraphybridvalue(container, key, value):
132 def wraphybridvalue(container, key, value):
133 """Wrap an element of hybrid container to be mappable
133 """Wrap an element of hybrid container to be mappable
134
134
135 The key is passed to the makemap function of the given container, which
135 The key is passed to the makemap function of the given container, which
136 should be an item generated by iter(container).
136 should be an item generated by iter(container).
137 """
137 """
138 makemap = getattr(container, '_makemap', None)
138 makemap = getattr(container, '_makemap', None)
139 if makemap is None:
139 if makemap is None:
140 return value
140 return value
141 if util.safehasattr(value, '_makemap'):
141 if util.safehasattr(value, '_makemap'):
142 # a nested hybrid list/dict, which has its own way of map operation
142 # a nested hybrid list/dict, which has its own way of map operation
143 return value
143 return value
144 return mappable(None, key, value, makemap)
144 return mappable(None, key, value, makemap)
145
145
146 def compatdict(context, mapping, name, data, key='key', value='value',
146 def compatdict(context, mapping, name, data, key='key', value='value',
147 fmt=None, plural=None, separator=' '):
147 fmt=None, plural=None, separator=' '):
148 """Wrap data like hybriddict(), but also supports old-style list template
148 """Wrap data like hybriddict(), but also supports old-style list template
149
149
150 This exists for backward compatibility with the old-style template. Use
150 This exists for backward compatibility with the old-style template. Use
151 hybriddict() for new template keywords.
151 hybriddict() for new template keywords.
152 """
152 """
153 c = [{key: k, value: v} for k, v in data.iteritems()]
153 c = [{key: k, value: v} for k, v in data.iteritems()]
154 f = _showcompatlist(context, mapping, name, c, plural, separator)
154 f = _showcompatlist(context, mapping, name, c, plural, separator)
155 return hybriddict(data, key=key, value=value, fmt=fmt, gen=f)
155 return hybriddict(data, key=key, value=value, fmt=fmt, gen=f)
156
156
157 def compatlist(context, mapping, name, data, element=None, fmt=None,
157 def compatlist(context, mapping, name, data, element=None, fmt=None,
158 plural=None, separator=' '):
158 plural=None, separator=' '):
159 """Wrap data like hybridlist(), but also supports old-style list template
159 """Wrap data like hybridlist(), but also supports old-style list template
160
160
161 This exists for backward compatibility with the old-style template. Use
161 This exists for backward compatibility with the old-style template. Use
162 hybridlist() for new template keywords.
162 hybridlist() for new template keywords.
163 """
163 """
164 f = _showcompatlist(context, mapping, name, data, plural, separator)
164 f = _showcompatlist(context, mapping, name, data, plural, separator)
165 return hybridlist(data, name=element or name, fmt=fmt, gen=f)
165 return hybridlist(data, name=element or name, fmt=fmt, gen=f)
166
166
167 def _showcompatlist(context, mapping, name, values, plural=None, separator=' '):
167 def _showcompatlist(context, mapping, name, values, plural=None, separator=' '):
168 """Return a generator that renders old-style list template
168 """Return a generator that renders old-style list template
169
169
170 name is name of key in template map.
170 name is name of key in template map.
171 values is list of strings or dicts.
171 values is list of strings or dicts.
172 plural is plural of name, if not simply name + 's'.
172 plural is plural of name, if not simply name + 's'.
173 separator is used to join values as a string
173 separator is used to join values as a string
174
174
175 expansion works like this, given name 'foo'.
175 expansion works like this, given name 'foo'.
176
176
177 if values is empty, expand 'no_foos'.
177 if values is empty, expand 'no_foos'.
178
178
179 if 'foo' not in template map, return values as a string,
179 if 'foo' not in template map, return values as a string,
180 joined by 'separator'.
180 joined by 'separator'.
181
181
182 expand 'start_foos'.
182 expand 'start_foos'.
183
183
184 for each value, expand 'foo'. if 'last_foo' in template
184 for each value, expand 'foo'. if 'last_foo' in template
185 map, expand it instead of 'foo' for last key.
185 map, expand it instead of 'foo' for last key.
186
186
187 expand 'end_foos'.
187 expand 'end_foos'.
188 """
188 """
189 if not plural:
189 if not plural:
190 plural = name + 's'
190 plural = name + 's'
191 if not values:
191 if not values:
192 noname = 'no_' + plural
192 noname = 'no_' + plural
193 if context.preload(noname):
193 if context.preload(noname):
194 yield context.process(noname, mapping)
194 yield context.process(noname, mapping)
195 return
195 return
196 if not context.preload(name):
196 if not context.preload(name):
197 if isinstance(values[0], bytes):
197 if isinstance(values[0], bytes):
198 yield separator.join(values)
198 yield separator.join(values)
199 else:
199 else:
200 for v in values:
200 for v in values:
201 r = dict(v)
201 r = dict(v)
202 r.update(mapping)
202 r.update(mapping)
203 yield r
203 yield r
204 return
204 return
205 startname = 'start_' + plural
205 startname = 'start_' + plural
206 if context.preload(startname):
206 if context.preload(startname):
207 yield context.process(startname, mapping)
207 yield context.process(startname, mapping)
208 def one(v, tag=name):
208 def one(v, tag=name):
209 vmapping = {}
209 vmapping = {}
210 try:
210 try:
211 vmapping.update(v)
211 vmapping.update(v)
212 # Python 2 raises ValueError if the type of v is wrong. Python
212 # Python 2 raises ValueError if the type of v is wrong. Python
213 # 3 raises TypeError.
213 # 3 raises TypeError.
214 except (AttributeError, TypeError, ValueError):
214 except (AttributeError, TypeError, ValueError):
215 try:
215 try:
216 # Python 2 raises ValueError trying to destructure an e.g.
216 # Python 2 raises ValueError trying to destructure an e.g.
217 # bytes. Python 3 raises TypeError.
217 # bytes. Python 3 raises TypeError.
218 for a, b in v:
218 for a, b in v:
219 vmapping[a] = b
219 vmapping[a] = b
220 except (TypeError, ValueError):
220 except (TypeError, ValueError):
221 vmapping[name] = v
221 vmapping[name] = v
222 vmapping = context.overlaymap(mapping, vmapping)
222 vmapping = context.overlaymap(mapping, vmapping)
223 return context.process(tag, vmapping)
223 return context.process(tag, vmapping)
224 lastname = 'last_' + name
224 lastname = 'last_' + name
225 if context.preload(lastname):
225 if context.preload(lastname):
226 last = values.pop()
226 last = values.pop()
227 else:
227 else:
228 last = None
228 last = None
229 for v in values:
229 for v in values:
230 yield one(v)
230 yield one(v)
231 if last is not None:
231 if last is not None:
232 yield one(last, tag=lastname)
232 yield one(last, tag=lastname)
233 endname = 'end_' + plural
233 endname = 'end_' + plural
234 if context.preload(endname):
234 if context.preload(endname):
235 yield context.process(endname, mapping)
235 yield context.process(endname, mapping)
236
236
237 def flatten(thing):
237 def flatten(thing):
238 """Yield a single stream from a possibly nested set of iterators"""
238 """Yield a single stream from a possibly nested set of iterators"""
239 thing = unwraphybrid(thing)
239 thing = unwraphybrid(thing)
240 if isinstance(thing, bytes):
240 if isinstance(thing, bytes):
241 yield thing
241 yield thing
242 elif isinstance(thing, str):
242 elif isinstance(thing, str):
243 # We can only hit this on Python 3, and it's here to guard
243 # We can only hit this on Python 3, and it's here to guard
244 # against infinite recursion.
244 # against infinite recursion.
245 raise error.ProgrammingError('Mercurial IO including templates is done'
245 raise error.ProgrammingError('Mercurial IO including templates is done'
246 ' with bytes, not strings, got %r' % thing)
246 ' with bytes, not strings, got %r' % thing)
247 elif thing is None:
247 elif thing is None:
248 pass
248 pass
249 elif not util.safehasattr(thing, '__iter__'):
249 elif not util.safehasattr(thing, '__iter__'):
250 yield pycompat.bytestr(thing)
250 yield pycompat.bytestr(thing)
251 else:
251 else:
252 for i in thing:
252 for i in thing:
253 i = unwraphybrid(i)
253 i = unwraphybrid(i)
254 if isinstance(i, bytes):
254 if isinstance(i, bytes):
255 yield i
255 yield i
256 elif i is None:
256 elif i is None:
257 pass
257 pass
258 elif not util.safehasattr(i, '__iter__'):
258 elif not util.safehasattr(i, '__iter__'):
259 yield pycompat.bytestr(i)
259 yield pycompat.bytestr(i)
260 else:
260 else:
261 for j in flatten(i):
261 for j in flatten(i):
262 yield j
262 yield j
263
263
264 def stringify(thing):
264 def stringify(thing):
265 """Turn values into bytes by converting into text and concatenating them"""
265 """Turn values into bytes by converting into text and concatenating them"""
266 if isinstance(thing, bytes):
266 if isinstance(thing, bytes):
267 return thing # retain localstr to be round-tripped
267 return thing # retain localstr to be round-tripped
268 return b''.join(flatten(thing))
268 return b''.join(flatten(thing))
269
269
270 def findsymbolicname(arg):
270 def findsymbolicname(arg):
271 """Find symbolic name for the given compiled expression; returns None
271 """Find symbolic name for the given compiled expression; returns None
272 if nothing found reliably"""
272 if nothing found reliably"""
273 while True:
273 while True:
274 func, data = arg
274 func, data = arg
275 if func is runsymbol:
275 if func is runsymbol:
276 return data
276 return data
277 elif func is runfilter:
277 elif func is runfilter:
278 arg = data[0]
278 arg = data[0]
279 else:
279 else:
280 return None
280 return None
281
281
282 def evalrawexp(context, mapping, arg):
282 def evalrawexp(context, mapping, arg):
283 """Evaluate given argument as a bare template object which may require
283 """Evaluate given argument as a bare template object which may require
284 further processing (such as folding generator of strings)"""
284 further processing (such as folding generator of strings)"""
285 func, data = arg
285 func, data = arg
286 return func(context, mapping, data)
286 return func(context, mapping, data)
287
287
288 def evalfuncarg(context, mapping, arg):
288 def evalfuncarg(context, mapping, arg):
289 """Evaluate given argument as value type"""
289 """Evaluate given argument as value type"""
290 thing = evalrawexp(context, mapping, arg)
290 thing = evalrawexp(context, mapping, arg)
291 thing = unwrapvalue(thing)
291 thing = unwrapvalue(thing)
292 # evalrawexp() may return string, generator of strings or arbitrary object
292 # evalrawexp() may return string, generator of strings or arbitrary object
293 # such as date tuple, but filter does not want generator.
293 # such as date tuple, but filter does not want generator.
294 if isinstance(thing, types.GeneratorType):
294 if isinstance(thing, types.GeneratorType):
295 thing = stringify(thing)
295 thing = stringify(thing)
296 return thing
296 return thing
297
297
298 def evalboolean(context, mapping, arg):
298 def evalboolean(context, mapping, arg):
299 """Evaluate given argument as boolean, but also takes boolean literals"""
299 """Evaluate given argument as boolean, but also takes boolean literals"""
300 func, data = arg
300 func, data = arg
301 if func is runsymbol:
301 if func is runsymbol:
302 thing = func(context, mapping, data, default=None)
302 thing = func(context, mapping, data, default=None)
303 if thing is None:
303 if thing is None:
304 # not a template keyword, takes as a boolean literal
304 # not a template keyword, takes as a boolean literal
305 thing = stringutil.parsebool(data)
305 thing = stringutil.parsebool(data)
306 else:
306 else:
307 thing = func(context, mapping, data)
307 thing = func(context, mapping, data)
308 thing = unwrapvalue(thing)
308 thing = unwrapvalue(thing)
309 if isinstance(thing, bool):
309 if isinstance(thing, bool):
310 return thing
310 return thing
311 # other objects are evaluated as strings, which means 0 is True, but
311 # other objects are evaluated as strings, which means 0 is True, but
312 # empty dict/list should be False as they are expected to be ''
312 # empty dict/list should be False as they are expected to be ''
313 return bool(stringify(thing))
313 return bool(stringify(thing))
314
314
315 def evalinteger(context, mapping, arg, err=None):
315 def evalinteger(context, mapping, arg, err=None):
316 v = evalfuncarg(context, mapping, arg)
316 v = evalfuncarg(context, mapping, arg)
317 try:
317 try:
318 return int(v)
318 return int(v)
319 except (TypeError, ValueError):
319 except (TypeError, ValueError):
320 raise error.ParseError(err or _('not an integer'))
320 raise error.ParseError(err or _('not an integer'))
321
321
322 def evalstring(context, mapping, arg):
322 def evalstring(context, mapping, arg):
323 return stringify(evalrawexp(context, mapping, arg))
323 return stringify(evalrawexp(context, mapping, arg))
324
324
325 def evalstringliteral(context, mapping, arg):
325 def evalstringliteral(context, mapping, arg):
326 """Evaluate given argument as string template, but returns symbol name
326 """Evaluate given argument as string template, but returns symbol name
327 if it is unknown"""
327 if it is unknown"""
328 func, data = arg
328 func, data = arg
329 if func is runsymbol:
329 if func is runsymbol:
330 thing = func(context, mapping, data, default=data)
330 thing = func(context, mapping, data, default=data)
331 else:
331 else:
332 thing = func(context, mapping, data)
332 thing = func(context, mapping, data)
333 return stringify(thing)
333 return stringify(thing)
334
334
335 _evalfuncbytype = {
335 _evalfuncbytype = {
336 bool: evalboolean,
337 bytes: evalstring,
336 bytes: evalstring,
338 int: evalinteger,
337 int: evalinteger,
339 }
338 }
340
339
341 def evalastype(context, mapping, arg, typ):
340 def evalastype(context, mapping, arg, typ):
342 """Evaluate given argument and coerce its type"""
341 """Evaluate given argument and coerce its type"""
343 try:
342 try:
344 f = _evalfuncbytype[typ]
343 f = _evalfuncbytype[typ]
345 except KeyError:
344 except KeyError:
346 raise error.ProgrammingError('invalid type specified: %r' % typ)
345 raise error.ProgrammingError('invalid type specified: %r' % typ)
347 return f(context, mapping, arg)
346 return f(context, mapping, arg)
348
347
349 def runinteger(context, mapping, data):
348 def runinteger(context, mapping, data):
350 return int(data)
349 return int(data)
351
350
352 def runstring(context, mapping, data):
351 def runstring(context, mapping, data):
353 return data
352 return data
354
353
355 def _recursivesymbolblocker(key):
354 def _recursivesymbolblocker(key):
356 def showrecursion(**args):
355 def showrecursion(**args):
357 raise error.Abort(_("recursive reference '%s' in template") % key)
356 raise error.Abort(_("recursive reference '%s' in template") % key)
358 return showrecursion
357 return showrecursion
359
358
360 def runsymbol(context, mapping, key, default=''):
359 def runsymbol(context, mapping, key, default=''):
361 v = context.symbol(mapping, key)
360 v = context.symbol(mapping, key)
362 if v is None:
361 if v is None:
363 # put poison to cut recursion. we can't move this to parsing phase
362 # put poison to cut recursion. we can't move this to parsing phase
364 # because "x = {x}" is allowed if "x" is a keyword. (issue4758)
363 # because "x = {x}" is allowed if "x" is a keyword. (issue4758)
365 safemapping = mapping.copy()
364 safemapping = mapping.copy()
366 safemapping[key] = _recursivesymbolblocker(key)
365 safemapping[key] = _recursivesymbolblocker(key)
367 try:
366 try:
368 v = context.process(key, safemapping)
367 v = context.process(key, safemapping)
369 except TemplateNotFound:
368 except TemplateNotFound:
370 v = default
369 v = default
371 if callable(v) and getattr(v, '_requires', None) is None:
370 if callable(v) and getattr(v, '_requires', None) is None:
372 # old templatekw: expand all keywords and resources
371 # old templatekw: expand all keywords and resources
373 # (TODO: deprecate this after porting web template keywords to new API)
372 # (TODO: deprecate this after porting web template keywords to new API)
374 props = {k: context._resources.lookup(context, mapping, k)
373 props = {k: context._resources.lookup(context, mapping, k)
375 for k in context._resources.knownkeys()}
374 for k in context._resources.knownkeys()}
376 # pass context to _showcompatlist() through templatekw._showlist()
375 # pass context to _showcompatlist() through templatekw._showlist()
377 props['templ'] = context
376 props['templ'] = context
378 props.update(mapping)
377 props.update(mapping)
379 return v(**pycompat.strkwargs(props))
378 return v(**pycompat.strkwargs(props))
380 if callable(v):
379 if callable(v):
381 # new templatekw
380 # new templatekw
382 try:
381 try:
383 return v(context, mapping)
382 return v(context, mapping)
384 except ResourceUnavailable:
383 except ResourceUnavailable:
385 # unsupported keyword is mapped to empty just like unknown keyword
384 # unsupported keyword is mapped to empty just like unknown keyword
386 return None
385 return None
387 return v
386 return v
388
387
389 def runtemplate(context, mapping, template):
388 def runtemplate(context, mapping, template):
390 for arg in template:
389 for arg in template:
391 yield evalrawexp(context, mapping, arg)
390 yield evalrawexp(context, mapping, arg)
392
391
393 def runfilter(context, mapping, data):
392 def runfilter(context, mapping, data):
394 arg, filt = data
393 arg, filt = data
395 thing = evalfuncarg(context, mapping, arg)
394 thing = evalfuncarg(context, mapping, arg)
396 try:
395 try:
397 return filt(thing)
396 return filt(thing)
398 except (ValueError, AttributeError, TypeError):
397 except (ValueError, AttributeError, TypeError):
399 sym = findsymbolicname(arg)
398 sym = findsymbolicname(arg)
400 if sym:
399 if sym:
401 msg = (_("template filter '%s' is not compatible with keyword '%s'")
400 msg = (_("template filter '%s' is not compatible with keyword '%s'")
402 % (pycompat.sysbytes(filt.__name__), sym))
401 % (pycompat.sysbytes(filt.__name__), sym))
403 else:
402 else:
404 msg = (_("incompatible use of template filter '%s'")
403 msg = (_("incompatible use of template filter '%s'")
405 % pycompat.sysbytes(filt.__name__))
404 % pycompat.sysbytes(filt.__name__))
406 raise error.Abort(msg)
405 raise error.Abort(msg)
407
406
408 def runmap(context, mapping, data):
407 def runmap(context, mapping, data):
409 darg, targ = data
408 darg, targ = data
410 d = evalrawexp(context, mapping, darg)
409 d = evalrawexp(context, mapping, darg)
411 if util.safehasattr(d, 'itermaps'):
410 if util.safehasattr(d, 'itermaps'):
412 diter = d.itermaps()
411 diter = d.itermaps()
413 else:
412 else:
414 try:
413 try:
415 diter = iter(d)
414 diter = iter(d)
416 except TypeError:
415 except TypeError:
417 sym = findsymbolicname(darg)
416 sym = findsymbolicname(darg)
418 if sym:
417 if sym:
419 raise error.ParseError(_("keyword '%s' is not iterable") % sym)
418 raise error.ParseError(_("keyword '%s' is not iterable") % sym)
420 else:
419 else:
421 raise error.ParseError(_("%r is not iterable") % d)
420 raise error.ParseError(_("%r is not iterable") % d)
422
421
423 for i, v in enumerate(diter):
422 for i, v in enumerate(diter):
424 if isinstance(v, dict):
423 if isinstance(v, dict):
425 lm = context.overlaymap(mapping, v)
424 lm = context.overlaymap(mapping, v)
426 lm['index'] = i
425 lm['index'] = i
427 yield evalrawexp(context, lm, targ)
426 yield evalrawexp(context, lm, targ)
428 else:
427 else:
429 # v is not an iterable of dicts, this happen when 'key'
428 # v is not an iterable of dicts, this happen when 'key'
430 # has been fully expanded already and format is useless.
429 # has been fully expanded already and format is useless.
431 # If so, return the expanded value.
430 # If so, return the expanded value.
432 yield v
431 yield v
433
432
434 def runmember(context, mapping, data):
433 def runmember(context, mapping, data):
435 darg, memb = data
434 darg, memb = data
436 d = evalrawexp(context, mapping, darg)
435 d = evalrawexp(context, mapping, darg)
437 if util.safehasattr(d, 'tomap'):
436 if util.safehasattr(d, 'tomap'):
438 lm = context.overlaymap(mapping, d.tomap())
437 lm = context.overlaymap(mapping, d.tomap())
439 return runsymbol(context, lm, memb)
438 return runsymbol(context, lm, memb)
440 if util.safehasattr(d, 'get'):
439 if util.safehasattr(d, 'get'):
441 return getdictitem(d, memb)
440 return getdictitem(d, memb)
442
441
443 sym = findsymbolicname(darg)
442 sym = findsymbolicname(darg)
444 if sym:
443 if sym:
445 raise error.ParseError(_("keyword '%s' has no member") % sym)
444 raise error.ParseError(_("keyword '%s' has no member") % sym)
446 else:
445 else:
447 raise error.ParseError(_("%r has no member") % pycompat.bytestr(d))
446 raise error.ParseError(_("%r has no member") % pycompat.bytestr(d))
448
447
449 def runnegate(context, mapping, data):
448 def runnegate(context, mapping, data):
450 data = evalinteger(context, mapping, data,
449 data = evalinteger(context, mapping, data,
451 _('negation needs an integer argument'))
450 _('negation needs an integer argument'))
452 return -data
451 return -data
453
452
454 def runarithmetic(context, mapping, data):
453 def runarithmetic(context, mapping, data):
455 func, left, right = data
454 func, left, right = data
456 left = evalinteger(context, mapping, left,
455 left = evalinteger(context, mapping, left,
457 _('arithmetic only defined on integers'))
456 _('arithmetic only defined on integers'))
458 right = evalinteger(context, mapping, right,
457 right = evalinteger(context, mapping, right,
459 _('arithmetic only defined on integers'))
458 _('arithmetic only defined on integers'))
460 try:
459 try:
461 return func(left, right)
460 return func(left, right)
462 except ZeroDivisionError:
461 except ZeroDivisionError:
463 raise error.Abort(_('division by zero is not defined'))
462 raise error.Abort(_('division by zero is not defined'))
464
463
465 def getdictitem(dictarg, key):
464 def getdictitem(dictarg, key):
466 val = dictarg.get(key)
465 val = dictarg.get(key)
467 if val is None:
466 if val is None:
468 return
467 return
469 return wraphybridvalue(dictarg, key, val)
468 return wraphybridvalue(dictarg, key, val)
General Comments 0
You need to be logged in to leave comments. Login now