-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsort-flags.ts
56 lines (53 loc) · 1.75 KB
/
sort-flags.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
import type { RegExpContext, UnparsableRegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
export default createRule("sort-flags", {
meta: {
docs: {
description: "require regex flags to be sorted",
category: "Stylistic Issues",
recommended: true,
},
fixable: "code",
schema: [],
messages: {
sortFlags:
"The flags '{{flags}}' should be in the order '{{sortedFlags}}'.",
},
type: "suggestion", // "problem",
},
create(context) {
function sortFlags(flagsStr: string): string {
return [...flagsStr]
.sort((a, b) => a.codePointAt(0)! - b.codePointAt(0)!)
.join("")
}
function visit({
regexpNode,
flagsString,
ownsFlags,
getFlagsLocation,
fixReplaceFlags,
}: RegExpContext | UnparsableRegExpContext) {
if (flagsString && ownsFlags) {
const sortedFlags = sortFlags(flagsString)
if (flagsString !== sortedFlags) {
context.report({
node: regexpNode,
loc: getFlagsLocation(),
messageId: "sortFlags",
data: { flags: flagsString, sortedFlags },
fix: fixReplaceFlags(sortedFlags, false),
})
}
}
}
return defineRegexpVisitor(context, {
createVisitor(regexpContext) {
visit(regexpContext)
return {}
},
visitInvalid: visit,
visitUnknown: visit,
})
},
})