From patchwork Wed Apr 12 15:53:23 2017 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [7,of,9] templater: add dict() constructor From: Yuya Nishihara X-Patchwork-Id: 20138 Message-Id: <9477eee4e9d3ebb38769.1492012403@mimosa> To: mercurial-devel@mercurial-scm.org Date: Thu, 13 Apr 2017 00:53:23 +0900 # HG changeset patch # User Yuya Nishihara # Date 1491227646 -32400 # Mon Apr 03 22:54:06 2017 +0900 # Node ID 9477eee4e9d3ebb387691d9626c0616387c1959a # Parent 902f2a928a842508239707885301648c325928cb templater: add dict() constructor It's troublesome to build JSON by template, so let's add programmatic way. diff --git a/mercurial/templater.py b/mercurial/templater.py --- a/mercurial/templater.py +++ b/mercurial/templater.py @@ -532,6 +532,14 @@ def date(context, mapping, args): # i18n: "date" is a keyword raise error.ParseError(_("date expects a date information")) +@templatefunc('dict([key=value...])', argspec='**kwargs') +def dict_(context, mapping, args): + """Construct a dict from key-value pairs.""" + data = util.sortdict() + data.update((k, evalfuncarg(context, mapping, v)) + for k, v in args['kwargs'].iteritems()) + return templatekw.hybriddict(data) + @templatefunc('diff([includepattern [, excludepattern]])') def diff(context, mapping, args): """Show a diff, optionally diff --git a/tests/test-command-template.t b/tests/test-command-template.t --- a/tests/test-command-template.t +++ b/tests/test-command-template.t @@ -3404,6 +3404,22 @@ Test branches inside if statement: $ hg log -r 0 --template '{if(branches, "yes", "no")}\n' no +Test dict constructor: + + $ hg log -r 0 -T '{dict(y=node|short, x=rev)}\n' + y=f7769ec2ab97 x=0 + $ hg log -r 0 -T '{dict(x=rev, y=node|short) % "{key}={value}\n"}' + x=0 + y=f7769ec2ab97 + $ hg log -r 0 -T '{dict(x=rev, y=node|short)|json}\n' + {"x": 0, "y": "f7769ec2ab97"} + $ hg log -r 0 -T '{dict()|json}\n' + {} + + $ hg log -r 0 -T '{dict(x=rev, x=node)}' + hg: parse error: dict got multiple values for keyword argument 'x' + [255] + Test get function: $ hg log -r 0 --template '{get(extras, "branch")}\n'