max-lines-per-function.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /**
  2. * @fileoverview A rule to set the maximum number of line of code in a function.
  3. * @author Pete Ward <peteward44@gmail.com>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. const lodash = require("lodash");
  11. //------------------------------------------------------------------------------
  12. // Constants
  13. //------------------------------------------------------------------------------
  14. const OPTIONS_SCHEMA = {
  15. type: "object",
  16. properties: {
  17. max: {
  18. type: "integer",
  19. minimum: 0
  20. },
  21. skipComments: {
  22. type: "boolean"
  23. },
  24. skipBlankLines: {
  25. type: "boolean"
  26. },
  27. IIFEs: {
  28. type: "boolean"
  29. }
  30. },
  31. additionalProperties: false
  32. };
  33. const OPTIONS_OR_INTEGER_SCHEMA = {
  34. oneOf: [
  35. OPTIONS_SCHEMA,
  36. {
  37. type: "integer",
  38. minimum: 1
  39. }
  40. ]
  41. };
  42. /**
  43. * Given a list of comment nodes, return a map with numeric keys (source code line numbers) and comment token values.
  44. * @param {Array} comments An array of comment nodes.
  45. * @returns {Map.<string,Node>} A map with numeric keys (source code line numbers) and comment token values.
  46. */
  47. function getCommentLineNumbers(comments) {
  48. const map = new Map();
  49. comments.forEach(comment => {
  50. for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
  51. map.set(i, comment);
  52. }
  53. });
  54. return map;
  55. }
  56. //------------------------------------------------------------------------------
  57. // Rule Definition
  58. //------------------------------------------------------------------------------
  59. module.exports = {
  60. meta: {
  61. type: "suggestion",
  62. docs: {
  63. description: "enforce a maximum number of line of code in a function",
  64. category: "Stylistic Issues",
  65. recommended: false,
  66. url: "https://eslint.org/docs/rules/max-lines-per-function"
  67. },
  68. schema: [
  69. OPTIONS_OR_INTEGER_SCHEMA
  70. ],
  71. messages: {
  72. exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}."
  73. }
  74. },
  75. create(context) {
  76. const sourceCode = context.getSourceCode();
  77. const lines = sourceCode.lines;
  78. const option = context.options[0];
  79. let maxLines = 50;
  80. let skipComments = false;
  81. let skipBlankLines = false;
  82. let IIFEs = false;
  83. if (typeof option === "object") {
  84. maxLines = typeof option.max === "number" ? option.max : 50;
  85. skipComments = !!option.skipComments;
  86. skipBlankLines = !!option.skipBlankLines;
  87. IIFEs = !!option.IIFEs;
  88. } else if (typeof option === "number") {
  89. maxLines = option;
  90. }
  91. const commentLineNumbers = getCommentLineNumbers(sourceCode.getAllComments());
  92. //--------------------------------------------------------------------------
  93. // Helpers
  94. //--------------------------------------------------------------------------
  95. /**
  96. * Tells if a comment encompasses the entire line.
  97. * @param {string} line The source line with a trailing comment
  98. * @param {number} lineNumber The one-indexed line number this is on
  99. * @param {ASTNode} comment The comment to remove
  100. * @returns {boolean} If the comment covers the entire line
  101. */
  102. function isFullLineComment(line, lineNumber, comment) {
  103. const start = comment.loc.start,
  104. end = comment.loc.end,
  105. isFirstTokenOnLine = start.line === lineNumber && !line.slice(0, start.column).trim(),
  106. isLastTokenOnLine = end.line === lineNumber && !line.slice(end.column).trim();
  107. return comment &&
  108. (start.line < lineNumber || isFirstTokenOnLine) &&
  109. (end.line > lineNumber || isLastTokenOnLine);
  110. }
  111. /**
  112. * Identifies is a node is a FunctionExpression which is part of an IIFE
  113. * @param {ASTNode} node Node to test
  114. * @returns {boolean} True if it's an IIFE
  115. */
  116. function isIIFE(node) {
  117. return (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node;
  118. }
  119. /**
  120. * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property
  121. * @param {ASTNode} node Node to test
  122. * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property
  123. */
  124. function isEmbedded(node) {
  125. if (!node.parent) {
  126. return false;
  127. }
  128. if (node !== node.parent.value) {
  129. return false;
  130. }
  131. if (node.parent.type === "MethodDefinition") {
  132. return true;
  133. }
  134. if (node.parent.type === "Property") {
  135. return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set";
  136. }
  137. return false;
  138. }
  139. /**
  140. * Count the lines in the function
  141. * @param {ASTNode} funcNode Function AST node
  142. * @returns {void}
  143. * @private
  144. */
  145. function processFunction(funcNode) {
  146. const node = isEmbedded(funcNode) ? funcNode.parent : funcNode;
  147. if (!IIFEs && isIIFE(node)) {
  148. return;
  149. }
  150. let lineCount = 0;
  151. for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) {
  152. const line = lines[i];
  153. if (skipComments) {
  154. if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) {
  155. continue;
  156. }
  157. }
  158. if (skipBlankLines) {
  159. if (line.match(/^\s*$/u)) {
  160. continue;
  161. }
  162. }
  163. lineCount++;
  164. }
  165. if (lineCount > maxLines) {
  166. const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(funcNode));
  167. context.report({
  168. node,
  169. messageId: "exceed",
  170. data: { name, lineCount, maxLines }
  171. });
  172. }
  173. }
  174. //--------------------------------------------------------------------------
  175. // Public API
  176. //--------------------------------------------------------------------------
  177. return {
  178. FunctionDeclaration: processFunction,
  179. FunctionExpression: processFunction,
  180. ArrowFunctionExpression: processFunction
  181. };
  182. }
  183. };