2006-02-28 02:07:25 +03:00
|
|
|
# templater.py - template expansion for output
|
|
|
|
#
|
|
|
|
# Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
|
|
|
|
#
|
2009-04-26 03:08:54 +04:00
|
|
|
# This software may be used and distributed according to the terms of the
|
2010-01-20 07:20:08 +03:00
|
|
|
# GNU General Public License version 2 or any later version.
|
2006-02-28 02:07:25 +03:00
|
|
|
|
2015-08-09 04:23:53 +03:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
|
|
|
import os
|
|
|
|
import re
|
2012-11-29 02:55:42 +04:00
|
|
|
import types
|
2015-08-09 04:23:53 +03:00
|
|
|
|
|
|
|
from .i18n import _
|
|
|
|
from . import (
|
|
|
|
config,
|
|
|
|
error,
|
|
|
|
minirst,
|
|
|
|
parser,
|
2016-03-29 20:10:44 +03:00
|
|
|
registrar,
|
2015-08-09 04:23:53 +03:00
|
|
|
revset as revsetmod,
|
|
|
|
templatefilters,
|
|
|
|
templatekw,
|
|
|
|
util,
|
|
|
|
)
|
2010-12-20 21:09:00 +03:00
|
|
|
|
|
|
|
# template parsing
|
|
|
|
|
|
|
|
elements = {
|
parser: separate actions for primary expression and prefix operator
This will allow us to define both a primary expression, ":", and a prefix
operator, ":y". The ambiguity will be resolved by the next patch.
Prefix actions in elements table are adjusted as follows:
original prefix primary prefix
----------------- -------- -----------------
("group", 1, ")") -> n/a ("group", 1, ")")
("negate", 19) -> n/a ("negate", 19)
("symbol",) -> "symbol" n/a
2015-07-05 06:02:13 +03:00
|
|
|
# token-type: binding-strength, primary, prefix, infix, suffix
|
|
|
|
"(": (20, None, ("group", 1, ")"), ("func", 1, ")"), None),
|
|
|
|
",": (2, None, None, ("list", 2), None),
|
|
|
|
"|": (5, None, None, ("|", 5), None),
|
|
|
|
"%": (6, None, None, ("%", 6), None),
|
|
|
|
")": (0, None, None, None, None),
|
2016-10-09 15:51:04 +03:00
|
|
|
"+": (3, None, None, ("+", 3), None),
|
|
|
|
"-": (3, None, ("negate", 10), ("-", 3), None),
|
|
|
|
"*": (4, None, None, ("*", 4), None),
|
|
|
|
"/": (4, None, None, ("/", 4), None),
|
parser: separate actions for primary expression and prefix operator
This will allow us to define both a primary expression, ":", and a prefix
operator, ":y". The ambiguity will be resolved by the next patch.
Prefix actions in elements table are adjusted as follows:
original prefix primary prefix
----------------- -------- -----------------
("group", 1, ")") -> n/a ("group", 1, ")")
("negate", 19) -> n/a ("negate", 19)
("symbol",) -> "symbol" n/a
2015-07-05 06:02:13 +03:00
|
|
|
"integer": (0, "integer", None, None, None),
|
|
|
|
"symbol": (0, "symbol", None, None, None),
|
|
|
|
"string": (0, "string", None, None, None),
|
|
|
|
"template": (0, "template", None, None, None),
|
|
|
|
"end": (0, None, None, None, None),
|
2010-12-20 21:09:00 +03:00
|
|
|
}
|
|
|
|
|
2016-03-27 14:29:03 +03:00
|
|
|
def tokenize(program, start, end, term=None):
|
|
|
|
"""Parse a template expression into a stream of tokens, which must end
|
|
|
|
with term if specified"""
|
2010-12-20 21:09:00 +03:00
|
|
|
pos = start
|
|
|
|
while pos < end:
|
|
|
|
c = program[pos]
|
|
|
|
if c.isspace(): # skip inter-token whitespace
|
|
|
|
pass
|
2016-10-09 15:51:04 +03:00
|
|
|
elif c in "(,)%|+-*/": # handle simple operators
|
2010-12-20 21:09:00 +03:00
|
|
|
yield (c, None, pos)
|
2015-06-15 17:11:35 +03:00
|
|
|
elif c in '"\'': # handle quoted templates
|
|
|
|
s = pos + 1
|
|
|
|
data, pos = _parsetemplate(program, s, end, c)
|
|
|
|
yield ('template', data, s)
|
|
|
|
pos -= 1
|
2015-06-21 07:28:21 +03:00
|
|
|
elif c == 'r' and program[pos:pos + 2] in ("r'", 'r"'):
|
|
|
|
# handle quoted strings
|
|
|
|
c = program[pos + 1]
|
|
|
|
s = pos = pos + 2
|
2010-12-20 21:09:00 +03:00
|
|
|
while pos < end: # find closing quote
|
|
|
|
d = program[pos]
|
2015-06-21 07:24:43 +03:00
|
|
|
if d == '\\': # skip over escaped characters
|
2010-12-20 21:09:00 +03:00
|
|
|
pos += 2
|
|
|
|
continue
|
|
|
|
if d == c:
|
2015-06-20 12:24:11 +03:00
|
|
|
yield ('string', program[s:pos], s)
|
2010-12-20 21:09:00 +03:00
|
|
|
break
|
|
|
|
pos += 1
|
|
|
|
else:
|
|
|
|
raise error.ParseError(_("unterminated string"), s)
|
2016-10-09 15:51:04 +03:00
|
|
|
elif c.isdigit():
|
2015-05-01 14:43:55 +03:00
|
|
|
s = pos
|
|
|
|
while pos < end:
|
|
|
|
d = program[pos]
|
|
|
|
if not d.isdigit():
|
|
|
|
break
|
|
|
|
pos += 1
|
|
|
|
yield ('integer', program[s:pos], s)
|
|
|
|
pos -= 1
|
templater: parse \"...\" as string for 2.9.2-3.4 compatibility (issue4733)
As of Mercurial 3.4, there were several syntax rules to process nested
template strings. Unfortunately, they were inconsistent and conflicted
each other.
a. buildmap() rule
- template string is _parsed_ as string, and parsed as template
- <\"> is not allowed in nested template:
{xs % "{f(\"{x}\")}"} -> parse error
- template escaping <\{> is handled consistently:
{xs % "\{x}"} -> escaped
b. _evalifliteral() rule
- template string is _interpreted_ as string, and parsed as template
in crafted environment to avoid double processing of escape sequences
- <\"> is allowed in nested template:
{if(x, "{f(\"{x}\")}")}
- <\{> and escape sequences in string literal in nested template are not
handled well
c. pad() rule
- template string is first interpreted as string, and parsed as template,
which means escape sequences are processed twice
- <\"> is allowed in nested template:
{pad("{xs % \"{x}\"}', 10)}
Because of the issue of template escaping, issue4714, 56e0b66a4c27 (in stable)
unified the rule (b) to (a). Then, 41e044cfb1ef (in default) unified the rule
(c) to (b) = (a). But they disabled the following syntax that was somewhat
considered valid.
{if(rev, "{if(rev, \"{rev}\")}")}
{pad("{files % \"{file}\"}", 10)}
So, this patch introduces \"...\" literal to work around the escaped-quoted
nested template strings. Because this parsing rule exists only for the backward
compatibility, it is designed to copy the behavior of old _evalifliteral() as
possible.
Future patches will introduce a better parsing rule similar to a command
substitution of POSIX shells or a string interpolation of Ruby, where extra
escapes won't be necessary at all.
{pad("{files % "{file}"}", 10)}
~~~~~~~~~~~~~~~~~~
parsed as a template, not as a string
Because <\> character wasn't allowed in a template fragment, this patch won't
introduce more breakages. But the syntax of nested templates are interpreted
differently by people, there might be unknown issues. So if we want, we could
instead remove e926f2ef639a, 72be08a15d8d and 56e0b66a4c27 from the stable
branch as the bug fixed by these patches existed for longer periods.
554d6fcc3c8, "strip single backslash before quotation mark in quoted template",
should be superseded by this patch. I'll remove it later.
2015-06-25 16:07:38 +03:00
|
|
|
elif (c == '\\' and program[pos:pos + 2] in (r"\'", r'\"')
|
|
|
|
or c == 'r' and program[pos:pos + 3] in (r"r\'", r'r\"')):
|
|
|
|
# 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
|
|
|
|
if c == 'r':
|
|
|
|
pos += 1
|
2015-06-20 12:24:11 +03:00
|
|
|
token = 'string'
|
templater: parse \"...\" as string for 2.9.2-3.4 compatibility (issue4733)
As of Mercurial 3.4, there were several syntax rules to process nested
template strings. Unfortunately, they were inconsistent and conflicted
each other.
a. buildmap() rule
- template string is _parsed_ as string, and parsed as template
- <\"> is not allowed in nested template:
{xs % "{f(\"{x}\")}"} -> parse error
- template escaping <\{> is handled consistently:
{xs % "\{x}"} -> escaped
b. _evalifliteral() rule
- template string is _interpreted_ as string, and parsed as template
in crafted environment to avoid double processing of escape sequences
- <\"> is allowed in nested template:
{if(x, "{f(\"{x}\")}")}
- <\{> and escape sequences in string literal in nested template are not
handled well
c. pad() rule
- template string is first interpreted as string, and parsed as template,
which means escape sequences are processed twice
- <\"> is allowed in nested template:
{pad("{xs % \"{x}\"}', 10)}
Because of the issue of template escaping, issue4714, 56e0b66a4c27 (in stable)
unified the rule (b) to (a). Then, 41e044cfb1ef (in default) unified the rule
(c) to (b) = (a). But they disabled the following syntax that was somewhat
considered valid.
{if(rev, "{if(rev, \"{rev}\")}")}
{pad("{files % \"{file}\"}", 10)}
So, this patch introduces \"...\" literal to work around the escaped-quoted
nested template strings. Because this parsing rule exists only for the backward
compatibility, it is designed to copy the behavior of old _evalifliteral() as
possible.
Future patches will introduce a better parsing rule similar to a command
substitution of POSIX shells or a string interpolation of Ruby, where extra
escapes won't be necessary at all.
{pad("{files % "{file}"}", 10)}
~~~~~~~~~~~~~~~~~~
parsed as a template, not as a string
Because <\> character wasn't allowed in a template fragment, this patch won't
introduce more breakages. But the syntax of nested templates are interpreted
differently by people, there might be unknown issues. So if we want, we could
instead remove e926f2ef639a, 72be08a15d8d and 56e0b66a4c27 from the stable
branch as the bug fixed by these patches existed for longer periods.
554d6fcc3c8, "strip single backslash before quotation mark in quoted template",
should be superseded by this patch. I'll remove it later.
2015-06-25 16:07:38 +03:00
|
|
|
else:
|
2015-06-15 17:11:35 +03:00
|
|
|
token = 'template'
|
templater: parse \"...\" as string for 2.9.2-3.4 compatibility (issue4733)
As of Mercurial 3.4, there were several syntax rules to process nested
template strings. Unfortunately, they were inconsistent and conflicted
each other.
a. buildmap() rule
- template string is _parsed_ as string, and parsed as template
- <\"> is not allowed in nested template:
{xs % "{f(\"{x}\")}"} -> parse error
- template escaping <\{> is handled consistently:
{xs % "\{x}"} -> escaped
b. _evalifliteral() rule
- template string is _interpreted_ as string, and parsed as template
in crafted environment to avoid double processing of escape sequences
- <\"> is allowed in nested template:
{if(x, "{f(\"{x}\")}")}
- <\{> and escape sequences in string literal in nested template are not
handled well
c. pad() rule
- template string is first interpreted as string, and parsed as template,
which means escape sequences are processed twice
- <\"> is allowed in nested template:
{pad("{xs % \"{x}\"}', 10)}
Because of the issue of template escaping, issue4714, 56e0b66a4c27 (in stable)
unified the rule (b) to (a). Then, 41e044cfb1ef (in default) unified the rule
(c) to (b) = (a). But they disabled the following syntax that was somewhat
considered valid.
{if(rev, "{if(rev, \"{rev}\")}")}
{pad("{files % \"{file}\"}", 10)}
So, this patch introduces \"...\" literal to work around the escaped-quoted
nested template strings. Because this parsing rule exists only for the backward
compatibility, it is designed to copy the behavior of old _evalifliteral() as
possible.
Future patches will introduce a better parsing rule similar to a command
substitution of POSIX shells or a string interpolation of Ruby, where extra
escapes won't be necessary at all.
{pad("{files % "{file}"}", 10)}
~~~~~~~~~~~~~~~~~~
parsed as a template, not as a string
Because <\> character wasn't allowed in a template fragment, this patch won't
introduce more breakages. But the syntax of nested templates are interpreted
differently by people, there might be unknown issues. So if we want, we could
instead remove e926f2ef639a, 72be08a15d8d and 56e0b66a4c27 from the stable
branch as the bug fixed by these patches existed for longer periods.
554d6fcc3c8, "strip single backslash before quotation mark in quoted template",
should be superseded by this patch. I'll remove it later.
2015-06-25 16:07:38 +03:00
|
|
|
quote = program[pos:pos + 2]
|
|
|
|
s = pos = pos + 2
|
|
|
|
while pos < end: # find closing escaped quote
|
|
|
|
if program.startswith('\\\\\\', pos, end):
|
|
|
|
pos += 4 # skip over double escaped characters
|
|
|
|
continue
|
|
|
|
if program.startswith(quote, pos, end):
|
2015-09-10 00:43:45 +03:00
|
|
|
# interpret as if it were a part of an outer string
|
2015-09-10 17:25:10 +03:00
|
|
|
data = parser.unescapestr(program[s:pos])
|
2015-06-15 17:11:35 +03:00
|
|
|
if token == 'template':
|
|
|
|
data = _parsetemplate(data, 0, len(data))[0]
|
templater: parse \"...\" as string for 2.9.2-3.4 compatibility (issue4733)
As of Mercurial 3.4, there were several syntax rules to process nested
template strings. Unfortunately, they were inconsistent and conflicted
each other.
a. buildmap() rule
- template string is _parsed_ as string, and parsed as template
- <\"> is not allowed in nested template:
{xs % "{f(\"{x}\")}"} -> parse error
- template escaping <\{> is handled consistently:
{xs % "\{x}"} -> escaped
b. _evalifliteral() rule
- template string is _interpreted_ as string, and parsed as template
in crafted environment to avoid double processing of escape sequences
- <\"> is allowed in nested template:
{if(x, "{f(\"{x}\")}")}
- <\{> and escape sequences in string literal in nested template are not
handled well
c. pad() rule
- template string is first interpreted as string, and parsed as template,
which means escape sequences are processed twice
- <\"> is allowed in nested template:
{pad("{xs % \"{x}\"}', 10)}
Because of the issue of template escaping, issue4714, 56e0b66a4c27 (in stable)
unified the rule (b) to (a). Then, 41e044cfb1ef (in default) unified the rule
(c) to (b) = (a). But they disabled the following syntax that was somewhat
considered valid.
{if(rev, "{if(rev, \"{rev}\")}")}
{pad("{files % \"{file}\"}", 10)}
So, this patch introduces \"...\" literal to work around the escaped-quoted
nested template strings. Because this parsing rule exists only for the backward
compatibility, it is designed to copy the behavior of old _evalifliteral() as
possible.
Future patches will introduce a better parsing rule similar to a command
substitution of POSIX shells or a string interpolation of Ruby, where extra
escapes won't be necessary at all.
{pad("{files % "{file}"}", 10)}
~~~~~~~~~~~~~~~~~~
parsed as a template, not as a string
Because <\> character wasn't allowed in a template fragment, this patch won't
introduce more breakages. But the syntax of nested templates are interpreted
differently by people, there might be unknown issues. So if we want, we could
instead remove e926f2ef639a, 72be08a15d8d and 56e0b66a4c27 from the stable
branch as the bug fixed by these patches existed for longer periods.
554d6fcc3c8, "strip single backslash before quotation mark in quoted template",
should be superseded by this patch. I'll remove it later.
2015-06-25 16:07:38 +03:00
|
|
|
yield (token, data, s)
|
|
|
|
pos += 1
|
|
|
|
break
|
|
|
|
pos += 1
|
|
|
|
else:
|
|
|
|
raise error.ParseError(_("unterminated string"), s)
|
2010-12-20 21:09:00 +03:00
|
|
|
elif c.isalnum() or c in '_':
|
|
|
|
s = pos
|
|
|
|
pos += 1
|
|
|
|
while pos < end: # find end of symbol
|
|
|
|
d = program[pos]
|
|
|
|
if not (d.isalnum() or d == "_"):
|
|
|
|
break
|
|
|
|
pos += 1
|
|
|
|
sym = program[s:pos]
|
2013-04-10 08:38:08 +04:00
|
|
|
yield ('symbol', sym, s)
|
2010-12-20 21:09:00 +03:00
|
|
|
pos -= 1
|
2016-03-27 14:29:03 +03:00
|
|
|
elif c == term:
|
2015-06-15 17:03:30 +03:00
|
|
|
yield ('end', None, pos + 1)
|
|
|
|
return
|
2010-12-20 21:09:00 +03:00
|
|
|
else:
|
|
|
|
raise error.ParseError(_("syntax error"), pos)
|
|
|
|
pos += 1
|
2016-03-27 14:29:03 +03:00
|
|
|
if term:
|
|
|
|
raise error.ParseError(_("unterminated template expansion"), start)
|
|
|
|
yield ('end', None, pos)
|
2010-12-20 21:09:00 +03:00
|
|
|
|
2015-06-15 17:11:35 +03:00
|
|
|
def _parsetemplate(tmpl, start, stop, quote=''):
|
|
|
|
r"""
|
|
|
|
>>> _parsetemplate('foo{bar}"baz', 0, 12)
|
|
|
|
([('string', 'foo'), ('symbol', 'bar'), ('string', '"baz')], 12)
|
|
|
|
>>> _parsetemplate('foo{bar}"baz', 0, 12, quote='"')
|
|
|
|
([('string', 'foo'), ('symbol', 'bar')], 9)
|
|
|
|
>>> _parsetemplate('foo"{bar}', 0, 9, quote='"')
|
|
|
|
([('string', 'foo')], 4)
|
|
|
|
>>> _parsetemplate(r'foo\"bar"baz', 0, 12, quote='"')
|
|
|
|
([('string', 'foo"'), ('string', 'bar')], 9)
|
|
|
|
>>> _parsetemplate(r'foo\\"bar', 0, 10, quote='"')
|
2015-06-20 12:24:11 +03:00
|
|
|
([('string', 'foo\\')], 6)
|
2015-06-15 17:11:35 +03:00
|
|
|
"""
|
2010-12-20 21:09:00 +03:00
|
|
|
parsed = []
|
2015-06-15 17:11:35 +03:00
|
|
|
sepchars = '{' + quote
|
2015-06-15 16:55:34 +03:00
|
|
|
pos = start
|
2015-06-20 18:49:26 +03:00
|
|
|
p = parser.parser(elements)
|
2010-12-20 21:09:00 +03:00
|
|
|
while pos < stop:
|
2015-06-15 17:11:35 +03:00
|
|
|
n = min((tmpl.find(c, pos, stop) for c in sepchars),
|
|
|
|
key=lambda n: (n < 0, n))
|
2010-12-20 21:09:00 +03:00
|
|
|
if n < 0:
|
2015-09-10 17:25:10 +03:00
|
|
|
parsed.append(('string', parser.unescapestr(tmpl[pos:stop])))
|
2015-06-15 17:00:42 +03:00
|
|
|
pos = stop
|
2010-12-20 21:09:00 +03:00
|
|
|
break
|
2015-06-15 17:11:35 +03:00
|
|
|
c = tmpl[n]
|
2015-05-04 04:17:34 +03:00
|
|
|
bs = (n - pos) - len(tmpl[pos:n].rstrip('\\'))
|
2015-06-13 14:23:52 +03:00
|
|
|
if bs % 2 == 1:
|
|
|
|
# escaped (e.g. '\{', '\\\{', but not '\\{')
|
2015-09-10 17:25:10 +03:00
|
|
|
parsed.append(('string', parser.unescapestr(tmpl[pos:n - 1]) + c))
|
2010-12-20 21:09:00 +03:00
|
|
|
pos = n + 1
|
|
|
|
continue
|
|
|
|
if n > pos:
|
2015-09-10 17:25:10 +03:00
|
|
|
parsed.append(('string', parser.unescapestr(tmpl[pos:n])))
|
2015-06-15 17:11:35 +03:00
|
|
|
if c == quote:
|
|
|
|
return parsed, n + 1
|
2010-12-20 21:09:00 +03:00
|
|
|
|
2016-03-27 14:29:03 +03:00
|
|
|
parseres, pos = p.parse(tokenize(tmpl, n + 1, stop, '}'))
|
2011-03-17 01:09:14 +03:00
|
|
|
parsed.append(parseres)
|
2015-06-15 17:11:35 +03:00
|
|
|
|
|
|
|
if quote:
|
|
|
|
raise error.ParseError(_("unterminated string"), start)
|
2015-06-15 16:55:34 +03:00
|
|
|
return parsed, pos
|
2010-12-20 21:09:00 +03:00
|
|
|
|
2016-02-13 17:20:47 +03:00
|
|
|
def _unnesttemplatelist(tree):
|
|
|
|
"""Expand list of templates to node tuple
|
|
|
|
|
|
|
|
>>> def f(tree):
|
|
|
|
... print prettyformat(_unnesttemplatelist(tree))
|
|
|
|
>>> f(('template', []))
|
|
|
|
('string', '')
|
|
|
|
>>> f(('template', [('string', 'foo')]))
|
|
|
|
('string', 'foo')
|
|
|
|
>>> f(('template', [('string', 'foo'), ('symbol', 'rev')]))
|
|
|
|
(template
|
|
|
|
('string', 'foo')
|
|
|
|
('symbol', 'rev'))
|
|
|
|
>>> f(('template', [('symbol', 'rev')])) # template(rev) -> str
|
|
|
|
(template
|
|
|
|
('symbol', 'rev'))
|
|
|
|
>>> f(('template', [('template', [('string', 'foo')])]))
|
|
|
|
('string', 'foo')
|
|
|
|
"""
|
|
|
|
if not isinstance(tree, tuple):
|
|
|
|
return tree
|
|
|
|
op = tree[0]
|
|
|
|
if op != 'template':
|
|
|
|
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:
|
|
|
|
return ('string', '') # empty template ""
|
|
|
|
elif len(xs) == 1 and xs[0][0] == 'string':
|
|
|
|
return xs[0] # fast path for string with no template fragment "x"
|
|
|
|
else:
|
|
|
|
return (op,) + xs
|
|
|
|
|
2016-02-13 17:54:24 +03:00
|
|
|
def parse(tmpl):
|
|
|
|
"""Parse template string into tree"""
|
2015-06-15 16:55:34 +03:00
|
|
|
parsed, pos = _parsetemplate(tmpl, 0, len(tmpl))
|
2016-02-13 17:54:24 +03:00
|
|
|
assert pos == len(tmpl), 'unquoted template should be consumed'
|
2016-02-13 17:20:47 +03:00
|
|
|
return _unnesttemplatelist(('template', parsed))
|
|
|
|
|
2016-03-27 14:29:03 +03:00
|
|
|
def _parseexpr(expr):
|
|
|
|
"""Parse a template expression into tree
|
|
|
|
|
|
|
|
>>> _parseexpr('"foo"')
|
|
|
|
('string', 'foo')
|
|
|
|
>>> _parseexpr('foo(bar)')
|
|
|
|
('func', ('symbol', 'foo'), ('symbol', 'bar'))
|
|
|
|
>>> _parseexpr('foo(')
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ParseError: ('not a prefix: end', 4)
|
|
|
|
>>> _parseexpr('"foo" "bar"')
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ParseError: ('invalid token', 7)
|
|
|
|
"""
|
|
|
|
p = parser.parser(elements)
|
|
|
|
tree, pos = p.parse(tokenize(expr, 0, len(expr)))
|
|
|
|
if pos != len(expr):
|
|
|
|
raise error.ParseError(_('invalid token'), pos)
|
|
|
|
return _unnesttemplatelist(tree)
|
|
|
|
|
2016-02-13 17:20:47 +03:00
|
|
|
def prettyformat(tree):
|
|
|
|
return parser.prettyformat(tree, ('integer', 'string', 'symbol'))
|
2016-02-13 17:54:24 +03:00
|
|
|
|
2015-05-02 12:05:04 +03:00
|
|
|
def compileexp(exp, context, curmethods):
|
2016-04-03 07:23:40 +03:00
|
|
|
"""Compile parsed template tree to (func, data) pair"""
|
2010-12-20 21:09:00 +03:00
|
|
|
t = exp[0]
|
2015-05-02 12:05:04 +03:00
|
|
|
if t in curmethods:
|
|
|
|
return curmethods[t](exp, context)
|
2010-12-20 21:09:00 +03:00
|
|
|
raise error.ParseError(_("unknown method '%s'") % t)
|
|
|
|
|
|
|
|
# template evaluation
|
|
|
|
|
|
|
|
def getsymbol(exp):
|
|
|
|
if exp[0] == 'symbol':
|
|
|
|
return exp[1]
|
2014-06-13 05:07:21 +04:00
|
|
|
raise error.ParseError(_("expected a symbol, got '%s'") % exp[0])
|
2010-12-20 21:09:00 +03:00
|
|
|
|
|
|
|
def getlist(x):
|
|
|
|
if not x:
|
|
|
|
return []
|
|
|
|
if x[0] == 'list':
|
|
|
|
return getlist(x[1]) + [x[2]]
|
|
|
|
return [x]
|
|
|
|
|
|
|
|
def gettemplate(exp, context):
|
2016-02-13 17:54:24 +03:00
|
|
|
"""Compile given template tree or load named template from map file;
|
|
|
|
returns (func, data) pair"""
|
2016-02-14 09:42:49 +03:00
|
|
|
if exp[0] in ('template', 'string'):
|
2016-02-13 17:54:24 +03:00
|
|
|
return compileexp(exp, context, methods)
|
2010-12-20 21:09:00 +03:00
|
|
|
if exp[0] == 'symbol':
|
2015-06-16 16:13:19 +03:00
|
|
|
# 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.
|
2010-12-20 21:09:00 +03:00
|
|
|
return context._load(exp[1])
|
|
|
|
raise error.ParseError(_("expected template specifier"))
|
|
|
|
|
2015-09-01 12:57:50 +03:00
|
|
|
def evalfuncarg(context, mapping, arg):
|
|
|
|
func, data = arg
|
|
|
|
# func() may return string, generator of strings or arbitrary object such
|
|
|
|
# as date tuple, but filter does not want generator.
|
|
|
|
thing = func(context, mapping, data)
|
|
|
|
if isinstance(thing, types.GeneratorType):
|
|
|
|
thing = stringify(thing)
|
|
|
|
return thing
|
|
|
|
|
2016-08-18 10:29:22 +03:00
|
|
|
def evalboolean(context, mapping, arg):
|
2016-04-22 15:29:13 +03:00
|
|
|
"""Evaluate given argument as boolean, but also takes boolean literals"""
|
2016-08-18 10:29:22 +03:00
|
|
|
func, data = arg
|
2016-04-22 15:29:13 +03:00
|
|
|
if func is runsymbol:
|
|
|
|
thing = func(context, mapping, data, default=None)
|
|
|
|
if thing is None:
|
|
|
|
# not a template keyword, takes as a boolean literal
|
|
|
|
thing = util.parsebool(data)
|
|
|
|
else:
|
|
|
|
thing = func(context, mapping, data)
|
2016-08-18 10:29:22 +03:00
|
|
|
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 ''
|
|
|
|
return bool(stringify(thing))
|
|
|
|
|
2016-02-14 06:42:25 +03:00
|
|
|
def evalinteger(context, mapping, arg, err):
|
2016-02-14 06:48:14 +03:00
|
|
|
v = evalfuncarg(context, mapping, arg)
|
2016-02-14 06:42:25 +03:00
|
|
|
try:
|
2016-02-14 06:48:14 +03:00
|
|
|
return int(v)
|
|
|
|
except (TypeError, ValueError):
|
2016-02-14 06:42:25 +03:00
|
|
|
raise error.ParseError(err)
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
def evalstring(context, mapping, arg):
|
|
|
|
func, data = arg
|
|
|
|
return stringify(func(context, mapping, data))
|
|
|
|
|
2015-06-11 16:58:27 +03:00
|
|
|
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)
|
|
|
|
return stringify(thing)
|
|
|
|
|
2015-05-01 14:43:55 +03:00
|
|
|
def runinteger(context, mapping, data):
|
|
|
|
return int(data)
|
|
|
|
|
2010-12-20 21:09:00 +03:00
|
|
|
def runstring(context, mapping, data):
|
|
|
|
return data
|
|
|
|
|
2015-07-22 17:29:41 +03:00
|
|
|
def _recursivesymbolblocker(key):
|
|
|
|
def showrecursion(**args):
|
|
|
|
raise error.Abort(_("recursive reference '%s' in template") % key)
|
|
|
|
return showrecursion
|
|
|
|
|
2015-07-23 17:41:29 +03:00
|
|
|
def _runrecursivesymbol(context, mapping, key):
|
|
|
|
raise error.Abort(_("recursive reference '%s' in template") % key)
|
|
|
|
|
2015-06-11 16:58:27 +03:00
|
|
|
def runsymbol(context, mapping, key, default=''):
|
2010-12-20 21:09:00 +03:00
|
|
|
v = mapping.get(key)
|
|
|
|
if v is None:
|
2013-09-22 13:52:18 +04:00
|
|
|
v = context._defaults.get(key)
|
|
|
|
if v is None:
|
2015-07-22 17:29:41 +03:00
|
|
|
# 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)
|
2013-09-22 13:52:18 +04:00
|
|
|
try:
|
2015-07-22 17:29:41 +03:00
|
|
|
v = context.process(key, safemapping)
|
2013-09-22 13:52:18 +04:00
|
|
|
except TemplateNotFound:
|
2015-06-11 16:58:27 +03:00
|
|
|
v = default
|
2014-06-23 17:24:56 +04:00
|
|
|
if callable(v):
|
2010-12-20 21:09:00 +03:00
|
|
|
return v(**mapping)
|
|
|
|
return v
|
|
|
|
|
templater: take any string literals as template, but not for rawstring (BC)
This patch series is intended to unify the interpretation of string literals.
It is breaking change that boldly assumes
a. string literal "..." never contains template-like fragment or it is
intended to be a template
b. we tend to use raw string literal r"..." for regexp pattern in which "{"
should have different meaning
Currently, we don't have a comprehensible rule how string literals are
evaluated in template functions. For example, fill() takes "initialindent"
and "hangindent" as templates, but not for "text", whereas "text" is a
template in pad() function.
date(date, fmt)
diff(includepattern, excludepattern)
fill(text, width, initialident: T, hangindent: T)
get(dict, key)
if(expr, then: T, else: T)
ifcontains(search, thing, then: T, else: T)
ifeq(expr1, expr2, then: T, else: T)
indent(text, indentchars, firstline)
join(list, sep)
label(label: T, expr: T)
pad(text: T, width, fillchar, right)
revset(query, formatargs...])
rstdoc(text, style)
shortest(node, minlength)
startswith(pattern, text)
strip(text, chars)
sub(pattern, replacement, expression: T)
word(number, text, separator)
expr % template: T
T: interpret "string" or r"rawstring" as template
This patch series adjusts the rule as follows:
a. string literal, '' or "", starts template processing (BC)
b. raw string literal, r'' or r"", disables both \-escape and template
processing (BC, done by subsequent patches)
c. fragment not surrounded by {} is non-templated string
"ccc{'aaa'}{r'bbb'}"
------------------ *: template
--- c: string
--- a: template
--- b: rawstring
Because this can eliminate the compilation of template arguments from the
evaluation phase, "hg log -Tdefault" gets faster.
% cd mozilla-central
% LANG=C HGRCPATH=/dev/null hg log -Tdefault -r0:10000 --time > /dev/null
before: real 4.870 secs (user 4.860+0.000 sys 0.010+0.000)
after: real 3.480 secs (user 3.440+0.000 sys 0.030+0.000)
Also, this will allow us to parse nested templates at once for better error
indication.
2015-06-13 13:49:54 +03:00
|
|
|
def buildtemplate(exp, context):
|
2016-02-13 17:20:47 +03:00
|
|
|
ctmpl = [compileexp(e, context, methods) for e in exp[1:]]
|
templater: take any string literals as template, but not for rawstring (BC)
This patch series is intended to unify the interpretation of string literals.
It is breaking change that boldly assumes
a. string literal "..." never contains template-like fragment or it is
intended to be a template
b. we tend to use raw string literal r"..." for regexp pattern in which "{"
should have different meaning
Currently, we don't have a comprehensible rule how string literals are
evaluated in template functions. For example, fill() takes "initialindent"
and "hangindent" as templates, but not for "text", whereas "text" is a
template in pad() function.
date(date, fmt)
diff(includepattern, excludepattern)
fill(text, width, initialident: T, hangindent: T)
get(dict, key)
if(expr, then: T, else: T)
ifcontains(search, thing, then: T, else: T)
ifeq(expr1, expr2, then: T, else: T)
indent(text, indentchars, firstline)
join(list, sep)
label(label: T, expr: T)
pad(text: T, width, fillchar, right)
revset(query, formatargs...])
rstdoc(text, style)
shortest(node, minlength)
startswith(pattern, text)
strip(text, chars)
sub(pattern, replacement, expression: T)
word(number, text, separator)
expr % template: T
T: interpret "string" or r"rawstring" as template
This patch series adjusts the rule as follows:
a. string literal, '' or "", starts template processing (BC)
b. raw string literal, r'' or r"", disables both \-escape and template
processing (BC, done by subsequent patches)
c. fragment not surrounded by {} is non-templated string
"ccc{'aaa'}{r'bbb'}"
------------------ *: template
--- c: string
--- a: template
--- b: rawstring
Because this can eliminate the compilation of template arguments from the
evaluation phase, "hg log -Tdefault" gets faster.
% cd mozilla-central
% LANG=C HGRCPATH=/dev/null hg log -Tdefault -r0:10000 --time > /dev/null
before: real 4.870 secs (user 4.860+0.000 sys 0.010+0.000)
after: real 3.480 secs (user 3.440+0.000 sys 0.030+0.000)
Also, this will allow us to parse nested templates at once for better error
indication.
2015-06-13 13:49:54 +03:00
|
|
|
return (runtemplate, ctmpl)
|
|
|
|
|
2015-06-12 18:15:22 +03:00
|
|
|
def runtemplate(context, mapping, template):
|
|
|
|
for func, data in template:
|
|
|
|
yield func(context, mapping, data)
|
|
|
|
|
2010-12-20 21:09:00 +03:00
|
|
|
def buildfilter(exp, context):
|
2015-09-01 13:04:10 +03:00
|
|
|
arg = compileexp(exp[1], context, methods)
|
2015-07-04 09:59:03 +03:00
|
|
|
n = getsymbol(exp[2])
|
|
|
|
if n in context._filters:
|
|
|
|
filt = context._filters[n]
|
2015-09-01 13:04:10 +03:00
|
|
|
return (runfilter, (arg, filt))
|
2015-07-04 10:03:36 +03:00
|
|
|
if n in funcs:
|
|
|
|
f = funcs[n]
|
2015-09-01 13:04:10 +03:00
|
|
|
return (f, [arg])
|
2015-07-04 09:59:03 +03:00
|
|
|
raise error.ParseError(_("unknown function '%s'") % n)
|
2010-12-20 21:09:00 +03:00
|
|
|
|
|
|
|
def runfilter(context, mapping, data):
|
2015-09-01 13:04:10 +03:00
|
|
|
arg, filt = data
|
|
|
|
thing = evalfuncarg(context, mapping, arg)
|
2012-08-18 02:12:01 +04:00
|
|
|
try:
|
2015-02-23 18:04:55 +03:00
|
|
|
return filt(thing)
|
2012-08-18 02:12:01 +04:00
|
|
|
except (ValueError, AttributeError, TypeError):
|
2015-09-01 13:04:10 +03:00
|
|
|
if isinstance(arg[1], tuple):
|
|
|
|
dt = arg[1][1]
|
2012-08-18 02:12:01 +04:00
|
|
|
else:
|
2015-09-01 13:04:10 +03:00
|
|
|
dt = arg[1]
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_("template filter '%s' is not compatible with "
|
2012-08-18 02:12:01 +04:00
|
|
|
"keyword '%s'") % (filt.func_name, dt))
|
2010-12-20 21:09:00 +03:00
|
|
|
|
|
|
|
def buildmap(exp, context):
|
2015-05-02 12:05:04 +03:00
|
|
|
func, data = compileexp(exp[1], context, methods)
|
2016-02-13 17:54:24 +03:00
|
|
|
tfunc, tdata = gettemplate(exp[2], context)
|
|
|
|
return (runmap, (func, data, tfunc, tdata))
|
2010-12-20 21:09:00 +03:00
|
|
|
|
|
|
|
def runmap(context, mapping, data):
|
2016-02-13 17:54:24 +03:00
|
|
|
func, data, tfunc, tdata = data
|
2010-12-20 21:09:00 +03:00
|
|
|
d = func(context, mapping, data)
|
2016-01-16 07:42:37 +03:00
|
|
|
if util.safehasattr(d, 'itermaps'):
|
2016-02-14 07:58:46 +03:00
|
|
|
diter = d.itermaps()
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
diter = iter(d)
|
|
|
|
except TypeError:
|
|
|
|
if func is runsymbol:
|
|
|
|
raise error.ParseError(_("keyword '%s' is not iterable") % data)
|
|
|
|
else:
|
|
|
|
raise error.ParseError(_("%r is not iterable") % d)
|
2012-09-22 03:54:00 +04:00
|
|
|
|
2016-02-14 07:58:46 +03:00
|
|
|
for i in diter:
|
2016-02-24 22:31:55 +03:00
|
|
|
lm = mapping.copy()
|
2010-12-20 21:09:00 +03:00
|
|
|
if isinstance(i, dict):
|
|
|
|
lm.update(i)
|
2012-11-13 02:05:39 +04:00
|
|
|
lm['originalnode'] = mapping.get('node')
|
2016-02-13 17:54:24 +03:00
|
|
|
yield tfunc(context, lm, tdata)
|
2010-12-20 21:09:00 +03:00
|
|
|
else:
|
|
|
|
# v is not an iterable of dicts, this happen when 'key'
|
|
|
|
# has been fully expanded already and format is useless.
|
|
|
|
# If so, return the expanded value.
|
|
|
|
yield i
|
|
|
|
|
2016-10-09 15:51:04 +03:00
|
|
|
def buildnegate(exp, context):
|
|
|
|
arg = compileexp(exp[1], context, exprmethods)
|
|
|
|
return (runnegate, arg)
|
|
|
|
|
|
|
|
def runnegate(context, mapping, data):
|
|
|
|
data = evalinteger(context, mapping, data,
|
|
|
|
_('negation needs an integer argument'))
|
|
|
|
return -data
|
|
|
|
|
|
|
|
def buildarithmetic(exp, context, func):
|
|
|
|
left = compileexp(exp[1], context, exprmethods)
|
|
|
|
right = compileexp(exp[2], context, exprmethods)
|
|
|
|
return (runarithmetic, (func, left, right))
|
|
|
|
|
|
|
|
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'))
|
2016-10-09 18:09:20 +03:00
|
|
|
try:
|
|
|
|
return func(left, right)
|
|
|
|
except ZeroDivisionError:
|
|
|
|
raise error.Abort(_('division by zero is not defined'))
|
2016-10-09 15:51:04 +03:00
|
|
|
|
2010-12-20 21:09:00 +03:00
|
|
|
def buildfunc(exp, context):
|
|
|
|
n = getsymbol(exp[1])
|
2015-05-02 12:05:04 +03:00
|
|
|
args = [compileexp(x, context, exprmethods) for x in getlist(exp[2])]
|
2011-07-23 23:33:35 +04:00
|
|
|
if n in funcs:
|
|
|
|
f = funcs[n]
|
|
|
|
return (f, args)
|
2010-12-20 21:09:00 +03:00
|
|
|
if n in context._filters:
|
|
|
|
if len(args) != 1:
|
|
|
|
raise error.ParseError(_("filter %s expects one argument") % n)
|
|
|
|
f = context._filters[n]
|
2015-09-01 13:04:10 +03:00
|
|
|
return (runfilter, (args[0], f))
|
2014-03-28 02:21:27 +04:00
|
|
|
raise error.ParseError(_("unknown function '%s'") % n)
|
2010-12-20 21:09:00 +03:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
# dict of template built-in functions
|
|
|
|
funcs = {}
|
|
|
|
|
|
|
|
templatefunc = registrar.templatefunc(funcs)
|
|
|
|
|
|
|
|
@templatefunc('date(date[, fmt])')
|
2013-06-29 14:27:53 +04:00
|
|
|
def date(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Format a date. See :hg:`help dates` for formatting
|
2015-07-04 10:07:42 +03:00
|
|
|
strings. The default is a Unix date format, including the timezone:
|
|
|
|
"Mon Sep 04 15:13:13 2006 0700"."""
|
2013-06-29 14:27:53 +04:00
|
|
|
if not (1 <= len(args) <= 2):
|
2014-10-31 20:43:08 +03:00
|
|
|
# i18n: "date" is a keyword
|
2013-06-29 14:27:53 +04:00
|
|
|
raise error.ParseError(_("date expects one or two arguments"))
|
|
|
|
|
2016-02-14 07:36:50 +03:00
|
|
|
date = evalfuncarg(context, mapping, args[0])
|
2015-05-03 11:33:14 +03:00
|
|
|
fmt = None
|
2013-06-29 14:27:53 +04:00
|
|
|
if len(args) == 2:
|
2016-02-14 07:30:32 +03:00
|
|
|
fmt = evalstring(context, mapping, args[1])
|
2015-05-03 11:33:14 +03:00
|
|
|
try:
|
|
|
|
if fmt is None:
|
|
|
|
return util.datestr(date)
|
|
|
|
else:
|
|
|
|
return util.datestr(date, fmt)
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
# i18n: "date" is a keyword
|
|
|
|
raise error.ParseError(_("date expects a date information"))
|
2013-06-29 14:27:53 +04:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('diff([includepattern [, excludepattern]])')
|
2014-08-28 17:45:36 +04:00
|
|
|
def diff(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Show a diff, optionally
|
2015-04-02 06:19:43 +03:00
|
|
|
specifying files to include or exclude."""
|
2014-08-28 17:45:36 +04:00
|
|
|
if len(args) > 2:
|
|
|
|
# i18n: "diff" is a keyword
|
2015-11-30 22:30:16 +03:00
|
|
|
raise error.ParseError(_("diff expects zero, one, or two arguments"))
|
2014-08-28 17:45:36 +04:00
|
|
|
|
|
|
|
def getpatterns(i):
|
|
|
|
if i < len(args):
|
2016-02-14 07:30:32 +03:00
|
|
|
s = evalstring(context, mapping, args[i]).strip()
|
2014-08-28 17:45:36 +04:00
|
|
|
if s:
|
|
|
|
return [s]
|
|
|
|
return []
|
|
|
|
|
|
|
|
ctx = mapping['ctx']
|
|
|
|
chunks = ctx.diff(match=ctx.match([], getpatterns(0), getpatterns(1)))
|
|
|
|
|
|
|
|
return ''.join(chunks)
|
|
|
|
|
2016-09-23 11:15:05 +03:00
|
|
|
@templatefunc('files(pattern)')
|
|
|
|
def files(context, mapping, args):
|
|
|
|
"""All files of the current changeset matching the pattern. See
|
|
|
|
:hg:`help patterns`."""
|
|
|
|
if not len(args) == 1:
|
|
|
|
# i18n: "files" is a keyword
|
|
|
|
raise error.ParseError(_("files expects one argument"))
|
|
|
|
|
|
|
|
raw = evalstring(context, mapping, args[0])
|
|
|
|
ctx = mapping['ctx']
|
|
|
|
m = ctx.match([raw])
|
|
|
|
files = list(ctx.matches(m))
|
|
|
|
return templatekw.showlist("file", files, **mapping)
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('fill(text[, width[, initialident[, hangindent]]])')
|
2013-06-29 14:27:53 +04:00
|
|
|
def fill(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Fill many
|
2015-04-02 06:19:43 +03:00
|
|
|
paragraphs with optional indentation. See the "fill" filter."""
|
2013-06-29 14:27:53 +04:00
|
|
|
if not (1 <= len(args) <= 4):
|
2014-10-31 20:43:08 +03:00
|
|
|
# i18n: "fill" is a keyword
|
2013-06-29 14:27:53 +04:00
|
|
|
raise error.ParseError(_("fill expects one to four arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
text = evalstring(context, mapping, args[0])
|
2013-06-29 14:27:53 +04:00
|
|
|
width = 76
|
|
|
|
initindent = ''
|
|
|
|
hangindent = ''
|
|
|
|
if 2 <= len(args) <= 4:
|
2016-02-14 06:42:25 +03:00
|
|
|
width = evalinteger(context, mapping, args[1],
|
|
|
|
# i18n: "fill" is a keyword
|
|
|
|
_("fill expects an integer width"))
|
2013-06-29 14:27:53 +04:00
|
|
|
try:
|
2016-02-14 07:30:32 +03:00
|
|
|
initindent = evalstring(context, mapping, args[2])
|
|
|
|
hangindent = evalstring(context, mapping, args[3])
|
2013-06-29 14:27:53 +04:00
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return templatefilters.fill(text, width, initindent, hangindent)
|
|
|
|
|
2016-04-22 15:32:30 +03:00
|
|
|
@templatefunc('pad(text, width[, fillchar=\' \'[, left=False]])')
|
2014-01-17 12:16:48 +04:00
|
|
|
def pad(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Pad text with a
|
2015-04-02 06:19:43 +03:00
|
|
|
fill character."""
|
2014-01-17 12:16:48 +04:00
|
|
|
if not (2 <= len(args) <= 4):
|
2014-10-31 20:43:08 +03:00
|
|
|
# i18n: "pad" is a keyword
|
2014-01-17 12:16:48 +04:00
|
|
|
raise error.ParseError(_("pad() expects two to four arguments"))
|
|
|
|
|
2016-02-14 07:05:09 +03:00
|
|
|
width = evalinteger(context, mapping, args[1],
|
|
|
|
# i18n: "pad" is a keyword
|
|
|
|
_("pad() expects an integer width"))
|
2014-01-17 12:16:48 +04:00
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
text = evalstring(context, mapping, args[0])
|
2014-01-17 12:16:48 +04:00
|
|
|
|
2016-04-22 15:32:30 +03:00
|
|
|
left = False
|
2014-01-17 12:16:48 +04:00
|
|
|
fillchar = ' '
|
|
|
|
if len(args) > 2:
|
2016-02-14 07:30:32 +03:00
|
|
|
fillchar = evalstring(context, mapping, args[2])
|
2014-01-17 12:16:48 +04:00
|
|
|
if len(args) > 3:
|
2016-04-22 15:32:30 +03:00
|
|
|
left = evalboolean(context, mapping, args[3])
|
2014-01-17 12:16:48 +04:00
|
|
|
|
2016-04-22 15:32:30 +03:00
|
|
|
if left:
|
2014-01-17 12:16:48 +04:00
|
|
|
return text.rjust(width, fillchar)
|
|
|
|
else:
|
|
|
|
return text.ljust(width, fillchar)
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('indent(text, indentchars[, firstline])')
|
2015-04-04 11:03:52 +03:00
|
|
|
def indent(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Indents all non-empty lines
|
2015-04-04 11:03:52 +03:00
|
|
|
with the characters given in the indentchars string. An optional
|
|
|
|
third parameter will override the indent for the first line only
|
|
|
|
if present."""
|
|
|
|
if not (2 <= len(args) <= 3):
|
|
|
|
# i18n: "indent" is a keyword
|
|
|
|
raise error.ParseError(_("indent() expects two or three arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
text = evalstring(context, mapping, args[0])
|
|
|
|
indent = evalstring(context, mapping, args[1])
|
2015-04-04 11:03:52 +03:00
|
|
|
|
|
|
|
if len(args) == 3:
|
2016-02-14 07:30:32 +03:00
|
|
|
firstline = evalstring(context, mapping, args[2])
|
2015-04-04 11:03:52 +03:00
|
|
|
else:
|
|
|
|
firstline = indent
|
|
|
|
|
|
|
|
# the indent function doesn't indent the first line, so we do it here
|
|
|
|
return templatefilters.indent(firstline + text, indent)
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('get(dict, key)')
|
2013-02-09 02:49:14 +04:00
|
|
|
def get(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Get an attribute/key from an object. Some keywords
|
2015-04-02 06:19:43 +03:00
|
|
|
are complex types. This function allows you to obtain the value of an
|
2015-08-31 00:50:55 +03:00
|
|
|
attribute on these types."""
|
2013-02-09 02:49:14 +04:00
|
|
|
if len(args) != 2:
|
|
|
|
# i18n: "get" is a keyword
|
|
|
|
raise error.ParseError(_("get() expects two arguments"))
|
|
|
|
|
2016-02-13 18:05:58 +03:00
|
|
|
dictarg = evalfuncarg(context, mapping, args[0])
|
2013-02-09 02:49:14 +04:00
|
|
|
if not util.safehasattr(dictarg, 'get'):
|
|
|
|
# i18n: "get" is a keyword
|
|
|
|
raise error.ParseError(_("get() expects a dict as first argument"))
|
|
|
|
|
2016-02-13 18:05:58 +03:00
|
|
|
key = evalfuncarg(context, mapping, args[1])
|
2016-01-16 07:53:32 +03:00
|
|
|
return dictarg.get(key)
|
2013-02-09 02:49:14 +04:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('if(expr, then[, else])')
|
2012-09-25 00:26:56 +04:00
|
|
|
def if_(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Conditionally execute based on the result of
|
2015-04-02 06:19:43 +03:00
|
|
|
an expression."""
|
2012-09-25 00:26:56 +04:00
|
|
|
if not (2 <= len(args) <= 3):
|
2012-10-30 22:59:27 +04:00
|
|
|
# i18n: "if" is a keyword
|
2012-09-25 00:26:56 +04:00
|
|
|
raise error.ParseError(_("if expects two or three arguments"))
|
|
|
|
|
2016-08-18 10:29:22 +03:00
|
|
|
test = evalboolean(context, mapping, args[0])
|
2012-09-25 00:26:56 +04:00
|
|
|
if test:
|
2015-06-10 15:44:43 +03:00
|
|
|
yield args[1][0](context, mapping, args[1][1])
|
2012-09-25 00:26:56 +04:00
|
|
|
elif len(args) == 3:
|
2015-06-10 15:44:43 +03:00
|
|
|
yield args[2][0](context, mapping, args[2][1])
|
2012-09-25 00:26:56 +04:00
|
|
|
|
2016-10-01 04:55:32 +03:00
|
|
|
@templatefunc('ifcontains(needle, haystack, then[, else])')
|
2014-02-12 09:10:00 +04:00
|
|
|
def ifcontains(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Conditionally execute based
|
2016-10-01 04:55:32 +03:00
|
|
|
on whether the item "needle" is in "haystack"."""
|
2014-02-12 09:10:00 +04:00
|
|
|
if not (3 <= len(args) <= 4):
|
|
|
|
# i18n: "ifcontains" is a keyword
|
|
|
|
raise error.ParseError(_("ifcontains expects three or four arguments"))
|
|
|
|
|
2016-10-01 04:55:32 +03:00
|
|
|
needle = evalstring(context, mapping, args[0])
|
|
|
|
haystack = evalfuncarg(context, mapping, args[1])
|
2014-02-12 09:10:00 +04:00
|
|
|
|
2016-10-01 04:55:32 +03:00
|
|
|
if needle in haystack:
|
2015-06-10 15:44:43 +03:00
|
|
|
yield args[2][0](context, mapping, args[2][1])
|
2014-02-12 09:10:00 +04:00
|
|
|
elif len(args) == 4:
|
2015-06-10 15:44:43 +03:00
|
|
|
yield args[3][0](context, mapping, args[3][1])
|
2014-02-12 09:10:00 +04:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('ifeq(expr1, expr2, then[, else])')
|
2012-09-25 00:26:56 +04:00
|
|
|
def ifeq(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Conditionally execute based on
|
2015-04-02 06:19:43 +03:00
|
|
|
whether 2 items are equivalent."""
|
2012-09-25 00:26:56 +04:00
|
|
|
if not (3 <= len(args) <= 4):
|
2012-10-30 22:59:27 +04:00
|
|
|
# i18n: "ifeq" is a keyword
|
2012-09-25 00:26:56 +04:00
|
|
|
raise error.ParseError(_("ifeq expects three or four arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
test = evalstring(context, mapping, args[0])
|
|
|
|
match = evalstring(context, mapping, args[1])
|
2012-09-25 00:26:56 +04:00
|
|
|
if test == match:
|
2015-06-10 15:44:43 +03:00
|
|
|
yield args[2][0](context, mapping, args[2][1])
|
2012-09-25 00:26:56 +04:00
|
|
|
elif len(args) == 4:
|
2015-06-10 15:44:43 +03:00
|
|
|
yield args[3][0](context, mapping, args[3][1])
|
2012-09-25 00:26:56 +04:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('join(list, sep)')
|
2013-06-29 14:27:53 +04:00
|
|
|
def join(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Join items in a list with a delimiter."""
|
2013-06-29 14:27:53 +04:00
|
|
|
if not (1 <= len(args) <= 2):
|
|
|
|
# i18n: "join" is a keyword
|
|
|
|
raise error.ParseError(_("join expects one or two arguments"))
|
|
|
|
|
|
|
|
joinset = args[0][0](context, mapping, args[0][1])
|
2016-01-16 07:42:37 +03:00
|
|
|
if util.safehasattr(joinset, 'itermaps'):
|
2013-06-29 14:27:53 +04:00
|
|
|
jf = joinset.joinfmt
|
2016-01-16 07:42:37 +03:00
|
|
|
joinset = [jf(x) for x in joinset.itermaps()]
|
2013-06-29 14:27:53 +04:00
|
|
|
|
|
|
|
joiner = " "
|
|
|
|
if len(args) > 1:
|
2016-02-14 07:30:32 +03:00
|
|
|
joiner = evalstring(context, mapping, args[1])
|
2013-06-29 14:27:53 +04:00
|
|
|
|
|
|
|
first = True
|
|
|
|
for x in joinset:
|
|
|
|
if first:
|
|
|
|
first = False
|
|
|
|
else:
|
|
|
|
yield joiner
|
|
|
|
yield x
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('label(label, expr)')
|
2012-12-23 07:46:26 +04:00
|
|
|
def label(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Apply a label to generated content. Content with
|
2015-04-02 06:19:43 +03:00
|
|
|
a label applied can result in additional post-processing, such as
|
|
|
|
automatic colorization."""
|
2012-12-23 07:46:26 +04:00
|
|
|
if len(args) != 2:
|
|
|
|
# i18n: "label" is a keyword
|
|
|
|
raise error.ParseError(_("label expects two arguments"))
|
|
|
|
|
2016-03-09 17:59:26 +03:00
|
|
|
ui = mapping['ui']
|
2015-06-11 17:04:14 +03:00
|
|
|
thing = evalstring(context, mapping, args[1])
|
|
|
|
# preserve unknown symbol as literal so effects like 'red', 'bold',
|
|
|
|
# etc. don't need to be quoted
|
|
|
|
label = evalstringliteral(context, mapping, args[0])
|
|
|
|
|
2016-03-08 15:08:33 +03:00
|
|
|
return ui.label(thing, label)
|
2012-12-23 07:46:26 +04:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('latesttag([pattern])')
|
2015-08-24 06:44:58 +03:00
|
|
|
def latesttag(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""The global tags matching the given pattern on the
|
2015-08-24 06:44:58 +03:00
|
|
|
most recent globally tagged ancestor of this changeset."""
|
|
|
|
if len(args) > 1:
|
|
|
|
# i18n: "latesttag" is a keyword
|
|
|
|
raise error.ParseError(_("latesttag expects at most one argument"))
|
|
|
|
|
|
|
|
pattern = None
|
|
|
|
if len(args) == 1:
|
2016-02-14 07:30:32 +03:00
|
|
|
pattern = evalstring(context, mapping, args[0])
|
2015-08-24 06:44:58 +03:00
|
|
|
|
|
|
|
return templatekw.showlatesttags(pattern, **mapping)
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('localdate(date[, tz])')
|
2015-09-01 13:15:16 +03:00
|
|
|
def localdate(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Converts a date to the specified timezone.
|
2015-08-18 16:15:46 +03:00
|
|
|
The default is local date."""
|
|
|
|
if not (1 <= len(args) <= 2):
|
2015-09-01 13:15:16 +03:00
|
|
|
# i18n: "localdate" is a keyword
|
2015-08-18 16:15:46 +03:00
|
|
|
raise error.ParseError(_("localdate expects one or two arguments"))
|
2015-09-01 13:15:16 +03:00
|
|
|
|
|
|
|
date = evalfuncarg(context, mapping, args[0])
|
|
|
|
try:
|
|
|
|
date = util.parsedate(date)
|
|
|
|
except AttributeError: # not str nor date tuple
|
|
|
|
# i18n: "localdate" is a keyword
|
|
|
|
raise error.ParseError(_("localdate expects a date information"))
|
2015-08-18 16:15:46 +03:00
|
|
|
if len(args) >= 2:
|
|
|
|
tzoffset = None
|
|
|
|
tz = evalfuncarg(context, mapping, args[1])
|
|
|
|
if isinstance(tz, str):
|
2016-07-27 23:14:19 +03:00
|
|
|
tzoffset, remainder = util.parsetimezone(tz)
|
|
|
|
if remainder:
|
|
|
|
tzoffset = None
|
2015-08-18 16:15:46 +03:00
|
|
|
if tzoffset is None:
|
|
|
|
try:
|
|
|
|
tzoffset = int(tz)
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
# i18n: "localdate" is a keyword
|
|
|
|
raise error.ParseError(_("localdate expects a timezone"))
|
|
|
|
else:
|
|
|
|
tzoffset = util.makedate()[1]
|
2015-09-01 13:15:16 +03:00
|
|
|
return (date[0], tzoffset)
|
|
|
|
|
2016-10-09 15:51:04 +03:00
|
|
|
@templatefunc('mod(a, b)')
|
|
|
|
def mod(context, mapping, args):
|
|
|
|
"""Calculate a mod b such that a / b + a mod b == a"""
|
|
|
|
if not len(args) == 2:
|
|
|
|
# i18n: "mod" is a keyword
|
|
|
|
raise error.ParseError(_("mod expects two arguments"))
|
|
|
|
|
2016-10-09 18:09:20 +03:00
|
|
|
func = lambda a, b: a % b
|
|
|
|
return runarithmetic(context, mapping, (func, args[0], args[1]))
|
2016-10-09 15:51:04 +03:00
|
|
|
|
2016-10-08 16:24:26 +03:00
|
|
|
@templatefunc('relpath(path)')
|
|
|
|
def relpath(context, mapping, args):
|
|
|
|
"""Convert a repository-absolute path into a filesystem path relative to
|
|
|
|
the current working directory."""
|
|
|
|
if len(args) != 1:
|
|
|
|
# i18n: "relpath" is a keyword
|
|
|
|
raise error.ParseError(_("relpath expects one argument"))
|
|
|
|
|
|
|
|
repo = mapping['ctx'].repo()
|
|
|
|
path = evalstring(context, mapping, args[0])
|
|
|
|
return repo.pathto(path)
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('revset(query[, formatargs...])')
|
template: add revset() template function
Adds a template function that executes a revset and returns the list of
revisions as the result. It has the signature 'revset(query [, args...])'. The
args are optional and are applied to the query string using the standard
python string.format(args) pattern. This allows things like:
'{revset("parents({0})", rev)}' to produce the parents of each individual
commit in the log output. If no args are specified, the revset result is
cached for the duration of the templater; so it's better to not use args if
performance is a concern.
By itself, revset() can be used to print commit parents, print the common
ancestor of a commit with the main branch, etc.
It can be used with the ifcontains() function to do things like
'{ifcontains(rev, revset('.'), label(...), ...)}' to color the working copy
parent, to color certain branches, to color draft commits, etc.
2014-02-12 09:04:12 +04:00
|
|
|
def revset(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Execute a revision set query. See
|
2015-04-02 06:19:43 +03:00
|
|
|
:hg:`help revset`."""
|
template: add revset() template function
Adds a template function that executes a revset and returns the list of
revisions as the result. It has the signature 'revset(query [, args...])'. The
args are optional and are applied to the query string using the standard
python string.format(args) pattern. This allows things like:
'{revset("parents({0})", rev)}' to produce the parents of each individual
commit in the log output. If no args are specified, the revset result is
cached for the duration of the templater; so it's better to not use args if
performance is a concern.
By itself, revset() can be used to print commit parents, print the common
ancestor of a commit with the main branch, etc.
It can be used with the ifcontains() function to do things like
'{ifcontains(rev, revset('.'), label(...), ...)}' to color the working copy
parent, to color certain branches, to color draft commits, etc.
2014-02-12 09:04:12 +04:00
|
|
|
if not len(args) > 0:
|
|
|
|
# i18n: "revset" is a keyword
|
|
|
|
raise error.ParseError(_("revset expects one or more arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
raw = evalstring(context, mapping, args[0])
|
template: add revset() template function
Adds a template function that executes a revset and returns the list of
revisions as the result. It has the signature 'revset(query [, args...])'. The
args are optional and are applied to the query string using the standard
python string.format(args) pattern. This allows things like:
'{revset("parents({0})", rev)}' to produce the parents of each individual
commit in the log output. If no args are specified, the revset result is
cached for the duration of the templater; so it's better to not use args if
performance is a concern.
By itself, revset() can be used to print commit parents, print the common
ancestor of a commit with the main branch, etc.
It can be used with the ifcontains() function to do things like
'{ifcontains(rev, revset('.'), label(...), ...)}' to color the working copy
parent, to color certain branches, to color draft commits, etc.
2014-02-12 09:04:12 +04:00
|
|
|
ctx = mapping['ctx']
|
2015-03-13 06:11:15 +03:00
|
|
|
repo = ctx.repo()
|
template: add revset() template function
Adds a template function that executes a revset and returns the list of
revisions as the result. It has the signature 'revset(query [, args...])'. The
args are optional and are applied to the query string using the standard
python string.format(args) pattern. This allows things like:
'{revset("parents({0})", rev)}' to produce the parents of each individual
commit in the log output. If no args are specified, the revset result is
cached for the duration of the templater; so it's better to not use args if
performance is a concern.
By itself, revset() can be used to print commit parents, print the common
ancestor of a commit with the main branch, etc.
It can be used with the ifcontains() function to do things like
'{ifcontains(rev, revset('.'), label(...), ...)}' to color the working copy
parent, to color certain branches, to color draft commits, etc.
2014-02-12 09:04:12 +04:00
|
|
|
|
2014-08-23 16:23:02 +04:00
|
|
|
def query(expr):
|
|
|
|
m = revsetmod.match(repo.ui, expr)
|
2015-02-02 16:21:07 +03:00
|
|
|
return m(repo)
|
2014-08-23 16:23:02 +04:00
|
|
|
|
template: add revset() template function
Adds a template function that executes a revset and returns the list of
revisions as the result. It has the signature 'revset(query [, args...])'. The
args are optional and are applied to the query string using the standard
python string.format(args) pattern. This allows things like:
'{revset("parents({0})", rev)}' to produce the parents of each individual
commit in the log output. If no args are specified, the revset result is
cached for the duration of the templater; so it's better to not use args if
performance is a concern.
By itself, revset() can be used to print commit parents, print the common
ancestor of a commit with the main branch, etc.
It can be used with the ifcontains() function to do things like
'{ifcontains(rev, revset('.'), label(...), ...)}' to color the working copy
parent, to color certain branches, to color draft commits, etc.
2014-02-12 09:04:12 +04:00
|
|
|
if len(args) > 1:
|
2016-02-13 18:27:09 +03:00
|
|
|
formatargs = [evalfuncarg(context, mapping, a) for a in args[1:]]
|
2014-08-23 16:23:02 +04:00
|
|
|
revs = query(revsetmod.formatspec(raw, *formatargs))
|
2016-02-12 12:39:48 +03:00
|
|
|
revs = list(revs)
|
template: add revset() template function
Adds a template function that executes a revset and returns the list of
revisions as the result. It has the signature 'revset(query [, args...])'. The
args are optional and are applied to the query string using the standard
python string.format(args) pattern. This allows things like:
'{revset("parents({0})", rev)}' to produce the parents of each individual
commit in the log output. If no args are specified, the revset result is
cached for the duration of the templater; so it's better to not use args if
performance is a concern.
By itself, revset() can be used to print commit parents, print the common
ancestor of a commit with the main branch, etc.
It can be used with the ifcontains() function to do things like
'{ifcontains(rev, revset('.'), label(...), ...)}' to color the working copy
parent, to color certain branches, to color draft commits, etc.
2014-02-12 09:04:12 +04:00
|
|
|
else:
|
|
|
|
revsetcache = mapping['cache'].setdefault("revsetcache", {})
|
|
|
|
if raw in revsetcache:
|
|
|
|
revs = revsetcache[raw]
|
|
|
|
else:
|
2014-08-23 16:23:02 +04:00
|
|
|
revs = query(raw)
|
2016-02-12 12:39:48 +03:00
|
|
|
revs = list(revs)
|
template: add revset() template function
Adds a template function that executes a revset and returns the list of
revisions as the result. It has the signature 'revset(query [, args...])'. The
args are optional and are applied to the query string using the standard
python string.format(args) pattern. This allows things like:
'{revset("parents({0})", rev)}' to produce the parents of each individual
commit in the log output. If no args are specified, the revset result is
cached for the duration of the templater; so it's better to not use args if
performance is a concern.
By itself, revset() can be used to print commit parents, print the common
ancestor of a commit with the main branch, etc.
It can be used with the ifcontains() function to do things like
'{ifcontains(rev, revset('.'), label(...), ...)}' to color the working copy
parent, to color certain branches, to color draft commits, etc.
2014-02-12 09:04:12 +04:00
|
|
|
revsetcache[raw] = revs
|
|
|
|
|
2015-09-11 18:21:41 +03:00
|
|
|
return templatekw.showrevslist("revision", revs, **mapping)
|
template: add revset() template function
Adds a template function that executes a revset and returns the list of
revisions as the result. It has the signature 'revset(query [, args...])'. The
args are optional and are applied to the query string using the standard
python string.format(args) pattern. This allows things like:
'{revset("parents({0})", rev)}' to produce the parents of each individual
commit in the log output. If no args are specified, the revset result is
cached for the duration of the templater; so it's better to not use args if
performance is a concern.
By itself, revset() can be used to print commit parents, print the common
ancestor of a commit with the main branch, etc.
It can be used with the ifcontains() function to do things like
'{ifcontains(rev, revset('.'), label(...), ...)}' to color the working copy
parent, to color certain branches, to color draft commits, etc.
2014-02-12 09:04:12 +04:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('rstdoc(text, style)')
|
2013-02-10 01:51:21 +04:00
|
|
|
def rstdoc(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Format ReStructuredText."""
|
2013-02-10 01:51:21 +04:00
|
|
|
if len(args) != 2:
|
|
|
|
# i18n: "rstdoc" is a keyword
|
|
|
|
raise error.ParseError(_("rstdoc expects two arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
text = evalstring(context, mapping, args[0])
|
|
|
|
style = evalstring(context, mapping, args[1])
|
2013-02-10 01:51:21 +04:00
|
|
|
|
2013-04-22 12:27:56 +04:00
|
|
|
return minirst.format(text, style=style, keep=['verbose'])
|
2013-02-10 01:51:21 +04:00
|
|
|
|
2016-05-03 19:49:54 +03:00
|
|
|
@templatefunc('separate(sep, args)')
|
|
|
|
def separate(context, mapping, args):
|
|
|
|
"""Add a separator between non-empty arguments."""
|
|
|
|
if not args:
|
|
|
|
# i18n: "separate" is a keyword
|
|
|
|
raise error.ParseError(_("separate expects at least one argument"))
|
|
|
|
|
|
|
|
sep = evalstring(context, mapping, args[0])
|
|
|
|
first = True
|
|
|
|
for arg in args[1:]:
|
|
|
|
argstr = evalstring(context, mapping, arg)
|
|
|
|
if not argstr:
|
|
|
|
continue
|
|
|
|
if first:
|
|
|
|
first = False
|
|
|
|
else:
|
|
|
|
yield sep
|
|
|
|
yield argstr
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('shortest(node, minlength=4)')
|
2014-01-17 12:10:37 +04:00
|
|
|
def shortest(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Obtain the shortest representation of
|
2015-04-02 06:19:43 +03:00
|
|
|
a node."""
|
2014-01-17 12:10:37 +04:00
|
|
|
if not (1 <= len(args) <= 2):
|
2014-10-31 20:43:08 +03:00
|
|
|
# i18n: "shortest" is a keyword
|
2014-01-17 12:10:37 +04:00
|
|
|
raise error.ParseError(_("shortest() expects one or two arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
node = evalstring(context, mapping, args[0])
|
2014-01-17 12:10:37 +04:00
|
|
|
|
|
|
|
minlength = 4
|
|
|
|
if len(args) > 1:
|
2016-02-14 07:09:17 +03:00
|
|
|
minlength = evalinteger(context, mapping, args[1],
|
|
|
|
# i18n: "shortest" is a keyword
|
|
|
|
_("shortest() expects an integer minlength"))
|
2014-01-17 12:10:37 +04:00
|
|
|
|
2016-10-25 15:49:30 +03:00
|
|
|
# _partialmatch() of filtered changelog could take O(len(repo)) time,
|
|
|
|
# which would be unacceptably slow. so we look for hash collision in
|
|
|
|
# unfiltered space, which means some hashes may be slightly longer.
|
|
|
|
cl = mapping['ctx']._repo.unfiltered().changelog
|
2014-01-17 12:10:37 +04:00
|
|
|
def isvalid(test):
|
|
|
|
try:
|
2016-10-23 08:05:23 +03:00
|
|
|
if cl._partialmatch(test) is None:
|
|
|
|
return False
|
2014-02-06 08:22:28 +04:00
|
|
|
|
2014-01-17 12:10:37 +04:00
|
|
|
try:
|
2014-02-20 10:46:13 +04:00
|
|
|
i = int(test)
|
|
|
|
# if we are a pure int, then starting with zero will not be
|
|
|
|
# confused as a rev; or, obviously, if the int is larger than
|
|
|
|
# the value of the tip rev
|
|
|
|
if test[0] == '0' or i > len(cl):
|
|
|
|
return True
|
2014-01-17 12:10:37 +04:00
|
|
|
return False
|
|
|
|
except ValueError:
|
|
|
|
return True
|
|
|
|
except error.RevlogError:
|
|
|
|
return False
|
|
|
|
|
|
|
|
shortest = node
|
|
|
|
startlength = max(6, minlength)
|
|
|
|
length = startlength
|
|
|
|
while True:
|
|
|
|
test = node[:length]
|
|
|
|
if isvalid(test):
|
|
|
|
shortest = test
|
|
|
|
if length == minlength or length > startlength:
|
|
|
|
return shortest
|
|
|
|
length -= 1
|
|
|
|
else:
|
|
|
|
length += 1
|
|
|
|
if len(shortest) <= length:
|
|
|
|
return shortest
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('strip(text[, chars])')
|
2013-06-25 21:02:22 +04:00
|
|
|
def strip(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Strip characters from a string. By default,
|
2015-07-04 10:07:42 +03:00
|
|
|
strips all leading and trailing whitespace."""
|
2013-06-25 21:02:22 +04:00
|
|
|
if not (1 <= len(args) <= 2):
|
2014-10-31 20:43:08 +03:00
|
|
|
# i18n: "strip" is a keyword
|
2013-06-25 21:02:22 +04:00
|
|
|
raise error.ParseError(_("strip expects one or two arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
text = evalstring(context, mapping, args[0])
|
2013-06-25 21:02:22 +04:00
|
|
|
if len(args) == 2:
|
2016-02-14 07:30:32 +03:00
|
|
|
chars = evalstring(context, mapping, args[1])
|
2013-06-25 21:02:22 +04:00
|
|
|
return text.strip(chars)
|
|
|
|
return text.strip()
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('sub(pattern, replacement, expression)')
|
2013-06-29 14:27:53 +04:00
|
|
|
def sub(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Perform text substitution
|
2015-04-02 06:19:43 +03:00
|
|
|
using regular expressions."""
|
2013-06-29 14:27:53 +04:00
|
|
|
if len(args) != 3:
|
|
|
|
# i18n: "sub" is a keyword
|
|
|
|
raise error.ParseError(_("sub expects three arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
pat = evalstring(context, mapping, args[0])
|
|
|
|
rpl = evalstring(context, mapping, args[1])
|
|
|
|
src = evalstring(context, mapping, args[2])
|
2015-09-07 15:58:17 +03:00
|
|
|
try:
|
|
|
|
patre = re.compile(pat)
|
|
|
|
except re.error:
|
|
|
|
# i18n: "sub" is a keyword
|
|
|
|
raise error.ParseError(_("sub got an invalid pattern: %s") % pat)
|
|
|
|
try:
|
|
|
|
yield patre.sub(rpl, src)
|
|
|
|
except re.error:
|
|
|
|
# i18n: "sub" is a keyword
|
|
|
|
raise error.ParseError(_("sub got an invalid replacement: %s") % rpl)
|
2013-06-29 14:27:53 +04:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('startswith(pattern, text)')
|
2014-06-13 04:53:37 +04:00
|
|
|
def startswith(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Returns the value from the "text" argument
|
2015-04-02 06:19:43 +03:00
|
|
|
if it begins with the content from the "pattern" argument."""
|
2014-06-13 04:53:37 +04:00
|
|
|
if len(args) != 2:
|
2014-07-31 21:14:24 +04:00
|
|
|
# i18n: "startswith" is a keyword
|
2014-06-13 04:53:37 +04:00
|
|
|
raise error.ParseError(_("startswith expects two arguments"))
|
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
patn = evalstring(context, mapping, args[0])
|
|
|
|
text = evalstring(context, mapping, args[1])
|
2014-06-13 04:53:37 +04:00
|
|
|
if text.startswith(patn):
|
|
|
|
return text
|
|
|
|
return ''
|
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
@templatefunc('word(number, text[, separator])')
|
2014-06-13 05:02:23 +04:00
|
|
|
def word(context, mapping, args):
|
2016-03-29 20:10:44 +03:00
|
|
|
"""Return the nth word from a string."""
|
2014-06-13 05:02:23 +04:00
|
|
|
if not (2 <= len(args) <= 3):
|
2014-07-31 21:14:24 +04:00
|
|
|
# i18n: "word" is a keyword
|
2014-06-13 05:02:23 +04:00
|
|
|
raise error.ParseError(_("word expects two or three arguments, got %d")
|
|
|
|
% len(args))
|
|
|
|
|
2016-02-14 06:42:25 +03:00
|
|
|
num = evalinteger(context, mapping, args[0],
|
|
|
|
# i18n: "word" is a keyword
|
|
|
|
_("word expects an integer index"))
|
2016-02-14 07:30:32 +03:00
|
|
|
text = evalstring(context, mapping, args[1])
|
2014-06-13 05:02:23 +04:00
|
|
|
if len(args) == 3:
|
2016-02-14 07:30:32 +03:00
|
|
|
splitter = evalstring(context, mapping, args[2])
|
2014-06-13 05:02:23 +04:00
|
|
|
else:
|
|
|
|
splitter = None
|
|
|
|
|
|
|
|
tokens = text.split(splitter)
|
2015-10-05 19:37:26 +03:00
|
|
|
if num >= len(tokens) or num < -len(tokens):
|
2014-06-13 05:02:23 +04:00
|
|
|
return ''
|
|
|
|
else:
|
|
|
|
return tokens[num]
|
|
|
|
|
2015-05-02 12:05:04 +03:00
|
|
|
# methods to interpret function arguments or inner expressions (e.g. {_(x)})
|
|
|
|
exprmethods = {
|
2015-05-01 14:43:55 +03:00
|
|
|
"integer": lambda e, c: (runinteger, e[1]),
|
2010-12-20 21:09:00 +03:00
|
|
|
"string": lambda e, c: (runstring, e[1]),
|
|
|
|
"symbol": lambda e, c: (runsymbol, e[1]),
|
templater: take any string literals as template, but not for rawstring (BC)
This patch series is intended to unify the interpretation of string literals.
It is breaking change that boldly assumes
a. string literal "..." never contains template-like fragment or it is
intended to be a template
b. we tend to use raw string literal r"..." for regexp pattern in which "{"
should have different meaning
Currently, we don't have a comprehensible rule how string literals are
evaluated in template functions. For example, fill() takes "initialindent"
and "hangindent" as templates, but not for "text", whereas "text" is a
template in pad() function.
date(date, fmt)
diff(includepattern, excludepattern)
fill(text, width, initialident: T, hangindent: T)
get(dict, key)
if(expr, then: T, else: T)
ifcontains(search, thing, then: T, else: T)
ifeq(expr1, expr2, then: T, else: T)
indent(text, indentchars, firstline)
join(list, sep)
label(label: T, expr: T)
pad(text: T, width, fillchar, right)
revset(query, formatargs...])
rstdoc(text, style)
shortest(node, minlength)
startswith(pattern, text)
strip(text, chars)
sub(pattern, replacement, expression: T)
word(number, text, separator)
expr % template: T
T: interpret "string" or r"rawstring" as template
This patch series adjusts the rule as follows:
a. string literal, '' or "", starts template processing (BC)
b. raw string literal, r'' or r"", disables both \-escape and template
processing (BC, done by subsequent patches)
c. fragment not surrounded by {} is non-templated string
"ccc{'aaa'}{r'bbb'}"
------------------ *: template
--- c: string
--- a: template
--- b: rawstring
Because this can eliminate the compilation of template arguments from the
evaluation phase, "hg log -Tdefault" gets faster.
% cd mozilla-central
% LANG=C HGRCPATH=/dev/null hg log -Tdefault -r0:10000 --time > /dev/null
before: real 4.870 secs (user 4.860+0.000 sys 0.010+0.000)
after: real 3.480 secs (user 3.440+0.000 sys 0.030+0.000)
Also, this will allow us to parse nested templates at once for better error
indication.
2015-06-13 13:49:54 +03:00
|
|
|
"template": buildtemplate,
|
2015-05-02 12:05:04 +03:00
|
|
|
"group": lambda e, c: compileexp(e[1], c, exprmethods),
|
2010-12-20 21:09:00 +03:00
|
|
|
# ".": buildmember,
|
|
|
|
"|": buildfilter,
|
|
|
|
"%": buildmap,
|
|
|
|
"func": buildfunc,
|
2016-10-09 15:51:04 +03:00
|
|
|
"+": lambda e, c: buildarithmetic(e, c, lambda a, b: a + b),
|
|
|
|
"-": lambda e, c: buildarithmetic(e, c, lambda a, b: a - b),
|
|
|
|
"negate": buildnegate,
|
|
|
|
"*": lambda e, c: buildarithmetic(e, c, lambda a, b: a * b),
|
|
|
|
"/": lambda e, c: buildarithmetic(e, c, lambda a, b: a // b),
|
2010-12-20 21:09:00 +03:00
|
|
|
}
|
|
|
|
|
2015-05-02 12:05:04 +03:00
|
|
|
# methods to interpret top-level template (e.g. {x}, {x|_}, {x % "y"})
|
|
|
|
methods = exprmethods.copy()
|
2015-05-01 14:43:55 +03:00
|
|
|
methods["integer"] = exprmethods["symbol"] # '{1}' as variable
|
2015-05-02 12:05:04 +03:00
|
|
|
|
2016-03-27 14:31:56 +03:00
|
|
|
class _aliasrules(parser.basealiasrules):
|
|
|
|
"""Parsing and expansion rule set of template aliases"""
|
|
|
|
_section = _('template alias')
|
|
|
|
_parse = staticmethod(_parseexpr)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _trygetfunc(tree):
|
|
|
|
"""Return (name, args) if tree is func(...) or ...|filter; otherwise
|
|
|
|
None"""
|
|
|
|
if tree[0] == 'func' and tree[1][0] == 'symbol':
|
|
|
|
return tree[1][1], getlist(tree[2])
|
|
|
|
if tree[0] == '|' and tree[2][0] == 'symbol':
|
|
|
|
return tree[2][1], [tree[1]]
|
|
|
|
|
|
|
|
def expandaliases(tree, aliases):
|
|
|
|
"""Return new tree of aliases are expanded"""
|
|
|
|
aliasmap = _aliasrules.buildmap(aliases)
|
|
|
|
return _aliasrules.expand(aliasmap, tree)
|
|
|
|
|
2010-12-20 21:09:00 +03:00
|
|
|
# template engine
|
2006-02-27 20:35:43 +03:00
|
|
|
|
2009-05-12 14:04:05 +04:00
|
|
|
stringify = templatefilters.stringify
|
2008-10-17 22:34:31 +04:00
|
|
|
|
2010-04-06 00:25:08 +04:00
|
|
|
def _flatten(thing):
|
|
|
|
'''yield a single stream from a possibly nested set of iterators'''
|
|
|
|
if isinstance(thing, str):
|
|
|
|
yield thing
|
2016-08-18 09:55:07 +03:00
|
|
|
elif thing is None:
|
|
|
|
pass
|
2011-07-26 00:30:19 +04:00
|
|
|
elif not util.safehasattr(thing, '__iter__'):
|
2016-08-18 09:55:07 +03:00
|
|
|
yield str(thing)
|
2010-04-06 00:25:08 +04:00
|
|
|
else:
|
2010-04-06 00:25:08 +04:00
|
|
|
for i in thing:
|
|
|
|
if isinstance(i, str):
|
|
|
|
yield i
|
2016-08-18 09:55:07 +03:00
|
|
|
elif i is None:
|
|
|
|
pass
|
2011-07-26 00:30:19 +04:00
|
|
|
elif not util.safehasattr(i, '__iter__'):
|
2016-08-18 09:55:07 +03:00
|
|
|
yield str(i)
|
|
|
|
else:
|
2010-04-06 00:25:08 +04:00
|
|
|
for j in _flatten(i):
|
|
|
|
yield j
|
|
|
|
|
2015-05-04 04:03:13 +03:00
|
|
|
def unquotestring(s):
|
2016-03-26 12:12:12 +03:00
|
|
|
'''unwrap quotes if any; otherwise returns unmodified string'''
|
2016-03-27 11:42:19 +03:00
|
|
|
if len(s) < 2 or s[0] not in "'\"" or s[0] != s[-1]:
|
2016-03-26 12:12:12 +03:00
|
|
|
return s
|
2015-06-27 09:28:46 +03:00
|
|
|
return s[1:-1]
|
2006-02-26 23:59:28 +03:00
|
|
|
|
2009-04-06 17:09:54 +04:00
|
|
|
class engine(object):
|
2006-02-28 02:07:25 +03:00
|
|
|
'''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
|
2007-04-10 21:24:28 +04:00
|
|
|
looks for strings like this: {foo}. it expands {foo} by looking up
|
2006-02-28 02:07:25 +03:00
|
|
|
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|...}.'''
|
|
|
|
|
2016-03-27 14:59:36 +03:00
|
|
|
def __init__(self, loader, filters=None, defaults=None, aliases=()):
|
2010-04-06 00:25:08 +04:00
|
|
|
self._loader = loader
|
2015-09-24 11:04:58 +03:00
|
|
|
if filters is None:
|
|
|
|
filters = {}
|
2010-04-06 00:25:08 +04:00
|
|
|
self._filters = filters
|
2015-09-24 11:05:21 +03:00
|
|
|
if defaults is None:
|
|
|
|
defaults = {}
|
2010-04-06 00:25:08 +04:00
|
|
|
self._defaults = defaults
|
2016-03-27 14:59:36 +03:00
|
|
|
self._aliasmap = _aliasrules.buildmap(aliases)
|
2016-02-13 17:54:24 +03:00
|
|
|
self._cache = {} # key: (func, data)
|
2009-04-06 17:09:54 +04:00
|
|
|
|
2010-04-06 00:25:08 +04:00
|
|
|
def _load(self, t):
|
|
|
|
'''load, parse, and cache a template'''
|
|
|
|
if t not in self._cache:
|
2015-07-23 17:41:29 +03:00
|
|
|
# put poison to cut recursion while compiling 't'
|
2016-02-13 17:54:24 +03:00
|
|
|
self._cache[t] = (_runrecursivesymbol, t)
|
2015-07-23 17:41:29 +03:00
|
|
|
try:
|
2016-04-03 07:23:40 +03:00
|
|
|
x = parse(self._loader(t))
|
2016-03-27 14:59:36 +03:00
|
|
|
if self._aliasmap:
|
|
|
|
x = _aliasrules.expand(self._aliasmap, x)
|
2016-04-03 07:23:40 +03:00
|
|
|
self._cache[t] = compileexp(x, self, methods)
|
2015-07-23 17:41:29 +03:00
|
|
|
except: # re-raises
|
|
|
|
del self._cache[t]
|
|
|
|
raise
|
2010-04-06 00:25:08 +04:00
|
|
|
return self._cache[t]
|
|
|
|
|
2010-12-20 21:09:00 +03:00
|
|
|
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.'''
|
2016-02-13 17:54:24 +03:00
|
|
|
func, data = self._load(t)
|
|
|
|
return _flatten(func(self, mapping, data))
|
2009-04-06 17:09:54 +04:00
|
|
|
|
2009-05-12 14:05:19 +04:00
|
|
|
engines = {'default': engine}
|
|
|
|
|
2013-05-03 05:23:14 +04:00
|
|
|
def stylelist():
|
2014-09-28 18:57:37 +04:00
|
|
|
paths = templatepaths()
|
2014-01-23 04:29:50 +04:00
|
|
|
if not paths:
|
|
|
|
return _('no templates found, try `hg debuginstall` for more info')
|
2015-12-31 11:16:59 +03:00
|
|
|
dirlist = os.listdir(paths[0])
|
2013-05-03 05:23:14 +04:00
|
|
|
stylelist = []
|
|
|
|
for file in dirlist:
|
|
|
|
split = file.split(".")
|
2016-03-02 08:27:07 +03:00
|
|
|
if split[-1] in ('orig', 'rej'):
|
|
|
|
continue
|
2013-05-03 05:23:14 +04:00
|
|
|
if split[0] == "map-cmdline":
|
|
|
|
stylelist.append(split[1])
|
2013-05-03 05:41:22 +04:00
|
|
|
return ", ".join(sorted(stylelist))
|
2013-05-03 05:23:14 +04:00
|
|
|
|
2016-04-03 17:18:30 +03:00
|
|
|
def _readmapfile(mapfile):
|
|
|
|
"""Load template elements from the given map file"""
|
|
|
|
if not os.path.exists(mapfile):
|
|
|
|
raise error.Abort(_("style '%s' not found") % mapfile,
|
|
|
|
hint=_("available styles: %s") % stylelist())
|
|
|
|
|
|
|
|
base = os.path.dirname(mapfile)
|
|
|
|
conf = config.config(includepaths=templatepaths())
|
|
|
|
conf.read(mapfile)
|
|
|
|
|
|
|
|
cache = {}
|
|
|
|
tmap = {}
|
|
|
|
for key, val in conf[''].items():
|
|
|
|
if not val:
|
|
|
|
raise error.ParseError(_('missing value'), conf.source('', key))
|
|
|
|
if val[0] in "'\"":
|
|
|
|
if val[0] != val[-1]:
|
|
|
|
raise error.ParseError(_('unmatched quotes'),
|
|
|
|
conf.source('', key))
|
|
|
|
cache[key] = unquotestring(val)
|
2016-08-17 21:40:27 +03:00
|
|
|
elif key == "__base__":
|
|
|
|
# treat as a pointer to a base class for this style
|
|
|
|
path = util.normpath(os.path.join(base, val))
|
2016-08-25 03:43:45 +03:00
|
|
|
|
|
|
|
# fallback check in template paths
|
|
|
|
if not os.path.exists(path):
|
|
|
|
for p in templatepaths():
|
|
|
|
p2 = util.normpath(os.path.join(p, val))
|
|
|
|
if os.path.isfile(p2):
|
|
|
|
path = p2
|
|
|
|
break
|
|
|
|
p3 = util.normpath(os.path.join(p2, "map"))
|
|
|
|
if os.path.isfile(p3):
|
|
|
|
path = p3
|
|
|
|
break
|
|
|
|
|
2016-08-17 21:40:27 +03:00
|
|
|
bcache, btmap = _readmapfile(path)
|
|
|
|
for k in bcache:
|
|
|
|
if k not in cache:
|
|
|
|
cache[k] = bcache[k]
|
|
|
|
for k in btmap:
|
|
|
|
if k not in tmap:
|
|
|
|
tmap[k] = btmap[k]
|
2016-04-03 17:18:30 +03:00
|
|
|
else:
|
|
|
|
val = 'default', val
|
|
|
|
if ':' in val[1]:
|
|
|
|
val = val[1].split(':', 1)
|
|
|
|
tmap[key] = val[0], os.path.join(base, val[1])
|
|
|
|
return cache, tmap
|
|
|
|
|
2015-10-08 22:55:45 +03:00
|
|
|
class TemplateNotFound(error.Abort):
|
2013-09-22 13:52:18 +04:00
|
|
|
pass
|
|
|
|
|
2009-04-06 17:09:54 +04:00
|
|
|
class templater(object):
|
|
|
|
|
2016-03-27 14:59:36 +03:00
|
|
|
def __init__(self, filters=None, defaults=None, cache=None, aliases=(),
|
2008-11-22 02:51:40 +03:00
|
|
|
minchunk=1024, maxchunk=65536):
|
2006-02-28 02:07:25 +03:00
|
|
|
'''set up template engine.
|
|
|
|
filters is dict of functions. each transforms a value into another.
|
2016-03-27 14:59:36 +03:00
|
|
|
defaults is dict of default map definitions.
|
|
|
|
aliases is list of alias (name, replacement) pairs.
|
|
|
|
'''
|
2015-09-24 11:06:10 +03:00
|
|
|
if filters is None:
|
|
|
|
filters = {}
|
2015-09-24 11:06:41 +03:00
|
|
|
if defaults is None:
|
|
|
|
defaults = {}
|
2015-09-24 11:07:09 +03:00
|
|
|
if cache is None:
|
|
|
|
cache = {}
|
2006-03-18 20:51:25 +03:00
|
|
|
self.cache = cache.copy()
|
2006-02-26 23:59:28 +03:00
|
|
|
self.map = {}
|
2009-05-12 14:04:05 +04:00
|
|
|
self.filters = templatefilters.filters.copy()
|
|
|
|
self.filters.update(filters)
|
2006-03-15 22:28:00 +03:00
|
|
|
self.defaults = defaults
|
2016-03-27 14:59:36 +03:00
|
|
|
self._aliases = aliases
|
2008-11-22 02:51:40 +03:00
|
|
|
self.minchunk, self.maxchunk = minchunk, maxchunk
|
2010-12-22 22:16:03 +03:00
|
|
|
self.ecache = {}
|
2006-02-26 23:59:28 +03:00
|
|
|
|
2016-04-03 17:26:48 +03:00
|
|
|
@classmethod
|
|
|
|
def frommapfile(cls, mapfile, filters=None, defaults=None, cache=None,
|
|
|
|
minchunk=1024, maxchunk=65536):
|
|
|
|
"""Create templater from the specified map file"""
|
2016-03-27 14:59:36 +03:00
|
|
|
t = cls(filters, defaults, cache, [], minchunk, maxchunk)
|
2016-04-03 17:18:30 +03:00
|
|
|
cache, tmap = _readmapfile(mapfile)
|
2016-04-03 17:26:48 +03:00
|
|
|
t.cache.update(cache)
|
|
|
|
t.map = tmap
|
|
|
|
return t
|
2006-02-26 23:59:28 +03:00
|
|
|
|
2006-02-27 07:53:37 +03:00
|
|
|
def __contains__(self, key):
|
2006-11-13 22:26:57 +03:00
|
|
|
return key in self.cache or key in self.map
|
2006-02-27 07:53:37 +03:00
|
|
|
|
2009-04-06 17:09:54 +04:00
|
|
|
def load(self, t):
|
2008-06-29 15:16:25 +04:00
|
|
|
'''Get the template for the given template name. Use a local cache.'''
|
2012-05-12 18:00:57 +04:00
|
|
|
if t not in self.cache:
|
2006-02-27 23:41:20 +03:00
|
|
|
try:
|
2011-05-02 12:11:18 +04:00
|
|
|
self.cache[t] = util.readfile(self.map[t][1])
|
2015-06-24 08:20:08 +03:00
|
|
|
except KeyError as inst:
|
2013-09-22 13:52:18 +04:00
|
|
|
raise TemplateNotFound(_('"%s" not in template map') %
|
|
|
|
inst.args[0])
|
2015-06-24 08:20:08 +03:00
|
|
|
except IOError as inst:
|
2006-02-27 23:41:20 +03:00
|
|
|
raise IOError(inst.args[0], _('template file %s: %s') %
|
2009-05-12 14:05:19 +04:00
|
|
|
(self.map[t][1], inst.args[1]))
|
2008-06-29 15:16:25 +04:00
|
|
|
return self.cache[t]
|
2006-02-27 20:15:59 +03:00
|
|
|
|
2010-04-06 00:25:08 +04:00
|
|
|
def __call__(self, t, **mapping):
|
2009-05-12 14:05:19 +04:00
|
|
|
ttype = t in self.map and self.map[t][0] or 'default'
|
2010-12-22 22:16:03 +03:00
|
|
|
if ttype not in self.ecache:
|
2016-04-03 05:20:50 +03:00
|
|
|
try:
|
|
|
|
ecls = engines[ttype]
|
|
|
|
except KeyError:
|
|
|
|
raise error.Abort(_('invalid template engine: %s') % ttype)
|
2016-03-27 14:59:36 +03:00
|
|
|
self.ecache[ttype] = ecls(self.load, self.filters, self.defaults,
|
|
|
|
self._aliases)
|
2010-12-22 22:16:03 +03:00
|
|
|
proc = self.ecache[ttype]
|
2009-05-12 14:05:19 +04:00
|
|
|
|
2010-04-06 00:25:08 +04:00
|
|
|
stream = proc.process(t, mapping)
|
2008-11-22 02:51:40 +03:00
|
|
|
if self.minchunk:
|
|
|
|
stream = util.increasingchunks(stream, min=self.minchunk,
|
|
|
|
max=self.maxchunk)
|
|
|
|
return stream
|
2008-11-27 18:07:13 +03:00
|
|
|
|
2014-09-28 18:57:37 +04:00
|
|
|
def templatepaths():
|
|
|
|
'''return locations used for template files.'''
|
2014-09-28 18:57:37 +04:00
|
|
|
pathsrel = ['templates']
|
2014-09-28 18:57:37 +04:00
|
|
|
paths = [os.path.normpath(os.path.join(util.datapath, f))
|
|
|
|
for f in pathsrel]
|
|
|
|
return [p for p in paths if os.path.isdir(p)]
|
2006-05-03 21:25:28 +04:00
|
|
|
|
2014-09-28 18:57:37 +04:00
|
|
|
def templatepath(name):
|
|
|
|
'''return location of template file. returns None if not found.'''
|
|
|
|
for p in templatepaths():
|
|
|
|
f = os.path.join(p, name)
|
|
|
|
if os.path.exists(f):
|
|
|
|
return f
|
|
|
|
return None
|
|
|
|
|
2009-11-12 18:39:11 +03:00
|
|
|
def stylemap(styles, paths=None):
|
2009-04-04 19:46:11 +04:00
|
|
|
"""Return path to mapfile for a given style.
|
|
|
|
|
|
|
|
Searches mapfile in the following locations:
|
|
|
|
1. templatepath/style/map
|
|
|
|
2. templatepath/map-style
|
|
|
|
3. templatepath/map
|
|
|
|
"""
|
|
|
|
|
|
|
|
if paths is None:
|
2014-09-28 18:57:37 +04:00
|
|
|
paths = templatepaths()
|
2009-04-04 19:46:11 +04:00
|
|
|
elif isinstance(paths, str):
|
2009-04-27 18:26:31 +04:00
|
|
|
paths = [paths]
|
2009-04-04 19:46:11 +04:00
|
|
|
|
2009-11-12 18:39:11 +03:00
|
|
|
if isinstance(styles, str):
|
|
|
|
styles = [styles]
|
|
|
|
|
|
|
|
for style in styles:
|
2015-03-13 15:18:59 +03:00
|
|
|
# only plain name is allowed to honor template paths
|
|
|
|
if (not style
|
|
|
|
or style in (os.curdir, os.pardir)
|
|
|
|
or os.sep in style
|
|
|
|
or os.altsep and os.altsep in style):
|
2009-11-12 18:39:11 +03:00
|
|
|
continue
|
|
|
|
locations = [os.path.join(style, 'map'), 'map-' + style]
|
|
|
|
locations.append('map')
|
|
|
|
|
|
|
|
for path in paths:
|
|
|
|
for location in locations:
|
|
|
|
mapfile = os.path.join(path, location)
|
|
|
|
if os.path.isfile(mapfile):
|
|
|
|
return style, mapfile
|
2009-04-04 19:46:11 +04:00
|
|
|
|
|
|
|
raise RuntimeError("No hgweb templates found in %r" % paths)
|
2015-04-03 15:36:39 +03:00
|
|
|
|
2016-03-29 20:10:44 +03:00
|
|
|
def loadfunction(ui, extname, registrarobj):
|
|
|
|
"""Load template function from specified registrarobj
|
|
|
|
"""
|
|
|
|
for name, func in registrarobj._table.iteritems():
|
|
|
|
funcs[name] = func
|
|
|
|
|
2015-04-03 15:36:39 +03:00
|
|
|
# tell hggettext to extract docstrings from these functions:
|
|
|
|
i18nfunctions = funcs.values()
|