]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-global-assign.js
import 8.3.0 source
[pve-eslint.git] / eslint / lib / rules / no-global-assign.js
1 /**
2 * @fileoverview Rule to disallow assignments to native objects or read-only global variables
3 * @author Ilya Volodin
4 */
5
6 "use strict";
7
8 //------------------------------------------------------------------------------
9 // Rule Definition
10 //------------------------------------------------------------------------------
11
12 module.exports = {
13 meta: {
14 type: "suggestion",
15
16 docs: {
17 description: "disallow assignments to native objects or read-only global variables",
18 recommended: true,
19 url: "https://eslint.org/docs/rules/no-global-assign"
20 },
21
22 schema: [
23 {
24 type: "object",
25 properties: {
26 exceptions: {
27 type: "array",
28 items: { type: "string" },
29 uniqueItems: true
30 }
31 },
32 additionalProperties: false
33 }
34 ],
35
36 messages: {
37 globalShouldNotBeModified: "Read-only global '{{name}}' should not be modified."
38 }
39 },
40
41 create(context) {
42 const config = context.options[0];
43 const exceptions = (config && config.exceptions) || [];
44
45 /**
46 * Reports write references.
47 * @param {Reference} reference A reference to check.
48 * @param {int} index The index of the reference in the references.
49 * @param {Reference[]} references The array that the reference belongs to.
50 * @returns {void}
51 */
52 function checkReference(reference, index, references) {
53 const identifier = reference.identifier;
54
55 if (reference.init === false &&
56 reference.isWrite() &&
57
58 /*
59 * Destructuring assignments can have multiple default value,
60 * so possibly there are multiple writeable references for the same identifier.
61 */
62 (index === 0 || references[index - 1].identifier !== identifier)
63 ) {
64 context.report({
65 node: identifier,
66 messageId: "globalShouldNotBeModified",
67 data: {
68 name: identifier.name
69 }
70 });
71 }
72 }
73
74 /**
75 * Reports write references if a given variable is read-only builtin.
76 * @param {Variable} variable A variable to check.
77 * @returns {void}
78 */
79 function checkVariable(variable) {
80 if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) {
81 variable.references.forEach(checkReference);
82 }
83 }
84
85 return {
86 Program() {
87 const globalScope = context.getScope();
88
89 globalScope.variables.forEach(checkVariable);
90 }
91 };
92 }
93 };