UNPKG

4.02 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to enforce the position of line comments
3 * @author Alberto Rodríguez
4 */
5"use strict";
6
7const astUtils = require("../ast-utils");
8
9//------------------------------------------------------------------------------
10// Rule Definition
11//------------------------------------------------------------------------------
12
13module.exports = {
14 meta: {
15 docs: {
16 description: "enforce position of line comments",
17 category: "Stylistic Issues",
18 recommended: false,
19 url: "https://eslint.org/docs/rules/line-comment-position"
20 },
21
22 schema: [
23 {
24 oneOf: [
25 {
26 enum: ["above", "beside"]
27 },
28 {
29 type: "object",
30 properties: {
31 position: {
32 enum: ["above", "beside"]
33 },
34 ignorePattern: {
35 type: "string"
36 },
37 applyDefaultPatterns: {
38 type: "boolean"
39 },
40 applyDefaultIgnorePatterns: {
41 type: "boolean"
42 }
43 },
44 additionalProperties: false
45 }
46 ]
47 }
48 ]
49 },
50
51 create(context) {
52 const options = context.options[0];
53
54 let above,
55 ignorePattern,
56 applyDefaultIgnorePatterns = true;
57
58 if (!options || typeof options === "string") {
59 above = !options || options === "above";
60
61 } else {
62 above = options.position === "above";
63 ignorePattern = options.ignorePattern;
64
65 if (options.hasOwnProperty("applyDefaultIgnorePatterns")) {
66 applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false;
67 } else {
68 applyDefaultIgnorePatterns = options.applyDefaultPatterns !== false;
69 }
70 }
71
72 const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN;
73 const fallThroughRegExp = /^\s*falls?\s?through/;
74 const customIgnoreRegExp = new RegExp(ignorePattern);
75 const sourceCode = context.getSourceCode();
76
77 //--------------------------------------------------------------------------
78 // Public
79 //--------------------------------------------------------------------------
80
81 return {
82 Program() {
83 const comments = sourceCode.getAllComments();
84
85 comments.filter(token => token.type === "Line").forEach(node => {
86 if (applyDefaultIgnorePatterns && (defaultIgnoreRegExp.test(node.value) || fallThroughRegExp.test(node.value))) {
87 return;
88 }
89
90 if (ignorePattern && customIgnoreRegExp.test(node.value)) {
91 return;
92 }
93
94 const previous = sourceCode.getTokenBefore(node, { includeComments: true });
95 const isOnSameLine = previous && previous.loc.end.line === node.loc.start.line;
96
97 if (above) {
98 if (isOnSameLine) {
99 context.report({
100 node,
101 message: "Expected comment to be above code."
102 });
103 }
104 } else {
105 if (!isOnSameLine) {
106 context.report({
107 node,
108 message: "Expected comment to be beside code."
109 });
110 }
111 }
112 });
113 }
114 };
115 }
116};