[PATCH 2 of 3] templater: add len template filter

Anton Shestakov engored at ya.ru
Mon Sep 8 07:04:46 CDT 2014


# HG changeset patch
# User Anton Shestakov <engored at ya.ru>
# Date 1410176607 -32400
#      Mon Sep 08 20:43:27 2014 +0900
# Node ID 82b3cffda4868d23ce436adac8687645f5f7441b
# Parent  9bb0ab35e90ac9ebf6adbd6e503f3412d9f2adb7
templater: add len template filter

Currently there is no way of telling how much children or bookmarks or tags a
certain changeset has in a template. It is possible to tell if a changeset have
either 0 or not 0 bookmarks, but no way to tell if it has 1 or 2 of them, for
example.

This filter, simply named len, makes it possible to count the number of items
in a list or the length of a string (or, anything that python's len can count).
E.g.: {children|len}, {bookmarks|len}, {file_adds|len}.

The reason why it needs a wrapper (i.e. not "len": len,) is that the python
builtin function doesn't have a func_name, which matters if the filter is not
compatible with a keyword (func_name is used to print a message). I've used a
trailing underscore to make it different from builtin function as pep8
recommends, so in case the filter is not compatible with a keywords the message
is, for example:
abort: template filter 'len_' is not compatible with keyword 'rev'

diff --git a/mercurial/templatefilters.py b/mercurial/templatefilters.py
--- a/mercurial/templatefilters.py
+++ b/mercurial/templatefilters.py
@@ -224,6 +224,10 @@ def jsonescape(s):
         s = s.replace(k, v)
     return ''.join(_uescape(c) for c in s)
 
+def len_(i):
+    """:len: List or text. Returns the length as an integer."""
+    return len(i)
+
 def localdate(text):
     """:localdate: Date. Converts a date to local date."""
     return (util.parsedate(text)[0], util.makedate()[1])
@@ -379,6 +383,7 @@ filters = {
     "isodatesec": isodatesec,
     "json": json,
     "jsonescape": jsonescape,
+    "len": len_,
     "localdate": localdate,
     "nonempty": nonempty,
     "obfuscate": obfuscate,


More information about the Mercurial-devel mailing list