@@ -362,6 +362,11 @@
return ""
return pycompat.bytestr(thing)
+@templatefilter('strlen')
+def stringlen(text):
+ """Any text. Turns the value into its length."""
+ return len(text)
+
@templatefilter('stripdir')
def stripdir(text):
"""Treat the text as path and strip a directory level, if
@@ -1015,6 +1015,25 @@
# i18n: "sub" is a keyword
raise error.ParseError(_("sub got an invalid replacement: %s") % rpl)
+@templatefunc('substr(text, start[, end])')
+def substring(context, mapping, args):
+ """Returns a substring of the given text. Negative indices reference the end
+ of the string."""
+ if len(args) < 2 or len(args) > 3:
+ raise error.ParseError(_("substring takes 2 or 3 arguments"))
+
+ text = evalstring(context, mapping, args[0])
+ textlen = len(text)
+ start = evalinteger(context, mapping, args[1],
+ _("start expects an integer index"))
+ end = -1
+ if len(args) > 2:
+ end = evalinteger(context, mapping, args[2],
+ _("end expects an integer index"))
+
+ # Python's [] already handles start and end boundary conditions.
+ return text[start:end]
+
@templatefunc('startswith(pattern, text)')
def startswith(context, mapping, args):
"""Returns the value from the "text" argument
@@ -4011,6 +4011,35 @@
o line 1
line 2
+Test stringlen and substring
+Full desc is "Modify, add, remove, rename".
+String idxs: 012345678901
+Reverse string idxs: 10987654321
+
+ $ hg log -R a -r . --template '{desc|strlen}\n'
+ 27
+ $ hg log -R a -r . --template '{substr(desc, 5, 10)}\n'
+ y, ad
+ $ hg log -R a -r . --template '{substr(desc, 5, -10)}\n'
+ y, add, remo
+ $ hg log -R a -r . --template '{substr(desc, 5, strlen(desc) - 10)}\n'
+ y, add, remo
+ $ hg log -R a -r . --template '{substr(desc, -10, -3)}\n'
+ ve, ren
+
+Test substr with invalid indices
+
+ $ hg log -R a -r . --template '{substr(desc, 5, 200)}\n'
+ y, add, remove, rename
+ $ hg log -R a -r . --template '{substr(desc, 10, 5)}\n'
+
+ $ hg log -R a -r . --template '{substr(desc, 100, 200)}\n'
+
+ $ hg log -R a -r . --template '{substr(desc, -100, -50)}\n'
+
+ $ hg log -R a -r . --template '{substr(desc, -50, -100)}\n'
+
+
Test bad template with better error message
$ hg log -Gv -R a --template '{desc|user()}'