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
|
|
|
|
2017-09-03 08:56:31 +03:00
|
|
|
from __future__ import absolute_import, print_function
|
2015-08-09 04:23:53 +03:00
|
|
|
|
|
|
|
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 (
|
2017-03-18 15:02:20 +03:00
|
|
|
color,
|
2015-08-09 04:23:53 +03:00
|
|
|
config,
|
2017-03-18 14:50:15 +03:00
|
|
|
encoding,
|
2015-08-09 04:23:53 +03:00
|
|
|
error,
|
|
|
|
minirst,
|
template: compute verb in obsfateverb
Add a template function obsfateverb which use the markers information to
compute a better obsfate verb.
The current logic behind the obsfate verb is simple for the moment:
- If the successorsets is empty, the changeset has been pruned, for example:
Obsfate: pruned
- If the successorsets length is 1, the changeset has been rewritten without
divergence, for example:
Obsfate: rewritten as 2:337fec4d2edc, 3:f257fde29c7a
- If the successorsets length is more than 1, the changeset has diverged, for
example:
Obsfate: split as 2:337fec4d2edc, 3:f257fde29c7a
As the divergence might occurs on a subset of successors, we might see some
successors twice:
Obsfate: split as 9:0b997eb7ceee, 5:dd800401bd8c, 10:eceed8f98ffc; split
as 8:b18bc8331526, 5:dd800401bd8c, 10:eceed8f98ffc
2017-07-03 16:33:27 +03:00
|
|
|
obsutil,
|
2015-08-09 04:23:53 +03:00
|
|
|
parser,
|
2016-12-17 17:44:24 +03:00
|
|
|
pycompat,
|
2016-03-29 20:10:44 +03:00
|
|
|
registrar,
|
2015-08-09 04:23:53 +03:00
|
|
|
revset as revsetmod,
|
2017-02-19 12:19:33 +03:00
|
|
|
revsetlang,
|
2017-10-01 13:13:09 +03:00
|
|
|
scmutil,
|
2015-08-09 04:23:53 +03:00
|
|
|
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),
|
2017-09-09 13:32:56 +03:00
|
|
|
".": (18, None, None, (".", 18), None),
|
2017-04-24 15:37:11 +03:00
|
|
|
"%": (15, None, None, ("%", 15), None),
|
2017-04-03 14:44:05 +03:00
|
|
|
"|": (15, None, None, ("|", 15), None),
|
|
|
|
"*": (5, None, None, ("*", 5), None),
|
|
|
|
"/": (5, None, None, ("/", 5), None),
|
|
|
|
"+": (4, None, None, ("+", 4), None),
|
|
|
|
"-": (4, None, ("negate", 19), ("-", 4), None),
|
2017-04-03 14:55:55 +03:00
|
|
|
"=": (3, None, None, ("keyvalue", 3), None),
|
2017-04-03 14:37:25 +03:00
|
|
|
",": (2, None, None, ("list", 2), None),
|
|
|
|
")": (0, None, None, None, 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
|
2017-05-04 22:56:49 +03:00
|
|
|
program = pycompat.bytestr(program)
|
2010-12-20 21:09:00 +03:00
|
|
|
while pos < end:
|
|
|
|
c = program[pos]
|
|
|
|
if c.isspace(): # skip inter-token whitespace
|
|
|
|
pass
|
2017-09-09 13:32:56 +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"""
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parsetemplate(b'foo{bar}"baz', 0, 12)
|
2015-06-15 17:11:35 +03:00
|
|
|
([('string', 'foo'), ('symbol', 'bar'), ('string', '"baz')], 12)
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parsetemplate(b'foo{bar}"baz', 0, 12, quote=b'"')
|
2015-06-15 17:11:35 +03:00
|
|
|
([('string', 'foo'), ('symbol', 'bar')], 9)
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parsetemplate(b'foo"{bar}', 0, 9, quote=b'"')
|
2015-06-15 17:11:35 +03:00
|
|
|
([('string', 'foo')], 4)
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parsetemplate(br'foo\"bar"baz', 0, 12, quote=b'"')
|
2015-06-15 17:11:35 +03:00
|
|
|
([('string', 'foo"'), ('string', 'bar')], 9)
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parsetemplate(br'foo\\"bar', 0, 10, quote=b'"')
|
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
|
2017-09-03 11:37:17 +03:00
|
|
|
c = tmpl[n:n + 1]
|
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):
|
2017-09-03 08:56:31 +03:00
|
|
|
... print(pycompat.sysstr(prettyformat(_unnesttemplatelist(tree))))
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> f((b'template', []))
|
2017-09-03 15:17:25 +03:00
|
|
|
(string '')
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> f((b'template', [(b'string', b'foo')]))
|
2017-09-03 15:17:25 +03:00
|
|
|
(string 'foo')
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> f((b'template', [(b'string', b'foo'), (b'symbol', b'rev')]))
|
2016-02-13 17:20:47 +03:00
|
|
|
(template
|
2017-09-03 15:17:25 +03:00
|
|
|
(string 'foo')
|
|
|
|
(symbol 'rev'))
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> f((b'template', [(b'symbol', b'rev')])) # template(rev) -> str
|
2016-02-13 17:20:47 +03:00
|
|
|
(template
|
2017-09-03 15:17:25 +03:00
|
|
|
(symbol 'rev'))
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> f((b'template', [(b'template', [(b'string', b'foo')])]))
|
2017-09-03 15:17:25 +03:00
|
|
|
(string 'foo')
|
2016-02-13 17:20:47 +03:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parseexpr(b'"foo"')
|
2016-03-27 14:29:03 +03:00
|
|
|
('string', 'foo')
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parseexpr(b'foo(bar)')
|
2016-03-27 14:29:03 +03:00
|
|
|
('func', ('symbol', 'foo'), ('symbol', 'bar'))
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parseexpr(b'foo(')
|
2016-03-27 14:29:03 +03:00
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ParseError: ('not a prefix: end', 4)
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> _parseexpr(b'"foo" "bar"')
|
2016-03-27 14:29:03 +03:00
|
|
|
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"))
|
|
|
|
|
2017-04-08 17:33:32 +03:00
|
|
|
def findsymbolicname(arg):
|
|
|
|
"""Find symbolic name for the given compiled expression; returns None
|
|
|
|
if nothing found reliably"""
|
|
|
|
while True:
|
|
|
|
func, data = arg
|
|
|
|
if func is runsymbol:
|
|
|
|
return data
|
|
|
|
elif func is runfilter:
|
|
|
|
arg = data[0]
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
2017-09-02 17:13:54 +03:00
|
|
|
def evalrawexp(context, mapping, arg):
|
|
|
|
"""Evaluate given argument as a bare template object which may require
|
|
|
|
further processing (such as folding generator of strings)"""
|
2015-09-01 12:57:50 +03:00
|
|
|
func, data = arg
|
2017-09-02 17:13:54 +03:00
|
|
|
return func(context, mapping, data)
|
|
|
|
|
|
|
|
def evalfuncarg(context, mapping, arg):
|
|
|
|
"""Evaluate given argument as value type"""
|
|
|
|
thing = evalrawexp(context, mapping, arg)
|
templatekw: add new-style template expansion to {manifest}
The goal is to allow us to easily access to nested data. The dot operator
will be introduced later so we can write '{p1.files}' instead of
'{revset("p1()") % "{files}"}' for example.
In the example above, 'p1' needs to carry a mapping dict along with its
string representation. If it were a list or a dict, it could be wrapped
semi-transparently with the _hybrid class, but for non-list/dict types,
it would be difficult to proxy all necessary functions to underlying value
type because several core operations may conflict with the ones of the
underlying value:
- hash(value) should be different from hash(wrapped(value)), which means
dict[wrapped(value)] would be invalid
- 'value == wrapped(value)' would be false, breaks 'ifcontains'
- len(wrapped(value)) may be either len(value) or len(iter(wrapped(value)))
So the wrapper has no proxy functions and its scope designed to be minimal.
It's unwrapped at eval*() functions so we don't have to care for a wrapped
object unless it's really needed:
# most template functions just call evalfuncarg()
unwrapped_value = evalfuncarg(context, mapping, args[n])
# if wrapped value is needed, use evalrawexp()
maybe_wrapped_value = evalrawexp(context, mapping, args[n])
Another idea was to wrap every template variable with a tagging class, but
which seemed uneasy without a static type checker.
This patch updates {manifest} to a mappable as an example.
2016-04-24 12:41:23 +03:00
|
|
|
thing = templatekw.unwrapvalue(thing)
|
2017-09-02 17:13:54 +03:00
|
|
|
# evalrawexp() may return string, generator of strings or arbitrary object
|
|
|
|
# such as date tuple, but filter does not want generator.
|
2015-09-01 12:57:50 +03:00
|
|
|
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)
|
templatekw: add new-style template expansion to {manifest}
The goal is to allow us to easily access to nested data. The dot operator
will be introduced later so we can write '{p1.files}' instead of
'{revset("p1()") % "{files}"}' for example.
In the example above, 'p1' needs to carry a mapping dict along with its
string representation. If it were a list or a dict, it could be wrapped
semi-transparently with the _hybrid class, but for non-list/dict types,
it would be difficult to proxy all necessary functions to underlying value
type because several core operations may conflict with the ones of the
underlying value:
- hash(value) should be different from hash(wrapped(value)), which means
dict[wrapped(value)] would be invalid
- 'value == wrapped(value)' would be false, breaks 'ifcontains'
- len(wrapped(value)) may be either len(value) or len(iter(wrapped(value)))
So the wrapper has no proxy functions and its scope designed to be minimal.
It's unwrapped at eval*() functions so we don't have to care for a wrapped
object unless it's really needed:
# most template functions just call evalfuncarg()
unwrapped_value = evalfuncarg(context, mapping, args[n])
# if wrapped value is needed, use evalrawexp()
maybe_wrapped_value = evalrawexp(context, mapping, args[n])
Another idea was to wrap every template variable with a tagging class, but
which seemed uneasy without a static type checker.
This patch updates {manifest} to a mappable as an example.
2016-04-24 12:41:23 +03:00
|
|
|
thing = templatekw.unwrapvalue(thing)
|
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))
|
|
|
|
|
2017-09-19 17:13:46 +03:00
|
|
|
def evalinteger(context, mapping, arg, err=None):
|
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):
|
2017-09-19 17:13:46 +03:00
|
|
|
raise error.ParseError(err or _('not an integer'))
|
2016-02-14 06:42:25 +03:00
|
|
|
|
2016-02-14 07:30:32 +03:00
|
|
|
def evalstring(context, mapping, arg):
|
2017-09-02 17:13:54 +03:00
|
|
|
return stringify(evalrawexp(context, mapping, arg))
|
2016-02-14 07:30:32 +03:00
|
|
|
|
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)
|
|
|
|
|
2017-09-19 17:13:46 +03:00
|
|
|
_evalfuncbytype = {
|
|
|
|
bool: evalboolean,
|
|
|
|
bytes: evalstring,
|
|
|
|
int: evalinteger,
|
|
|
|
}
|
|
|
|
|
|
|
|
def evalastype(context, mapping, arg, typ):
|
|
|
|
"""Evaluate given argument and coerce its type"""
|
|
|
|
try:
|
|
|
|
f = _evalfuncbytype[typ]
|
|
|
|
except KeyError:
|
|
|
|
raise error.ProgrammingError('invalid type specified: %r' % typ)
|
|
|
|
return f(context, mapping, arg)
|
|
|
|
|
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):
|
2017-06-22 00:46:16 +03:00
|
|
|
return v(**pycompat.strkwargs(mapping))
|
2010-12-20 21:09:00 +03:00
|
|
|
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):
|
2017-09-02 17:13:54 +03:00
|
|
|
for arg in template:
|
|
|
|
yield evalrawexp(context, mapping, arg)
|
2015-06-12 18:15:22 +03:00
|
|
|
|
2010-12-20 21:09:00 +03:00
|
|
|
def buildfilter(exp, context):
|
2015-07-04 09:59:03 +03:00
|
|
|
n = getsymbol(exp[2])
|
|
|
|
if n in context._filters:
|
|
|
|
filt = context._filters[n]
|
2017-04-03 15:22:39 +03:00
|
|
|
arg = compileexp(exp[1], context, methods)
|
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]
|
2017-04-03 15:22:39 +03:00
|
|
|
args = _buildfuncargs(exp[1], context, methods, n, f._argspec)
|
|
|
|
return (f, args)
|
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):
|
2017-04-08 17:33:32 +03:00
|
|
|
sym = findsymbolicname(arg)
|
|
|
|
if sym:
|
|
|
|
msg = (_("template filter '%s' is not compatible with keyword '%s'")
|
2017-10-17 17:51:43 +03:00
|
|
|
% (pycompat.sysbytes(filt.__name__), sym))
|
2012-08-18 02:12:01 +04:00
|
|
|
else:
|
2017-10-17 17:51:43 +03:00
|
|
|
msg = (_("incompatible use of template filter '%s'")
|
|
|
|
% pycompat.sysbytes(filt.__name__))
|
2017-04-08 17:33:32 +03:00
|
|
|
raise error.Abort(msg)
|
2010-12-20 21:09:00 +03:00
|
|
|
|
|
|
|
def buildmap(exp, context):
|
2017-09-02 17:09:34 +03:00
|
|
|
darg = compileexp(exp[1], context, methods)
|
|
|
|
targ = gettemplate(exp[2], context)
|
|
|
|
return (runmap, (darg, targ))
|
2010-12-20 21:09:00 +03:00
|
|
|
|
|
|
|
def runmap(context, mapping, data):
|
2017-09-02 17:13:54 +03:00
|
|
|
darg, targ = data
|
|
|
|
d = evalrawexp(context, mapping, darg)
|
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:
|
2017-09-02 17:13:54 +03:00
|
|
|
sym = findsymbolicname(darg)
|
2017-09-09 13:01:18 +03:00
|
|
|
if sym:
|
|
|
|
raise error.ParseError(_("keyword '%s' is not iterable") % sym)
|
2016-02-14 07:58:46 +03:00
|
|
|
else:
|
|
|
|
raise error.ParseError(_("%r is not iterable") % d)
|
2012-09-22 03:54:00 +04:00
|
|
|
|
2016-04-22 15:46:33 +03:00
|
|
|
for i, v in enumerate(diter):
|
2016-02-24 22:31:55 +03:00
|
|
|
lm = mapping.copy()
|
2016-04-22 15:46:33 +03:00
|
|
|
lm['index'] = i
|
2016-04-22 15:45:06 +03:00
|
|
|
if isinstance(v, dict):
|
|
|
|
lm.update(v)
|
2012-11-13 02:05:39 +04:00
|
|
|
lm['originalnode'] = mapping.get('node')
|
2017-09-02 17:13:54 +03:00
|
|
|
yield evalrawexp(context, lm, targ)
|
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.
|
2016-04-22 15:45:06 +03:00
|
|
|
yield v
|
2010-12-20 21:09:00 +03:00
|
|
|
|
2017-09-09 13:32:56 +03:00
|
|
|
def buildmember(exp, context):
|
|
|
|
darg = compileexp(exp[1], context, methods)
|
|
|
|
memb = getsymbol(exp[2])
|
|
|
|
return (runmember, (darg, memb))
|
|
|
|
|
|
|
|
def runmember(context, mapping, data):
|
|
|
|
darg, memb = data
|
|
|
|
d = evalrawexp(context, mapping, darg)
|
|
|
|
if util.safehasattr(d, 'tomap'):
|
|
|
|
lm = mapping.copy()
|
|
|
|
lm.update(d.tomap())
|
|
|
|
return runsymbol(context, lm, memb)
|
2017-09-18 17:07:17 +03:00
|
|
|
if util.safehasattr(d, 'get'):
|
|
|
|
return _getdictitem(d, memb)
|
2017-09-09 13:32:56 +03:00
|
|
|
|
|
|
|
sym = findsymbolicname(darg)
|
|
|
|
if sym:
|
|
|
|
raise error.ParseError(_("keyword '%s' has no member") % sym)
|
|
|
|
else:
|
|
|
|
raise error.ParseError(_("%r has no member") % d)
|
|
|
|
|
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])
|
2011-07-23 23:33:35 +04:00
|
|
|
if n in funcs:
|
|
|
|
f = funcs[n]
|
2017-04-03 15:22:39 +03:00
|
|
|
args = _buildfuncargs(exp[2], context, exprmethods, n, f._argspec)
|
2011-07-23 23:33:35 +04:00
|
|
|
return (f, args)
|
2010-12-20 21:09:00 +03:00
|
|
|
if n in context._filters:
|
2017-04-03 15:22:39 +03:00
|
|
|
args = _buildfuncargs(exp[2], context, exprmethods, n, argspec=None)
|
2010-12-20 21:09:00 +03:00
|
|
|
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
|
|
|
|
2017-04-03 15:22:39 +03:00
|
|
|
def _buildfuncargs(exp, context, curmethods, funcname, argspec):
|
|
|
|
"""Compile parsed tree of function arguments into list or dict of
|
2017-04-03 16:07:09 +03:00
|
|
|
(func, data) pairs
|
|
|
|
|
|
|
|
>>> context = engine(lambda t: (runsymbol, t))
|
|
|
|
>>> def fargs(expr, argspec):
|
|
|
|
... x = _parseexpr(expr)
|
|
|
|
... n = getsymbol(x[1])
|
|
|
|
... return _buildfuncargs(x[2], context, exprmethods, n, argspec)
|
2017-09-03 11:33:10 +03:00
|
|
|
>>> list(fargs(b'a(l=1, k=2)', b'k l m').keys())
|
2017-04-09 05:58:27 +03:00
|
|
|
['l', 'k']
|
2017-09-03 08:32:11 +03:00
|
|
|
>>> args = fargs(b'a(opts=1, k=2)', b'**opts')
|
2017-09-03 11:33:10 +03:00
|
|
|
>>> list(args.keys()), list(args[b'opts'].keys())
|
2017-04-09 05:58:27 +03:00
|
|
|
(['opts'], ['opts', 'k'])
|
2017-04-03 16:07:09 +03:00
|
|
|
"""
|
2017-04-03 15:22:39 +03:00
|
|
|
def compiledict(xs):
|
2017-04-09 05:58:27 +03:00
|
|
|
return util.sortdict((k, compileexp(x, context, curmethods))
|
|
|
|
for k, x in xs.iteritems())
|
2017-04-03 15:22:39 +03:00
|
|
|
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
|
2017-04-03 16:07:09 +03:00
|
|
|
_poskeys, varkey, _keys, optkey = argspec = parser.splitargspec(argspec)
|
2017-04-03 15:22:39 +03:00
|
|
|
treeargs = parser.buildargsdict(getlist(exp), funcname, argspec,
|
|
|
|
keyvaluenode='keyvalue', keynode='symbol')
|
2017-04-09 05:58:27 +03:00
|
|
|
compargs = util.sortdict()
|
2017-04-03 15:22:39 +03:00
|
|
|
if varkey:
|
|
|
|
compargs[varkey] = compilelist(treeargs.pop(varkey))
|
2017-04-03 16:07:09 +03:00
|
|
|
if optkey:
|
|
|
|
compargs[optkey] = compiledict(treeargs.pop(optkey))
|
2017-04-03 15:22:39 +03:00
|
|
|
compargs.update(compiledict(treeargs))
|
|
|
|
return compargs
|
|
|
|
|
2017-04-03 14:55:55 +03:00
|
|
|
def buildkeyvaluepair(exp, content):
|
|
|
|
raise error.ParseError(_("can't use a key-value pair in this context"))
|
|
|
|
|
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
|
|
|
|
2017-04-03 17:13:49 +03:00
|
|
|
@templatefunc('dict([[key=]value...])', argspec='*args **kwargs')
|
2017-04-03 16:54:06 +03:00
|
|
|
def dict_(context, mapping, args):
|
2017-04-03 17:13:49 +03:00
|
|
|
"""Construct a dict from key-value pairs. A key may be omitted if
|
|
|
|
a value expression can provide an unambiguous name."""
|
2017-04-03 16:54:06 +03:00
|
|
|
data = util.sortdict()
|
2017-04-03 17:13:49 +03:00
|
|
|
|
|
|
|
for v in args['args']:
|
|
|
|
k = findsymbolicname(v)
|
|
|
|
if not k:
|
|
|
|
raise error.ParseError(_('dict key cannot be inferred'))
|
|
|
|
if k in data or k in args['kwargs']:
|
|
|
|
raise error.ParseError(_("duplicated dict key '%s' inferred") % k)
|
|
|
|
data[k] = evalfuncarg(context, mapping, v)
|
|
|
|
|
2017-04-03 16:54:06 +03:00
|
|
|
data.update((k, evalfuncarg(context, mapping, v))
|
|
|
|
for k, v in args['kwargs'].iteritems())
|
|
|
|
return templatekw.hybriddict(data)
|
|
|
|
|
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)
|
|
|
|
|
2017-10-01 13:13:09 +03:00
|
|
|
@templatefunc('extdata(source)', argspec='source')
|
|
|
|
def extdata(context, mapping, args):
|
|
|
|
"""Show a text read from the specified extdata source. (EXPERIMENTAL)"""
|
|
|
|
if 'source' not in args:
|
|
|
|
# i18n: "extdata" is a keyword
|
|
|
|
raise error.ParseError(_('extdata expects one argument'))
|
|
|
|
|
|
|
|
source = evalstring(context, mapping, args['source'])
|
|
|
|
cache = mapping['cache'].setdefault('extdata', {})
|
|
|
|
ctx = mapping['ctx']
|
|
|
|
if source in cache:
|
|
|
|
data = cache[source]
|
|
|
|
else:
|
|
|
|
data = cache[source] = scmutil.extdatasource(ctx.repo(), source)
|
|
|
|
return data.get(ctx.rev(), '')
|
|
|
|
|
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))
|
2017-04-05 15:47:34 +03:00
|
|
|
return templatekw.showlist("file", files, mapping)
|
2016-09-23 11:15:05 +03:00
|
|
|
|
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)
|
|
|
|
|
2017-02-25 10:26:58 +03:00
|
|
|
@templatefunc('formatnode(node)')
|
|
|
|
def formatnode(context, mapping, args):
|
|
|
|
"""Obtain the preferred form of a changeset hash. (DEPRECATED)"""
|
|
|
|
if len(args) != 1:
|
|
|
|
# i18n: "formatnode" is a keyword
|
|
|
|
raise error.ParseError(_("formatnode expects one argument"))
|
|
|
|
|
|
|
|
ui = mapping['ui']
|
|
|
|
node = evalstring(context, mapping, args[0])
|
|
|
|
if ui.debugflag:
|
|
|
|
return node
|
|
|
|
return templatefilters.short(node)
|
|
|
|
|
2017-04-03 16:23:52 +03:00
|
|
|
@templatefunc('pad(text, width[, fillchar=\' \'[, left=False]])',
|
|
|
|
argspec='text width fillchar left')
|
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."""
|
2017-04-03 16:23:52 +03:00
|
|
|
if 'text' not in args or 'width' not in args:
|
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"))
|
|
|
|
|
2017-04-03 16:23:52 +03:00
|
|
|
width = evalinteger(context, mapping, args['width'],
|
2016-02-14 07:05:09 +03:00
|
|
|
# i18n: "pad" is a keyword
|
|
|
|
_("pad() expects an integer width"))
|
2014-01-17 12:16:48 +04:00
|
|
|
|
2017-04-03 16:23:52 +03:00
|
|
|
text = evalstring(context, mapping, args['text'])
|
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 = ' '
|
2017-04-03 16:23:52 +03:00
|
|
|
if 'fillchar' in args:
|
|
|
|
fillchar = evalstring(context, mapping, args['fillchar'])
|
2017-03-18 15:02:20 +03:00
|
|
|
if len(color.stripeffects(fillchar)) != 1:
|
2017-03-18 14:38:44 +03:00
|
|
|
# i18n: "pad" is a keyword
|
|
|
|
raise error.ParseError(_("pad() expects a single fill character"))
|
2017-04-03 16:23:52 +03:00
|
|
|
if 'left' in args:
|
|
|
|
left = evalboolean(context, mapping, args['left'])
|
2014-01-17 12:16:48 +04:00
|
|
|
|
2017-03-18 15:02:20 +03:00
|
|
|
fillwidth = width - encoding.colwidth(color.stripeffects(text))
|
2017-03-18 14:50:15 +03:00
|
|
|
if fillwidth <= 0:
|
|
|
|
return text
|
2016-04-22 15:32:30 +03:00
|
|
|
if left:
|
2017-03-18 14:50:15 +03:00
|
|
|
return fillchar * fillwidth + text
|
2014-01-17 12:16:48 +04:00
|
|
|
else:
|
2017-03-18 14:50:15 +03:00
|
|
|
return text + fillchar * fillwidth
|
2014-01-17 12:16:48 +04:00
|
|
|
|
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])
|
2017-09-18 17:07:17 +03:00
|
|
|
return _getdictitem(dictarg, key)
|
|
|
|
|
|
|
|
def _getdictitem(dictarg, key):
|
2017-09-09 13:13:25 +03:00
|
|
|
val = dictarg.get(key)
|
|
|
|
if val is None:
|
|
|
|
return
|
|
|
|
return templatekw.wraphybridvalue(dictarg, key, val)
|
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:
|
2017-09-02 17:13:54 +03:00
|
|
|
yield evalrawexp(context, mapping, args[1])
|
2012-09-25 00:26:56 +04:00
|
|
|
elif len(args) == 3:
|
2017-09-02 17:13:54 +03:00
|
|
|
yield evalrawexp(context, mapping, args[2])
|
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
|
|
|
haystack = evalfuncarg(context, mapping, args[1])
|
2017-10-12 16:09:11 +03:00
|
|
|
try:
|
|
|
|
needle = evalastype(context, mapping, args[0],
|
|
|
|
getattr(haystack, 'keytype', None) or bytes)
|
|
|
|
found = (needle in haystack)
|
|
|
|
except error.ParseError:
|
|
|
|
found = False
|
2014-02-12 09:10:00 +04:00
|
|
|
|
2017-10-12 16:09:11 +03:00
|
|
|
if found:
|
2017-09-02 17:13:54 +03:00
|
|
|
yield evalrawexp(context, mapping, args[2])
|
2014-02-12 09:10:00 +04:00
|
|
|
elif len(args) == 4:
|
2017-09-02 17:13:54 +03:00
|
|
|
yield evalrawexp(context, mapping, args[3])
|
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:
|
2017-09-02 17:13:54 +03:00
|
|
|
yield evalrawexp(context, mapping, args[2])
|
2012-09-25 00:26:56 +04:00
|
|
|
elif len(args) == 4:
|
2017-09-02 17:13:54 +03:00
|
|
|
yield evalrawexp(context, mapping, args[3])
|
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"))
|
|
|
|
|
2017-09-02 17:13:54 +03:00
|
|
|
# TODO: perhaps this should be evalfuncarg(), but it can't because hgweb
|
|
|
|
# abuses generator as a keyword that returns a list of dicts.
|
|
|
|
joinset = evalrawexp(context, mapping, args[0])
|
templatekw: add new-style template expansion to {manifest}
The goal is to allow us to easily access to nested data. The dot operator
will be introduced later so we can write '{p1.files}' instead of
'{revset("p1()") % "{files}"}' for example.
In the example above, 'p1' needs to carry a mapping dict along with its
string representation. If it were a list or a dict, it could be wrapped
semi-transparently with the _hybrid class, but for non-list/dict types,
it would be difficult to proxy all necessary functions to underlying value
type because several core operations may conflict with the ones of the
underlying value:
- hash(value) should be different from hash(wrapped(value)), which means
dict[wrapped(value)] would be invalid
- 'value == wrapped(value)' would be false, breaks 'ifcontains'
- len(wrapped(value)) may be either len(value) or len(iter(wrapped(value)))
So the wrapper has no proxy functions and its scope designed to be minimal.
It's unwrapped at eval*() functions so we don't have to care for a wrapped
object unless it's really needed:
# most template functions just call evalfuncarg()
unwrapped_value = evalfuncarg(context, mapping, args[n])
# if wrapped value is needed, use evalrawexp()
maybe_wrapped_value = evalrawexp(context, mapping, args[n])
Another idea was to wrap every template variable with a tagging class, but
which seemed uneasy without a static type checker.
This patch updates {manifest} to a mappable as an example.
2016-04-24 12:41:23 +03:00
|
|
|
joinset = templatekw.unwrapvalue(joinset)
|
2017-09-24 09:22:46 +03:00
|
|
|
joinfmt = getattr(joinset, 'joinfmt', pycompat.identity)
|
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
|
2017-09-24 09:22:46 +03:00
|
|
|
yield joinfmt(x)
|
2013-06-29 14:27:53 +04:00
|
|
|
|
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
|
2017-04-09 07:10:54 +03:00
|
|
|
most recent globally tagged ancestor of this changeset.
|
|
|
|
If no such tags exist, the "{tag}" template resolves to
|
|
|
|
the string "null"."""
|
2015-08-24 06:44:58 +03:00
|
|
|
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)
|
|
|
|
|
2017-07-03 16:34:10 +03:00
|
|
|
@templatefunc('max(iterable)')
|
|
|
|
def max_(context, mapping, args, **kwargs):
|
|
|
|
"""Return the max of an iterable"""
|
|
|
|
if len(args) != 1:
|
|
|
|
# i18n: "max" is a keyword
|
|
|
|
raise error.ParseError(_("max expects one arguments"))
|
|
|
|
|
|
|
|
iterable = evalfuncarg(context, mapping, args[0])
|
|
|
|
try:
|
2017-09-09 13:13:25 +03:00
|
|
|
x = max(iterable)
|
2017-07-03 16:34:10 +03:00
|
|
|
except (TypeError, ValueError):
|
|
|
|
# i18n: "max" is a keyword
|
|
|
|
raise error.ParseError(_("max first argument should be an iterable"))
|
2017-09-09 13:13:25 +03:00
|
|
|
return templatekw.wraphybridvalue(iterable, x, x)
|
2017-07-03 16:34:10 +03:00
|
|
|
|
|
|
|
@templatefunc('min(iterable)')
|
|
|
|
def min_(context, mapping, args, **kwargs):
|
|
|
|
"""Return the min of an iterable"""
|
|
|
|
if len(args) != 1:
|
|
|
|
# i18n: "min" is a keyword
|
|
|
|
raise error.ParseError(_("min expects one arguments"))
|
|
|
|
|
|
|
|
iterable = evalfuncarg(context, mapping, args[0])
|
|
|
|
try:
|
2017-09-09 13:13:25 +03:00
|
|
|
x = min(iterable)
|
2017-07-03 16:34:10 +03:00
|
|
|
except (TypeError, ValueError):
|
|
|
|
# i18n: "min" is a keyword
|
|
|
|
raise error.ParseError(_("min first argument should be an iterable"))
|
2017-09-09 13:13:25 +03:00
|
|
|
return templatekw.wraphybridvalue(iterable, x, x)
|
2017-07-03 16:34:10 +03:00
|
|
|
|
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
|
|
|
|
2017-09-15 20:43:22 +03:00
|
|
|
@templatefunc('obsfateoperations(markers)')
|
|
|
|
def obsfateoperations(context, mapping, args):
|
|
|
|
"""Compute obsfate related information based on markers (EXPERIMENTAL)"""
|
|
|
|
if len(args) != 1:
|
|
|
|
# i18n: "obsfateoperations" is a keyword
|
|
|
|
raise error.ParseError(_("obsfateoperations expects one arguments"))
|
|
|
|
|
|
|
|
markers = evalfuncarg(context, mapping, args[0])
|
|
|
|
|
|
|
|
try:
|
|
|
|
data = obsutil.markersoperations(markers)
|
|
|
|
return templatekw.hybridlist(data, name='operation')
|
|
|
|
except (TypeError, KeyError):
|
|
|
|
# i18n: "obsfateoperations" is a keyword
|
|
|
|
errmsg = _("obsfateoperations first argument should be an iterable")
|
|
|
|
raise error.ParseError(errmsg)
|
|
|
|
|
2017-07-03 16:34:10 +03:00
|
|
|
@templatefunc('obsfatedate(markers)')
|
|
|
|
def obsfatedate(context, mapping, args):
|
|
|
|
"""Compute obsfate related information based on markers (EXPERIMENTAL)"""
|
|
|
|
if len(args) != 1:
|
|
|
|
# i18n: "obsfatedate" is a keyword
|
|
|
|
raise error.ParseError(_("obsfatedate expects one arguments"))
|
|
|
|
|
|
|
|
markers = evalfuncarg(context, mapping, args[0])
|
|
|
|
|
|
|
|
try:
|
|
|
|
data = obsutil.markersdates(markers)
|
|
|
|
return templatekw.hybridlist(data, name='date', fmt='%d %d')
|
|
|
|
except (TypeError, KeyError):
|
|
|
|
# i18n: "obsfatedate" is a keyword
|
|
|
|
errmsg = _("obsfatedate first argument should be an iterable")
|
|
|
|
raise error.ParseError(errmsg)
|
|
|
|
|
2017-07-03 16:34:00 +03:00
|
|
|
@templatefunc('obsfateusers(markers)')
|
|
|
|
def obsfateusers(context, mapping, args):
|
|
|
|
"""Compute obsfate related information based on markers (EXPERIMENTAL)"""
|
|
|
|
if len(args) != 1:
|
|
|
|
# i18n: "obsfateusers" is a keyword
|
|
|
|
raise error.ParseError(_("obsfateusers expects one arguments"))
|
|
|
|
|
|
|
|
markers = evalfuncarg(context, mapping, args[0])
|
|
|
|
|
|
|
|
try:
|
|
|
|
data = obsutil.markersusers(markers)
|
|
|
|
return templatekw.hybridlist(data, name='user')
|
|
|
|
except (TypeError, KeyError, ValueError):
|
|
|
|
# i18n: "obsfateusers" is a keyword
|
|
|
|
msg = _("obsfateusers first argument should be an iterable of "
|
|
|
|
"obsmakers")
|
|
|
|
raise error.ParseError(msg)
|
|
|
|
|
2017-10-19 13:35:47 +03:00
|
|
|
@templatefunc('obsfateverb(successors, markers)')
|
template: compute verb in obsfateverb
Add a template function obsfateverb which use the markers information to
compute a better obsfate verb.
The current logic behind the obsfate verb is simple for the moment:
- If the successorsets is empty, the changeset has been pruned, for example:
Obsfate: pruned
- If the successorsets length is 1, the changeset has been rewritten without
divergence, for example:
Obsfate: rewritten as 2:337fec4d2edc, 3:f257fde29c7a
- If the successorsets length is more than 1, the changeset has diverged, for
example:
Obsfate: split as 2:337fec4d2edc, 3:f257fde29c7a
As the divergence might occurs on a subset of successors, we might see some
successors twice:
Obsfate: split as 9:0b997eb7ceee, 5:dd800401bd8c, 10:eceed8f98ffc; split
as 8:b18bc8331526, 5:dd800401bd8c, 10:eceed8f98ffc
2017-07-03 16:33:27 +03:00
|
|
|
def obsfateverb(context, mapping, args):
|
|
|
|
"""Compute obsfate related information based on successors (EXPERIMENTAL)"""
|
2017-10-19 13:35:47 +03:00
|
|
|
if len(args) != 2:
|
template: compute verb in obsfateverb
Add a template function obsfateverb which use the markers information to
compute a better obsfate verb.
The current logic behind the obsfate verb is simple for the moment:
- If the successorsets is empty, the changeset has been pruned, for example:
Obsfate: pruned
- If the successorsets length is 1, the changeset has been rewritten without
divergence, for example:
Obsfate: rewritten as 2:337fec4d2edc, 3:f257fde29c7a
- If the successorsets length is more than 1, the changeset has diverged, for
example:
Obsfate: split as 2:337fec4d2edc, 3:f257fde29c7a
As the divergence might occurs on a subset of successors, we might see some
successors twice:
Obsfate: split as 9:0b997eb7ceee, 5:dd800401bd8c, 10:eceed8f98ffc; split
as 8:b18bc8331526, 5:dd800401bd8c, 10:eceed8f98ffc
2017-07-03 16:33:27 +03:00
|
|
|
# i18n: "obsfateverb" is a keyword
|
2017-10-19 13:35:47 +03:00
|
|
|
raise error.ParseError(_("obsfateverb expects two arguments"))
|
template: compute verb in obsfateverb
Add a template function obsfateverb which use the markers information to
compute a better obsfate verb.
The current logic behind the obsfate verb is simple for the moment:
- If the successorsets is empty, the changeset has been pruned, for example:
Obsfate: pruned
- If the successorsets length is 1, the changeset has been rewritten without
divergence, for example:
Obsfate: rewritten as 2:337fec4d2edc, 3:f257fde29c7a
- If the successorsets length is more than 1, the changeset has diverged, for
example:
Obsfate: split as 2:337fec4d2edc, 3:f257fde29c7a
As the divergence might occurs on a subset of successors, we might see some
successors twice:
Obsfate: split as 9:0b997eb7ceee, 5:dd800401bd8c, 10:eceed8f98ffc; split
as 8:b18bc8331526, 5:dd800401bd8c, 10:eceed8f98ffc
2017-07-03 16:33:27 +03:00
|
|
|
|
|
|
|
successors = evalfuncarg(context, mapping, args[0])
|
2017-10-19 13:35:47 +03:00
|
|
|
markers = evalfuncarg(context, mapping, args[1])
|
template: compute verb in obsfateverb
Add a template function obsfateverb which use the markers information to
compute a better obsfate verb.
The current logic behind the obsfate verb is simple for the moment:
- If the successorsets is empty, the changeset has been pruned, for example:
Obsfate: pruned
- If the successorsets length is 1, the changeset has been rewritten without
divergence, for example:
Obsfate: rewritten as 2:337fec4d2edc, 3:f257fde29c7a
- If the successorsets length is more than 1, the changeset has diverged, for
example:
Obsfate: split as 2:337fec4d2edc, 3:f257fde29c7a
As the divergence might occurs on a subset of successors, we might see some
successors twice:
Obsfate: split as 9:0b997eb7ceee, 5:dd800401bd8c, 10:eceed8f98ffc; split
as 8:b18bc8331526, 5:dd800401bd8c, 10:eceed8f98ffc
2017-07-03 16:33:27 +03:00
|
|
|
|
|
|
|
try:
|
2017-10-19 13:35:47 +03:00
|
|
|
return obsutil.obsfateverb(successors, markers)
|
template: compute verb in obsfateverb
Add a template function obsfateverb which use the markers information to
compute a better obsfate verb.
The current logic behind the obsfate verb is simple for the moment:
- If the successorsets is empty, the changeset has been pruned, for example:
Obsfate: pruned
- If the successorsets length is 1, the changeset has been rewritten without
divergence, for example:
Obsfate: rewritten as 2:337fec4d2edc, 3:f257fde29c7a
- If the successorsets length is more than 1, the changeset has diverged, for
example:
Obsfate: split as 2:337fec4d2edc, 3:f257fde29c7a
As the divergence might occurs on a subset of successors, we might see some
successors twice:
Obsfate: split as 9:0b997eb7ceee, 5:dd800401bd8c, 10:eceed8f98ffc; split
as 8:b18bc8331526, 5:dd800401bd8c, 10:eceed8f98ffc
2017-07-03 16:33:27 +03:00
|
|
|
except TypeError:
|
|
|
|
# i18n: "obsfateverb" is a keyword
|
|
|
|
errmsg = _("obsfateverb first argument should be countable")
|
|
|
|
raise error.ParseError(errmsg)
|
|
|
|
|
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):
|
2017-07-16 01:51:57 +03:00
|
|
|
m = revsetmod.match(repo.ui, expr, repo=repo)
|
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:]]
|
2017-02-19 12:19:33 +03:00
|
|
|
revs = query(revsetlang.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-10-18 00:16:55 +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
|
|
|
|
2017-04-03 15:22:39 +03:00
|
|
|
@templatefunc('separate(sep, args)', argspec='sep *args')
|
2016-05-03 19:49:54 +03:00
|
|
|
def separate(context, mapping, args):
|
|
|
|
"""Add a separator between non-empty arguments."""
|
2017-04-03 15:22:39 +03:00
|
|
|
if 'sep' not in args:
|
2016-05-03 19:49:54 +03:00
|
|
|
# i18n: "separate" is a keyword
|
|
|
|
raise error.ParseError(_("separate expects at least one argument"))
|
|
|
|
|
2017-04-03 15:22:39 +03:00
|
|
|
sep = evalstring(context, mapping, args['sep'])
|
2016-05-03 19:49:54 +03:00
|
|
|
first = True
|
2017-04-03 15:22:39 +03:00
|
|
|
for arg in args['args']:
|
2016-05-03 19:49:54 +03:00
|
|
|
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
|
2017-09-15 10:01:57 +03:00
|
|
|
return cl.shortest(node, minlength)
|
2014-01-17 12:10:37 +04:00
|
|
|
|
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),
|
2017-09-09 13:32:56 +03:00
|
|
|
".": buildmember,
|
2010-12-20 21:09:00 +03:00
|
|
|
"|": buildfilter,
|
|
|
|
"%": buildmap,
|
|
|
|
"func": buildfunc,
|
2017-04-03 14:55:55 +03:00
|
|
|
"keyvalue": buildkeyvaluepair,
|
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'''
|
2017-04-04 16:19:02 +03:00
|
|
|
thing = templatekw.unwraphybrid(thing)
|
2017-06-20 21:16:18 +03:00
|
|
|
if isinstance(thing, bytes):
|
2010-04-06 00:25:08 +04:00
|
|
|
yield thing
|
2017-10-14 18:30:17 +03:00
|
|
|
elif isinstance(thing, str):
|
|
|
|
# We can only hit this on Python 3, and it's here to guard
|
|
|
|
# against infinite recursion.
|
|
|
|
raise error.ProgrammingError('Mercurial IO including templates is done'
|
|
|
|
' with bytes, not strings')
|
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__'):
|
2017-06-20 23:50:34 +03:00
|
|
|
yield pycompat.bytestr(thing)
|
2010-04-06 00:25:08 +04:00
|
|
|
else:
|
2010-04-06 00:25:08 +04:00
|
|
|
for i in thing:
|
2017-04-04 16:19:02 +03:00
|
|
|
i = templatekw.unwraphybrid(i)
|
2017-06-20 21:16:18 +03:00
|
|
|
if isinstance(i, bytes):
|
2010-04-06 00:25:08 +04:00
|
|
|
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__'):
|
2017-06-20 23:50:34 +03:00
|
|
|
yield pycompat.bytestr(i)
|
2016-08-18 09:55:07 +03:00
|
|
|
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())
|
2017-10-14 11:51:01 +03:00
|
|
|
conf.read(mapfile, remap={'': 'templates'})
|
2016-04-03 17:18:30 +03:00
|
|
|
|
|
|
|
cache = {}
|
|
|
|
tmap = {}
|
2017-10-14 12:06:42 +03:00
|
|
|
aliases = []
|
2016-08-20 12:33:02 +03:00
|
|
|
|
2017-10-14 11:51:01 +03:00
|
|
|
val = conf.get('templates', '__base__')
|
2016-08-20 12:33:02 +03:00
|
|
|
if val and val[0] not in "'\"":
|
|
|
|
# treat as a pointer to a base class for this style
|
|
|
|
path = util.normpath(os.path.join(base, val))
|
|
|
|
|
|
|
|
# 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
|
|
|
|
|
2017-10-14 12:06:42 +03:00
|
|
|
cache, tmap, aliases = _readmapfile(path)
|
2016-08-20 12:33:02 +03:00
|
|
|
|
2017-10-14 11:51:01 +03:00
|
|
|
for key, val in conf['templates'].items():
|
2016-04-03 17:18:30 +03:00
|
|
|
if not val:
|
2017-10-14 11:51:01 +03:00
|
|
|
raise error.ParseError(_('missing value'),
|
|
|
|
conf.source('templates', key))
|
2016-04-03 17:18:30 +03:00
|
|
|
if val[0] in "'\"":
|
|
|
|
if val[0] != val[-1]:
|
|
|
|
raise error.ParseError(_('unmatched quotes'),
|
2017-10-14 11:51:01 +03:00
|
|
|
conf.source('templates', key))
|
2016-04-03 17:18:30 +03:00
|
|
|
cache[key] = unquotestring(val)
|
2016-08-20 12:33:02 +03:00
|
|
|
elif key != '__base__':
|
2016-04-03 17:18:30 +03:00
|
|
|
val = 'default', val
|
|
|
|
if ':' in val[1]:
|
|
|
|
val = val[1].split(':', 1)
|
|
|
|
tmap[key] = val[0], os.path.join(base, val[1])
|
2017-10-14 12:06:42 +03:00
|
|
|
aliases.extend(conf['templatealias'].items())
|
|
|
|
return cache, tmap, aliases
|
2016-04-03 17:18:30 +03:00
|
|
|
|
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)
|
2017-10-14 12:06:42 +03:00
|
|
|
cache, tmap, aliases = _readmapfile(mapfile)
|
2016-04-03 17:26:48 +03:00
|
|
|
t.cache.update(cache)
|
|
|
|
t.map = tmap
|
2017-10-14 12:06:42 +03:00
|
|
|
t._aliases = aliases
|
2016-04-03 17:26:48 +03:00
|
|
|
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
|
|
|
|
2017-04-22 13:56:47 +03:00
|
|
|
def render(self, mapping):
|
|
|
|
"""Render the default unnamed template and return result as string"""
|
2017-09-30 13:16:36 +03:00
|
|
|
mapping = pycompat.strkwargs(mapping)
|
2017-04-22 13:56:47 +03:00
|
|
|
return stringify(self('', **mapping))
|
|
|
|
|
2010-04-06 00:25:08 +04:00
|
|
|
def __call__(self, t, **mapping):
|
2017-06-22 00:40:24 +03:00
|
|
|
mapping = pycompat.byteskwargs(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)
|
2016-12-17 17:44:24 +03:00
|
|
|
or pycompat.ossep in style
|
2016-12-17 22:47:12 +03:00
|
|
|
or pycompat.osaltsep and pycompat.osaltsep 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()
|