Skip to content

Commit 74adfbc

Browse files
committed
tools: lint for function argument alignment
In function calls that span multiple lines, apply a custom lint rule to enforce argument alignment. With this rule, the following code will be flagged as an error by the linter because the arguments on the second line start in a different column than on the first line: myFunction(a, b, c, d); The following code will not be flagged as an error by the linter: myFunction(a, b, c, d);
1 parent 3f20b00 commit 74adfbc

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

.eslintrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ rules:
8585
prefer-const: 2
8686

8787
# Custom rules in tools/eslint-rules
88+
align-function-arguments: 2
8889
align-multiline-assignment: 2
8990
assert-fail-single-argument: 2
9091
new-with-error: [2, "Error", "RangeError", "TypeError", "SyntaxError", "ReferenceError"]
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @fileoverview Align arguments in multiline function calls
3+
* @author Rich Trott
4+
*/
5+
'use strict';
6+
7+
//------------------------------------------------------------------------------
8+
// Rule Definition
9+
//------------------------------------------------------------------------------
10+
function checkArgumentAlignment(context, node) {
11+
if (node.arguments.length === 0)
12+
return;
13+
14+
var msg = '';
15+
const first = node.arguments[0];
16+
var currentLine = first.loc.start.line;
17+
const firstColumn = first.loc.start.column;
18+
19+
node.arguments.slice(1).forEach((argument) => {
20+
if (argument.loc.start.line > currentLine) {
21+
// Ignore if there are multiple lines between arguments. This happens
22+
// in situations like this:
23+
// setTimeout(function() {
24+
// ... do stuff ...
25+
// }, 1);
26+
if (argument.loc.start.line === currentLine + 1) {
27+
if (argument.loc.start.column !== firstColumn) {
28+
msg = 'Function called with argument in column ' +
29+
`${argument.loc.start.column}, expected in ${firstColumn}`;
30+
}
31+
}
32+
currentLine = argument.loc.start.line;
33+
}
34+
});
35+
36+
if (msg)
37+
context.report(node, msg);
38+
}
39+
40+
module.exports = function(context) {
41+
return {
42+
'CallExpression': (node) => checkArgumentAlignment(context, node)
43+
};
44+
};

0 commit comments

Comments
 (0)