forked from eslint-community/eslint-plugin-eslint-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefer-object-rule.js
74 lines (63 loc) · 2.18 KB
/
prefer-object-rule.js
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
/**
* @author Brad Zacher <https://github.com/bradzacher>
*/
'use strict';
const utils = require('../utils');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'disallow rule exports where the export is a function.',
category: 'Rules',
recommended: false,
},
fixable: 'code',
schema: [],
messages: {
preferObject: 'Rules should be declared using the object style.',
},
},
create (context) {
// ----------------------------------------------------------------------
// Public
// ----------------------------------------------------------------------
const sourceCode = context.getSourceCode();
const ruleInfo = utils.getRuleInfo(sourceCode);
return {
Program () {
if (!ruleInfo || ruleInfo.isNewStyle) {
return;
}
context.report({
node: ruleInfo.create,
messageId: 'preferObject',
*fix (fixer) {
// note - we intentionally don't worry about formatting here, as otherwise we have
// to indent the function correctly
if (ruleInfo.create.type === 'FunctionExpression') {
const openParenToken = sourceCode.getFirstToken(
ruleInfo.create,
token => token.type === 'Punctuator' && token.value === '('
);
if (!openParenToken) {
// this shouldn't happen, but guarding against crashes just in case
return null;
}
yield fixer.replaceTextRange(
[ruleInfo.create.range[0], openParenToken.range[0]],
'{create'
);
yield fixer.insertTextAfter(ruleInfo.create, '}');
} else if (ruleInfo.create.type === 'ArrowFunctionExpression') {
yield fixer.insertTextBefore(ruleInfo.create, '{create: ');
yield fixer.insertTextAfter(ruleInfo.create, '}');
}
},
});
},
};
},
};