|
| 1 | +/** |
| 2 | + * @fileoverview Align arguments in multiline function calls |
| 3 | + * @author Rich Trott |
| 4 | + */ |
| 5 | +'use strict'; |
| 6 | + |
| 7 | +//------------------------------------------------------------------------------ |
| 8 | +// Rule Definition |
| 9 | +//------------------------------------------------------------------------------ |
| 10 | + |
| 11 | +function checkArgumentAlignment(context, node) { |
| 12 | + |
| 13 | + function isNodeFirstInLine(node, byEndLocation) { |
| 14 | + const firstToken = byEndLocation === true ? context.getLastToken(node, 1) : |
| 15 | + context.getTokenBefore(node); |
| 16 | + const startLine = byEndLocation === true ? node.loc.end.line : |
| 17 | + node.loc.start.line; |
| 18 | + const endLine = firstToken ? firstToken.loc.end.line : -1; |
| 19 | + |
| 20 | + return startLine !== endLine; |
| 21 | + } |
| 22 | + |
| 23 | + if (node.arguments.length === 0) |
| 24 | + return; |
| 25 | + |
| 26 | + var msg = ''; |
| 27 | + const first = node.arguments[0]; |
| 28 | + var currentLine = first.loc.start.line; |
| 29 | + const firstColumn = first.loc.start.column; |
| 30 | + |
| 31 | + const ignoreTypes = [ |
| 32 | + 'ArrowFunctionExpression', |
| 33 | + 'CallExpression', |
| 34 | + 'FunctionExpression', |
| 35 | + 'ObjectExpression', |
| 36 | + 'TemplateLiteral' |
| 37 | + ]; |
| 38 | + |
| 39 | + const args = node.arguments; |
| 40 | + |
| 41 | + // For now, don't bother trying to validate potentially complicating things |
| 42 | + // like closures. Different people will have very different ideas and it's |
| 43 | + // probably best to implement configuration options. |
| 44 | + if (args.some((node) => { return ignoreTypes.indexOf(node.type) !== -1; })) { |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + if (!isNodeFirstInLine(node)) { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + args.slice(1).forEach((argument) => { |
| 53 | + if (argument.loc.start.line === currentLine + 1) { |
| 54 | + if (argument.loc.start.column !== firstColumn) { |
| 55 | + msg = 'Function called with argument in column ' + |
| 56 | + `${argument.loc.start.column}, expected in ${firstColumn}`; |
| 57 | + } |
| 58 | + } |
| 59 | + currentLine = argument.loc.start.line; |
| 60 | + }); |
| 61 | + |
| 62 | + if (msg) |
| 63 | + context.report(node, msg); |
| 64 | +} |
| 65 | + |
| 66 | +module.exports = function(context) { |
| 67 | + return { |
| 68 | + 'CallExpression': (node) => checkArgumentAlignment(context, node) |
| 69 | + }; |
| 70 | +}; |
0 commit comments