]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-inline-comments.js
import 8.3.0 source
[pve-eslint.git] / eslint / lib / rules / no-inline-comments.js
1 /**
2 * @fileoverview Enforces or disallows inline comments.
3 * @author Greg Cochard
4 */
5 "use strict";
6
7 const astUtils = require("./utils/ast-utils");
8
9 //------------------------------------------------------------------------------
10 // Rule Definition
11 //------------------------------------------------------------------------------
12
13 module.exports = {
14 meta: {
15 type: "suggestion",
16
17 docs: {
18 description: "disallow inline comments after code",
19 recommended: false,
20 url: "https://eslint.org/docs/rules/no-inline-comments"
21 },
22
23 schema: [
24 {
25 type: "object",
26 properties: {
27 ignorePattern: {
28 type: "string"
29 }
30 },
31 additionalProperties: false
32 }
33 ],
34
35 messages: {
36 unexpectedInlineComment: "Unexpected comment inline with code."
37 }
38 },
39
40 create(context) {
41 const sourceCode = context.getSourceCode();
42 const options = context.options[0];
43 let customIgnoreRegExp;
44
45 if (options && options.ignorePattern) {
46 customIgnoreRegExp = new RegExp(options.ignorePattern, "u");
47 }
48
49 /**
50 * Will check that comments are not on lines starting with or ending with code
51 * @param {ASTNode} node The comment node to check
52 * @private
53 * @returns {void}
54 */
55 function testCodeAroundComment(node) {
56
57 const startLine = String(sourceCode.lines[node.loc.start.line - 1]),
58 endLine = String(sourceCode.lines[node.loc.end.line - 1]),
59 preamble = startLine.slice(0, node.loc.start.column).trim(),
60 postamble = endLine.slice(node.loc.end.column).trim(),
61 isPreambleEmpty = !preamble,
62 isPostambleEmpty = !postamble;
63
64 // Nothing on both sides
65 if (isPreambleEmpty && isPostambleEmpty) {
66 return;
67 }
68
69 // Matches the ignore pattern
70 if (customIgnoreRegExp && customIgnoreRegExp.test(node.value)) {
71 return;
72 }
73
74 // JSX Exception
75 if (
76 (isPreambleEmpty || preamble === "{") &&
77 (isPostambleEmpty || postamble === "}")
78 ) {
79 const enclosingNode = sourceCode.getNodeByRangeIndex(node.range[0]);
80
81 if (enclosingNode && enclosingNode.type === "JSXEmptyExpression") {
82 return;
83 }
84 }
85
86 // Don't report ESLint directive comments
87 if (astUtils.isDirectiveComment(node)) {
88 return;
89 }
90
91 context.report({
92 node,
93 messageId: "unexpectedInlineComment"
94 });
95 }
96
97 //--------------------------------------------------------------------------
98 // Public
99 //--------------------------------------------------------------------------
100
101 return {
102 Program() {
103 sourceCode.getAllComments()
104 .filter(token => token.type !== "Shebang")
105 .forEach(testCodeAroundComment);
106 }
107 };
108 }
109 };