##// END OF EJS Templates
encoding: alias cp65001 to utf-8 on Windows...
encoding: alias cp65001 to utf-8 on Windows As far as I can tell, cp65001 is the Windows name for UTF-8. I don't know how different it is from the UTF-8, but Python 3 appears to have introduced new codec for cp65001, so the alias is enabled only for Python 2. https://bugs.python.org/issue13216 This patch is untested, but hopefully fixes the following issue. https://bitbucket.org/tortoisehg/thg/issues/5127/

File last commit:

r38468:bc8d9253 default
r38633:44302901 stable
Show More
templateutil.py
689 lines | 23.3 KiB | text/x-python | PythonLexer
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 # templateutil.py - utility for template evaluation
#
# Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 import abc
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 import types
from .i18n import _
from . import (
error,
pycompat,
util,
)
Yuya Nishihara
stringutil: bulk-replace call sites to point to new module...
r37102 from .utils import (
Yuya Nishihara
templater: factor out function that parses argument as date tuple
r37241 dateutil,
Yuya Nishihara
stringutil: bulk-replace call sites to point to new module...
r37102 stringutil,
)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931
class ResourceUnavailable(error.Abort):
pass
class TemplateNotFound(error.Abort):
pass
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 class wrapped(object):
"""Object requiring extra conversion prior to displaying or processing
Yuya Nishihara
templater: define interface for objects requiring unwrapvalue()...
r37297 as value
Use unwrapvalue(), unwrapastype(), or unwraphybrid() to obtain the inner
object.
"""
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
Yuya Nishihara
templater: pass context to itermaps() for future extension...
r37340 def itermaps(self, context):
Yuya Nishihara
templater: define interface for objects which act as iterator of mappings
r37339 """Yield each template mapping"""
@abc.abstractmethod
Yuya Nishihara
templater: abstract away from joinfmt...
r37343 def join(self, context, mapping, sep):
"""Join items with the separator; Returns a bytes or (possibly nested)
generator of bytes
A pre-configured template may be rendered per item if this container
holds unprintable items.
"""
@abc.abstractmethod
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 def show(self, context, mapping):
"""Return a bytes or (possibly nested) generator of bytes representing
the underlying object
A pre-configured template may be rendered if the underlying object is
not printable.
"""
Yuya Nishihara
templater: define interface for objects requiring unwrapvalue()...
r37297 @abc.abstractmethod
def tovalue(self, context, mapping):
"""Move the inner value object out or create a value representation
A returned value must be serializable by templaterfilters.json().
"""
Yuya Nishihara
templatefilters: declare input type as date where appropriate...
r37244 # stub for representing a date type; may be a real date type that can
# provide a readable string value
class date(object):
pass
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 class hybrid(wrapped):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 """Wrapper for list or dict to support legacy template
This class allows us to handle both:
- "{files}" (legacy command-line-specific list hack) and
- "{files % '{file}\n'}" (hgweb-style with inlining and function support)
and to access raw values:
- "{ifcontains(file, files, ...)}", "{ifcontains(key, extras, ...)}"
- "{get(extras, key)}"
- "{files|json}"
"""
def __init__(self, gen, values, makemap, joinfmt, keytype=None):
Yuya Nishihara
templater: factor out generator of join()-ed items...
r37341 self._gen = gen # generator or function returning generator
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 self._values = values
self._makemap = makemap
Yuya Nishihara
templater: mark .joinfmt as a private attribute
r37345 self._joinfmt = joinfmt
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 self.keytype = keytype # hint for 'x in y' where type(x) is unresolved
Yuya Nishihara
templater: mark .gen as a private attribute
r37293
Yuya Nishihara
templater: pass context to itermaps() for future extension...
r37340 def itermaps(self, context):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 makemap = self._makemap
for x in self._values:
yield makemap(x)
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291
Yuya Nishihara
templater: abstract away from joinfmt...
r37343 def join(self, context, mapping, sep):
# TODO: switch gen to (context, mapping) API?
Yuya Nishihara
templater: mark .joinfmt as a private attribute
r37345 return joinitems((self._joinfmt(x) for x in self._values), sep)
Yuya Nishihara
templater: abstract away from joinfmt...
r37343
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 def show(self, context, mapping):
# TODO: switch gen to (context, mapping) API?
Yuya Nishihara
templater: mark .gen as a private attribute
r37293 gen = self._gen
Yuya Nishihara
templater: factor out generator of join()-ed items...
r37341 if gen is None:
Yuya Nishihara
templater: abstract away from joinfmt...
r37343 return self.join(context, mapping, ' ')
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 if callable(gen):
return gen()
return gen
Yuya Nishihara
templater: define interface for objects requiring unwrapvalue()...
r37297 def tovalue(self, context, mapping):
# TODO: return self._values and get rid of proxy methods
return self
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 def __contains__(self, x):
return x in self._values
def __getitem__(self, key):
return self._values[key]
def __len__(self):
return len(self._values)
def __iter__(self):
return iter(self._values)
def __getattr__(self, name):
if name not in (r'get', r'items', r'iteritems', r'iterkeys',
r'itervalues', r'keys', r'values'):
raise AttributeError(name)
return getattr(self._values, name)
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 class mappable(wrapped):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 """Wrapper for non-list/dict object to support map operation
This class allows us to handle both:
- "{manifest}"
- "{manifest % '{rev}:{node}'}"
- "{manifest.rev}"
Unlike a hybrid, this does not simulate the behavior of the underling
Yuya Nishihara
templater: define interface for objects requiring unwrapvalue()...
r37297 value.
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 """
def __init__(self, gen, key, value, makemap):
Yuya Nishihara
templater: drop unneeded generator from mappable object...
r37294 self._gen = gen # generator or function returning generator
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 self._key = key
self._value = value # may be generator of strings
self._makemap = makemap
def tomap(self):
return self._makemap(self._key)
Yuya Nishihara
templater: pass context to itermaps() for future extension...
r37340 def itermaps(self, context):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 yield self.tomap()
Yuya Nishihara
templater: abstract away from joinfmt...
r37343 def join(self, context, mapping, sep):
# TODO: just copies the old behavior where a value was a generator
# yielding one item, but reconsider about it. join() over a string
# has no consistent result because a string may be a bytes, or a
# generator yielding an item, or a generator yielding multiple items.
# Preserving all of the current behaviors wouldn't make any sense.
return self.show(context, mapping)
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 def show(self, context, mapping):
# TODO: switch gen to (context, mapping) API?
Yuya Nishihara
templater: mark .gen as a private attribute
r37293 gen = self._gen
Yuya Nishihara
templater: drop unneeded generator from mappable object...
r37294 if gen is None:
return pycompat.bytestr(self._value)
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 if callable(gen):
return gen()
return gen
Yuya Nishihara
templater: define interface for objects requiring unwrapvalue()...
r37297 def tovalue(self, context, mapping):
return _unthunk(context, mapping, self._value)
Yuya Nishihara
templater: add class representing a nested mappings...
r37417 class _mappingsequence(wrapped):
"""Wrapper for sequence of template mappings
This represents an inner template structure (i.e. a list of dicts),
which can also be rendered by the specified named/literal template.
Template mappings may be nested.
"""
def __init__(self, name=None, tmpl=None, sep=''):
if name is not None and tmpl is not None:
raise error.ProgrammingError('name and tmpl are mutually exclusive')
self._name = name
self._tmpl = tmpl
self._defaultsep = sep
def join(self, context, mapping, sep):
mapsiter = _iteroverlaymaps(context, mapping, self.itermaps(context))
if self._name:
itemiter = (context.process(self._name, m) for m in mapsiter)
elif self._tmpl:
itemiter = (context.expand(self._tmpl, m) for m in mapsiter)
else:
raise error.ParseError(_('not displayable without template'))
return joinitems(itemiter, sep)
def show(self, context, mapping):
return self.join(context, mapping, self._defaultsep)
def tovalue(self, context, mapping):
Yuya Nishihara
formatter: remove template resources from nested items before generating JSON
r37520 knownres = context.knownresourcekeys()
items = []
for nm in self.itermaps(context):
# drop internal resources (recursively) which shouldn't be displayed
lm = context.overlaymap(mapping, nm)
items.append({k: unwrapvalue(context, lm, v)
for k, v in nm.iteritems() if k not in knownres})
return items
Yuya Nishihara
templater: add class representing a nested mappings...
r37417
class mappinggenerator(_mappingsequence):
"""Wrapper for generator of template mappings
The function ``make(context, *args)`` should return a generator of
mapping dicts.
"""
def __init__(self, make, args=(), name=None, tmpl=None, sep=''):
super(mappinggenerator, self).__init__(name, tmpl, sep)
self._make = make
self._args = args
def itermaps(self, context):
return self._make(context, *self._args)
class mappinglist(_mappingsequence):
"""Wrapper for list of template mappings"""
def __init__(self, mappings, name=None, tmpl=None, sep=''):
super(mappinglist, self).__init__(name, tmpl, sep)
self._mappings = mappings
def itermaps(self, context):
return iter(self._mappings)
Yuya Nishihara
templater: wrap result of '%' operation so it never looks like a thunk...
r37517 class mappedgenerator(wrapped):
"""Wrapper for generator of strings which acts as a list
The function ``make(context, *args)`` should return a generator of
byte strings, or a generator of (possibly nested) generators of byte
strings (i.e. a generator for a list of byte strings.)
"""
def __init__(self, make, args=()):
self._make = make
self._args = args
def _gen(self, context):
return self._make(context, *self._args)
def itermaps(self, context):
raise error.ParseError(_('list of strings is not mappable'))
def join(self, context, mapping, sep):
return joinitems(self._gen(context), sep)
def show(self, context, mapping):
return self.join(context, mapping, '')
def tovalue(self, context, mapping):
return [stringify(context, mapping, x) for x in self._gen(context)]
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 def hybriddict(data, key='key', value='value', fmt=None, gen=None):
"""Wrap data to support both dict-like and string-like operations"""
prefmt = pycompat.identity
if fmt is None:
fmt = '%s=%s'
prefmt = pycompat.bytestr
return hybrid(gen, data, lambda k: {key: k, value: data[k]},
lambda k: fmt % (prefmt(k), prefmt(data[k])))
def hybridlist(data, name, fmt=None, gen=None):
"""Wrap data to support both list-like and string-like operations"""
prefmt = pycompat.identity
if fmt is None:
fmt = '%s'
prefmt = pycompat.bytestr
return hybrid(gen, data, lambda x: {name: x}, lambda x: fmt % prefmt(x))
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 def unwraphybrid(context, mapping, thing):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 """Return an object which can be stringified possibly by using a legacy
template"""
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 if not isinstance(thing, wrapped):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 return thing
Yuya Nishihara
templater: define interface for objects requiring unwraphybrid()...
r37291 return thing.show(context, mapping)
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939
Yuya Nishihara
templater: pass (context, mapping) down to unwrapvalue()...
r37295 def unwrapvalue(context, mapping, thing):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 """Move the inner value object out of the wrapper"""
Yuya Nishihara
templater: define interface for objects requiring unwrapvalue()...
r37297 if not isinstance(thing, wrapped):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 return thing
Yuya Nishihara
templater: define interface for objects requiring unwrapvalue()...
r37297 return thing.tovalue(context, mapping)
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939
def wraphybridvalue(container, key, value):
"""Wrap an element of hybrid container to be mappable
The key is passed to the makemap function of the given container, which
should be an item generated by iter(container).
"""
makemap = getattr(container, '_makemap', None)
if makemap is None:
return value
if util.safehasattr(value, '_makemap'):
# a nested hybrid list/dict, which has its own way of map operation
return value
return mappable(None, key, value, makemap)
def compatdict(context, mapping, name, data, key='key', value='value',
fmt=None, plural=None, separator=' '):
"""Wrap data like hybriddict(), but also supports old-style list template
This exists for backward compatibility with the old-style template. Use
hybriddict() for new template keywords.
"""
c = [{key: k, value: v} for k, v in data.iteritems()]
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 f = _showcompatlist(context, mapping, name, c, plural, separator)
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 return hybriddict(data, key=key, value=value, fmt=fmt, gen=f)
def compatlist(context, mapping, name, data, element=None, fmt=None,
plural=None, separator=' '):
"""Wrap data like hybridlist(), but also supports old-style list template
This exists for backward compatibility with the old-style template. Use
hybridlist() for new template keywords.
"""
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 f = _showcompatlist(context, mapping, name, data, plural, separator)
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 return hybridlist(data, name=element or name, fmt=fmt, gen=f)
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 def _showcompatlist(context, mapping, name, values, plural=None, separator=' '):
"""Return a generator that renders old-style list template
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 name is name of key in template map.
values is list of strings or dicts.
plural is plural of name, if not simply name + 's'.
separator is used to join values as a string
expansion works like this, given name 'foo'.
if values is empty, expand 'no_foos'.
if 'foo' not in template map, return values as a string,
joined by 'separator'.
expand 'start_foos'.
for each value, expand 'foo'. if 'last_foo' in template
map, expand it instead of 'foo' for last key.
expand 'end_foos'.
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 """
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 if not plural:
plural = name + 's'
if not values:
noname = 'no_' + plural
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 if context.preload(noname):
yield context.process(noname, mapping)
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 return
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 if not context.preload(name):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 if isinstance(values[0], bytes):
yield separator.join(values)
else:
for v in values:
r = dict(v)
r.update(mapping)
yield r
return
startname = 'start_' + plural
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 if context.preload(startname):
yield context.process(startname, mapping)
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 def one(v, tag=name):
Yuya Nishihara
templater: factor out function to create mapping dict for nested evaluation...
r37092 vmapping = {}
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 try:
vmapping.update(v)
# Python 2 raises ValueError if the type of v is wrong. Python
# 3 raises TypeError.
except (AttributeError, TypeError, ValueError):
try:
# Python 2 raises ValueError trying to destructure an e.g.
# bytes. Python 3 raises TypeError.
for a, b in v:
vmapping[a] = b
except (TypeError, ValueError):
vmapping[name] = v
Yuya Nishihara
templater: factor out function to create mapping dict for nested evaluation...
r37092 vmapping = context.overlaymap(mapping, vmapping)
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 return context.process(tag, vmapping)
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 lastname = 'last_' + name
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 if context.preload(lastname):
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 last = values.pop()
else:
last = None
for v in values:
yield one(v)
if last is not None:
yield one(last, tag=lastname)
endname = 'end_' + plural
Yuya Nishihara
templater: use template context to render old-style list template...
r37086 if context.preload(endname):
yield context.process(endname, mapping)
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 def flatten(context, mapping, thing):
Yuya Nishihara
templateutil: move flatten() from templater...
r37174 """Yield a single stream from a possibly nested set of iterators"""
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 thing = unwraphybrid(context, mapping, thing)
Yuya Nishihara
templateutil: move flatten() from templater...
r37174 if isinstance(thing, bytes):
yield thing
elif isinstance(thing, str):
# We can only hit this on Python 3, and it's here to guard
# against infinite recursion.
raise error.ProgrammingError('Mercurial IO including templates is done'
' with bytes, not strings, got %r' % thing)
elif thing is None:
pass
elif not util.safehasattr(thing, '__iter__'):
yield pycompat.bytestr(thing)
else:
for i in thing:
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 i = unwraphybrid(context, mapping, i)
Yuya Nishihara
templateutil: move flatten() from templater...
r37174 if isinstance(i, bytes):
yield i
elif i is None:
pass
elif not util.safehasattr(i, '__iter__'):
yield pycompat.bytestr(i)
else:
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 for j in flatten(context, mapping, i):
Yuya Nishihara
templateutil: move flatten() from templater...
r37174 yield j
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 def stringify(context, mapping, thing):
Yuya Nishihara
templater: move stringify() to templateutil module...
r36938 """Turn values into bytes by converting into text and concatenating them"""
Yuya Nishihara
templateutil: reimplement stringify() using flatten()
r37175 if isinstance(thing, bytes):
return thing # retain localstr to be round-tripped
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 return b''.join(flatten(context, mapping, thing))
Yuya Nishihara
templater: move stringify() to templateutil module...
r36938
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 def findsymbolicname(arg):
"""Find symbolic name for the given compiled expression; returns None
if nothing found reliably"""
while True:
func, data = arg
if func is runsymbol:
return data
elif func is runfilter:
arg = data[0]
else:
return None
Yuya Nishihara
templater: extract private function to evaluate generator to byte string
r37296 def _unthunk(context, mapping, thing):
"""Evaluate a lazy byte string into value"""
if not isinstance(thing, types.GeneratorType):
return thing
return stringify(context, mapping, thing)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 def evalrawexp(context, mapping, arg):
"""Evaluate given argument as a bare template object which may require
further processing (such as folding generator of strings)"""
func, data = arg
return func(context, mapping, data)
def evalfuncarg(context, mapping, arg):
"""Evaluate given argument as value type"""
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 return _unwrapvalue(context, mapping, evalrawexp(context, mapping, arg))
Yuya Nishihara
templater: extract type conversion from evalfuncarg()...
r37178
# TODO: unify this with unwrapvalue() once the bug of templatefunc.join()
# is fixed. we can't do that right now because join() has to take a generator
# of byte strings as it is, not a lazy byte string.
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 def _unwrapvalue(context, mapping, thing):
Yuya Nishihara
templater: pass (context, mapping) down to unwrapvalue()...
r37295 thing = unwrapvalue(context, mapping, thing)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 # evalrawexp() may return string, generator of strings or arbitrary object
# such as date tuple, but filter does not want generator.
Yuya Nishihara
templater: extract private function to evaluate generator to byte string
r37296 return _unthunk(context, mapping, thing)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931
def evalboolean(context, mapping, arg):
"""Evaluate given argument as boolean, but also takes boolean literals"""
func, data = arg
if func is runsymbol:
thing = func(context, mapping, data, default=None)
if thing is None:
# not a template keyword, takes as a boolean literal
Yuya Nishihara
stringutil: bulk-replace call sites to point to new module...
r37102 thing = stringutil.parsebool(data)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 else:
thing = func(context, mapping, data)
Yuya Nishihara
templater: pass (context, mapping) down to unwrapvalue()...
r37295 thing = unwrapvalue(context, mapping, thing)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 if isinstance(thing, bool):
return thing
# other objects are evaluated as strings, which means 0 is True, but
# empty dict/list should be False as they are expected to be ''
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 return bool(stringify(context, mapping, thing))
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931
Yuya Nishihara
templater: factor out function that parses argument as date tuple
r37241 def evaldate(context, mapping, arg, err=None):
"""Evaluate given argument as a date tuple or a date string; returns
a (unixtime, offset) tuple"""
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 thing = evalrawexp(context, mapping, arg)
return unwrapdate(context, mapping, thing, err)
Yuya Nishihara
templater: factor out function that parses argument as date tuple
r37241
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 def unwrapdate(context, mapping, thing, err=None):
thing = _unwrapvalue(context, mapping, thing)
Yuya Nishihara
templater: factor out function that parses argument as date tuple
r37241 try:
return dateutil.parsedate(thing)
except AttributeError:
raise error.ParseError(err or _('not a date tuple nor a string'))
Yuya Nishihara
templatefuncs: use evaldate() where seems appropriate...
r37242 except error.ParseError:
if not err:
raise
raise error.ParseError(err)
Yuya Nishihara
templater: factor out function that parses argument as date tuple
r37241
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 def evalinteger(context, mapping, arg, err=None):
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 thing = evalrawexp(context, mapping, arg)
return unwrapinteger(context, mapping, thing, err)
Yuya Nishihara
templater: extract unwrapinteger() function from evalinteger()
r37179
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 def unwrapinteger(context, mapping, thing, err=None):
thing = _unwrapvalue(context, mapping, thing)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 try:
Yuya Nishihara
templater: extract unwrapinteger() function from evalinteger()
r37179 return int(thing)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 except (TypeError, ValueError):
raise error.ParseError(err or _('not an integer'))
def evalstring(context, mapping, arg):
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 return stringify(context, mapping, evalrawexp(context, mapping, arg))
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931
def evalstringliteral(context, mapping, arg):
"""Evaluate given argument as string template, but returns symbol name
if it is unknown"""
func, data = arg
if func is runsymbol:
thing = func(context, mapping, data, default=data)
else:
thing = func(context, mapping, data)
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 return stringify(context, mapping, thing)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931
Yuya Nishihara
templater: factor out unwrapastype() from evalastype()...
r37180 _unwrapfuncbytype = {
Yuya Nishihara
templatefilters: allow declaration of input data type...
r37239 None: _unwrapvalue,
Yuya Nishihara
templater: factor out unwrapastype() from evalastype()...
r37180 bytes: stringify,
Yuya Nishihara
templatefilters: declare input type as date where appropriate...
r37244 date: unwrapdate,
Yuya Nishihara
templater: factor out unwrapastype() from evalastype()...
r37180 int: unwrapinteger,
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 }
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 def unwrapastype(context, mapping, thing, typ):
Yuya Nishihara
templater: factor out unwrapastype() from evalastype()...
r37180 """Move the inner value object out of the wrapper and coerce its type"""
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 try:
Yuya Nishihara
templater: factor out unwrapastype() from evalastype()...
r37180 f = _unwrapfuncbytype[typ]
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 except KeyError:
raise error.ProgrammingError('invalid type specified: %r' % typ)
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 return f(context, mapping, thing)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931
def runinteger(context, mapping, data):
return int(data)
def runstring(context, mapping, data):
return data
def _recursivesymbolblocker(key):
def showrecursion(**args):
raise error.Abort(_("recursive reference '%s' in template") % key)
return showrecursion
def runsymbol(context, mapping, key, default=''):
v = context.symbol(mapping, key)
if v is None:
# put poison to cut recursion. we can't move this to parsing phase
# because "x = {x}" is allowed if "x" is a keyword. (issue4758)
safemapping = mapping.copy()
safemapping[key] = _recursivesymbolblocker(key)
try:
v = context.process(key, safemapping)
except TemplateNotFound:
v = default
if callable(v) and getattr(v, '_requires', None) is None:
# old templatekw: expand all keywords and resources
Yuya Nishihara
templater: drop 'templ' from resources dict...
r37088 # (TODO: deprecate this after porting web template keywords to new API)
Yuya Nishihara
templater: introduce resourcemapper class...
r37091 props = {k: context._resources.lookup(context, mapping, k)
for k in context._resources.knownkeys()}
Yuya Nishihara
templater: drop 'templ' from resources dict...
r37088 # pass context to _showcompatlist() through templatekw._showlist()
props['templ'] = context
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 props.update(mapping)
return v(**pycompat.strkwargs(props))
if callable(v):
# new templatekw
try:
return v(context, mapping)
except ResourceUnavailable:
# unsupported keyword is mapped to empty just like unknown keyword
return None
return v
def runtemplate(context, mapping, template):
for arg in template:
yield evalrawexp(context, mapping, arg)
def runfilter(context, mapping, data):
arg, filt = data
Yuya Nishihara
templatefilters: allow declaration of input data type...
r37239 thing = evalrawexp(context, mapping, arg)
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 intype = getattr(filt, '_intype', None)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 try:
Yuya Nishihara
templater: pass (context, mapping) down to unwraphybrid()...
r37290 thing = unwrapastype(context, mapping, thing, intype)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 return filt(thing)
Yuya Nishihara
templater: attach hint to input-type error of runfilter()...
r37243 except error.ParseError as e:
raise error.ParseError(bytes(e), hint=_formatfiltererror(arg, filt))
def _formatfiltererror(arg, filt):
fn = pycompat.sysbytes(filt.__name__)
sym = findsymbolicname(arg)
if not sym:
return _("incompatible use of template filter '%s'") % fn
return (_("template filter '%s' is not compatible with keyword '%s'")
% (fn, sym))
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931
Yuya Nishihara
templater: complain about invalid application of '%' operator (BC)...
r37422 def _checkeditermaps(darg, d):
try:
for v in d:
if not isinstance(v, dict):
raise TypeError
yield v
except TypeError:
sym = findsymbolicname(darg)
if sym:
raise error.ParseError(_("keyword '%s' is not iterable of mappings")
% sym)
else:
raise error.ParseError(_("%r is not iterable of mappings") % d)
Yuya Nishihara
templater: add class representing a nested mappings...
r37417 def _iteroverlaymaps(context, origmapping, newmappings):
"""Generate combined mappings from the original mapping and an iterable
of partial mappings to override the original"""
for i, nm in enumerate(newmappings):
lm = context.overlaymap(origmapping, nm)
lm['index'] = i
yield lm
Yuya Nishihara
templater: wrap result of '%' operation so it never looks like a thunk...
r37517 def _applymap(context, mapping, diter, targ):
for lm in _iteroverlaymaps(context, mapping, diter):
yield evalrawexp(context, lm, targ)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 def runmap(context, mapping, data):
darg, targ = data
d = evalrawexp(context, mapping, darg)
Yuya Nishihara
templater: complain about invalid application of '%' operator (BC)...
r37422 # TODO: a generator should be rejected because it is a thunk of lazy
# string, but we can't because hgweb abuses generator as a keyword
# that returns a list of dicts.
Yuya Nishihara
templater: wrap result of '%' operation so it never looks like a thunk...
r37517 # TODO: drop _checkeditermaps() and pass 'd' to mappedgenerator so it
# can be restarted.
Yuya Nishihara
templater: define interface for objects which act as iterator of mappings
r37339 if isinstance(d, wrapped):
Yuya Nishihara
templater: pass context to itermaps() for future extension...
r37340 diter = d.itermaps(context)
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 else:
Yuya Nishihara
templater: complain about invalid application of '%' operator (BC)...
r37422 diter = _checkeditermaps(darg, d)
Yuya Nishihara
templater: wrap result of '%' operation so it never looks like a thunk...
r37517 return mappedgenerator(_applymap, args=(mapping, diter, targ))
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931
def runmember(context, mapping, data):
darg, memb = data
d = evalrawexp(context, mapping, darg)
if util.safehasattr(d, 'tomap'):
Yuya Nishihara
templater: factor out function to create mapping dict for nested evaluation...
r37092 lm = context.overlaymap(mapping, d.tomap())
Yuya Nishihara
templater: extract template evaluation utility to new module...
r36931 return runsymbol(context, lm, memb)
if util.safehasattr(d, 'get'):
return getdictitem(d, memb)
sym = findsymbolicname(darg)
if sym:
raise error.ParseError(_("keyword '%s' has no member") % sym)
else:
raise error.ParseError(_("%r has no member") % pycompat.bytestr(d))
def runnegate(context, mapping, data):
data = evalinteger(context, mapping, data,
_('negation needs an integer argument'))
return -data
def runarithmetic(context, mapping, data):
func, left, right = data
left = evalinteger(context, mapping, left,
_('arithmetic only defined on integers'))
right = evalinteger(context, mapping, right,
_('arithmetic only defined on integers'))
try:
return func(left, right)
except ZeroDivisionError:
raise error.Abort(_('division by zero is not defined'))
def getdictitem(dictarg, key):
val = dictarg.get(key)
if val is None:
return
Yuya Nishihara
templater: move hybrid class and functions to templateutil module...
r36939 return wraphybridvalue(dictarg, key, val)
Yuya Nishihara
templater: factor out generator of join()-ed items...
r37341
def joinitems(itemiter, sep):
"""Join items with the separator; Returns generator of bytes"""
first = True
for x in itemiter:
if first:
first = False
Yuya Nishihara
templater: micro-optimize join() with empty separator
r37342 elif sep:
Yuya Nishihara
templater: factor out generator of join()-ed items...
r37341 yield sep
yield x