blob: 3d26108a71504ace6b7ff9e1a76a05cec95a6d11 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
2 * @fileoverview Enforce a maximum number of classes per file
3 * @author James Garbutt <https://github.com/43081j>
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11
12//------------------------------------------------------------------------------
13// Rule Definition
14//------------------------------------------------------------------------------
15
16module.exports = {
17 meta: {
18 type: "suggestion",
19
20 docs: {
21 description: "enforce a maximum number of classes per file",
Yang Guo4fd355c2019-09-19 10:59:03 +020022 recommended: false,
23 url: "https://eslint.org/docs/rules/max-classes-per-file"
24 },
25
26 schema: [
27 {
Tim van der Lippe0fb47802021-11-08 16:23:10 +000028 oneOf: [
29 {
30 type: "integer",
31 minimum: 1
32 },
33 {
34 type: "object",
35 properties: {
36 ignoreExpressions: {
37 type: "boolean"
38 },
39 max: {
40 type: "integer",
41 minimum: 1
42 }
43 },
44 additionalProperties: false
45 }
46 ]
Yang Guo4fd355c2019-09-19 10:59:03 +020047 }
48 ],
49
50 messages: {
51 maximumExceeded: "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}."
52 }
53 },
54 create(context) {
Tim van der Lippe0fb47802021-11-08 16:23:10 +000055 const [option = {}] = context.options;
56 const [ignoreExpressions, max] = typeof option === "number"
57 ? [false, option || 1]
58 : [option.ignoreExpressions, option.max || 1];
Yang Guo4fd355c2019-09-19 10:59:03 +020059
60 let classCount = 0;
61
62 return {
63 Program() {
64 classCount = 0;
65 },
66 "Program:exit"(node) {
Tim van der Lippe0fb47802021-11-08 16:23:10 +000067 if (classCount > max) {
Yang Guo4fd355c2019-09-19 10:59:03 +020068 context.report({
69 node,
70 messageId: "maximumExceeded",
71 data: {
72 classCount,
Tim van der Lippe0fb47802021-11-08 16:23:10 +000073 max
Yang Guo4fd355c2019-09-19 10:59:03 +020074 }
75 });
76 }
77 },
Tim van der Lippe0fb47802021-11-08 16:23:10 +000078 "ClassDeclaration"() {
Yang Guo4fd355c2019-09-19 10:59:03 +020079 classCount++;
Tim van der Lippe0fb47802021-11-08 16:23:10 +000080 },
81 "ClassExpression"() {
82 if (!ignoreExpressions) {
83 classCount++;
84 }
Yang Guo4fd355c2019-09-19 10:59:03 +020085 }
86 };
87 }
88};