Skip to content

Commit 3a2c549

Browse files
committedAug 7, 2023
fix(plugin): named-tuple-spacing handling, close #232
1 parent 59308e8 commit 3a2c549

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed
 

‎packages/eslint-plugin-antfu/src/rules/named-tuple-spacing.ts

+15-11
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@ export const RULE_NAME = 'named-tuple-spacing'
44
export type MessageIds = 'expectedSpaceAfter' | 'unexpectedSpaceBetween' | 'unexpectedSpaceBefore'
55
export type Options = []
66

7+
const RE = /^([\w_$]+)(\s*)(\?\s*)?:(\s*)(.*)$/
8+
79
export default createEslintRule<Options, MessageIds>({
810
name: RULE_NAME,
911
meta: {
1012
type: 'suggestion',
1113
docs: {
1214
description: 'Expect space before type declaration in named tuple',
13-
recommended: 'error',
15+
recommended: 'stylistic',
1416
},
1517
fixable: 'code',
1618
schema: [],
@@ -24,16 +26,18 @@ export default createEslintRule<Options, MessageIds>({
2426
create: (context) => {
2527
const sourceCode = context.getSourceCode()
2628
return {
27-
TSNamedTupleMember: (node) => {
29+
TSNamedTupleMember: (node: any) => {
2830
const code = sourceCode.text.slice(node.range[0], node.range[1])
2931

30-
const reg = /(\w+)(\s*)(\?\s*)?:(\s*)(\w+)/
32+
const match = code.match(RE)
33+
if (!match)
34+
return
3135

3236
const labelName = node.label.name
33-
const spaceBeforeColon = code.match(reg)?.[2]
34-
const optionalMark = code.match(reg)?.[3]
35-
const spacesAfterColon = code.match(reg)?.[4]
36-
const elementType = code.match(reg)?.[5]
37+
const spaceBeforeColon = match[2]
38+
const optionalMark = match[3]
39+
const spacesAfterColon = match[4]
40+
const elementType = match[5]
3741

3842
function getReplaceValue() {
3943
let ret = labelName
@@ -49,7 +53,7 @@ export default createEslintRule<Options, MessageIds>({
4953
node,
5054
messageId: 'unexpectedSpaceBetween',
5155
*fix(fixer) {
52-
yield fixer.replaceTextRange(node.range, code.replace(reg, getReplaceValue()))
56+
yield fixer.replaceTextRange(node.range, code.replace(RE, getReplaceValue()))
5357
},
5458
})
5559
}
@@ -59,17 +63,17 @@ export default createEslintRule<Options, MessageIds>({
5963
node,
6064
messageId: 'unexpectedSpaceBefore',
6165
*fix(fixer) {
62-
yield fixer.replaceTextRange(node.range, code.replace(reg, getReplaceValue()))
66+
yield fixer.replaceTextRange(node.range, code.replace(RE, getReplaceValue()))
6367
},
6468
})
6569
}
6670

67-
if (spacesAfterColon.length !== 1) {
71+
if (spacesAfterColon != null && spacesAfterColon.length !== 1) {
6872
context.report({
6973
node,
7074
messageId: 'expectedSpaceAfter',
7175
*fix(fixer) {
72-
yield fixer.replaceTextRange(node.range, code.replace(reg, getReplaceValue()))
76+
yield fixer.replaceTextRange(node.range, code.replace(RE, getReplaceValue()))
7377
},
7478
})
7579
}

0 commit comments

Comments
 (0)
Please sign in to comment.