templater.py
1120 lines
| 36.6 KiB
| text/x-python
|
PythonLexer
/ mercurial / templater.py
|
r1909 | # templater.py - template expansion for output | ||
# | ||||
# Copyright 2005, 2006 Matt Mackall <mpm@selenic.com> | ||||
# | ||||
|
r8225 | # This software may be used and distributed according to the terms of the | ||
|
r10263 | # GNU General Public License version 2 or any later version. | ||
|
r1909 | |||
|
r37032 | """Slightly complicated template engine for commands and hgweb | ||
This module provides low-level interface to the template engine. See the | ||||
formatter and cmdutil modules if you are looking for high-level functions | ||||
such as ``cmdutil.rendertemplate(ctx, tmpl)``. | ||||
Internal Data Types | ||||
------------------- | ||||
Template keywords and functions take a dictionary of current symbols and | ||||
resources (a "mapping") and return result. Inputs and outputs must be one | ||||
of the following data types: | ||||
bytes | ||||
a byte string, which is generally a human-readable text in local encoding. | ||||
generator | ||||
a lazily-evaluated byte string, which is a possibly nested generator of | ||||
values of any printable types, and will be folded by ``stringify()`` | ||||
or ``flatten()``. | ||||
None | ||||
sometimes represents an empty value, which can be stringified to ''. | ||||
True, False, int, float | ||||
can be stringified as such. | ||||
|
r38228 | wrappedbytes, wrappedvalue | ||
a wrapper for the above printable types. | ||||
|
r38304 | date | ||
represents a (unixtime, offset) tuple. | ||||
|
r37032 | |||
hybrid | ||||
represents a list/dict of printable values, which can also be converted | ||||
to mappings by % operator. | ||||
|
r38302 | hybriditem | ||
|
r37032 | represents a scalar printable value, also supports % operator. | ||
|
r37417 | |||
|
r45080 | revslist | ||
represents a list of revision numbers. | ||||
|
r37417 | mappinggenerator, mappinglist | ||
represents mappings (i.e. a list of dicts), which may have default | ||||
output format. | ||||
|
r37517 | |||
|
r40509 | mappingdict | ||
represents a single mapping (i.e. a dict), which may have default output | ||||
format. | ||||
|
r40971 | mappingnone | ||
represents None of Optional[mappable], which will be mapped to an empty | ||||
string by % operation. | ||||
|
r37517 | mappedgenerator | ||
a lazily-evaluated list of byte strings, which is e.g. a result of % | ||||
operation. | ||||
|
r37032 | """ | ||
|
r34139 | from __future__ import absolute_import, print_function | ||
|
r25985 | |||
|
r37091 | import abc | ||
|
r25985 | import os | ||
from .i18n import _ | ||||
|
r43359 | from .pycompat import getattr | ||
|
r25985 | from . import ( | ||
config, | ||||
|
r31520 | encoding, | ||
|
r25985 | error, | ||
parser, | ||||
|
r30615 | pycompat, | ||
|
r25985 | templatefilters, | ||
|
r36940 | templatefuncs, | ||
|
r36931 | templateutil, | ||
|
r25985 | util, | ||
) | ||||
|
r44070 | from .utils import ( | ||
resourceutil, | ||||
stringutil, | ||||
) | ||||
|
r36461 | |||
|
r13176 | # template parsing | ||
elements = { | ||||
|
r25815 | # token-type: binding-strength, primary, prefix, infix, suffix | ||
|
r43347 | b"(": (20, None, (b"group", 1, b")"), (b"func", 1, b")"), None), | ||
b".": (18, None, None, (b".", 18), None), | ||||
b"%": (15, None, None, (b"%", 15), None), | ||||
b"|": (15, None, None, (b"|", 15), None), | ||||
b"*": (5, None, None, (b"*", 5), None), | ||||
b"/": (5, None, None, (b"/", 5), None), | ||||
b"+": (4, None, None, (b"+", 4), None), | ||||
b"-": (4, None, (b"negate", 19), (b"-", 4), None), | ||||
b"=": (3, None, None, (b"keyvalue", 3), None), | ||||
b",": (2, None, None, (b"list", 2), None), | ||||
b")": (0, None, None, None, None), | ||||
b"integer": (0, b"integer", None, None, None), | ||||
b"symbol": (0, b"symbol", None, None, None), | ||||
b"string": (0, b"string", None, None, None), | ||||
b"template": (0, b"template", None, None, None), | ||||
b"end": (0, None, None, None, None), | ||||
|
r13176 | } | ||
|
r43346 | |||
|
r28911 | def tokenize(program, start, end, term=None): | ||
"""Parse a template expression into a stream of tokens, which must end | ||||
with term if specified""" | ||||
|
r13176 | pos = start | ||
|
r32154 | program = pycompat.bytestr(program) | ||
|
r13176 | while pos < end: | ||
c = program[pos] | ||||
|
r43346 | if c.isspace(): # skip inter-token whitespace | ||
|
r13176 | pass | ||
|
r43347 | elif c in b"(=,).%|+-*/": # handle simple operators | ||
|
r13176 | yield (c, None, pos) | ||
|
r43347 | elif c in b'"\'': # handle quoted templates | ||
|
r25783 | s = pos + 1 | ||
data, pos = _parsetemplate(program, s, end, c) | ||||
|
r43347 | yield (b'template', data, s) | ||
|
r25783 | pos -= 1 | ||
|
r43347 | elif c == b'r' and program[pos : pos + 2] in (b"r'", b'r"'): | ||
|
r25784 | # handle quoted strings | ||
c = program[pos + 1] | ||||
s = pos = pos + 2 | ||||
|
r43346 | while pos < end: # find closing quote | ||
|
r13176 | d = program[pos] | ||
|
r43347 | if d == b'\\': # skip over escaped characters | ||
|
r13176 | pos += 2 | ||
continue | ||||
if d == c: | ||||
|
r43347 | yield (b'string', program[s:pos], s) | ||
|
r13176 | break | ||
pos += 1 | ||||
else: | ||||
|
r43347 | raise error.ParseError(_(b"unterminated string"), s) | ||
|
r30115 | elif c.isdigit(): | ||
|
r25002 | s = pos | ||
while pos < end: | ||||
d = program[pos] | ||||
if not d.isdigit(): | ||||
break | ||||
pos += 1 | ||||
|
r43347 | yield (b'integer', program[s:pos], s) | ||
|
r25002 | pos -= 1 | ||
|
r43346 | elif ( | ||
|
r43347 | c == b'\\' | ||
|
r43346 | and program[pos : pos + 2] in (br"\'", br'\"') | ||
|
r43347 | or c == b'r' | ||
|
r43346 | and program[pos : pos + 3] in (br"r\'", br'r\"') | ||
): | ||||
|
r25676 | # handle escaped quoted strings for compatibility with 2.9.2-3.4, | ||
# where some of nested templates were preprocessed as strings and | ||||
# then compiled. therefore, \"...\" was allowed. (issue4733) | ||||
# | ||||
# processing flow of _evalifliteral() at 5ab28a2e9962: | ||||
# outer template string -> stringify() -> compiletemplate() | ||||
# ------------------------ ------------ ------------------ | ||||
# {f("\\\\ {g(\"\\\"\")}"} \\ {g("\"")} [r'\\', {g("\"")}] | ||||
# ~~~~~~~~ | ||||
# escaped quoted string | ||||
|
r43347 | if c == b'r': | ||
|
r25676 | pos += 1 | ||
|
r43347 | token = b'string' | ||
|
r25676 | else: | ||
|
r43347 | token = b'template' | ||
|
r43346 | quote = program[pos : pos + 2] | ||
|
r25676 | s = pos = pos + 2 | ||
|
r43346 | while pos < end: # find closing escaped quote | ||
|
r43347 | if program.startswith(b'\\\\\\', pos, end): | ||
|
r43346 | pos += 4 # skip over double escaped characters | ||
|
r25676 | continue | ||
if program.startswith(quote, pos, end): | ||||
|
r26215 | # interpret as if it were a part of an outer string | ||
|
r26231 | data = parser.unescapestr(program[s:pos]) | ||
|
r43347 | if token == b'template': | ||
|
r25783 | data = _parsetemplate(data, 0, len(data))[0] | ||
|
r25676 | yield (token, data, s) | ||
pos += 1 | ||||
break | ||||
pos += 1 | ||||
else: | ||||
|
r43347 | raise error.ParseError(_(b"unterminated string"), s) | ||
elif c.isalnum() or c in b'_': | ||||
|
r13176 | s = pos | ||
pos += 1 | ||||
|
r43346 | while pos < end: # find end of symbol | ||
|
r13176 | d = program[pos] | ||
|
r43347 | if not (d.isalnum() or d == b"_"): | ||
|
r13176 | break | ||
pos += 1 | ||||
sym = program[s:pos] | ||||
|
r43347 | yield (b'symbol', sym, s) | ||
|
r13176 | pos -= 1 | ||
|
r28911 | elif c == term: | ||
|
r43347 | yield (b'end', None, pos) | ||
|
r25782 | return | ||
|
r13176 | else: | ||
|
r43347 | raise error.ParseError(_(b"syntax error"), pos) | ||
|
r13176 | pos += 1 | ||
|
r28911 | if term: | ||
|
r43347 | raise error.ParseError(_(b"unterminated template expansion"), start) | ||
yield (b'end', None, pos) | ||||
|
r13176 | |||
|
r43346 | |||
|
r43347 | def _parsetemplate(tmpl, start, stop, quote=b''): | ||
|
r25783 | r""" | ||
|
r34133 | >>> _parsetemplate(b'foo{bar}"baz', 0, 12) | ||
|
r25783 | ([('string', 'foo'), ('symbol', 'bar'), ('string', '"baz')], 12) | ||
|
r34133 | >>> _parsetemplate(b'foo{bar}"baz', 0, 12, quote=b'"') | ||
|
r25783 | ([('string', 'foo'), ('symbol', 'bar')], 9) | ||
|
r34133 | >>> _parsetemplate(b'foo"{bar}', 0, 9, quote=b'"') | ||
|
r25783 | ([('string', 'foo')], 4) | ||
|
r34133 | >>> _parsetemplate(br'foo\"bar"baz', 0, 12, quote=b'"') | ||
|
r25783 | ([('string', 'foo"'), ('string', 'bar')], 9) | ||
|
r34133 | >>> _parsetemplate(br'foo\\"bar', 0, 10, quote=b'"') | ||
|
r25785 | ([('string', 'foo\\')], 6) | ||
|
r25783 | """ | ||
|
r13176 | parsed = [] | ||
|
r36258 | for typ, val, pos in _scantemplate(tmpl, start, stop, quote): | ||
|
r43347 | if typ == b'string': | ||
|
r36258 | parsed.append((typ, val)) | ||
|
r43347 | elif typ == b'template': | ||
|
r36258 | parsed.append(val) | ||
|
r43347 | elif typ == b'end': | ||
|
r36258 | return parsed, pos | ||
else: | ||||
|
r43347 | raise error.ProgrammingError(b'unexpected type: %s' % typ) | ||
raise error.ProgrammingError(b'unterminated scanning of template') | ||||
|
r36258 | |||
|
r43346 | |||
|
r36527 | def scantemplate(tmpl, raw=False): | ||
r"""Scan (type, start, end) positions of outermost elements in template | ||||
If raw=True, a backslash is not taken as an escape character just like | ||||
r'' string in Python. Note that this is different from r'' literal in | ||||
template in that no template fragment can appear in r'', e.g. r'{foo}' | ||||
is a literal '{foo}', but ('{foo}', raw=True) is a template expression | ||||
'foo'. | ||||
|
r36259 | |||
>>> list(scantemplate(b'foo{bar}"baz')) | ||||
[('string', 0, 3), ('template', 3, 8), ('string', 8, 12)] | ||||
>>> list(scantemplate(b'outer{"inner"}outer')) | ||||
[('string', 0, 5), ('template', 5, 14), ('string', 14, 19)] | ||||
>>> list(scantemplate(b'foo\\{escaped}')) | ||||
[('string', 0, 5), ('string', 5, 13)] | ||||
|
r36527 | >>> list(scantemplate(b'foo\\{escaped}', raw=True)) | ||
[('string', 0, 4), ('template', 4, 13)] | ||||
|
r36259 | """ | ||
last = None | ||||
|
r36527 | for typ, val, pos in _scantemplate(tmpl, 0, len(tmpl), raw=raw): | ||
|
r36259 | if last: | ||
yield last + (pos,) | ||||
|
r43347 | if typ == b'end': | ||
|
r36259 | return | ||
else: | ||||
last = (typ, pos) | ||||
|
r43347 | raise error.ProgrammingError(b'unterminated scanning of template') | ||
|
r36259 | |||
|
r43346 | |||
|
r43347 | def _scantemplate(tmpl, start, stop, quote=b'', raw=False): | ||
|
r36258 | """Parse template string into chunks of strings and template expressions""" | ||
|
r43347 | sepchars = b'{' + quote | ||
|
r36527 | unescape = [parser.unescapestr, pycompat.identity][raw] | ||
|
r25781 | pos = start | ||
|
r25654 | p = parser.parser(elements) | ||
|
r36687 | try: | ||
while pos < stop: | ||||
|
r43346 | n = min( | ||
(tmpl.find(c, pos, stop) for c in pycompat.bytestr(sepchars)), | ||||
key=lambda n: (n < 0, n), | ||||
) | ||||
|
r36687 | if n < 0: | ||
|
r43347 | yield (b'string', unescape(tmpl[pos:stop]), pos) | ||
|
r36687 | pos = stop | ||
break | ||||
|
r43346 | c = tmpl[n : n + 1] | ||
|
r36687 | bs = 0 # count leading backslashes | ||
if not raw: | ||||
|
r43347 | bs = (n - pos) - len(tmpl[pos:n].rstrip(b'\\')) | ||
|
r36687 | if bs % 2 == 1: | ||
# escaped (e.g. '\{', '\\\{', but not '\\{') | ||||
|
r43347 | yield (b'string', unescape(tmpl[pos : n - 1]) + c, pos) | ||
|
r36687 | pos = n + 1 | ||
continue | ||||
if n > pos: | ||||
|
r43347 | yield (b'string', unescape(tmpl[pos:n]), pos) | ||
|
r36687 | if c == quote: | ||
|
r43347 | yield (b'end', None, n + 1) | ||
|
r36687 | return | ||
|
r13176 | |||
|
r43347 | parseres, pos = p.parse(tokenize(tmpl, n + 1, stop, b'}')) | ||
if not tmpl.startswith(b'}', pos): | ||||
raise error.ParseError(_(b"invalid token"), pos) | ||||
yield (b'template', parseres, n) | ||||
|
r36709 | pos += 1 | ||
|
r25783 | |||
|
r36687 | if quote: | ||
|
r43347 | raise error.ParseError(_(b"unterminated string"), start) | ||
|
r36687 | except error.ParseError as inst: | ||
|
r43368 | _addparseerrorhint(inst, tmpl) | ||
|
r36687 | raise | ||
|
r43347 | yield (b'end', None, pos) | ||
|
r13176 | |||
|
r43346 | |||
|
r43368 | def _addparseerrorhint(inst, tmpl): | ||
if len(inst.args) <= 1: | ||||
return # no location | ||||
loc = inst.args[1] | ||||
# Offset the caret location by the number of newlines before the | ||||
# location of the error, since we will replace one-char newlines | ||||
# with the two-char literal r'\n'. | ||||
offset = tmpl[:loc].count(b'\n') | ||||
tmpl = tmpl.replace(b'\n', br'\n') | ||||
# We want the caret to point to the place in the template that | ||||
# failed to parse, but in a hint we get a open paren at the | ||||
# start. Therefore, we print "loc + 1" spaces (instead of "loc") | ||||
# to line up the caret with the location of the error. | ||||
inst.hint = tmpl + b'\n' + b' ' * (loc + 1 + offset) + b'^ ' + _(b'here') | ||||
|
r28547 | def _unnesttemplatelist(tree): | ||
"""Expand list of templates to node tuple | ||||
>>> def f(tree): | ||||
|
r34139 | ... print(pycompat.sysstr(prettyformat(_unnesttemplatelist(tree)))) | ||
|
r34133 | >>> f((b'template', [])) | ||
|
r34075 | (string '') | ||
|
r34133 | >>> f((b'template', [(b'string', b'foo')])) | ||
|
r34075 | (string 'foo') | ||
|
r34133 | >>> f((b'template', [(b'string', b'foo'), (b'symbol', b'rev')])) | ||
|
r28547 | (template | ||
|
r34075 | (string 'foo') | ||
(symbol 'rev')) | ||||
|
r34133 | >>> f((b'template', [(b'symbol', b'rev')])) # template(rev) -> str | ||
|
r28547 | (template | ||
|
r34075 | (symbol 'rev')) | ||
|
r34133 | >>> f((b'template', [(b'template', [(b'string', b'foo')])])) | ||
|
r34075 | (string 'foo') | ||
|
r28547 | """ | ||
if not isinstance(tree, tuple): | ||||
return tree | ||||
op = tree[0] | ||||
|
r43347 | if op != b'template': | ||
|
r28547 | return (op,) + tuple(_unnesttemplatelist(x) for x in tree[1:]) | ||
assert len(tree) == 2 | ||||
xs = tuple(_unnesttemplatelist(x) for x in tree[1]) | ||||
if not xs: | ||||
|
r43347 | return (b'string', b'') # empty template "" | ||
elif len(xs) == 1 and xs[0][0] == b'string': | ||||
|
r28547 | return xs[0] # fast path for string with no template fragment "x" | ||
else: | ||||
return (op,) + xs | ||||
|
r43346 | |||
|
r28545 | def parse(tmpl): | ||
"""Parse template string into tree""" | ||||
|
r25781 | parsed, pos = _parsetemplate(tmpl, 0, len(tmpl)) | ||
|
r43347 | assert pos == len(tmpl), b'unquoted template should be consumed' | ||
return _unnesttemplatelist((b'template', parsed)) | ||||
|
r28547 | |||
|
r43346 | |||
|
r43368 | def parseexpr(expr): | ||
|
r28911 | """Parse a template expression into tree | ||
|
r43368 | >>> parseexpr(b'"foo"') | ||
|
r28911 | ('string', 'foo') | ||
|
r43368 | >>> parseexpr(b'foo(bar)') | ||
|
r28911 | ('func', ('symbol', 'foo'), ('symbol', 'bar')) | ||
|
r43368 | >>> parseexpr(b'foo(') | ||
|
r28911 | Traceback (most recent call last): | ||
... | ||||
ParseError: ('not a prefix: end', 4) | ||||
|
r43368 | >>> parseexpr(b'"foo" "bar"') | ||
|
r28911 | Traceback (most recent call last): | ||
... | ||||
ParseError: ('invalid token', 7) | ||||
""" | ||||
|
r43368 | try: | ||
return _parseexpr(expr) | ||||
except error.ParseError as inst: | ||||
_addparseerrorhint(inst, expr) | ||||
raise | ||||
def _parseexpr(expr): | ||||
|
r28911 | p = parser.parser(elements) | ||
tree, pos = p.parse(tokenize(expr, 0, len(expr))) | ||||
if pos != len(expr): | ||||
|
r43347 | raise error.ParseError(_(b'invalid token'), pos) | ||
|
r28911 | return _unnesttemplatelist(tree) | ||
|
r43346 | |||
|
r28547 | def prettyformat(tree): | ||
|
r43347 | return parser.prettyformat(tree, (b'integer', b'string', b'symbol')) | ||
|
r28545 | |||
|
r43346 | |||
|
r25001 | def compileexp(exp, context, curmethods): | ||
|
r28956 | """Compile parsed template tree to (func, data) pair""" | ||
|
r35762 | if not exp: | ||
|
r43347 | raise error.ParseError(_(b"missing argument")) | ||
|
r13176 | t = exp[0] | ||
|
r40652 | return curmethods[t](exp, context) | ||
|
r13176 | |||
|
r43346 | |||
|
r13176 | # template evaluation | ||
|
r43346 | |||
|
r13176 | def getsymbol(exp): | ||
|
r43347 | if exp[0] == b'symbol': | ||
|
r13176 | return exp[1] | ||
|
r43347 | raise error.ParseError(_(b"expected a symbol, got '%s'") % exp[0]) | ||
|
r13176 | |||
|
r43346 | |||
|
r13176 | def getlist(x): | ||
if not x: | ||||
return [] | ||||
|
r43347 | if x[0] == b'list': | ||
|
r13176 | return getlist(x[1]) + [x[2]] | ||
return [x] | ||||
|
r43346 | |||
|
r13176 | def gettemplate(exp, context): | ||
|
r28545 | """Compile given template tree or load named template from map file; | ||
returns (func, data) pair""" | ||||
|
r43347 | if exp[0] in (b'template', b'string'): | ||
|
r28545 | return compileexp(exp, context, methods) | ||
|
r43347 | if exp[0] == b'symbol': | ||
|
r25599 | # unlike runsymbol(), here 'symbol' is always taken as template name | ||
# even if it exists in mapping. this allows us to override mapping | ||||
# by web templates, e.g. 'changelogtag' is redefined in map file. | ||||
|
r13176 | return context._load(exp[1]) | ||
|
r43347 | raise error.ParseError(_(b"expected template specifier")) | ||
|
r13176 | |||
|
r43346 | |||
|
r27940 | def _runrecursivesymbol(context, mapping, key): | ||
|
r43347 | raise error.Abort(_(b"recursive reference '%s' in template") % key) | ||
|
r27940 | |||
|
r43346 | |||
|
r25596 | def buildtemplate(exp, context): | ||
|
r28547 | ctmpl = [compileexp(e, context, methods) for e in exp[1:]] | ||
|
r36931 | return (templateutil.runtemplate, ctmpl) | ||
|
r25595 | |||
|
r43346 | |||
|
r13176 | def buildfilter(exp, context): | ||
|
r26104 | n = getsymbol(exp[2]) | ||
if n in context._filters: | ||||
filt = context._filters[n] | ||||
|
r31886 | arg = compileexp(exp[1], context, methods) | ||
|
r36931 | return (templateutil.runfilter, (arg, filt)) | ||
|
r36930 | if n in context._funcs: | ||
f = context._funcs[n] | ||||
|
r31886 | args = _buildfuncargs(exp[1], context, methods, n, f._argspec) | ||
return (f, args) | ||||
|
r43347 | raise error.ParseError(_(b"unknown function '%s'") % n) | ||
|
r13176 | |||
|
r43346 | |||
|
r13176 | def buildmap(exp, context): | ||
|
r34326 | darg = compileexp(exp[1], context, methods) | ||
targ = gettemplate(exp[2], context) | ||||
|
r36931 | return (templateutil.runmap, (darg, targ)) | ||
|
r13176 | |||
|
r43346 | |||
|
r34536 | def buildmember(exp, context): | ||
darg = compileexp(exp[1], context, methods) | ||||
memb = getsymbol(exp[2]) | ||||
|
r36931 | return (templateutil.runmember, (darg, memb)) | ||
|
r34536 | |||
|
r43346 | |||
|
r30115 | def buildnegate(exp, context): | ||
arg = compileexp(exp[1], context, exprmethods) | ||||
|
r36931 | return (templateutil.runnegate, arg) | ||
|
r30115 | |||
|
r43346 | |||
|
r30115 | def buildarithmetic(exp, context, func): | ||
left = compileexp(exp[1], context, exprmethods) | ||||
right = compileexp(exp[2], context, exprmethods) | ||||
|
r36931 | return (templateutil.runarithmetic, (func, left, right)) | ||
|
r30115 | |||
|
r43346 | |||
|
r13176 | def buildfunc(exp, context): | ||
n = getsymbol(exp[1]) | ||||
|
r36930 | if n in context._funcs: | ||
f = context._funcs[n] | ||||
|
r31886 | args = _buildfuncargs(exp[2], context, exprmethods, n, f._argspec) | ||
|
r14925 | return (f, args) | ||
|
r13176 | if n in context._filters: | ||
|
r31886 | args = _buildfuncargs(exp[2], context, exprmethods, n, argspec=None) | ||
|
r13176 | if len(args) != 1: | ||
|
r43347 | raise error.ParseError(_(b"filter %s expects one argument") % n) | ||
|
r13176 | f = context._filters[n] | ||
|
r36931 | return (templateutil.runfilter, (args[0], f)) | ||
|
r43347 | raise error.ParseError(_(b"unknown function '%s'") % n) | ||
|
r13176 | |||
|
r43346 | |||
|
r31886 | def _buildfuncargs(exp, context, curmethods, funcname, argspec): | ||
"""Compile parsed tree of function arguments into list or dict of | ||||
|
r31921 | (func, data) pairs | ||
|
r37002 | >>> context = engine(lambda t: (templateutil.runsymbol, t)) | ||
|
r31921 | >>> def fargs(expr, argspec): | ||
... x = _parseexpr(expr) | ||||
... n = getsymbol(x[1]) | ||||
... return _buildfuncargs(x[2], context, exprmethods, n, argspec) | ||||
|
r34141 | >>> list(fargs(b'a(l=1, k=2)', b'k l m').keys()) | ||
|
r31922 | ['l', 'k'] | ||
|
r34133 | >>> args = fargs(b'a(opts=1, k=2)', b'**opts') | ||
|
r34141 | >>> list(args.keys()), list(args[b'opts'].keys()) | ||
|
r31922 | (['opts'], ['opts', 'k']) | ||
|
r31921 | """ | ||
|
r43346 | |||
|
r31886 | def compiledict(xs): | ||
|
r43346 | return util.sortdict( | ||
|
r43376 | (k, compileexp(x, context, curmethods)) | ||
for k, x in pycompat.iteritems(xs) | ||||
|
r43346 | ) | ||
|
r31886 | def compilelist(xs): | ||
return [compileexp(x, context, curmethods) for x in xs] | ||||
if not argspec: | ||||
# filter or function with no argspec: return list of positional args | ||||
return compilelist(getlist(exp)) | ||||
# function with argspec: return dict of named args | ||||
|
r31921 | _poskeys, varkey, _keys, optkey = argspec = parser.splitargspec(argspec) | ||
|
r43346 | treeargs = parser.buildargsdict( | ||
getlist(exp), | ||||
funcname, | ||||
argspec, | ||||
|
r43347 | keyvaluenode=b'keyvalue', | ||
keynode=b'symbol', | ||||
|
r43346 | ) | ||
|
r31922 | compargs = util.sortdict() | ||
|
r31886 | if varkey: | ||
compargs[varkey] = compilelist(treeargs.pop(varkey)) | ||||
|
r31921 | if optkey: | ||
compargs[optkey] = compiledict(treeargs.pop(optkey)) | ||||
|
r31886 | compargs.update(compiledict(treeargs)) | ||
return compargs | ||||
|
r43346 | |||
|
r31885 | def buildkeyvaluepair(exp, content): | ||
|
r43347 | raise error.ParseError(_(b"can't use a key-value pair in this context")) | ||
|
r31885 | |||
|
r43346 | |||
|
r40652 | def buildlist(exp, context): | ||
|
r43346 | raise error.ParseError( | ||
|
r43347 | _(b"can't use a list in this context"), | ||
hint=_(b'check place of comma and parens'), | ||||
|
r43346 | ) | ||
|
r40652 | |||
|
r25001 | # methods to interpret function arguments or inner expressions (e.g. {_(x)}) | ||
exprmethods = { | ||||
|
r43347 | b"integer": lambda e, c: (templateutil.runinteger, e[1]), | ||
b"string": lambda e, c: (templateutil.runstring, e[1]), | ||||
b"symbol": lambda e, c: (templateutil.runsymbol, e[1]), | ||||
b"template": buildtemplate, | ||||
b"group": lambda e, c: compileexp(e[1], c, exprmethods), | ||||
b".": buildmember, | ||||
b"|": buildfilter, | ||||
b"%": buildmap, | ||||
b"func": buildfunc, | ||||
b"keyvalue": buildkeyvaluepair, | ||||
b"list": buildlist, | ||||
b"+": lambda e, c: buildarithmetic(e, c, lambda a, b: a + b), | ||||
b"-": lambda e, c: buildarithmetic(e, c, lambda a, b: a - b), | ||||
b"negate": buildnegate, | ||||
b"*": lambda e, c: buildarithmetic(e, c, lambda a, b: a * b), | ||||
b"/": lambda e, c: buildarithmetic(e, c, lambda a, b: a // b), | ||||
|
r43346 | } | ||
|
r13176 | |||
|
r25001 | # methods to interpret top-level template (e.g. {x}, {x|_}, {x % "y"}) | ||
methods = exprmethods.copy() | ||||
|
r43347 | methods[b"integer"] = exprmethods[b"symbol"] # '{1}' as variable | ||
|
r25001 | |||
|
r43346 | |||
|
r28912 | class _aliasrules(parser.basealiasrules): | ||
"""Parsing and expansion rule set of template aliases""" | ||||
|
r43346 | |||
|
r43347 | _section = _(b'template alias') | ||
|
r28912 | _parse = staticmethod(_parseexpr) | ||
@staticmethod | ||||
def _trygetfunc(tree): | ||||
"""Return (name, args) if tree is func(...) or ...|filter; otherwise | ||||
None""" | ||||
|
r43347 | if tree[0] == b'func' and tree[1][0] == b'symbol': | ||
|
r28912 | return tree[1][1], getlist(tree[2]) | ||
|
r43347 | if tree[0] == b'|' and tree[2][0] == b'symbol': | ||
|
r28912 | return tree[2][1], [tree[1]] | ||
|
r43346 | |||
|
r28912 | def expandaliases(tree, aliases): | ||
"""Return new tree of aliases are expanded""" | ||||
aliasmap = _aliasrules.buildmap(aliases) | ||||
return _aliasrules.expand(aliasmap, tree) | ||||
|
r43346 | |||
|
r13176 | # template engine | ||
|
r1901 | |||
|
r43346 | |||
|
r24988 | def unquotestring(s): | ||
|
r28630 | '''unwrap quotes if any; otherwise returns unmodified string''' | ||
|
r43347 | if len(s) < 2 or s[0] not in b"'\"" or s[0] != s[-1]: | ||
|
r28630 | return s | ||
|
r25696 | return s[1:-1] | ||
|
r1896 | |||
|
r43346 | |||
|
r43775 | class resourcemapper(object): # pytype: disable=ignored-metaclass | ||
|
r37091 | """Mapper of internal template resources""" | ||
__metaclass__ = abc.ABCMeta | ||||
@abc.abstractmethod | ||||
|
r39618 | def availablekeys(self, mapping): | ||
|
r37093 | """Return a set of available resource keys based on the given mapping""" | ||
@abc.abstractmethod | ||||
|
r37091 | def knownkeys(self): | ||
"""Return a set of supported resource keys""" | ||||
@abc.abstractmethod | ||||
|
r39618 | def lookup(self, mapping, key): | ||
|
r37091 | """Return a resource for the key if available; otherwise None""" | ||
|
r37120 | @abc.abstractmethod | ||
def populatemap(self, context, origmapping, newmapping): | ||||
"""Return a dict of additional mapping items which should be paired | ||||
with the given new mapping""" | ||||
|
r43346 | |||
|
r37091 | class nullresourcemapper(resourcemapper): | ||
|
r39618 | def availablekeys(self, mapping): | ||
|
r37093 | return set() | ||
|
r37091 | def knownkeys(self): | ||
return set() | ||||
|
r39618 | def lookup(self, mapping, key): | ||
|
r37091 | return None | ||
|
r37120 | def populatemap(self, context, origmapping, newmapping): | ||
return {} | ||||
|
r43346 | |||
|
r8218 | class engine(object): | ||
|
r1909 | '''template expansion engine. | ||
template expansion works like this. a map file contains key=value | ||||
pairs. if value is quoted, it is treated as string. otherwise, it | ||||
is treated as name of template file. | ||||
templater is asked to expand a key in map. it looks up key, and | ||||
|
r4334 | looks for strings like this: {foo}. it expands {foo} by looking up | ||
|
r1909 | foo in map, and substituting it. expansion is recursive: it stops | ||
when there is no more {foo} to replace. | ||||
expansion also allows formatting and filtering. | ||||
format uses key to expand each item in list. syntax is | ||||
{key%format}. | ||||
filter uses function to transform value. syntax is | ||||
{key|filter1|filter2|...}.''' | ||||
|
r38373 | def __init__(self, loader, filters=None, defaults=None, resources=None): | ||
|
r10848 | self._loader = loader | ||
|
r26330 | if filters is None: | ||
filters = {} | ||||
|
r10848 | self._filters = filters | ||
|
r36940 | self._funcs = templatefuncs.funcs # make this a parameter if needed | ||
|
r26331 | if defaults is None: | ||
defaults = {} | ||||
|
r35484 | if resources is None: | ||
|
r37091 | resources = nullresourcemapper() | ||
|
r10848 | self._defaults = defaults | ||
|
r35484 | self._resources = resources | ||
|
r28545 | self._cache = {} # key: (func, data) | ||
|
r37416 | self._tmplcache = {} # literal template: (func, data) | ||
|
r8218 | |||
|
r37092 | def overlaymap(self, origmapping, newmapping): | ||
"""Create combined mapping from the original mapping and partial | ||||
mapping to override the original""" | ||||
|
r37093 | # do not copy symbols which overrides the defaults depending on | ||
# new resources, so the defaults will be re-evaluated (issue5612) | ||||
knownres = self._resources.knownkeys() | ||||
|
r39618 | newres = self._resources.availablekeys(newmapping) | ||
|
r43346 | mapping = { | ||
k: v | ||||
|
r43376 | for k, v in pycompat.iteritems(origmapping) | ||
|
r43346 | if ( | ||
k in knownres # not a symbol per self.symbol() | ||||
or newres.isdisjoint(self._defaultrequires(k)) | ||||
) | ||||
} | ||||
|
r37092 | mapping.update(newmapping) | ||
|
r37120 | mapping.update( | ||
|
r43346 | self._resources.populatemap(self, origmapping, newmapping) | ||
) | ||||
|
r37092 | return mapping | ||
|
r37093 | def _defaultrequires(self, key): | ||
"""Resource keys required by the specified default symbol function""" | ||||
v = self._defaults.get(key) | ||||
if v is None or not callable(v): | ||||
return () | ||||
return getattr(v, '_requires', ()) | ||||
|
r35483 | def symbol(self, mapping, key): | ||
"""Resolve symbol to value or function; None if nothing found""" | ||||
|
r35486 | v = None | ||
|
r37091 | if key not in self._resources.knownkeys(): | ||
|
r35486 | v = mapping.get(key) | ||
|
r35483 | if v is None: | ||
v = self._defaults.get(key) | ||||
return v | ||||
|
r37519 | def availableresourcekeys(self, mapping): | ||
"""Return a set of available resource keys based on the given mapping""" | ||||
|
r39618 | return self._resources.availablekeys(mapping) | ||
|
r37519 | |||
def knownresourcekeys(self): | ||||
"""Return a set of supported resource keys""" | ||||
return self._resources.knownkeys() | ||||
|
r35483 | def resource(self, mapping, key): | ||
"""Return internal data (e.g. cache) used for keyword/function | ||||
evaluation""" | ||||
|
r39618 | v = self._resources.lookup(mapping, key) | ||
|
r35484 | if v is None: | ||
|
r36931 | raise templateutil.ResourceUnavailable( | ||
|
r43347 | _(b'template resource not available: %s') % key | ||
|
r43346 | ) | ||
|
r35484 | return v | ||
|
r35483 | |||
|
r13176 | def _load(self, t): | ||
'''load, parse, and cache a template''' | ||||
if t not in self._cache: | ||||
|
r38373 | x = self._loader(t) | ||
|
r27940 | # put poison to cut recursion while compiling 't' | ||
|
r28545 | self._cache[t] = (_runrecursivesymbol, t) | ||
|
r27940 | try: | ||
|
r28956 | self._cache[t] = compileexp(x, self, methods) | ||
|
r43346 | except: # re-raises | ||
|
r27940 | del self._cache[t] | ||
raise | ||||
|
r13176 | return self._cache[t] | ||
|
r37416 | def _parse(self, tmpl): | ||
"""Parse and cache a literal template""" | ||||
if tmpl not in self._tmplcache: | ||||
x = parse(tmpl) | ||||
self._tmplcache[tmpl] = compileexp(x, self, methods) | ||||
return self._tmplcache[tmpl] | ||||
|
r37085 | def preload(self, t): | ||
"""Load, parse, and cache the specified template if available""" | ||||
try: | ||||
self._load(t) | ||||
return True | ||||
except templateutil.TemplateNotFound: | ||||
return False | ||||
|
r10853 | def process(self, t, mapping): | ||
'''Perform expansion. t is name of map element to expand. | ||||
mapping contains added elements for use during expansion. Is a | ||||
generator.''' | ||||
|
r28545 | func, data = self._load(t) | ||
|
r37416 | return self._expand(func, data, mapping) | ||
def expand(self, tmpl, mapping): | ||||
"""Perform expansion over a literal template | ||||
No user aliases will be expanded since this is supposed to be called | ||||
with an internal template string. | ||||
""" | ||||
func, data = self._parse(tmpl) | ||||
return self._expand(func, data, mapping) | ||||
def _expand(self, func, data, mapping): | ||||
|
r37120 | # populate additional items only if they don't exist in the given | ||
# mapping. this is slightly different from overlaymap() because the | ||||
# initial 'revcache' may contain pre-computed items. | ||||
extramapping = self._resources.populatemap(self, {}, mapping) | ||||
if extramapping: | ||||
extramapping.update(mapping) | ||||
mapping = extramapping | ||||
|
r37290 | return templateutil.flatten(self, mapping, func(self, mapping, data)) | ||
|
r8218 | |||
|
r43346 | |||
|
r19125 | def stylelist(): | ||
|
r45755 | path = templatedir() | ||
if not path: | ||||
|
r43347 | return _(b'no templates found, try `hg debuginstall` for more info') | ||
|
r45755 | dirlist = os.listdir(path) | ||
|
r19125 | stylelist = [] | ||
for file in dirlist: | ||||
|
r43347 | split = file.split(b".") | ||
if split[-1] in (b'orig', b'rej'): | ||||
|
r28403 | continue | ||
|
r43347 | if split[0] == b"map-cmdline": | ||
|
r19125 | stylelist.append(split[1]) | ||
|
r43347 | return b", ".join(sorted(stylelist)) | ||
|
r19125 | |||
|
r43346 | |||
|
r45868 | def _open_mapfile(mapfile): | ||
if os.path.exists(mapfile): | ||||
return util.posixfile(mapfile, b'rb') | ||||
raise error.Abort( | ||||
_(b"style '%s' not found") % mapfile, | ||||
hint=_(b"available styles: %s") % stylelist(), | ||||
) | ||||
def _readmapfile(fp, mapfile): | ||||
|
r28953 | """Load template elements from the given map file""" | ||
base = os.path.dirname(mapfile) | ||||
|
r45770 | conf = config.config() | ||
|
r45769 | |||
|
r45817 | def include(rel, remap, sections): | ||
|
r45872 | subresource = None | ||
if base: | ||||
abs = os.path.normpath(os.path.join(base, rel)) | ||||
|
r45770 | if os.path.isfile(abs): | ||
|
r45872 | subresource = util.posixfile(abs, b'rb') | ||
if not subresource: | ||||
|
r45873 | if pycompat.ossep not in rel: | ||
abs = rel | ||||
subresource = resourceutil.open_resource( | ||||
b'mercurial.templates', rel | ||||
) | ||||
else: | ||||
dir = templatedir() | ||||
if dir: | ||||
abs = os.path.normpath(os.path.join(dir, rel)) | ||||
if os.path.isfile(abs): | ||||
subresource = util.posixfile(abs, b'rb') | ||||
|
r45872 | if subresource: | ||
data = subresource.read() | ||||
conf.parse( | ||||
abs, data, sections=sections, remap=remap, include=include, | ||||
) | ||||
|
r45769 | |||
|
r45868 | data = fp.read() | ||
|
r45769 | conf.parse(mapfile, data, remap={b'': b'templates'}, include=include) | ||
|
r28953 | |||
cache = {} | ||||
tmap = {} | ||||
|
r34716 | aliases = [] | ||
|
r34713 | |||
|
r43347 | val = conf.get(b'templates', b'__base__') | ||
if val and val[0] not in b"'\"": | ||||
|
r34713 | # treat as a pointer to a base class for this style | ||
|
r45821 | path = os.path.normpath(os.path.join(base, val)) | ||
|
r34713 | |||
# fallback check in template paths | ||||
if not os.path.exists(path): | ||||
|
r45773 | dir = templatedir() | ||
if dir is not None: | ||||
|
r45821 | p2 = os.path.normpath(os.path.join(dir, val)) | ||
|
r45773 | if os.path.isfile(p2): | ||
path = p2 | ||||
else: | ||||
|
r45821 | p3 = os.path.normpath(os.path.join(p2, b"map")) | ||
|
r45773 | if os.path.isfile(p3): | ||
path = p3 | ||||
|
r34713 | |||
|
r45868 | fp = _open_mapfile(path) | ||
cache, tmap, aliases = _readmapfile(fp, path) | ||||
|
r34713 | |||
|
r43347 | for key, val in conf[b'templates'].items(): | ||
|
r28953 | if not val: | ||
|
r43346 | raise error.ParseError( | ||
|
r43347 | _(b'missing value'), conf.source(b'templates', key) | ||
|
r43346 | ) | ||
|
r43347 | if val[0] in b"'\"": | ||
|
r28953 | if val[0] != val[-1]: | ||
|
r43346 | raise error.ParseError( | ||
|
r43347 | _(b'unmatched quotes'), conf.source(b'templates', key) | ||
|
r43346 | ) | ||
|
r28953 | cache[key] = unquotestring(val) | ||
|
r43347 | elif key != b'__base__': | ||
|
r38372 | tmap[key] = os.path.join(base, val) | ||
|
r43347 | aliases.extend(conf[b'templatealias'].items()) | ||
|
r34716 | return cache, tmap, aliases | ||
|
r28953 | |||
|
r43346 | |||
|
r38457 | class loader(object): | ||
"""Load template fragments optionally from a map file""" | ||||
|
r35497 | |||
|
r38457 | def __init__(self, cache, aliases): | ||
|
r26334 | if cache is None: | ||
cache = {} | ||||
|
r1975 | self.cache = cache.copy() | ||
|
r38370 | self._map = {} | ||
|
r38373 | self._aliasmap = _aliasrules.buildmap(aliases) | ||
|
r1896 | |||
|
r1899 | def __contains__(self, key): | ||
|
r38370 | return key in self.cache or key in self._map | ||
|
r1899 | |||
|
r8218 | def load(self, t): | ||
|
r38373 | """Get parsed tree for the given template name. Use a local cache.""" | ||
|
r16686 | if t not in self.cache: | ||
|
r1905 | try: | ||
|
r45882 | mapfile, fp = open_template(self._map[t]) | ||
self.cache[t] = fp.read() | ||||
|
r25660 | except KeyError as inst: | ||
|
r36931 | raise templateutil.TemplateNotFound( | ||
|
r43347 | _(b'"%s" not in template map') % inst.args[0] | ||
|
r43346 | ) | ||
|
r25660 | except IOError as inst: | ||
|
r43347 | reason = _(b'template file %s: %s') % ( | ||
|
r43346 | self._map[t], | ||
stringutil.forcebytestr(inst.args[1]), | ||||
) | ||||
|
r36518 | raise IOError(inst.args[0], encoding.strfromlocal(reason)) | ||
|
r38373 | return self._parse(self.cache[t]) | ||
def _parse(self, tmpl): | ||||
x = parse(tmpl) | ||||
if self._aliasmap: | ||||
x = _aliasrules.expand(self._aliasmap, x) | ||||
return x | ||||
|
r1896 | |||
|
r38374 | def _findsymbolsused(self, tree, syms): | ||
if not tree: | ||||
return | ||||
op = tree[0] | ||||
|
r43347 | if op == b'symbol': | ||
|
r38374 | s = tree[1] | ||
if s in syms[0]: | ||||
|
r43346 | return # avoid recursion: s -> cache[s] -> s | ||
|
r38374 | syms[0].add(s) | ||
if s in self.cache or s in self._map: | ||||
# s may be a reference for named template | ||||
self._findsymbolsused(self.load(s), syms) | ||||
return | ||||
|
r43347 | if op in {b'integer', b'string'}: | ||
|
r38374 | return | ||
# '{arg|func}' == '{func(arg)}' | ||||
|
r43347 | if op == b'|': | ||
|
r38374 | syms[1].add(getsymbol(tree[2])) | ||
self._findsymbolsused(tree[1], syms) | ||||
return | ||||
|
r43347 | if op == b'func': | ||
|
r38374 | syms[1].add(getsymbol(tree[1])) | ||
self._findsymbolsused(tree[2], syms) | ||||
return | ||||
for x in tree[1:]: | ||||
self._findsymbolsused(x, syms) | ||||
|
r38457 | def symbolsused(self, t): | ||
"""Look up (keywords, filters/functions) referenced from the name | ||||
template 't' | ||||
This may load additional templates from the map file. | ||||
""" | ||||
syms = (set(), set()) | ||||
self._findsymbolsused(self.load(t), syms) | ||||
return syms | ||||
|
r43346 | |||
|
r38457 | class templater(object): | ||
|
r43346 | def __init__( | ||
self, | ||||
filters=None, | ||||
defaults=None, | ||||
resources=None, | ||||
cache=None, | ||||
aliases=(), | ||||
minchunk=1024, | ||||
maxchunk=65536, | ||||
): | ||||
|
r38457 | """Create template engine optionally with preloaded template fragments | ||
- ``filters``: a dict of functions to transform a value into another. | ||||
- ``defaults``: a dict of symbol values/functions; may be overridden | ||||
by a ``mapping`` dict. | ||||
- ``resources``: a resourcemapper object to look up internal data | ||||
(e.g. cache), inaccessible from user template. | ||||
- ``cache``: a dict of preloaded template fragments. | ||||
- ``aliases``: a list of alias (name, replacement) pairs. | ||||
self.cache may be updated later to register additional template | ||||
fragments. | ||||
""" | ||||
|
r38459 | allfilters = templatefilters.filters.copy() | ||
if filters: | ||||
allfilters.update(filters) | ||||
|
r38457 | self._loader = loader(cache, aliases) | ||
|
r38459 | self._proc = engine(self._loader.load, allfilters, defaults, resources) | ||
|
r38457 | self._minchunk, self._maxchunk = minchunk, maxchunk | ||
@classmethod | ||||
|
r43346 | def frommapfile( | ||
cls, | ||||
mapfile, | ||||
|
r45870 | fp=None, | ||
|
r43346 | filters=None, | ||
defaults=None, | ||||
resources=None, | ||||
cache=None, | ||||
minchunk=1024, | ||||
maxchunk=65536, | ||||
): | ||||
|
r38457 | """Create templater from the specified map file""" | ||
t = cls(filters, defaults, resources, cache, [], minchunk, maxchunk) | ||||
|
r45870 | if not fp: | ||
fp = _open_mapfile(mapfile) | ||||
|
r45868 | cache, tmap, aliases = _readmapfile(fp, mapfile) | ||
|
r38457 | t._loader.cache.update(cache) | ||
t._loader._map = tmap | ||||
t._loader._aliasmap = _aliasrules.buildmap(aliases) | ||||
return t | ||||
def __contains__(self, key): | ||||
return key in self._loader | ||||
@property | ||||
def cache(self): | ||||
return self._loader.cache | ||||
|
r38459 | # for highlight extension to insert one-time 'colorize' filter | ||
@property | ||||
def _filters(self): | ||||
return self._proc._filters | ||||
@property | ||||
def defaults(self): | ||||
return self._proc._defaults | ||||
|
r38457 | def load(self, t): | ||
"""Get parsed tree for the given template name. Use a local cache.""" | ||||
return self._loader.load(t) | ||||
|
r38374 | def symbolsuseddefault(self): | ||
"""Look up (keywords, filters/functions) referenced from the default | ||||
unnamed template | ||||
This may load additional templates from the map file. | ||||
""" | ||||
|
r43347 | return self.symbolsused(b'') | ||
|
r38374 | |||
def symbolsused(self, t): | ||||
"""Look up (keywords, filters/functions) referenced from the name | ||||
template 't' | ||||
This may load additional templates from the map file. | ||||
""" | ||||
|
r38457 | return self._loader.symbolsused(t) | ||
|
r38374 | |||
|
r37003 | def renderdefault(self, mapping): | ||
|
r32873 | """Render the default unnamed template and return result as string""" | ||
|
r43347 | return self.render(b'', mapping) | ||
|
r37004 | |||
def render(self, t, mapping): | ||||
"""Render the specified named template and return result as string""" | ||||
|
r37176 | return b''.join(self.generate(t, mapping)) | ||
|
r32873 | |||
|
r37037 | def generate(self, t, mapping): | ||
"""Return a generator that renders the specified named template and | ||||
yields chunks""" | ||||
|
r38458 | stream = self._proc.process(t, mapping) | ||
|
r38370 | if self._minchunk: | ||
|
r43346 | stream = util.increasingchunks( | ||
stream, min=self._minchunk, max=self._maxchunk | ||||
) | ||||
|
r7396 | return stream | ||
|
r7434 | |||
|
r43346 | |||
|
r45755 | def templatedir(): | ||
'''return the directory used for template files, or None.''' | ||||
|
r45754 | path = os.path.normpath(os.path.join(resourceutil.datapath, b'templates')) | ||
|
r45755 | return path if os.path.isdir(path) else None | ||
|
r2189 | |||
|
r43346 | |||
|
r45876 | def open_template(name, templatepath=None): | ||
|
r45871 | '''returns a file-like object for the given template, and its full path | ||
If the name is a relative path and we're in a frozen binary, the template | ||||
will be read from the mercurial.templates package instead. The returned path | ||||
will then be the relative path. | ||||
''' | ||||
|
r45881 | # Does the name point directly to a map file? | ||
|
r45882 | if os.path.isfile(name) or os.path.isabs(name): | ||
|
r45881 | return name, open(name, mode='rb') | ||
# Does the name point to a template in the provided templatepath, or | ||||
# in mercurial/templates/ if no path was provided? | ||||
|
r45876 | if templatepath is None: | ||
templatepath = templatedir() | ||||
|
r45881 | if templatepath is not None: | ||
|
r45869 | f = os.path.join(templatepath, name) | ||
|
r45880 | return f, open(f, mode='rb') | ||
|
r45881 | |||
# Otherwise try to read it using the resources API | ||||
|
r46023 | name_parts = name.split(b'/') | ||
package_name = b'.'.join([b'mercurial', b'templates'] + name_parts[:-1]) | ||||
|
r45881 | return ( | ||
name, | ||||
resourceutil.open_resource(package_name, name_parts[-1]), | ||||
) | ||||
|
r45880 | |||
def try_open_template(name, templatepath=None): | ||||
try: | ||||
return open_template(name, templatepath) | ||||
except (EnvironmentError, ImportError): | ||||
return None, None | ||||