1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | 'use strict';
|
12 |
|
13 | const utils = require('./utils/utils');
|
14 | const SHOULD_USE_ISDEFINED_OR_ISUNDEFINED = 'You should not use directly the "undefined" keyword. Prefer ' +
|
15 | 'angular.isUndefined or angular.isDefined';
|
16 | const SHOULD_NOT_USE_BANG_WITH_ISDEFINED = 'Instead of !angular.isDefined, you can use the out-of-box angular.isUndefined method';
|
17 | const SHOULD_NOT_USE_BANG_WITH_ISUNDEFINED = 'Instead of !angular.isUndefined, you can use the out-of-box angular.isDefined method';
|
18 |
|
19 | module.exports = {
|
20 | meta: {
|
21 | schema: [],
|
22 | fixable: 'code'
|
23 | },
|
24 | create: function(context) {
|
25 | function isCompareOperator(operator) {
|
26 | return operator === '===' || operator === '!==' || operator === '==' || operator === '!=';
|
27 | }
|
28 | function reportError(node, message, fix) {
|
29 | context.report({
|
30 | node,
|
31 | message,
|
32 | fix
|
33 | });
|
34 | }
|
35 | var sourceCode = context.getSourceCode();
|
36 |
|
37 | |
38 |
|
39 |
|
40 | return {
|
41 | MemberExpression: function(node) {
|
42 | if (node.object.name === 'angular' &&
|
43 | node.parent !== undefined &&
|
44 | node.parent.parent !== undefined &&
|
45 | node.parent.parent.operator === '!') {
|
46 | if (node.property.name === 'isDefined') {
|
47 | reportError(node, SHOULD_NOT_USE_BANG_WITH_ISDEFINED, fixer => fixer.replaceText(node.parent.parent, `angular.isUndefined(${node.parent.arguments[0].name})`));
|
48 | } else if (node.property.name === 'isUndefined') {
|
49 | reportError(node, SHOULD_NOT_USE_BANG_WITH_ISUNDEFINED, fixer => fixer.replaceText(node.parent.parent, `angular.isDefined(${node.parent.arguments[0].name})`));
|
50 | }
|
51 | }
|
52 | },
|
53 | BinaryExpression: function(node) {
|
54 | if (isCompareOperator(node.operator)) {
|
55 | let method = (node.operator === '!=' || node.operator === '!==') ? 'isDefined' : 'isUndefined';
|
56 |
|
57 | if (utils.isTypeOfStatement(node.left) && node.right.value === 'undefined') {
|
58 | reportError(node, SHOULD_USE_ISDEFINED_OR_ISUNDEFINED, fixer => fixer.replaceText(node, `angular.${method}(${sourceCode.getText(node.left)})`));
|
59 | } else if (utils.isTypeOfStatement(node.right) && node.left.value === 'undefined') {
|
60 | reportError(node, SHOULD_USE_ISDEFINED_OR_ISUNDEFINED, fixer => fixer.replaceText(node, `angular.${method}(${sourceCode.getText(node.right)})`));
|
61 | } else if (node.left.type === 'Identifier' && node.left.name === 'undefined') {
|
62 | reportError(node, SHOULD_USE_ISDEFINED_OR_ISUNDEFINED, fixer => fixer.replaceText(node, `angular.${method}(${node.right.name})`));
|
63 | } else if (node.right.type === 'Identifier' && node.right.name === 'undefined') {
|
64 | reportError(node, SHOULD_USE_ISDEFINED_OR_ISUNDEFINED, fixer => fixer.replaceText(node, `angular.${method}(${node.left.name})`));
|
65 | }
|
66 | }
|
67 | }
|
68 | };
|
69 | }
|
70 | };
|