-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathconsistent-list-newline.ts
More file actions
350 lines (324 loc) · 11 KB
/
consistent-list-newline.ts
File metadata and controls
350 lines (324 loc) · 11 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import type { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils'
import type { RuleFix, RuleFixer, RuleListener } from '@typescript-eslint/utils/ts-eslint'
import { createEslintRule } from '../utils'
export const RULE_NAME = 'consistent-list-newline'
export type MessageIds = 'shouldWrap' | 'shouldNotWrap'
export type Options = [{
ArrayExpression?: boolean
ArrayPattern?: boolean
ArrowFunctionExpression?: boolean
CallExpression?: boolean
ExportNamedDeclaration?: boolean
FunctionDeclaration?: boolean
FunctionExpression?: boolean
IfStatement?: boolean
ImportDeclaration?: boolean
JSONArrayExpression?: boolean
JSONObjectExpression?: boolean
JSXOpeningElement?: boolean
NewExpression?: boolean
ObjectExpression?: boolean
ObjectPattern?: boolean
TSFunctionType?: boolean
TSInterfaceDeclaration?: boolean
TSTupleType?: boolean
TSTypeLiteral?: boolean
TSTypeParameterDeclaration?: boolean
TSTypeParameterInstantiation?: boolean
}]
function isCommaToken(token: TSESTree.Token): boolean {
return token.type === 'Punctuator' && token.value === ','
}
export default createEslintRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'layout',
docs: {
description: 'Having line breaks styles to object, array and named imports',
},
fixable: 'whitespace',
schema: [{
type: 'object',
properties: {
ArrayExpression: { type: 'boolean' },
ArrayPattern: { type: 'boolean' },
ArrowFunctionExpression: { type: 'boolean' },
CallExpression: { type: 'boolean' },
ExportNamedDeclaration: { type: 'boolean' },
FunctionDeclaration: { type: 'boolean' },
FunctionExpression: { type: 'boolean' },
IfStatement: { type: 'boolean' },
ImportDeclaration: { type: 'boolean' },
JSONArrayExpression: { type: 'boolean' },
JSONObjectExpression: { type: 'boolean' },
JSXOpeningElement: { type: 'boolean' },
NewExpression: { type: 'boolean' },
ObjectExpression: { type: 'boolean' },
ObjectPattern: { type: 'boolean' },
TSFunctionType: { type: 'boolean' },
TSInterfaceDeclaration: { type: 'boolean' },
TSTupleType: { type: 'boolean' },
TSTypeLiteral: { type: 'boolean' },
TSTypeParameterDeclaration: { type: 'boolean' },
TSTypeParameterInstantiation: { type: 'boolean' },
} satisfies Record<keyof Options[0], { type: 'boolean' }>,
additionalProperties: false,
}],
messages: {
shouldWrap: 'Should have line breaks between items, in node {{name}}',
shouldNotWrap: 'Should not have line breaks between items, in node {{name}}',
},
},
defaultOptions: [{}],
create: (context, [options = {}] = [{}]) => {
const multilineNodes = new Set([
'ArrayExpression',
'FunctionDeclaration',
'IfStatement',
'ObjectExpression',
'ObjectPattern',
'TSTypeLiteral',
'TSTupleType',
'TSInterfaceDeclaration',
])
function removeLines(fixer: RuleFixer, start: number, end: number, delimiter?: string): RuleFix {
const range = [start, end] as const
const code = context.sourceCode.text.slice(...range)
return fixer.replaceTextRange(range, code.replace(/(\r\n|\n)/g, delimiter ?? ''))
}
function getDelimiter(root: TSESTree.Node, current: TSESTree.Node): string | undefined {
if (root.type !== 'TSInterfaceDeclaration' && root.type !== 'TSTypeLiteral')
return
const currentContent = context.sourceCode.text.slice(current.range[0], current.range[1])
return currentContent.match(/(?:,|;)$/) ? undefined : ','
}
function hasComments(current: TSESTree.Node): boolean {
let program: TSESTree.Node = current
while (program.type !== 'Program')
program = program.parent
const currentRange = current.range
return !!program.comments?.some((comment) => {
const commentRange = comment.range
return (
commentRange[0] > currentRange[0]
&& commentRange[1] < currentRange[1]
)
})
}
function check(
node: TSESTree.Node,
children: (TSESTree.Node | null)[],
nextNode?: TSESTree.Node,
): void {
const items = children.filter(Boolean) as TSESTree.Node[]
if (items.length === 0)
return
// Look for the opening bracket, we first try to get the first token of the parent node
// and fallback to the token before the first item
let startToken = ['CallExpression', 'NewExpression'].includes(node.type)
? undefined
: context.sourceCode.getFirstToken(node)
if (node.type === 'CallExpression') {
startToken = context.sourceCode.getTokenAfter(
node.typeArguments
? node.typeArguments
: node.callee.type === 'MemberExpression'
? node.callee.property
: node.callee,
)
}
if (startToken?.type !== 'Punctuator')
startToken = context.sourceCode.getTokenBefore(items[0])
const endToken = context.sourceCode.getTokenAfter(items[items.length - 1])
const startLine = startToken!.loc.start.line
if (startToken!.loc.start.line === endToken!.loc.end.line)
return
let mode: 'inline' | 'newline' | null = null
let lastLine = startLine
items.forEach((item, idx) => {
if (mode == null) {
mode = item.loc.start.line === lastLine ? 'inline' : 'newline'
lastLine = item.loc.end.line
return
}
const currentStart = item.loc.start.line
if (mode === 'newline' && currentStart === lastLine) {
context.report({
node: item,
messageId: 'shouldWrap',
data: {
name: node.type,
},
* fix(fixer) {
yield fixer.insertTextBefore(item, '\n')
},
})
}
else if (mode === 'inline' && currentStart !== lastLine) {
const lastItem = items[idx - 1]
if (context.sourceCode.getCommentsBefore(item).length > 0)
return
const content = context.sourceCode.text.slice(lastItem!.range[1], item.range[0])
if (content.includes('\n')) {
context.report({
node: item,
messageId: 'shouldNotWrap',
data: {
name: node.type,
},
* fix(fixer) {
yield removeLines(fixer, lastItem!.range[1], item.range[0], getDelimiter(node, lastItem))
},
})
}
}
lastLine = item.loc.end.line
})
const endRange = nextNode
? Math.min(
context.sourceCode.getTokenBefore(nextNode)!.range[0],
node.range[1],
)
: node.range[1]
const endLoc = context.sourceCode.getLocFromIndex(endRange)
const lastItem = items[items.length - 1]!
if (mode === 'newline' && endLoc.line === lastLine) {
context.report({
node: lastItem,
messageId: 'shouldWrap',
data: {
name: node.type,
},
* fix(fixer) {
yield fixer.insertTextAfter(lastItem, '\n')
},
})
}
else if (mode === 'inline' && endLoc.line !== lastLine) {
// If there is only one multiline item, we allow the closing bracket to be on the a different line
if (items.length === 1 && !(multilineNodes as Set<AST_NODE_TYPES>).has(node.type))
return
const nextToken = context.sourceCode.getTokenAfter(lastItem)
if (context.sourceCode.getCommentsAfter(nextToken && isCommaToken(nextToken) ? nextToken : lastItem).length > 0)
return
const content = context.sourceCode.text.slice(lastItem.range[1], endRange)
if (content.includes('\n')) {
context.report({
node: lastItem,
messageId: 'shouldNotWrap',
data: {
name: node.type,
},
* fix(fixer) {
const delimiter = items.length === 1 ? '' : getDelimiter(node, lastItem)
yield removeLines(fixer, lastItem.range[1], endRange, delimiter)
},
})
}
}
}
const listenser = {
ObjectExpression: (node) => {
check(node, node.properties)
},
ArrayExpression: (node) => {
check(node, node.elements)
},
ImportDeclaration: (node) => {
check(
node,
node.specifiers[0]?.type === 'ImportDefaultSpecifier'
? node.specifiers.slice(1)
: node.specifiers,
)
},
ExportNamedDeclaration: (node) => {
check(node, node.specifiers)
},
FunctionDeclaration: (node) => {
check(
node,
node.params,
node.returnType || node.body,
)
},
FunctionExpression: (node) => {
check(
node,
node.params,
node.returnType || node.body,
)
},
IfStatement: (node) => {
check(node, [node.test], node.consequent)
},
ArrowFunctionExpression: (node) => {
if (node.params.length <= 1)
return
check(
node,
node.params,
node.returnType || node.body,
)
},
CallExpression: (node) => {
check(node, node.arguments)
},
TSInterfaceDeclaration: (node) => {
check(node, node.body.body)
},
TSTypeLiteral: (node) => {
check(node, node.members)
},
TSTupleType: (node) => {
check(node, node.elementTypes)
},
TSFunctionType: (node) => {
check(node, node.params)
},
NewExpression: (node) => {
check(node, node.arguments)
},
TSTypeParameterDeclaration(node) {
check(node, node.params)
},
TSTypeParameterInstantiation(node) {
check(node, node.params)
},
ObjectPattern(node) {
check(node, node.properties, node.typeAnnotation)
},
ArrayPattern(node) {
check(node, node.elements)
},
JSXOpeningElement(node) {
if (node.attributes.some(attr => attr.loc.start.line !== attr.loc.end.line))
return
check(node, node.attributes)
},
JSONArrayExpression(node: TSESTree.ArrayExpression) {
if (hasComments(node))
return
check(node, node.elements)
},
JSONObjectExpression(node: TSESTree.ObjectExpression) {
if (hasComments(node))
return
check(node, node.properties)
},
} satisfies RuleListener
type KeysListener = keyof typeof listenser
type KeysOptions = keyof Options[0]
// Type assertion to check if all keys are exported
exportType<KeysListener, KeysOptions>()
exportType<KeysOptions, KeysListener>()
;(Object.keys(options) as KeysOptions[])
.forEach((key) => {
if (options[key] === false)
delete listenser[key]
})
return listenser
},
})
// eslint-disable-next-line unused-imports/no-unused-vars, ts/explicit-function-return-type
function exportType<A, B extends A>() {}