max-lines-per-function.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /**
  2. * @fileoverview max lines per function for react
  3. * @author Lisonglin
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const getFunctionNameWithKind = require("eslint-plugin-react-func/lib/utils/getFunctionNameWithKind.js");
  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. function isContainJSX(type) {
  140. return ['JSXElement', 'JSXFragment'].includes(type)
  141. }
  142. function checkIsJSXElement(node) {
  143. const functionText = sourceCode.getText(node) || '';
  144. return (functionText.includes('<') && (functionText.includes('/>') || functionText.includes('</')));
  145. }
  146. function checkIsCustomHook(name) {
  147. return /use*/.test(name);
  148. }
  149. function isReactEle(node) {
  150. const bodyType = lodash.get(node, 'body.type', '');
  151. const keyName = lodash.get(node, 'key.name', '');
  152. const parentName = lodash.get(node, 'parent.id.name', '');
  153. const functionName = getFunctionNameWithKind(node);
  154. const isClassComponent = keyName === 'render';
  155. const isJSXElement = isContainJSX(bodyType) || checkIsJSXElement(node);
  156. const isCustomHook = checkIsCustomHook(functionName) || checkIsCustomHook(parentName);
  157. const isReactEle = isJSXElement || isClassComponent || isCustomHook;
  158. return isReactEle;
  159. }
  160. function getCurrentFunctionTextLineArray(node) {
  161. return sourceCode.lines.slice(node.loc.start.line - 1, node.loc.end.line);
  162. }
  163. function checkIsCommonFunction(lineTexts) {
  164. return lineTexts[0].includes('function');
  165. }
  166. function checkIsObjectFunction(lineTexts) {
  167. try {
  168. const isCommonFunction = checkIsCommonFunction(lineTexts);
  169. if (isCommonFunction) return false;
  170. const arrowOperatorIndex = lineTexts.findIndex(line => line.includes('=>'));
  171. const isNotContainArrowFunction = arrowOperatorIndex === -1;
  172. if (isNotContainArrowFunction) return true;
  173. const rightParenthesesIndex = lineTexts.findIndex(line => line.includes(')'));
  174. if (rightParenthesesIndex === -1) return false;
  175. return (rightParenthesesIndex < arrowOperatorIndex);
  176. } catch (e) {
  177. return false;
  178. }
  179. }
  180. function getArgumentsLineNum(node) {
  181. try {
  182. if (isReactEle(node)) return 0;
  183. const emptyLine = 0;
  184. let argumentsLineNum = emptyLine;
  185. const lineTexts = getCurrentFunctionTextLineArray(node);
  186. const isCommonFunction = checkIsCommonFunction(lineTexts);
  187. const isObjectFunction = checkIsObjectFunction(lineTexts);
  188. const isArrowFunction = !isCommonFunction && !isObjectFunction;
  189. if (isCommonFunction || isObjectFunction) {
  190. argumentsLineNum = lineTexts.findIndex(line => line.includes(')'));
  191. }
  192. if (isArrowFunction) {
  193. argumentsLineNum = lineTexts.findIndex(line => line.includes('=>'));
  194. }
  195. if (argumentsLineNum === -1) return emptyLine;
  196. return argumentsLineNum;
  197. } catch(e) {
  198. return emptyLine;
  199. }
  200. }
  201. /**
  202. * Count the lines in the function
  203. * @param {ASTNode} funcNode Function AST node
  204. * @returns {void}
  205. * @private
  206. */
  207. function processFunction(funcNode) {
  208. const node = isEmbedded(funcNode) ? funcNode.parent : funcNode;
  209. const argumentsLineNum = getArgumentsLineNum(node);
  210. if (!IIFEs && isIIFE(node)) {
  211. return;
  212. }
  213. let lineCount = 0;
  214. for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) {
  215. const line = lines[i];
  216. if (skipComments) {
  217. if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) {
  218. continue;
  219. }
  220. }
  221. if (skipBlankLines) {
  222. if (line.match(/^\s*$/u)) {
  223. continue;
  224. }
  225. }
  226. lineCount++;
  227. }
  228. const baseFunctionLineNum = 2
  229. lineCount = lineCount - argumentsLineNum - baseFunctionLineNum;
  230. const isOverLength = lineCount > maxLines;
  231. const isError = isOverLength && !isReactEle(node);
  232. if (isError) {
  233. const functionName = getFunctionNameWithKind(node);
  234. const name = lodash.upperFirst(functionName);
  235. context.report({
  236. node,
  237. messageId: "exceed",
  238. data: { name, lineCount, maxLines }
  239. });
  240. }
  241. }
  242. //--------------------------------------------------------------------------
  243. // Public API
  244. //--------------------------------------------------------------------------
  245. return {
  246. FunctionDeclaration: processFunction,
  247. FunctionExpression: processFunction,
  248. ArrowFunctionExpression: processFunction
  249. };
  250. }
  251. };