/
cyclomatic-complexity.ts
62 lines (55 loc) · 1.82 KB
/
cyclomatic-complexity.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import type {
TmplAstBoundAttribute,
TmplAstTextAttribute,
} from '@angular-eslint/bundled-angular-compiler';
import { getTemplateParserServices } from '@angular-eslint/utils';
import { createESLintRule } from '../utils/create-eslint-rule';
type Options = [{ maxComplexity: number }];
export type MessageIds = 'cyclomaticComplexity';
export const RULE_NAME = 'cyclomatic-complexity';
const DEFAULT_MAX_COMPLEXITY = 5;
export default createESLintRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description: `Checks cyclomatic complexity against a specified limit. It is a quantitative measure of the number of linearly independent paths through a program's source code`,
recommended: false,
},
schema: [
{
type: 'object',
properties: {
maxComplexity: {
type: 'number',
minimum: 1,
},
},
additionalProperties: false,
},
],
messages: {
cyclomaticComplexity:
'The cyclomatic complexity {{totalComplexity}} exceeds the defined limit {{maxComplexity}}',
},
},
defaultOptions: [{ maxComplexity: DEFAULT_MAX_COMPLEXITY }],
create(context, [{ maxComplexity }]) {
let totalComplexity = 0;
const parserServices = getTemplateParserServices(context);
return {
'BoundAttribute[name=/^(ngForOf|ngIf|ngSwitchCase)$/], TextAttribute[name="ngSwitchDefault"]'({
sourceSpan,
}: TmplAstBoundAttribute | TmplAstTextAttribute) {
totalComplexity += 1;
if (totalComplexity <= maxComplexity) return;
const loc = parserServices.convertNodeSourceSpanToLoc(sourceSpan);
context.report({
messageId: 'cyclomaticComplexity',
loc,
data: { maxComplexity, totalComplexity },
});
},
};
},
});