no-inline-comments.js
2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @fileoverview Enforces or disallows inline comments.
* @author Greg Cochard
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "disallow inline comments after code",
category: "Stylistic Issues",
recommended: false,
url: "https://eslint.org/docs/rules/no-inline-comments"
},
schema: []
},
create(context) {
const sourceCode = context.getSourceCode();
/**
* Will check that comments are not on lines starting with or ending with code
* @param {ASTNode} node The comment node to check
* @private
* @returns {void}
*/
function testCodeAroundComment(node) {
const startLine = String(sourceCode.lines[node.loc.start.line - 1]),
endLine = String(sourceCode.lines[node.loc.end.line - 1]),
preamble = startLine.slice(0, node.loc.start.column).trim(),
postamble = endLine.slice(node.loc.end.column).trim(),
isPreambleEmpty = !preamble,
isPostambleEmpty = !postamble;
// Nothing on both sides
if (isPreambleEmpty && isPostambleEmpty) {
return;
}
// JSX Exception
if (
(isPreambleEmpty || preamble === "{") &&
(isPostambleEmpty || postamble === "}")
) {
const enclosingNode = sourceCode.getNodeByRangeIndex(node.range[0]);
if (enclosingNode && enclosingNode.type === "JSXEmptyExpression") {
return;
}
}
// Don't report ESLint directive comments
if (astUtils.isDirectiveComment(node)) {
return;
}
context.report({ node, message: "Unexpected comment inline with code." });
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
Program() {
const comments = sourceCode.getAllComments();
comments.filter(token => token.type !== "Shebang").forEach(testCodeAroundComment);
}
};
}
};