-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathprefer-regexp-exec.ts
48 lines (46 loc) · 1.63 KB
/
prefer-regexp-exec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { CallExpression } from "estree"
import { createRule } from "../utils"
import { isKnownMethodCall, getStaticValue } from "../utils/ast-utils"
import { createTypeTracker } from "../utils/type-tracker"
// Inspired by https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/prefer-regexp-exec.md
export default createRule("prefer-regexp-exec", {
meta: {
docs: {
description:
"enforce that `RegExp#exec` is used instead of `String#match` if no global flag is provided",
category: "Best Practices",
recommended: false,
},
schema: [],
messages: {
disallow: "Use the `RegExp#exec()` method instead.",
},
type: "suggestion", // "problem",
},
create(context) {
const typeTracer = createTypeTracker(context)
return {
CallExpression(node: CallExpression) {
if (!isKnownMethodCall(node, { match: 1 })) {
return
}
const arg = node.arguments[0]
const evaluated = getStaticValue(context, arg)
if (
evaluated &&
evaluated.value instanceof RegExp &&
evaluated.value.flags.includes("g")
) {
return
}
if (!typeTracer.isString(node.callee.object)) {
return
}
context.report({
node,
messageId: "disallow",
})
},
}
},
})