UNPKG

2.64 kBJavaScriptView Raw
1/**
2 * disallow unused DI parameters
3 *
4 * Unused dependencies should not be injected.
5 *
6 * @version 0.8.0
7 * @category bestPractice
8 * @sinceAngularVersion 1.x
9 */
10'use strict';
11
12var angularRule = require('./utils/angular-rule');
13
14
15module.exports = {
16 meta: {
17 schema: []
18 },
19 create: angularRule(function(context) {
20 // Keeps track of visited scopes in the collectAngularScopes function to prevent infinite recursion on circular references.
21 var visitedScopes = [];
22
23 // This collects the variable scopes for the injectible functions which have been collected.
24 function collectAngularScopes(scope) {
25 if (visitedScopes.indexOf(scope) === -1) {
26 visitedScopes.push(scope);
27 scope.childScopes.forEach(function(child) {
28 collectAngularScopes(child);
29 });
30 }
31 }
32
33 function reportUnusedVariables(callee, fn) {
34 if (!fn) {
35 return;
36 }
37 visitedScopes.some(function(scope) {
38 if (scope.block !== fn) {
39 return;
40 }
41 scope.variables.forEach(function(variable) {
42 if (variable.name === 'arguments') {
43 return;
44 }
45 if (fn.params.indexOf(variable.identifiers[0]) === -1) {
46 return;
47 }
48 if (variable.references.length === 0) {
49 context.report(fn, 'Unused injected value {{name}}', variable);
50 }
51 });
52 return true;
53 });
54 }
55
56 return {
57 'angular?animation': reportUnusedVariables,
58 'angular?config': reportUnusedVariables,
59 'angular?controller': reportUnusedVariables,
60 'angular?directive': reportUnusedVariables,
61 'angular?factory': reportUnusedVariables,
62 'angular?filter': reportUnusedVariables,
63 'angular?inject': reportUnusedVariables,
64 'angular?run': reportUnusedVariables,
65 'angular?service': reportUnusedVariables,
66 'angular?provider': function(callee, providerFn, $get) {
67 reportUnusedVariables(null, providerFn);
68 reportUnusedVariables(null, $get);
69 },
70
71 // Actually find and report unused injected variables.
72 'Program:exit': function() {
73 var globalScope = context.getScope();
74 collectAngularScopes(globalScope);
75 }
76 };
77 })
78};