1 | /**
|
2 | * @fileoverview Validates newlines before and after dots
|
3 | * @author Greg Cochard
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | const astUtils = require("../ast-utils");
|
9 |
|
10 | //------------------------------------------------------------------------------
|
11 | // Rule Definition
|
12 | //------------------------------------------------------------------------------
|
13 |
|
14 | module.exports = {
|
15 | meta: {
|
16 | docs: {
|
17 | description: "enforce consistent newlines before and after dots",
|
18 | category: "Best Practices",
|
19 | recommended: false
|
20 | },
|
21 |
|
22 | schema: [
|
23 | {
|
24 | enum: ["object", "property"]
|
25 | }
|
26 | ]
|
27 | },
|
28 |
|
29 | create(context) {
|
30 |
|
31 | const config = context.options[0];
|
32 |
|
33 | // default to onObject if no preference is passed
|
34 | const onObject = config === "object" || !config;
|
35 |
|
36 | const sourceCode = context.getSourceCode();
|
37 |
|
38 | /**
|
39 | * Reports if the dot between object and property is on the correct loccation.
|
40 | * @param {ASTNode} obj The object owning the property.
|
41 | * @param {ASTNode} prop The property of the object.
|
42 | * @param {ASTNode} node The corresponding node of the token.
|
43 | * @returns {void}
|
44 | */
|
45 | function checkDotLocation(obj, prop, node) {
|
46 | const dot = sourceCode.getTokenBefore(prop);
|
47 |
|
48 | if (dot.type === "Punctuator" && dot.value === ".") {
|
49 | if (onObject) {
|
50 | if (!astUtils.isTokenOnSameLine(obj, dot)) {
|
51 | context.report(node, dot.loc.start, "Expected dot to be on same line as object.");
|
52 | }
|
53 | } else if (!astUtils.isTokenOnSameLine(dot, prop)) {
|
54 | context.report(node, dot.loc.start, "Expected dot to be on same line as property.");
|
55 | }
|
56 | }
|
57 | }
|
58 |
|
59 | /**
|
60 | * Checks the spacing of the dot within a member expression.
|
61 | * @param {ASTNode} node The node to check.
|
62 | * @returns {void}
|
63 | */
|
64 | function checkNode(node) {
|
65 | checkDotLocation(node.object, node.property, node);
|
66 | }
|
67 |
|
68 | return {
|
69 | MemberExpression: checkNode
|
70 | };
|
71 | }
|
72 | };
|