|
| 1 | +/** |
| 2 | + * @fileoverview Align multiline variable assignments |
| 3 | + * @author Rich Trott |
| 4 | + */ |
| 5 | +'use strict'; |
| 6 | + |
| 7 | +//------------------------------------------------------------------------------ |
| 8 | +// Rule Definition |
| 9 | +//------------------------------------------------------------------------------ |
| 10 | +function getBinaryExpressionStarts(binaryExpression, starts) { |
| 11 | + starts = starts || []; |
| 12 | + function getStartsFromOneSide(side, starts) { |
| 13 | + starts.push(side.loc.start); |
| 14 | + if (side.type === 'BinaryExpression') { |
| 15 | + starts = getBinaryExpressionStarts(side, starts); |
| 16 | + } |
| 17 | + return starts; |
| 18 | + } |
| 19 | + |
| 20 | + starts = getStartsFromOneSide(binaryExpression.left, starts); |
| 21 | + starts = getStartsFromOneSide(binaryExpression.right, starts); |
| 22 | + return starts; |
| 23 | +} |
| 24 | + |
| 25 | +function checkExpressionAlignment(expression) { |
| 26 | + if (!expression) |
| 27 | + return; |
| 28 | + |
| 29 | + var msg = ''; |
| 30 | + |
| 31 | + switch (expression.type) { |
| 32 | + case 'BinaryExpression': |
| 33 | + var starts = getBinaryExpressionStarts(expression); |
| 34 | + var startLine = starts[0].line; |
| 35 | + const startColumn = starts[0].column; |
| 36 | + starts.forEach((loc) => { |
| 37 | + if (loc.line > startLine) { |
| 38 | + startLine = loc.line; |
| 39 | + if (loc.column !== startColumn) { |
| 40 | + msg = 'Misaligned multiline assignment'; |
| 41 | + } |
| 42 | + } |
| 43 | + }); |
| 44 | + break; |
| 45 | + } |
| 46 | + return msg; |
| 47 | +} |
| 48 | + |
| 49 | +function testAssignment(context, node) { |
| 50 | + const msg = checkExpressionAlignment(node.right); |
| 51 | + if (msg) |
| 52 | + context.report(node, msg); |
| 53 | +} |
| 54 | + |
| 55 | +function testDecleration(context, node) { |
| 56 | + node.declarations.forEach((declaration) => { |
| 57 | + const msg = checkExpressionAlignment(declaration.init); |
| 58 | + // const start = declaration.init.loc.start; |
| 59 | + if (msg) |
| 60 | + context.report(node, msg); |
| 61 | + }); |
| 62 | +} |
| 63 | + |
| 64 | +module.exports = function(context) { |
| 65 | + return { |
| 66 | + 'AssignmentExpression': (node) => testAssignment(context, node), |
| 67 | + 'VariableDeclaration': (node) => testDecleration(context, node) |
| 68 | + }; |
| 69 | +}; |
0 commit comments