templater: catch regexp error at sub() function
authorYuya Nishihara <yuya@tcha.org>
Mon, 07 Sep 2015 21:58:17 +0900
changeset 26188 662ea52d5dca
parent 26187 9cf65f43b49b
child 26189 663fbc336e22
templater: catch regexp error at sub() function This patch splits re.sub() into re.compile() and sub() so that it can distinguish which argument causes re.error.
mercurial/templater.py
tests/test-command-template.t
--- a/mercurial/templater.py	Tue Sep 08 23:00:44 2015 +0900
+++ b/mercurial/templater.py	Mon Sep 07 21:58:17 2015 +0900
@@ -660,7 +660,16 @@
     pat = stringify(args[0][0](context, mapping, args[0][1]))
     rpl = stringify(args[1][0](context, mapping, args[1][1]))
     src = stringify(args[2][0](context, mapping, args[2][1]))
-    yield re.sub(pat, rpl, src)
+    try:
+        patre = re.compile(pat)
+    except re.error:
+        # i18n: "sub" is a keyword
+        raise error.ParseError(_("sub got an invalid pattern: %s") % pat)
+    try:
+        yield patre.sub(rpl, src)
+    except re.error:
+        # i18n: "sub" is a keyword
+        raise error.ParseError(_("sub got an invalid replacement: %s") % rpl)
 
 def startswith(context, mapping, args):
     """:startswith(pattern, text): Returns the value from the "text" argument
--- a/tests/test-command-template.t	Tue Sep 08 23:00:44 2015 +0900
+++ b/tests/test-command-template.t	Mon Sep 07 21:58:17 2015 +0900
@@ -2731,6 +2731,13 @@
   $ hg log -R latesttag -r 10 --template '{sub("[0-9]", "x", "{rev}")}\n'
   xx
 
+  $ hg log -R latesttag -r 10 -T '{sub("[", "x", rev)}\n'
+  hg: parse error: sub got an invalid pattern: [
+  [255]
+  $ hg log -R latesttag -r 10 -T '{sub("[0-9]", r"\1", rev)}\n'
+  hg: parse error: sub got an invalid replacement: \1
+  [255]
+
 Test the strip function with chars specified:
 
   $ hg log -R latesttag --template '{desc}\n'