max-lines-per-function.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. if (!comments) {
  50. return map;
  51. }
  52. comments.forEach(comment => {
  53. for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
  54. map.set(i, comment);
  55. }
  56. });
  57. return map;
  58. }
  59. //------------------------------------------------------------------------------
  60. // Rule Definition
  61. //------------------------------------------------------------------------------
  62. module.exports = {
  63. meta: {
  64. type: "suggestion",
  65. docs: {
  66. description: "enforce a maximum number of line of code in a function",
  67. category: "Stylistic Issues",
  68. recommended: false,
  69. url: "https://eslint.org/docs/rules/max-lines-per-function"
  70. },
  71. schema: [
  72. OPTIONS_OR_INTEGER_SCHEMA
  73. ],
  74. messages: {
  75. exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}."
  76. }
  77. },
  78. create(context) {
  79. const sourceCode = context.getSourceCode();
  80. const lines = sourceCode.lines;
  81. const option = context.options[0];
  82. let maxLines = 50;
  83. let skipComments = false;
  84. let skipBlankLines = false;
  85. let IIFEs = false;
  86. if (typeof option === "object") {
  87. maxLines = typeof option.max === "number" ? option.max : 50;
  88. skipComments = !!option.skipComments;
  89. skipBlankLines = !!option.skipBlankLines;
  90. IIFEs = !!option.IIFEs;
  91. } else if (typeof option === "number") {
  92. maxLines = option;
  93. }
  94. const commentLineNumbers = getCommentLineNumbers(sourceCode.getAllComments());
  95. //--------------------------------------------------------------------------
  96. // Helpers
  97. //--------------------------------------------------------------------------
  98. /**
  99. * Tells if a comment encompasses the entire line.
  100. * @param {string} line The source line with a trailing comment
  101. * @param {number} lineNumber The one-indexed line number this is on
  102. * @param {ASTNode} comment The comment to remove
  103. * @returns {boolean} If the comment covers the entire line
  104. */
  105. function isFullLineComment(line, lineNumber, comment) {
  106. const start = comment.loc.start,
  107. end = comment.loc.end,
  108. isFirstTokenOnLine = start.line === lineNumber && !line.slice(0, start.column).trim(),
  109. isLastTokenOnLine = end.line === lineNumber && !line.slice(end.column).trim();
  110. return comment &&
  111. (start.line < lineNumber || isFirstTokenOnLine) &&
  112. (end.line > lineNumber || isLastTokenOnLine);
  113. }
  114. /**
  115. * Identifies is a node is a FunctionExpression which is part of an IIFE
  116. * @param {ASTNode} node Node to test
  117. * @returns {boolean} True if it's an IIFE
  118. */
  119. function isIIFE(node) {
  120. return node.type === "FunctionExpression" && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node;
  121. }
  122. /**
  123. * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property
  124. * @param {ASTNode} node Node to test
  125. * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property
  126. */
  127. function isEmbedded(node) {
  128. if (!node.parent) {
  129. return false;
  130. }
  131. if (node !== node.parent.value) {
  132. return false;
  133. }
  134. if (node.parent.type === "MethodDefinition") {
  135. return true;
  136. }
  137. if (node.parent.type === "Property") {
  138. return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set";
  139. }
  140. return false;
  141. }
  142. /**
  143. * Count the lines in the function
  144. * @param {ASTNode} funcNode Function AST node
  145. * @returns {void}
  146. * @private
  147. */
  148. function processFunction(funcNode) {
  149. const node = isEmbedded(funcNode) ? funcNode.parent : funcNode;
  150. if (!IIFEs && isIIFE(node)) {
  151. return;
  152. }
  153. let lineCount = 0;
  154. for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) {
  155. const line = lines[i];
  156. if (skipComments) {
  157. if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) {
  158. continue;
  159. }
  160. }
  161. if (skipBlankLines) {
  162. if (line.match(/^\s*$/u)) {
  163. continue;
  164. }
  165. }
  166. lineCount++;
  167. }
  168. if (lineCount > maxLines) {
  169. const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(funcNode));
  170. context.report({
  171. node,
  172. messageId: "exceed",
  173. data: { name, lineCount, maxLines }
  174. });
  175. }
  176. }
  177. //--------------------------------------------------------------------------
  178. // Public API
  179. //--------------------------------------------------------------------------
  180. return {
  181. FunctionDeclaration: processFunction,
  182. FunctionExpression: processFunction,
  183. ArrowFunctionExpression: processFunction
  184. };
  185. }
  186. };