max-classes-per-file.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * @fileoverview Enforce a maximum number of classes per file
  3. * @author James Garbutt <https://github.com/43081j>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. //------------------------------------------------------------------------------
  10. // Rule Definition
  11. //------------------------------------------------------------------------------
  12. /** @type {import('../types').Rule.RuleModule} */
  13. module.exports = {
  14. meta: {
  15. type: "suggestion",
  16. docs: {
  17. description: "Enforce a maximum number of classes per file",
  18. recommended: false,
  19. url: "https://eslint.org/docs/latest/rules/max-classes-per-file",
  20. },
  21. schema: [
  22. {
  23. oneOf: [
  24. {
  25. type: "integer",
  26. minimum: 1,
  27. },
  28. {
  29. type: "object",
  30. properties: {
  31. ignoreExpressions: {
  32. type: "boolean",
  33. },
  34. max: {
  35. type: "integer",
  36. minimum: 1,
  37. },
  38. },
  39. additionalProperties: false,
  40. },
  41. ],
  42. },
  43. ],
  44. messages: {
  45. maximumExceeded:
  46. "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}.",
  47. },
  48. },
  49. create(context) {
  50. const [option = {}] = context.options;
  51. const [ignoreExpressions, max] =
  52. typeof option === "number"
  53. ? [false, option || 1]
  54. : [option.ignoreExpressions, option.max || 1];
  55. let classCount = 0;
  56. return {
  57. Program() {
  58. classCount = 0;
  59. },
  60. "Program:exit"(node) {
  61. if (classCount > max) {
  62. context.report({
  63. node,
  64. messageId: "maximumExceeded",
  65. data: {
  66. classCount,
  67. max,
  68. },
  69. });
  70. }
  71. },
  72. ClassDeclaration() {
  73. classCount++;
  74. },
  75. ClassExpression() {
  76. if (!ignoreExpressions) {
  77. classCount++;
  78. }
  79. },
  80. };
  81. },
  82. };