Skip to content

Commit f7babcf

Browse files
authored
feat(eslint-plugin): add extension rule comma-dangle (typescript-eslint#2416)
1 parent c6f72fb commit f7babcf

File tree

7 files changed

+506
-0
lines changed

7 files changed

+506
-0
lines changed

packages/eslint-plugin/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ In these cases, we create what we call an extension rule; a rule within our plug
188188
| Name | Description | :heavy_check_mark: | :wrench: | :thought_balloon: |
189189
| ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ------------------ | -------- | ----------------- |
190190
| [`@typescript-eslint/brace-style`](./docs/rules/brace-style.md) | Enforce consistent brace style for blocks | | :wrench: | |
191+
| [`@typescript-eslint/comma-dangle`](./docs/rules/comma-dangle.md) | Require or disallow trailing comma | | :wrench: | |
191192
| [`@typescript-eslint/comma-spacing`](./docs/rules/comma-spacing.md) | Enforces consistent spacing before and after commas | | :wrench: | |
192193
| [`@typescript-eslint/default-param-last`](./docs/rules/default-param-last.md) | Enforce default parameters to be last | | | |
193194
| [`@typescript-eslint/dot-notation`](./docs/rules/dot-notation.md) | enforce dot notation whenever possible | | :wrench: | :thought_balloon: |
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Require or disallow trailing comma (`comma-dangle`)
2+
3+
## Rule Details
4+
5+
This rule extends the base [`eslint/comma-dangle`](https://eslint.org/docs/rules/comma-dangle) rule.
6+
It adds support for TypeScript syntax.
7+
8+
See the [ESLint documentation](https://eslint.org/docs/rules/comma-dangle) for more details on the `comma-dangle` rule.
9+
10+
## Rule Changes
11+
12+
```cjson
13+
{
14+
// note you must disable the base rule as it can report incorrect errors
15+
"comma-dangle": "off",
16+
"@typescript-eslint/comma-dangle": ["error"]
17+
}
18+
```
19+
20+
In addition to the options supported by the `comma-dangle` rule in ESLint core, the rule adds the following options:
21+
22+
## Options
23+
24+
This rule has a string option and an object option.
25+
26+
- Object option:
27+
28+
- `"enums"` is for trailing comma in enum. (e.g. `enum Foo = {Bar,}`)
29+
- `"generics"` is for trailing comma in generic. (e.g. `function foo<T,>() {}`)
30+
- `"tuples"` is for trailing comma in tuple. (e.g. `type Foo = [string,]`)
31+
32+
- [See the other options allowed](https://github.com/eslint/eslint/blob/master/docs/rules/comma-dangle.md#options)
33+
34+
<sup>Taken with ❤️ [from ESLint core](https://github.com/eslint/eslint/blob/master/docs/rules/comma-dangle.md)</sup>

packages/eslint-plugin/src/configs/all.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,5 +139,7 @@ export = {
139139
'@typescript-eslint/typedef': 'error',
140140
'@typescript-eslint/unbound-method': 'error',
141141
'@typescript-eslint/unified-signatures': 'error',
142+
'comma-dangle': 'off',
143+
'@typescript-eslint/comma-dangle': 'error',
142144
},
143145
};
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
import * as util from '../util';
2+
import baseRule from 'eslint/lib/rules/comma-dangle';
3+
import {
4+
TSESTree,
5+
AST_NODE_TYPES,
6+
} from '@typescript-eslint/experimental-utils';
7+
8+
export type Options = util.InferOptionsTypeFromRule<typeof baseRule>;
9+
export type MessageIds = util.InferMessageIdsTypeFromRule<typeof baseRule>;
10+
11+
type Option = Options[0];
12+
type NormalizedOptions = Required<
13+
Pick<Exclude<Option, string>, 'enums' | 'generics' | 'tuples'>
14+
>;
15+
16+
const OPTION_VALUE_SCHEME = [
17+
'always-multiline',
18+
'always',
19+
'never',
20+
'only-multiline',
21+
];
22+
23+
const DEFAULT_OPTION_VALUE = 'never';
24+
25+
function normalizeOptions(options: Option): NormalizedOptions {
26+
if (typeof options === 'string') {
27+
return {
28+
enums: options,
29+
generics: options,
30+
tuples: options,
31+
};
32+
}
33+
return {
34+
enums: options.enums ?? DEFAULT_OPTION_VALUE,
35+
generics: options.generics ?? DEFAULT_OPTION_VALUE,
36+
tuples: options.tuples ?? DEFAULT_OPTION_VALUE,
37+
};
38+
}
39+
40+
export default util.createRule<Options, MessageIds>({
41+
name: 'comma-dangle',
42+
meta: {
43+
type: 'layout',
44+
docs: {
45+
description: 'Require or disallow trailing comma',
46+
category: 'Stylistic Issues',
47+
recommended: false,
48+
extendsBaseRule: true,
49+
},
50+
schema: {
51+
definitions: {
52+
value: {
53+
enum: OPTION_VALUE_SCHEME,
54+
},
55+
valueWithIgnore: {
56+
enum: [...OPTION_VALUE_SCHEME, 'ignore'],
57+
},
58+
},
59+
type: 'array',
60+
items: [
61+
{
62+
oneOf: [
63+
{
64+
$ref: '#/definitions/value',
65+
},
66+
{
67+
type: 'object',
68+
properties: {
69+
arrays: { $ref: '#/definitions/valueWithIgnore' },
70+
objects: { $ref: '#/definitions/valueWithIgnore' },
71+
imports: { $ref: '#/definitions/valueWithIgnore' },
72+
exports: { $ref: '#/definitions/valueWithIgnore' },
73+
functions: { $ref: '#/definitions/valueWithIgnore' },
74+
enums: { $ref: '#/definitions/valueWithIgnore' },
75+
generics: { $ref: '#/definitions/valueWithIgnore' },
76+
tuples: { $ref: '#/definitions/valueWithIgnore' },
77+
},
78+
additionalProperties: false,
79+
},
80+
],
81+
},
82+
],
83+
},
84+
fixable: 'code',
85+
messages: baseRule.meta.messages,
86+
},
87+
defaultOptions: ['never'],
88+
create(context, [options]) {
89+
const rules = baseRule.create(context);
90+
const sourceCode = context.getSourceCode();
91+
const normalizedOptions = normalizeOptions(options);
92+
93+
const predicate = {
94+
always: forceComma,
95+
'always-multiline': forceCommaIfMultiline,
96+
'only-multiline': allowCommaIfMultiline,
97+
never: forbidComma,
98+
ignore: (): void => {},
99+
};
100+
101+
function last(nodes: TSESTree.Node[]): TSESTree.Node | null {
102+
return nodes[nodes.length - 1] ?? null;
103+
}
104+
105+
function getLastItem(node: TSESTree.Node): TSESTree.Node | null {
106+
switch (node.type) {
107+
case AST_NODE_TYPES.TSEnumDeclaration:
108+
return last(node.members);
109+
case AST_NODE_TYPES.TSTypeParameterDeclaration:
110+
return last(node.params);
111+
case AST_NODE_TYPES.TSTupleType:
112+
return last(node.elementTypes);
113+
default:
114+
return null;
115+
}
116+
}
117+
118+
function getTrailingToken(node: TSESTree.Node): TSESTree.Token | null {
119+
const last = getLastItem(node);
120+
const trailing = last && sourceCode.getTokenAfter(last);
121+
return trailing;
122+
}
123+
124+
function isMultiline(node: TSESTree.Node): boolean {
125+
const last = getLastItem(node);
126+
const lastToken = sourceCode.getLastToken(node);
127+
return last?.loc.end.line !== lastToken?.loc.end.line;
128+
}
129+
130+
function forbidComma(node: TSESTree.Node): void {
131+
const last = getLastItem(node);
132+
const trailing = getTrailingToken(node);
133+
if (last && trailing && util.isCommaToken(trailing)) {
134+
context.report({
135+
node,
136+
messageId: 'unexpected',
137+
fix(fixer) {
138+
return fixer.remove(trailing);
139+
},
140+
});
141+
}
142+
}
143+
144+
function forceComma(node: TSESTree.Node): void {
145+
const last = getLastItem(node);
146+
const trailing = getTrailingToken(node);
147+
if (last && trailing && !util.isCommaToken(trailing)) {
148+
context.report({
149+
node,
150+
messageId: 'missing',
151+
fix(fixer) {
152+
return fixer.insertTextAfter(last, ',');
153+
},
154+
});
155+
}
156+
}
157+
158+
function allowCommaIfMultiline(node: TSESTree.Node): void {
159+
if (!isMultiline(node)) {
160+
forbidComma(node);
161+
}
162+
}
163+
164+
function forceCommaIfMultiline(node: TSESTree.Node): void {
165+
if (isMultiline(node)) {
166+
forceComma(node);
167+
} else {
168+
forbidComma(node);
169+
}
170+
}
171+
172+
return {
173+
...rules,
174+
TSEnumDeclaration: predicate[normalizedOptions.enums],
175+
TSTypeParameterDeclaration: predicate[normalizedOptions.generics],
176+
TSTupleType: predicate[normalizedOptions.tuples],
177+
};
178+
},
179+
});

packages/eslint-plugin/src/rules/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import banTslintComment from './ban-tslint-comment';
66
import banTypes from './ban-types';
77
import braceStyle from './brace-style';
88
import classLiteralPropertyStyle from './class-literal-property-style';
9+
import commaDangle from './comma-dangle';
910
import commaSpacing from './comma-spacing';
1011
import confusingNonNullAssertionLikeNotEqual from './no-confusing-non-null-assertion';
1112
import consistentTypeAssertions from './consistent-type-assertions';
@@ -114,6 +115,7 @@ export default {
114115
'ban-types': banTypes,
115116
'brace-style': braceStyle,
116117
'class-literal-property-style': classLiteralPropertyStyle,
118+
'comma-dangle': commaDangle,
117119
'comma-spacing': commaSpacing,
118120
'consistent-type-assertions': consistentTypeAssertions,
119121
'consistent-type-definitions': consistentTypeDefinitions,

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy