Mercurial > hg
changeset 21821:4a445dc5abff
templater: introduce startswith function
This function returns a string only if it starts with a given string.
It is particularly useful when combined with splitlines and/or used with
conditionals that fail when empty strings are passed in to take action
based on the contents of a line.
author | Ryan McElroy <rmcelroy@fb.com> |
---|---|
date | Thu, 12 Jun 2014 17:53:37 -0700 |
parents | cce404b0c918 |
children | 028a48105191 |
files | mercurial/help/templates.txt mercurial/templater.py tests/test-command-template.t |
diffstat | 3 files changed, 45 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/mercurial/help/templates.txt Thu Jun 12 17:45:41 2014 -0700 +++ b/mercurial/help/templates.txt Thu Jun 12 17:53:37 2014 -0700 @@ -66,6 +66,8 @@ - shortest(node) +- startswith(string, text) + - strip(text[, chars]) - sub(pat, repl, expr) @@ -124,3 +126,7 @@ - Mark the working copy parent with '@':: $ hg log --template "{ifcontains(rev, revset('.'), '@')}\n" + +- Show only commit descriptions that start with "template":: + + $ hg log --template "{startswith(\"template\", firstline(desc))}\n"
--- a/mercurial/templater.py Thu Jun 12 17:45:41 2014 -0700 +++ b/mercurial/templater.py Thu Jun 12 17:53:37 2014 -0700 @@ -466,6 +466,17 @@ src = stringify(_evalifliteral(args[2], context, mapping)) yield re.sub(pat, rpl, src) +def startswith(context, mapping, args): + if len(args) != 2: + raise error.ParseError(_("startswith expects two arguments")) + + patn = stringify(args[0][0](context, mapping, args[0][1])) + text = stringify(args[1][0](context, mapping, args[1][1])) + if text.startswith(patn): + return text + return '' + + methods = { "string": lambda e, c: (runstring, e[1]), "rawstring": lambda e, c: (runrawstring, e[1]), @@ -490,6 +501,7 @@ "revset": revset, "rstdoc": rstdoc, "shortest": shortest, + "startswith": startswith, "strip": strip, "sub": sub, }
--- a/tests/test-command-template.t Thu Jun 12 17:45:41 2014 -0700 +++ b/tests/test-command-template.t Thu Jun 12 17:53:37 2014 -0700 @@ -1884,3 +1884,30 @@ | foo other 3 o foo line 1 foo line 2 + +Test startswith + $ hg log -Gv -R a --template "{startswith(desc)}" + hg: parse error: startswith expects two arguments + [255] + + $ hg log -Gv -R a --template "{startswith('line', desc)}" + @ + | + o + | + o + + o + |\ + | o + | | + o | + |/ + o + | + o + | + o + | + o line 1 + line 2