]> git.proxmox.com Git - pve-eslint.git/blame - eslint/lib/rules/global-require.js
exit with error also on warnings
[pve-eslint.git] / eslint / lib / rules / global-require.js
CommitLineData
eb39fafa
DC
1/**
2 * @fileoverview Rule for disallowing require() outside of the top-level module context
3 * @author Jamund Ferguson
4 */
5
6"use strict";
7
8const ACCEPTABLE_PARENTS = [
9 "AssignmentExpression",
10 "VariableDeclarator",
11 "MemberExpression",
12 "ExpressionStatement",
13 "CallExpression",
14 "ConditionalExpression",
15 "Program",
16 "VariableDeclaration"
17];
18
19/**
20 * Finds the eslint-scope reference in the given scope.
21 * @param {Object} scope The scope to search.
22 * @param {ASTNode} node The identifier node.
23 * @returns {Reference|null} Returns the found reference or null if none were found.
24 */
25function findReference(scope, node) {
26 const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] &&
27 reference.identifier.range[1] === node.range[1]);
28
29 /* istanbul ignore else: correctly returns null */
30 if (references.length === 1) {
31 return references[0];
32 }
33 return null;
34
35}
36
37/**
38 * Checks if the given identifier node is shadowed in the given scope.
39 * @param {Object} scope The current scope.
40 * @param {ASTNode} node The identifier node to check.
41 * @returns {boolean} Whether or not the name is shadowed.
42 */
43function isShadowed(scope, node) {
44 const reference = findReference(scope, node);
45
46 return reference && reference.resolved && reference.resolved.defs.length > 0;
47}
48
49module.exports = {
50 meta: {
56c4a2cb
DC
51 deprecated: true,
52
ebb53d86 53 replacedBy: [],
56c4a2cb 54
eb39fafa
DC
55 type: "suggestion",
56
57 docs: {
58 description: "require `require()` calls to be placed at top-level module scope",
59 category: "Node.js and CommonJS",
60 recommended: false,
61 url: "https://eslint.org/docs/rules/global-require"
62 },
63
64 schema: [],
65 messages: {
66 unexpected: "Unexpected require()."
67 }
68 },
69
70 create(context) {
71 return {
72 CallExpression(node) {
73 const currentScope = context.getScope();
74
75 if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) {
76 const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1);
77
78 if (!isGoodRequire) {
79 context.report({ node, messageId: "unexpected" });
80 }
81 }
82 }
83 };
84 }
85};