-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsort-keys.ts
174 lines (152 loc) · 5.45 KB
/
sort-keys.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { AST_NODE_TYPES } from '@typescript-eslint/types'
import { TSESTree } from '@typescript-eslint/utils'
import { ReportDescriptor, RuleContext } from '@typescript-eslint/utils/dist/ts-eslint'
import { ArrayUtils } from '../utils/array'
import { ComparerUtils } from '../utils/comparer'
import { ConfigUtils } from '../utils/config'
import { createRule } from '../utils/createRule'
import { FixUtils } from '../utils/fix'
type Options = []
// Define the message ID for unsorted keys
export const HAS_UNSORTED_KEYS_MESSAGE_ID = 'hasUnsortedKeys'
// Define the type for the message IDs
type MessageIds = typeof HAS_UNSORTED_KEYS_MESSAGE_ID
// Function to get config from the parent node
const getParentNodeConfig = (
node: TSESTree.Node,
parentTypes: AST_NODE_TYPES[],
deepCountingTypes: AST_NODE_TYPES[],
sourceCode: any,
) => {
let currentNode: TSESTree.Node = node
let deepLevel = 1
while ((currentNode = currentNode.parent) !== null) {
if (deepCountingTypes.includes(currentNode.type)) {
deepLevel += 1
}
if (parentTypes.includes(currentNode.type)) {
const commentExpectedEndLine = currentNode.loc.start.line - 1
const config = ConfigUtils.getConfig(sourceCode, '@sort-keys', commentExpectedEndLine)
if (config.deepLevel < deepLevel) {
return null
}
return { config, deepLevel }
}
}
return null
}
// Function to get config from the current node
const getCurrentNodeConfig = (node: TSESTree.Node, sourceCode: any) => {
const commentExpectedEndLine = node.loc.start.line - 1
const config = ConfigUtils.getConfig(sourceCode, '@sort-keys', commentExpectedEndLine)
return { config }
}
// Check if the properties of a node need sorting and report if necessary.
const checkAndReport = <N extends TSESTree.Node>(
node: N,
comparer: (a: TSESTree.Node, b: TSESTree.Node) => number,
getProperties: (node: N) => TSESTree.Node[],
sourceCode: any,
report: (descriptor: ReportDescriptor<'hasUnsortedKeys'>) => void,
) => {
const properties = getProperties(node)
const sortedProperties = [...properties].sort(comparer)
const needSort = ArrayUtils.zip2(properties, sortedProperties).some(
([property, sortedProperty]) => property !== sortedProperty,
)
if (needSort) {
const diffRanges = ArrayUtils.zip2(properties, sortedProperties).map(([from, to]) => ({
from: from.range,
to: to.range,
}))
const fixedText = FixUtils.getFixedText(sourceCode, node.range, diffRanges)
report({
node,
messageId: HAS_UNSORTED_KEYS_MESSAGE_ID,
fix(fixer) {
return fixer.replaceTextRange(node.range, fixedText)
},
})
}
}
// Create the rule for sorting keys based on the @sort-keys annotation
export default createRule<Options, MessageIds>({
name: 'sort-keys',
meta: {
docs: {
description: 'Sort keys in object if annotated as @sort-keys',
recommended: 'error',
suggestion: true,
},
fixable: 'code',
type: 'suggestion',
schema: [],
messages: {
[HAS_UNSORTED_KEYS_MESSAGE_ID]: `has unsorted keys`,
},
},
defaultOptions: [],
create(context) {
const sourceCode = context.getSourceCode()
return {
// Handle object expressions (e.g., object literals)
ObjectExpression(node): void {
const result = getParentNodeConfig(
node,
[AST_NODE_TYPES.VariableDeclaration, AST_NODE_TYPES.TSTypeAliasDeclaration],
[AST_NODE_TYPES.ObjectExpression],
sourceCode,
)
if (!result || !result.config) {
return
}
const { config, deepLevel } = result
const { isReversed } = config
const comparer = ComparerUtils.makeObjectPropertyComparer({ isReversed })
checkAndReport(node, comparer, (node) => node.properties, sourceCode, context.report)
},
// Handle TypeScript interface bodies
TSInterfaceBody(node): void {
const result = getParentNodeConfig(
node,
[AST_NODE_TYPES.TSInterfaceDeclaration],
[AST_NODE_TYPES.TSInterfaceBody],
sourceCode,
)
if (!result || !result.config) {
return
}
const { config, deepLevel } = result
const { isReversed } = config
const comparer = ComparerUtils.makeInterfacePropertyComparer({ isReversed })
checkAndReport(node, comparer, (node) => node.body, sourceCode, context.report)
},
// Handle TypeScript type literals
TSTypeLiteral(node): void {
const result = getParentNodeConfig(
node,
[AST_NODE_TYPES.TSInterfaceDeclaration, AST_NODE_TYPES.TSTypeAliasDeclaration],
[AST_NODE_TYPES.TSInterfaceBody, AST_NODE_TYPES.TSTypeLiteral],
sourceCode,
)
if (!result || !result.config) {
return
}
const { config, deepLevel } = result
const { isReversed } = config
const comparer = ComparerUtils.makeInterfacePropertyComparer({ isReversed })
checkAndReport(node, comparer, (node) => node.members, sourceCode, context.report)
},
// Handle TypeScript enum declarations
TSEnumDeclaration(node): void {
const { config } = getCurrentNodeConfig(node, sourceCode)
if (!config) {
return
}
const { isReversed } = config
const comparer = ComparerUtils.makeEnumMemberComparer({ isReversed })
checkAndReport(node, comparer, (node) => node.members, sourceCode, context.report)
},
}
},
})