Patchwork [3,of,8] templater: extend dot operator as a short for get(dict, key)

login
register
mail settings
Submitter Yuya Nishihara
Date Oct. 6, 2017, 4:05 p.m.
Message ID <bedf989f7037ebdd0071.1507305953@mimosa>
Download mbox | patch
Permalink /patch/24604/
State Accepted
Headers show

Comments

Yuya Nishihara - Oct. 6, 2017, 4:05 p.m.
# HG changeset patch
# User Yuya Nishihara <yuya@tcha.org>
# Date 1505743637 -32400
#      Mon Sep 18 23:07:17 2017 +0900
# Node ID bedf989f7037ebdd007121a534ba92c91e25e574
# Parent  b191c62651e04bf4ed9aceda32fd08c000570d82
templater: extend dot operator as a short for get(dict, key)

Patch

diff --git a/mercurial/help/templates.txt b/mercurial/help/templates.txt
--- a/mercurial/help/templates.txt
+++ b/mercurial/help/templates.txt
@@ -76,6 +76,7 @@  The dot operator can be used as a shorth
 
 - ``expr.member`` is roughly equivalent to ``expr % "{member}"`` if ``expr``
   returns a non-list/dict. The returned value is not stringified.
+- ``dict.key`` is identical to ``get(dict, "key")``.
 
 Aliases
 =======
diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -463,7 +463,8 @@  def runmember(context, mapping, data):
         lm = mapping.copy()
         lm.update(d.tomap())
         return runsymbol(context, lm, memb)
-    # TODO: d.get(memb) if dict-like?
+    if util.safehasattr(d, 'get'):
+        return _getdictitem(d, memb)
 
     sym = findsymbolicname(darg)
     if sym:
@@ -751,6 +752,9 @@  def get(context, mapping, args):
         raise error.ParseError(_("get() expects a dict as first argument"))
 
     key = evalfuncarg(context, mapping, args[1])
+    return _getdictitem(dictarg, key)
+
+def _getdictitem(dictarg, key):
     val = dictarg.get(key)
     if val is None:
         return
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
@@ -3184,6 +3184,8 @@  Test evaluation of dot operator:
 
   $ hg log -R latesttag -l1 -T '{min(revset("0:9")).node}\n'
   ce3cec86e6c26bd9bdfc590a6b92abc9680f1796
+  $ hg log -R latesttag -r0 -T '{extras.branch}\n'
+  default
 
   $ hg log -R latesttag -l1 -T '{author.invalid}\n'
   hg: parse error: keyword 'author' has no member