id-length.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /**
  2. * @fileoverview Rule that warns when identifier names are shorter or longer
  3. * than the values provided in configuration.
  4. * @author Burak Yigit Kaya aka BYK
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const { getGraphemeCount } = require("../shared/string-utils");
  11. const { getModuleExportName } = require("./utils/ast-utils");
  12. //------------------------------------------------------------------------------
  13. // Rule Definition
  14. //------------------------------------------------------------------------------
  15. /** @type {import('../shared/types').Rule} */
  16. module.exports = {
  17. meta: {
  18. type: "suggestion",
  19. docs: {
  20. description: "Enforce minimum and maximum identifier lengths",
  21. recommended: false,
  22. url: "https://eslint.org/docs/latest/rules/id-length"
  23. },
  24. schema: [
  25. {
  26. type: "object",
  27. properties: {
  28. min: {
  29. type: "integer",
  30. default: 2
  31. },
  32. max: {
  33. type: "integer"
  34. },
  35. exceptions: {
  36. type: "array",
  37. uniqueItems: true,
  38. items: {
  39. type: "string"
  40. }
  41. },
  42. exceptionPatterns: {
  43. type: "array",
  44. uniqueItems: true,
  45. items: {
  46. type: "string"
  47. }
  48. },
  49. properties: {
  50. enum: ["always", "never"]
  51. }
  52. },
  53. additionalProperties: false
  54. }
  55. ],
  56. messages: {
  57. tooShort: "Identifier name '{{name}}' is too short (< {{min}}).",
  58. tooShortPrivate: "Identifier name '#{{name}}' is too short (< {{min}}).",
  59. tooLong: "Identifier name '{{name}}' is too long (> {{max}}).",
  60. tooLongPrivate: "Identifier name #'{{name}}' is too long (> {{max}})."
  61. }
  62. },
  63. create(context) {
  64. const options = context.options[0] || {};
  65. const minLength = typeof options.min !== "undefined" ? options.min : 2;
  66. const maxLength = typeof options.max !== "undefined" ? options.max : Infinity;
  67. const properties = options.properties !== "never";
  68. const exceptions = new Set(options.exceptions);
  69. const exceptionPatterns = (options.exceptionPatterns || []).map(pattern => new RegExp(pattern, "u"));
  70. const reportedNodes = new Set();
  71. /**
  72. * Checks if a string matches the provided exception patterns
  73. * @param {string} name The string to check.
  74. * @returns {boolean} if the string is a match
  75. * @private
  76. */
  77. function matchesExceptionPattern(name) {
  78. return exceptionPatterns.some(pattern => pattern.test(name));
  79. }
  80. const SUPPORTED_EXPRESSIONS = {
  81. MemberExpression: properties && function(parent) {
  82. return !parent.computed && (
  83. // regular property assignment
  84. (parent.parent.left === parent && parent.parent.type === "AssignmentExpression" ||
  85. // or the last identifier in an ObjectPattern destructuring
  86. parent.parent.type === "Property" && parent.parent.value === parent &&
  87. parent.parent.parent.type === "ObjectPattern" && parent.parent.parent.parent.left === parent.parent.parent)
  88. );
  89. },
  90. AssignmentPattern(parent, node) {
  91. return parent.left === node;
  92. },
  93. VariableDeclarator(parent, node) {
  94. return parent.id === node;
  95. },
  96. Property(parent, node) {
  97. if (parent.parent.type === "ObjectPattern") {
  98. const isKeyAndValueSame = parent.value.name === parent.key.name;
  99. return (
  100. !isKeyAndValueSame && parent.value === node ||
  101. isKeyAndValueSame && parent.key === node && properties
  102. );
  103. }
  104. return properties && !parent.computed && parent.key.name === node.name;
  105. },
  106. ImportSpecifier(parent, node) {
  107. return (
  108. parent.local === node &&
  109. getModuleExportName(parent.imported) !== getModuleExportName(parent.local)
  110. );
  111. },
  112. ImportDefaultSpecifier: true,
  113. ImportNamespaceSpecifier: true,
  114. RestElement: true,
  115. FunctionExpression: true,
  116. ArrowFunctionExpression: true,
  117. ClassDeclaration: true,
  118. FunctionDeclaration: true,
  119. MethodDefinition: true,
  120. PropertyDefinition: true,
  121. CatchClause: true,
  122. ArrayPattern: true
  123. };
  124. return {
  125. [[
  126. "Identifier",
  127. "PrivateIdentifier"
  128. ]](node) {
  129. const name = node.name;
  130. const parent = node.parent;
  131. const nameLength = getGraphemeCount(name);
  132. const isShort = nameLength < minLength;
  133. const isLong = nameLength > maxLength;
  134. if (!(isShort || isLong) || exceptions.has(name) || matchesExceptionPattern(name)) {
  135. return; // Nothing to report
  136. }
  137. const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type];
  138. /*
  139. * We used the range instead of the node because it's possible
  140. * for the same identifier to be represented by two different
  141. * nodes, with the most clear example being shorthand properties:
  142. * { foo }
  143. * In this case, "foo" is represented by one node for the name
  144. * and one for the value. The only way to know they are the same
  145. * is to look at the range.
  146. */
  147. if (isValidExpression && !reportedNodes.has(node.range.toString()) && (isValidExpression === true || isValidExpression(parent, node))) {
  148. reportedNodes.add(node.range.toString());
  149. let messageId = isShort ? "tooShort" : "tooLong";
  150. if (node.type === "PrivateIdentifier") {
  151. messageId += "Private";
  152. }
  153. context.report({
  154. node,
  155. messageId,
  156. data: { name, min: minLength, max: maxLength }
  157. });
  158. }
  159. }
  160. };
  161. }
  162. };