max-classes-per-file.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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('../shared/types').Rule} */
  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/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: "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}."
  46. }
  47. },
  48. create(context) {
  49. const [option = {}] = context.options;
  50. const [ignoreExpressions, max] = typeof option === "number"
  51. ? [false, option || 1]
  52. : [option.ignoreExpressions, option.max || 1];
  53. let classCount = 0;
  54. return {
  55. Program() {
  56. classCount = 0;
  57. },
  58. "Program:exit"(node) {
  59. if (classCount > max) {
  60. context.report({
  61. node,
  62. messageId: "maximumExceeded",
  63. data: {
  64. classCount,
  65. max
  66. }
  67. });
  68. }
  69. },
  70. "ClassDeclaration"() {
  71. classCount++;
  72. },
  73. "ClassExpression"() {
  74. if (!ignoreExpressions) {
  75. classCount++;
  76. }
  77. }
  78. };
  79. }
  80. };