From e1187285f137d685bcfc9e2a771fa059ef9637a9 Mon Sep 17 00:00:00 2001 From: not-an-aardvark Date: Tue, 6 Sep 2016 17:24:21 -0400 Subject: [PATCH] Update: add fixer for wrap-regex (fixes #7013) (#7048) --- docs/rules/wrap-regex.md | 2 ++ lib/rules/wrap-regex.js | 10 ++++++++-- tests/lib/rules/wrap-regex.js | 15 ++++++++++----- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/docs/rules/wrap-regex.md b/docs/rules/wrap-regex.md index c5959a90e28..f8d118cf649 100644 --- a/docs/rules/wrap-regex.md +++ b/docs/rules/wrap-regex.md @@ -1,5 +1,7 @@ # Require Regex Literals to be Wrapped (wrap-regex) +(fixable) The `--fix` option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule. + When a regular expression is used in certain situations, it can end up looking like a division operator. For example: ```js diff --git a/lib/rules/wrap-regex.js b/lib/rules/wrap-regex.js index 71cfa06a756..79f3d30515d 100644 --- a/lib/rules/wrap-regex.js +++ b/lib/rules/wrap-regex.js @@ -17,7 +17,9 @@ module.exports = { recommended: false }, - schema: [] + schema: [], + + fixable: "code" }, create(context) { @@ -36,7 +38,11 @@ module.exports = { if (grandparent.type === "MemberExpression" && grandparent.object === node && (!source || source.value !== "(")) { - context.report(node, "Wrap the regexp literal in parens to disambiguate the slash."); + context.report({ + node, + message: "Wrap the regexp literal in parens to disambiguate the slash.", + fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`) + }); } } } diff --git a/tests/lib/rules/wrap-regex.js b/tests/lib/rules/wrap-regex.js index af409734e79..97261fdcd5b 100644 --- a/tests/lib/rules/wrap-regex.js +++ b/tests/lib/rules/wrap-regex.js @@ -28,10 +28,15 @@ ruleTester.run("wrap-regex", rule, { "a[/b/];" ], invalid: [ - { code: "/foo/.test(bar);", - errors: [{ message: "Wrap the regexp literal in parens to disambiguate the slash.", type: "Literal"}] }, - { code: "/foo/ig.test(bar);", - errors: [{ message: "Wrap the regexp literal in parens to disambiguate the slash.", type: "Literal"}] } - + { + code: "/foo/.test(bar);", + errors: [{ message: "Wrap the regexp literal in parens to disambiguate the slash.", type: "Literal"}], + output: "(/foo/).test(bar);" + }, + { + code: "/foo/ig.test(bar);", + errors: [{ message: "Wrap the regexp literal in parens to disambiguate the slash.", type: "Literal"}], + output: "(/foo/ig).test(bar);" + } ] });