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