Browse Source

tools: lint for alignment of variable assignments

Enforce alignment/indentation on variable assignments that span multiple
lines.

PR-URL: https://github.com/nodejs/node/pull/6242
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Johan Bergström <bugs@bergstroem.nu>
Reviewed-By: James M Snell <jasnell@gmail.com>
process-exit-stdio-flushing
Rich Trott 9 years ago
committed by James M Snell
parent
commit
ca698330ac
  1. 2
      .eslintrc
  2. 68
      tools/eslint-rules/align-multiline-assignment.js

2
.eslintrc

@ -86,7 +86,7 @@ rules:
# Custom rules in tools/eslint-rules # Custom rules in tools/eslint-rules
new-with-error: [2, "Error", "RangeError", "TypeError", "SyntaxError", "ReferenceError"] new-with-error: [2, "Error", "RangeError", "TypeError", "SyntaxError", "ReferenceError"]
align-multiline-assignment: 2
# Global scoped method and vars # Global scoped method and vars
globals: globals:

68
tools/eslint-rules/align-multiline-assignment.js

@ -0,0 +1,68 @@
/**
* @fileoverview Align multiline variable assignments
* @author Rich Trott
*/
'use strict';
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
function getBinaryExpressionStarts(binaryExpression, starts = []) {
function getStartsFromOneSide(side, starts) {
starts.push(side.loc.start);
if (side.type === 'BinaryExpression') {
starts = getBinaryExpressionStarts(side, starts);
}
return starts;
}
starts = getStartsFromOneSide(binaryExpression.left, starts);
starts = getStartsFromOneSide(binaryExpression.right, starts);
return starts;
}
function checkExpressionAlignment(expression) {
if (!expression)
return;
var msg = '';
switch (expression.type) {
case 'BinaryExpression':
var starts = getBinaryExpressionStarts(expression);
var startLine = starts[0].line;
const startColumn = starts[0].column;
starts.forEach((loc) => {
if (loc.line > startLine) {
startLine = loc.line;
if (loc.column !== startColumn) {
msg = 'Misaligned multiline assignment';
}
}
});
break;
}
return msg;
}
function testAssignment(context, node) {
const msg = checkExpressionAlignment(node.right);
if (msg)
context.report(node, msg);
}
function testDeclaration(context, node) {
node.declarations.forEach((declaration) => {
const msg = checkExpressionAlignment(declaration.init);
// const start = declaration.init.loc.start;
if (msg)
context.report(node, msg);
});
}
module.exports = function(context) {
return {
'AssignmentExpression': (node) => testAssignment(context, node),
'VariableDeclaration': (node) => testDeclaration(context, node)
};
};
Loading…
Cancel
Save