[PATCH] templater: catch regexp error at sub() function

Augie Fackler raf at durin42.com
Tue Sep 8 12:04:36 CDT 2015


On Mon, Sep 07, 2015 at 11:52:06PM +0900, Yuya Nishihara wrote:
> # HG changeset patch
> # User Yuya Nishihara <yuya at tcha.org>
> # Date 1441630697 -32400
> #      Mon Sep 07 21:58:17 2015 +0900
> # Node ID 2f77cf0385ace2539f313da8132e05d03841d846
> # Parent  7187f6e923d55cf6b7e6910d24645f303db671ee
> templater: catch regexp error at sub() function

Queued, thanks.

>
> This patch splits re.sub() into re.compile() and sub() so that it can
> distinguish which argument causes re.error.
>
> diff --git a/mercurial/templater.py b/mercurial/templater.py
> --- a/mercurial/templater.py
> +++ b/mercurial/templater.py
> @@ -660,7 +660,16 @@ def sub(context, mapping, args):
>      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
> diff --git a/tests/test-command-template.t b/tests/test-command-template.t
> --- a/tests/test-command-template.t
> +++ b/tests/test-command-template.t
> @@ -2731,6 +2731,13 @@ Test the sub function of templating for
>    $ 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'
> _______________________________________________
> Mercurial-devel mailing list
> Mercurial-devel at selenic.com
> https://selenic.com/mailman/listinfo/mercurial-devel


More information about the Mercurial-devel mailing list