-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathprefer-named-replacement.ts
77 lines (71 loc) · 2.54 KB
/
prefer-named-replacement.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { ObjectOption } from "../types"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
export default createRule("prefer-named-replacement", {
meta: {
docs: {
description: "enforce using named replacement",
category: "Stylistic Issues",
recommended: false,
},
fixable: "code",
schema: [
{
type: "object",
properties: {
strictTypes: { type: "boolean" },
},
additionalProperties: false,
},
],
messages: {
unexpected: "Unexpected indexed reference in replacement string.",
},
type: "suggestion", // "problem",
},
create(context) {
const strictTypes =
(context.options[0] as ObjectOption)?.strictTypes ?? true
const sourceCode = context.sourceCode
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const { node, getAllCapturingGroups, getCapturingGroupReferences } =
regexpContext
const capturingGroups = getAllCapturingGroups()
if (!capturingGroups.length) {
return {}
}
for (const ref of getCapturingGroupReferences({ strictTypes })) {
if (
ref.type === "ReplacementRef" &&
ref.kind === "index" &&
ref.range
) {
const cgNode = capturingGroups[ref.ref - 1]
if (cgNode && cgNode.name) {
context.report({
node,
loc: {
start: sourceCode.getLocFromIndex(ref.range[0]),
end: sourceCode.getLocFromIndex(ref.range[1]),
},
messageId: "unexpected",
fix(fixer) {
return fixer.replaceTextRange(
ref.range!,
`$<${cgNode.name}>`,
)
},
})
}
}
}
return {}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})