1 | /**
|
2 | * @fileoverview Enforces or disallows inline comments.
|
3 | * @author Greg Cochard
|
4 | */
|
5 | ;
|
6 |
|
7 | const astUtils = require("../ast-utils");
|
8 |
|
9 | //------------------------------------------------------------------------------
|
10 | // Rule Definition
|
11 | //------------------------------------------------------------------------------
|
12 |
|
13 | module.exports = {
|
14 | meta: {
|
15 | docs: {
|
16 | description: "disallow inline comments after code",
|
17 | category: "Stylistic Issues",
|
18 | recommended: false,
|
19 | url: "https://eslint.org/docs/rules/no-inline-comments"
|
20 | },
|
21 |
|
22 | schema: []
|
23 | },
|
24 |
|
25 | create(context) {
|
26 | const sourceCode = context.getSourceCode();
|
27 |
|
28 | /**
|
29 | * Will check that comments are not on lines starting with or ending with code
|
30 | * @param {ASTNode} node The comment node to check
|
31 | * @private
|
32 | * @returns {void}
|
33 | */
|
34 | function testCodeAroundComment(node) {
|
35 |
|
36 | // Get the whole line and cut it off at the start of the comment
|
37 | const startLine = String(sourceCode.lines[node.loc.start.line - 1]);
|
38 | const endLine = String(sourceCode.lines[node.loc.end.line - 1]);
|
39 |
|
40 | const preamble = startLine.slice(0, node.loc.start.column).trim();
|
41 |
|
42 | // Also check after the comment
|
43 | const postamble = endLine.slice(node.loc.end.column).trim();
|
44 |
|
45 | // Check that this comment isn't an ESLint directive
|
46 | const isDirective = astUtils.isDirectiveComment(node);
|
47 |
|
48 | // Should be empty if there was only whitespace around the comment
|
49 | if (!isDirective && (preamble || postamble)) {
|
50 | context.report({ node, message: "Unexpected comment inline with code." });
|
51 | }
|
52 | }
|
53 |
|
54 | //--------------------------------------------------------------------------
|
55 | // Public
|
56 | //--------------------------------------------------------------------------
|
57 |
|
58 | return {
|
59 | Program() {
|
60 | const comments = sourceCode.getAllComments();
|
61 |
|
62 | comments.filter(token => token.type !== "Shebang").forEach(testCodeAroundComment);
|
63 | }
|
64 | };
|
65 | }
|
66 | };
|