-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
init-declarations.ts
68 lines (58 loc) · 1.74 KB
/
init-declarations.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
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type {
InferMessageIdsTypeFromRule,
InferOptionsTypeFromRule,
} from '../util';
import { createRule } from '../util';
import { getESLintCoreRule } from '../util/getESLintCoreRule';
const baseRule = getESLintCoreRule('init-declarations');
export type Options = InferOptionsTypeFromRule<typeof baseRule>;
export type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;
export default createRule<Options, MessageIds>({
name: 'init-declarations',
meta: {
type: 'suggestion',
docs: {
description:
'Require or disallow initialization in variable declarations',
recommended: false,
extendsBaseRule: true,
},
hasSuggestions: baseRule.meta.hasSuggestions,
schema: baseRule.meta.schema,
messages: baseRule.meta.messages,
},
defaultOptions: ['always'],
create(context, [mode]) {
const rules = baseRule.create(context);
return {
'VariableDeclaration:exit'(node: TSESTree.VariableDeclaration): void {
if (mode === 'always') {
if (node.declare) {
return;
}
if (isAncestorNamespaceDeclared(node)) {
return;
}
}
rules['VariableDeclaration:exit'](node);
},
};
function isAncestorNamespaceDeclared(
node: TSESTree.VariableDeclaration,
): boolean {
let ancestor: TSESTree.Node | undefined = node.parent;
while (ancestor) {
if (
ancestor.type === AST_NODE_TYPES.TSModuleDeclaration &&
ancestor.declare
) {
return true;
}
ancestor = ancestor.parent;
}
return false;
}
},
});