Skip to content
Permalink
Browse files

Fix: global-require no longer warns if require is shadowed (fixes #4812)

  • Loading branch information...
platinumazure committed Jan 7, 2016
1 parent e7aeb9d commit c4c413932c9b9c96c737d8092d46c7cb31bb059f
Showing with 39 additions and 3 deletions.
  1. +36 −2 lib/rules/global-require.js
  2. +3 −1 tests/lib/rules/global-require.js
@@ -17,11 +17,45 @@ var ACCEPTABLE_PARENTS = [
"VariableDeclaration"
];

/**
* Finds the escope reference in the given scope.
* @param {Object} scope The scope to search.
* @param {ASTNode} node The identifier node.
* @returns {Reference|null} Returns the found reference or null if none were found.
*/
function findReference(scope, node) {
var references = scope.references.filter(function(reference) {
return reference.identifier.range[0] === node.range[0] &&
reference.identifier.range[1] === node.range[1];
});

/* istanbul ignore else: correctly returns null */
if (references.length === 1) {
return references[0];
} else {
return null;
}
}

/**
* Checks if the given identifier node is shadowed in the given scope.
* @param {Object} scope The current scope.
* @param {ASTNode} node The identifier node to check.
* @returns {boolean} Whether or not the name is shadowed.
*/
function isShadowed(scope, node) {
var reference = findReference(scope, node);
return reference && reference.resolved && reference.resolved.defs.length > 0;
}

module.exports = function(context) {
return {
"CallExpression": function(node) {
if (node.callee.name === "require") {
var isGoodRequire = context.getAncestors().every(function(parent) {
var currentScope = context.getScope(),
isGoodRequire;

if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) {
isGoodRequire = context.getAncestors().every(function(parent) {
return ACCEPTABLE_PARENTS.indexOf(parent.type) > -1;
});
if (!isGoodRequire) {
@@ -29,7 +29,9 @@ var valid = [
{ code: "require('y');" },
{ code: "function x(){}\n\n\nx();\n\n\nif (x > y) {\n\tdoSomething()\n\n}\n\nvar x = require('y').foo;" },
{ code: "var logger = require(DEBUG ? 'dev-logger' : 'logger');" },
{ code: "var logger = DEBUG ? require('dev-logger') : require('logger');" }
{ code: "var logger = DEBUG ? require('dev-logger') : require('logger');" },
{ code: "function localScopedRequire(require) { require('y'); }" },
{ code: "var someFunc = require('./someFunc'); someFunc(function(require) { return('bananas'); });" }
];

var message = "Unexpected require().";

0 comments on commit c4c4139

Please sign in to comment.
You can’t perform that action at this time.