Mercurial > public > mercurial-scm > hg-stable
diff mercurial/templater.py @ 31928:277b3e2d711b
templater: add shorthand for building a dict like {"key": key}
Like field init shorthand of Rust. This is convenient for building a JSON
object from selected keywords.
This means dict() won't support Python-like dict(iterable) syntax because
it's ambiguous. Perhaps it could be implemented as 'mapdict(xs % (k, v))'.
author | Yuya Nishihara <yuya@tcha.org> |
---|---|
date | Mon, 03 Apr 2017 23:13:49 +0900 |
parents | 2abc556dbe92 |
children | e5eab0fe69ee |
line wrap: on
line diff
--- a/mercurial/templater.py Sat Apr 08 23:33:32 2017 +0900 +++ b/mercurial/templater.py Mon Apr 03 23:13:49 2017 +0900 @@ -545,10 +545,20 @@ # i18n: "date" is a keyword raise error.ParseError(_("date expects a date information")) -@templatefunc('dict([key=value...])', argspec='**kwargs') +@templatefunc('dict([[key=]value...])', argspec='*args **kwargs') def dict_(context, mapping, args): - """Construct a dict from key-value pairs.""" + """Construct a dict from key-value pairs. A key may be omitted if + a value expression can provide an unambiguous name.""" data = util.sortdict() + + 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) + data.update((k, evalfuncarg(context, mapping, v)) for k, v in args['kwargs'].iteritems()) return templatekw.hybriddict(data)