-
Notifications
You must be signed in to change notification settings - Fork 1
/
no-unused-requires.js
90 lines (74 loc) · 2.43 KB
/
no-unused-requires.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict';
const util = require('./util');
exports.rule = {
meta: {
docs: {
description: 'disallow unused goog.require() calls'
},
fixable: 'code'
},
create: function(context) {
// a lookup of goog.require() nodes by argument
const requireStatements = {};
// used names from member expressions that match the goog.require() arg
const usedNames = {};
return {
ExpressionStatement: function(statement) {
if (util.isRequireStatement(statement)) {
const expression = statement.expression;
const arg = expression.arguments[0];
if (!arg || !arg.value) {
return;
}
const name = arg.value;
requireStatements[name] = statement;
}
},
MemberExpression: function(node) {
const name = util.getName(node);
if (name in requireStatements) {
const requiredAncestor = context.getAncestors().some(
ancestorNode => !!requireStatements[util.getName(ancestorNode)]);
if (!requiredAncestor) {
usedNames[name] = true;
}
}
},
Identifier: function(node) {
const name = node.name;
if (name in requireStatements) {
const ancestors = context.getAncestors();
if (ancestors.length && ancestors[0].type === 'MemberExpression') {
const requiredAncestor = ancestors.some(
ancestorNode => !!requireStatements[util.getName(ancestorNode)]);
if (!requiredAncestor) {
usedNames[name] = true;
}
} else {
usedNames[name] = true;
}
}
},
'Program:exit': function(node) {
const source = context.getSourceCode();
for (let name in requireStatements) {
if (!usedNames[name]) {
const unusedRequire = requireStatements[name];
context.report({
node: unusedRequire,
message: `Unused ${source.getText(unusedRequire)}`,
fix: function(fixer) {
const afterToken = source.getTokenAfter(unusedRequire, {includeComments: true});
const range = [
unusedRequire.range[0],
afterToken ? afterToken.range[0] : unusedRequire.range[1]
];
return fixer.removeRange(range);
}
});
}
}
}
};
}
};