|
| 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 | + function getStartsFromOneSide(side, starts) { |
| 12 | + starts.push(side.loc.start); |
| 13 | + if (side.type === 'BinaryExpression') { |
| 14 | + starts = getBinaryExpressionStarts(side, starts); |
| 15 | + } |
| 16 | + return starts; |
| 17 | + } |
| 18 | + |
| 19 | + starts = getStartsFromOneSide(binaryExpression.left, starts); |
| 20 | + starts = getStartsFromOneSide(binaryExpression.right, starts); |
| 21 | + return starts; |
| 22 | +} |
| 23 | + |
| 24 | +function checkExpressionAlignment(expression) { |
| 25 | + if (!expression) |
| 26 | + return; |
| 27 | + |
| 28 | + var msg = ''; |
| 29 | + |
| 30 | + switch (expression.type) { |
| 31 | + case 'BinaryExpression': |
| 32 | + var starts = getBinaryExpressionStarts(expression, []); |
| 33 | + var startLine = starts[0].line; |
| 34 | + const startColumn = starts[0].column; |
| 35 | + starts.forEach((loc) => { |
| 36 | + if (loc.line > startLine) { |
| 37 | + startLine = loc.line; |
| 38 | + if (loc.column !== startColumn) { |
| 39 | + msg = 'Misaligned multiline assignment'; |
| 40 | + } |
| 41 | + } |
| 42 | + }); |
| 43 | + break; |
| 44 | + } |
| 45 | + return msg; |
| 46 | +} |
| 47 | + |
| 48 | +function testAssignment(context, node) { |
| 49 | + const msg = checkExpressionAlignment(node.right); |
| 50 | + if (msg) |
| 51 | + context.report(node, msg); |
| 52 | +} |
| 53 | + |
| 54 | +function testDeclaration(context, node) { |
| 55 | + node.declarations.forEach((declaration) => { |
| 56 | + const msg = checkExpressionAlignment(declaration.init); |
| 57 | + if (msg) |
| 58 | + context.report(node, msg); |
| 59 | + }); |
| 60 | +} |
| 61 | + |
| 62 | +module.exports = function(context) { |
| 63 | + return { |
| 64 | + 'AssignmentExpression': (node) => testAssignment(context, node), |
| 65 | + 'VariableDeclaration': (node) => testDeclaration(context, node) |
| 66 | + }; |
| 67 | +}; |
0 commit comments