Mercurial > public > mercurial-scm > hg-stable
diff mercurial/templater.py @ 21846:8f23f8096606
templater: introduce word function
This function allows returning only the nth "word" from a string. By default
a string is split as by Python's split() function default, but an optional
third parameter can also override what string the string is split by.
author | Ryan McElroy <rmcelroy@fb.com> |
---|---|
date | Thu, 12 Jun 2014 18:02:23 -0700 |
parents | 028a48105191 |
children | 2896d450fec4 |
line wrap: on
line diff
--- a/mercurial/templater.py Thu Jul 03 23:01:37 2014 -0500 +++ b/mercurial/templater.py Thu Jun 12 18:02:23 2014 -0700 @@ -477,6 +477,25 @@ return '' +def word(context, mapping, args): + """return nth word from a string""" + if not (2 <= len(args) <= 3): + raise error.ParseError(_("word expects two or three arguments, got %d") + % len(args)) + + num = int(stringify(args[0][0](context, mapping, args[0][1]))) + text = stringify(args[1][0](context, mapping, args[1][1])) + if len(args) == 3: + splitter = stringify(args[2][0](context, mapping, args[2][1])) + else: + splitter = None + + tokens = text.split(splitter) + if num >= len(tokens): + return '' + else: + return tokens[num] + methods = { "string": lambda e, c: (runstring, e[1]), "rawstring": lambda e, c: (runrawstring, e[1]), @@ -504,6 +523,7 @@ "startswith": startswith, "strip": strip, "sub": sub, + "word": word, } # template engine