UNPKG

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