templater: move getdictitem() to hybrid class
authorYuya Nishihara <yuya@tcha.org>
Wed, 21 Mar 2018 01:39:44 +0900
changeset 38242 12b6ee9e88f3
parent 38241 ad06a4264daf
child 38243 06d11cd90516
templater: move getdictitem() to hybrid class Since a raw dict will never be returned by evalwrapped(), we don't need to support d.get(key).
mercurial/templatefuncs.py
mercurial/templateutil.py
--- a/mercurial/templatefuncs.py	Sat Apr 21 17:43:16 2018 +0900
+++ b/mercurial/templatefuncs.py	Wed Mar 21 01:39:44 2018 +0900
@@ -262,12 +262,12 @@
         raise error.ParseError(_("get() expects two arguments"))
 
     dictarg = evalwrapped(context, mapping, args[0])
-    if not util.safehasattr(dictarg, 'get'):
+    if not util.safehasattr(dictarg, 'getmember'):
         # i18n: "get" is a keyword
         raise error.ParseError(_("get() expects a dict as first argument"))
 
     key = evalfuncarg(context, mapping, args[1])
-    return templateutil.getdictitem(dictarg, key)
+    return dictarg.getmember(context, mapping, key)
 
 @templatefunc('if(expr, then[, else])')
 def if_(context, mapping, args):
--- a/mercurial/templateutil.py	Sat Apr 21 17:43:16 2018 +0900
+++ b/mercurial/templateutil.py	Wed Mar 21 01:39:44 2018 +0900
@@ -128,6 +128,17 @@
         self._joinfmt = joinfmt
         self.keytype = keytype  # hint for 'x in y' where type(x) is unresolved
 
+    def getmember(self, context, mapping, key):
+        # TODO: maybe split hybrid list/dict types?
+        if not util.safehasattr(self._values, 'get'):
+            raise error.ParseError(_('not a dictionary'))
+        return self._wrapvalue(key, self._values.get(key))
+
+    def _wrapvalue(self, key, val):
+        if val is None:
+            return
+        return wraphybridvalue(self, key, val)
+
     def itermaps(self, context):
         makemap = self._makemap
         for x in self._values:
@@ -667,8 +678,8 @@
         lm = context.overlaymap(mapping, d.tomap())
         return runsymbol(context, lm, memb)
     try:
-        if util.safehasattr(d, 'get'):
-            return getdictitem(d, memb)
+        if util.safehasattr(d, 'getmember'):
+            return d.getmember(context, mapping, memb)
         raise error.ParseError
     except error.ParseError:
         sym = findsymbolicname(darg)
@@ -693,12 +704,6 @@
     except ZeroDivisionError:
         raise error.Abort(_('division by zero is not defined'))
 
-def getdictitem(dictarg, key):
-    val = dictarg.get(key)
-    if val is None:
-        return
-    return wraphybridvalue(dictarg, key, val)
-
 def joinitems(itemiter, sep):
     """Join items with the separator; Returns generator of bytes"""
     first = True