crap-ts 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,173 +1,305 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, join } from "node:path";
4
+
1
5
  import ts from "typescript";
2
6
 
3
7
  import { calculateCrapScoreFromPercent } from "./crap-score.js";
4
8
 
5
9
  export function extractCoverageFunctions(coverageJson) {
6
- const coverageByFile = new Map();
7
-
8
- for (const [filePath, coverage] of Object.entries(coverageJson)) {
9
- const functions = Object.entries(coverage.fnMap ?? {}).flatMap(([id, metadata]) => {
10
- const startLine = metadata.loc?.start?.line;
11
- const endLine = metadata.loc?.end?.line;
12
-
13
- if (!startLine || !endLine) {
14
- return [];
15
- }
16
-
17
- return [
18
- {
19
- coveragePercent: (coverage.f?.[id] ?? 0) > 0 ? 100 : 0,
20
- declarationLine: metadata.line ?? startLine,
21
- endLine,
22
- startLine,
23
- },
24
- ];
25
- });
26
-
27
- coverageByFile.set(filePath, functions);
28
- }
29
-
30
- return coverageByFile;
10
+ const coverageByFile = new Map();
11
+
12
+ for (const [filePath, coverage] of Object.entries(coverageJson)) {
13
+ const functions = Object.entries(coverage.fnMap ?? {}).flatMap(
14
+ ([id, metadata]) => {
15
+ const startLine = metadata.loc?.start?.line;
16
+ const endLine = metadata.loc?.end?.line;
17
+
18
+ if (!startLine || !endLine) {
19
+ return [];
20
+ }
21
+
22
+ return [
23
+ {
24
+ coveragePercent: (coverage.f?.[id] ?? 0) > 0 ? 100 : 0,
25
+ declarationLine: metadata.line ?? startLine,
26
+ endLine,
27
+ startLine,
28
+ },
29
+ ];
30
+ },
31
+ );
32
+
33
+ coverageByFile.set(filePath, functions);
34
+ }
35
+
36
+ return coverageByFile;
31
37
  }
32
38
 
33
- export function analyzeFileRisk({ coverageFunctions, filePath, minLines, sourceText }) {
34
- const sourceFile = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true);
35
- const risks = [];
36
-
37
- function visit(node) {
38
- if (isFunctionLikeNode(node) && node.body) {
39
- const startLine =
40
- sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
41
- const endLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
42
- const lineCount = endLine - startLine + 1;
43
-
44
- if (lineCount >= minLines) {
45
- const complexity = calculateCyclomaticComplexity(node.body);
46
- const coveragePercent = getFunctionCoveragePercent({
47
- coverageFunctions,
48
- endLine,
49
- startLine,
50
- });
51
-
52
- risks.push({
53
- complexity,
54
- coveragePercent,
55
- crapScore: calculateCrapScoreFromPercent(complexity, coveragePercent),
56
- endLine,
57
- filePath,
58
- lineCount,
59
- name: getFunctionName(node, sourceFile),
60
- startLine,
61
- });
62
- }
63
- }
64
-
65
- ts.forEachChild(node, visit);
66
- }
67
-
68
- visit(sourceFile);
69
-
70
- return risks;
39
+ export async function analyzeFileRisk({
40
+ coverageFunctions,
41
+ filePath,
42
+ minLines,
43
+ sourceFilePath,
44
+ sourceText,
45
+ }) {
46
+ const adapter = await getTypescriptAdapter({
47
+ filePath,
48
+ sourceFilePath,
49
+ sourceText,
50
+ });
51
+ const { sourceFile } = adapter;
52
+ const risks = [];
53
+
54
+ function visit(node) {
55
+ if (isFunctionLikeNode(adapter, node) && node.body) {
56
+ const startLine =
57
+ sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))
58
+ .line + 1;
59
+ const endLine =
60
+ sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
61
+ const lineCount = endLine - startLine + 1;
62
+
63
+ if (lineCount >= minLines) {
64
+ const complexity = calculateCyclomaticComplexity(node.body, adapter);
65
+ const coveragePercent = getFunctionCoveragePercent({
66
+ coverageFunctions,
67
+ endLine,
68
+ startLine,
69
+ });
70
+
71
+ risks.push({
72
+ complexity,
73
+ coveragePercent,
74
+ crapScore: calculateCrapScoreFromPercent(complexity, coveragePercent),
75
+ endLine,
76
+ filePath,
77
+ lineCount,
78
+ name: getFunctionName(adapter, node, sourceFile),
79
+ startLine,
80
+ });
81
+ }
82
+ }
83
+
84
+ adapter.forEachChild(node, visit);
85
+ }
86
+
87
+ visit(sourceFile);
88
+
89
+ return risks;
71
90
  }
72
91
 
73
92
  export function formatRiskLine(risk) {
74
- return [
75
- `${risk.filePath}:${risk.startLine}`,
76
- risk.name,
77
- `CRAP ${risk.crapScore.toFixed(1)}`,
78
- `complexity ${risk.complexity}`,
79
- `coverage ${risk.coveragePercent.toFixed(0)}%`,
80
- `${risk.lineCount} lines`,
81
- ].join(" | ");
93
+ return [
94
+ `${risk.filePath}:${risk.startLine}`,
95
+ risk.name,
96
+ `CRAP ${risk.crapScore.toFixed(1)}`,
97
+ `complexity ${risk.complexity}`,
98
+ `coverage ${risk.coveragePercent.toFixed(0)}%`,
99
+ `${risk.lineCount} lines`,
100
+ ].join(" | ");
82
101
  }
83
102
 
84
- export function calculateCyclomaticComplexity(node) {
85
- let complexity = 1;
103
+ export function calculateCyclomaticComplexity(
104
+ node,
105
+ adapter = getDefaultComplexityAdapter(),
106
+ ) {
107
+ let complexity = 1;
86
108
 
87
- function visit(child) {
88
- if (addsDecisionPath(child)) {
89
- complexity += 1;
90
- }
109
+ function visit(child) {
110
+ if (addsDecisionPath(adapter, child)) {
111
+ complexity += 1;
112
+ }
91
113
 
92
- ts.forEachChild(child, visit);
93
- }
114
+ adapter.forEachChild(child, visit);
115
+ }
94
116
 
95
- visit(node);
117
+ visit(node);
96
118
 
97
- return complexity;
119
+ return complexity;
98
120
  }
99
121
 
100
- function addsDecisionPath(node) {
101
- if (
102
- ts.isIfStatement(node) ||
103
- ts.isForStatement(node) ||
104
- ts.isForInStatement(node) ||
105
- ts.isForOfStatement(node) ||
106
- ts.isWhileStatement(node) ||
107
- ts.isDoStatement(node) ||
108
- ts.isCaseClause(node) ||
109
- ts.isCatchClause(node) ||
110
- ts.isConditionalExpression(node)
111
- ) {
112
- return true;
113
- }
114
-
115
- return (
116
- ts.isBinaryExpression(node) &&
117
- (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
118
- node.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
119
- node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken)
120
- );
122
+ function addsDecisionPath(adapter, node) {
123
+ if (
124
+ adapter.isIfStatement(node) ||
125
+ adapter.isForStatement(node) ||
126
+ adapter.isForInStatement(node) ||
127
+ adapter.isForOfStatement(node) ||
128
+ adapter.isWhileStatement(node) ||
129
+ adapter.isDoStatement(node) ||
130
+ adapter.isCaseClause(node) ||
131
+ adapter.isCatchClause(node) ||
132
+ adapter.isConditionalExpression(node)
133
+ ) {
134
+ return true;
135
+ }
136
+
137
+ return (
138
+ adapter.isBinaryExpression(node) &&
139
+ (node.operatorToken.kind === adapter.SyntaxKind.AmpersandAmpersandToken ||
140
+ node.operatorToken.kind === adapter.SyntaxKind.BarBarToken ||
141
+ node.operatorToken.kind === adapter.SyntaxKind.QuestionQuestionToken)
142
+ );
121
143
  }
122
144
 
123
145
  function getFunctionCoveragePercent({ coverageFunctions, endLine, startLine }) {
124
- const exactMatch = coverageFunctions.find(
125
- (coverageFunction) =>
126
- coverageFunction.declarationLine === startLine ||
127
- (coverageFunction.startLine === startLine && coverageFunction.endLine === endLine),
128
- );
129
-
130
- if (exactMatch) {
131
- return exactMatch.coveragePercent;
132
- }
133
-
134
- const containingMatch = coverageFunctions.find(
135
- (coverageFunction) =>
136
- (coverageFunction.declarationLine >= startLine &&
137
- coverageFunction.declarationLine <= endLine) ||
138
- (coverageFunction.startLine <= endLine && coverageFunction.endLine >= startLine),
139
- );
140
-
141
- return containingMatch?.coveragePercent ?? 0;
146
+ const exactMatch = coverageFunctions.find(
147
+ (coverageFunction) =>
148
+ coverageFunction.declarationLine === startLine ||
149
+ (coverageFunction.startLine === startLine &&
150
+ coverageFunction.endLine === endLine),
151
+ );
152
+
153
+ if (exactMatch) {
154
+ return exactMatch.coveragePercent;
155
+ }
156
+
157
+ const containingMatch = coverageFunctions.find(
158
+ (coverageFunction) =>
159
+ (coverageFunction.declarationLine >= startLine &&
160
+ coverageFunction.declarationLine <= endLine) ||
161
+ (coverageFunction.startLine <= endLine &&
162
+ coverageFunction.endLine >= startLine),
163
+ );
164
+
165
+ return containingMatch?.coveragePercent ?? 0;
166
+ }
167
+
168
+ function getFunctionName(adapter, node, sourceFile) {
169
+ if (
170
+ (adapter.isFunctionDeclaration(node) ||
171
+ adapter.isFunctionExpression(node)) &&
172
+ node.name
173
+ ) {
174
+ return node.name.getText(sourceFile);
175
+ }
176
+
177
+ if (adapter.isMethodDeclaration(node) && node.name) {
178
+ return node.name.getText(sourceFile);
179
+ }
180
+
181
+ const parent = node.parent;
182
+
183
+ if (adapter.isVariableDeclaration(parent) && parent.name) {
184
+ return parent.name.getText(sourceFile);
185
+ }
186
+
187
+ if (adapter.isPropertyAssignment(parent) && parent.name) {
188
+ return parent.name.getText(sourceFile);
189
+ }
190
+
191
+ return "<anonymous>";
142
192
  }
143
193
 
144
- function getFunctionName(node, sourceFile) {
145
- if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) && node.name) {
146
- return node.name.getText(sourceFile);
147
- }
194
+ function isFunctionLikeNode(adapter, node) {
195
+ return (
196
+ adapter.isFunctionDeclaration(node) ||
197
+ adapter.isFunctionExpression(node) ||
198
+ adapter.isArrowFunction(node) ||
199
+ adapter.isMethodDeclaration(node)
200
+ );
201
+ }
148
202
 
149
- if (ts.isMethodDeclaration(node) && node.name) {
150
- return node.name.getText(sourceFile);
151
- }
203
+ function getTs5Adapter() {
204
+ return {
205
+ ...ts,
206
+ forEachChild: ts.forEachChild,
207
+ };
208
+ }
152
209
 
153
- const parent = node.parent;
210
+ function getDefaultComplexityAdapter() {
211
+ if (ts.createSourceFile) {
212
+ return getTs5Adapter();
213
+ }
154
214
 
155
- if (ts.isVariableDeclaration(parent) && parent.name) {
156
- return parent.name.getText(sourceFile);
157
- }
215
+ return getTs7NodeAdapter();
216
+ }
158
217
 
159
- if (ts.isPropertyAssignment(parent) && parent.name) {
160
- return parent.name.getText(sourceFile);
161
- }
218
+ function getTs7NodeAdapter() {
219
+ return {
220
+ SyntaxKind: ts7SyntaxKind,
221
+ forEachChild(node, visitor) {
222
+ node.forEachChild?.(visitor);
223
+ },
224
+ isBinaryExpression: isSyntaxKind(ts7SyntaxKind.BinaryExpression),
225
+ isCaseClause: isSyntaxKind(ts7SyntaxKind.CaseClause),
226
+ isCatchClause: isSyntaxKind(ts7SyntaxKind.CatchClause),
227
+ isConditionalExpression: isSyntaxKind(ts7SyntaxKind.ConditionalExpression),
228
+ isDoStatement: isSyntaxKind(ts7SyntaxKind.DoStatement),
229
+ isForInStatement: isSyntaxKind(ts7SyntaxKind.ForInStatement),
230
+ isForOfStatement: isSyntaxKind(ts7SyntaxKind.ForOfStatement),
231
+ isForStatement: isSyntaxKind(ts7SyntaxKind.ForStatement),
232
+ isIfStatement: isSyntaxKind(ts7SyntaxKind.IfStatement),
233
+ isWhileStatement: isSyntaxKind(ts7SyntaxKind.WhileStatement),
234
+ };
235
+ }
162
236
 
163
- return "<anonymous>";
237
+ function isSyntaxKind(kind) {
238
+ return (node) => node?.kind === kind;
164
239
  }
165
240
 
166
- function isFunctionLikeNode(node) {
167
- return (
168
- ts.isFunctionDeclaration(node) ||
169
- ts.isFunctionExpression(node) ||
170
- ts.isArrowFunction(node) ||
171
- ts.isMethodDeclaration(node)
172
- );
241
+ const ts7SyntaxKind = {
242
+ AmpersandAmpersandToken: 55,
243
+ BarBarToken: 56,
244
+ BinaryExpression: 227,
245
+ CaseClause: 297,
246
+ CatchClause: 300,
247
+ ConditionalExpression: 228,
248
+ DoStatement: 247,
249
+ ForInStatement: 250,
250
+ ForOfStatement: 251,
251
+ ForStatement: 249,
252
+ IfStatement: 246,
253
+ QuestionQuestionToken: 60,
254
+ WhileStatement: 248,
255
+ };
256
+
257
+ async function getTypescriptAdapter({ filePath, sourceFilePath, sourceText }) {
258
+ if (ts.createSourceFile) {
259
+ return {
260
+ ...getTs5Adapter(),
261
+ sourceFile: ts.createSourceFile(
262
+ filePath,
263
+ sourceText,
264
+ ts.ScriptTarget.Latest,
265
+ true,
266
+ ),
267
+ };
268
+ }
269
+
270
+ const [{ API }, ast] = await Promise.all([
271
+ import("typescript/unstable/sync"),
272
+ import("typescript/unstable/ast"),
273
+ ]);
274
+ const temporaryDirectory = mkdtempSync(join(tmpdir(), "crap-ts-"));
275
+ const resolvedPath = join(
276
+ temporaryDirectory,
277
+ basename(sourceFilePath ?? filePath),
278
+ );
279
+
280
+ writeFileSync(resolvedPath, sourceText);
281
+
282
+ const api = new API();
283
+
284
+ try {
285
+ const snapshot = api.updateSnapshot({ openFiles: [resolvedPath] });
286
+ const project = snapshot.getDefaultProjectForFile(resolvedPath);
287
+ const sourceFile = project?.program.getSourceFile(resolvedPath);
288
+
289
+ if (!sourceFile) {
290
+ throw new Error(`Unable to parse TypeScript source file: ${filePath}`);
291
+ }
292
+
293
+ return {
294
+ ...ast,
295
+ forEachChild(node, visitor) {
296
+ ast.visitEachChild(node, visitor, null);
297
+ },
298
+ sourceFile,
299
+ };
300
+ } finally {
301
+ api.close();
302
+
303
+ rmSync(temporaryDirectory, { force: true, recursive: true });
304
+ }
173
305
  }
@@ -1,14 +1,14 @@
1
1
  export interface CrapAuditOptions {
2
- all?: boolean;
3
- coverageCommand?: string;
4
- coveragePath?: string;
5
- cwd?: string;
6
- includes?: string[];
7
- limit?: number;
8
- maxScore?: number;
9
- minLines?: number;
10
- reportOnly?: boolean;
11
- skipCoverage?: boolean;
2
+ all?: boolean;
3
+ coverageCommand?: string;
4
+ coveragePath?: string;
5
+ cwd?: string;
6
+ includes?: string[];
7
+ limit?: number;
8
+ maxScore?: number;
9
+ minLines?: number;
10
+ reportOnly?: boolean;
11
+ skipCoverage?: boolean;
12
12
  }
13
13
 
14
- export function runCrapAudit(options?: CrapAuditOptions): number;
14
+ export function runCrapAudit(options?: CrapAuditOptions): Promise<number>;
@@ -2,102 +2,116 @@ import { spawnSync } from "node:child_process";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { isAbsolute, relative, resolve } from "node:path";
4
4
 
5
- import { analyzeFileRisk, extractCoverageFunctions, formatRiskLine } from "./crap-analysis.js";
5
+ import {
6
+ analyzeFileRisk,
7
+ extractCoverageFunctions,
8
+ formatRiskLine,
9
+ } from "./crap-analysis.js";
6
10
  import { normalizePath } from "./path-utils.js";
7
11
 
8
- export function runCrapAudit({
9
- all = false,
10
- coverageCommand,
11
- coveragePath = "coverage/unit/coverage-final.json",
12
- cwd = process.cwd(),
13
- includes = [],
14
- limit = 20,
15
- maxScore = 30,
16
- minLines = 10,
17
- reportOnly = false,
18
- skipCoverage = false,
12
+ export async function runCrapAudit({
13
+ all = false,
14
+ coverageCommand,
15
+ coveragePath = "coverage/unit/coverage-final.json",
16
+ cwd = process.cwd(),
17
+ includes = [],
18
+ limit = 20,
19
+ maxScore = 30,
20
+ minLines = 10,
21
+ reportOnly = false,
22
+ skipCoverage = false,
19
23
  } = {}) {
20
- if (!skipCoverage && coverageCommand) {
21
- const result = spawnSync(coverageCommand, {
22
- cwd,
23
- shell: true,
24
- stdio: "inherit",
25
- });
26
-
27
- if (result.status !== 0) {
28
- return result.status ?? 1;
29
- }
30
- }
31
-
32
- const resolvedCoveragePath = resolve(cwd, coveragePath);
33
-
34
- if (!existsSync(resolvedCoveragePath)) {
35
- console.error(`Missing coverage JSON: ${resolvedCoveragePath}`);
36
- console.error("Run coverage first, pass --coverage-file, or use a valid --coverage-command.");
37
- return 1;
38
- }
39
-
40
- const coverageJson = JSON.parse(readFileSync(resolvedCoveragePath, "utf8"));
41
- const coverageByFile = extractCoverageFunctions(coverageJson);
42
- const risks = [];
43
-
44
- for (const [coverageFilePath, coverageFunctions] of coverageByFile.entries()) {
45
- if (!shouldIncludePath(coverageFilePath, includes)) {
46
- continue;
47
- }
48
-
49
- const sourceFilePath = isAbsolute(coverageFilePath)
50
- ? coverageFilePath
51
- : resolve(cwd, coverageFilePath);
52
-
53
- if (!existsSync(sourceFilePath)) {
54
- continue;
55
- }
56
-
57
- const sourceText = readFileSync(sourceFilePath, "utf8");
58
- const relativeFilePath = relative(cwd, sourceFilePath);
59
-
60
- risks.push(
61
- ...analyzeFileRisk({
62
- coverageFunctions,
63
- filePath: relativeFilePath,
64
- minLines,
65
- sourceText,
66
- }),
67
- );
68
- }
69
-
70
- const sortedRisks = risks.sort((left, right) => right.crapScore - left.crapScore);
71
- const failingRisks = sortedRisks.filter((risk) => risk.crapScore > maxScore);
72
-
73
- console.log();
74
- console.log(
75
- `CRAP report: ${sortedRisks.length} functions checked, ${failingRisks.length} above ${maxScore}.`,
76
- );
77
-
78
- const printedRisks = all ? sortedRisks : sortedRisks.slice(0, limit);
79
-
80
- for (const risk of printedRisks) {
81
- console.log(formatRiskLine(risk));
82
- }
83
-
84
- if (failingRisks.length > 0 && !reportOnly) {
85
- console.error("");
86
- console.error(
87
- "CRAP check failed. Use --report-only while calibrating, or lower complexity / add coverage for the listed functions.",
88
- );
89
- return 1;
90
- }
91
-
92
- return 0;
24
+ if (!skipCoverage && coverageCommand) {
25
+ const result = spawnSync(coverageCommand, {
26
+ cwd,
27
+ shell: true,
28
+ stdio: "inherit",
29
+ });
30
+
31
+ if (result.status !== 0) {
32
+ return result.status ?? 1;
33
+ }
34
+ }
35
+
36
+ const resolvedCoveragePath = resolve(cwd, coveragePath);
37
+
38
+ if (!existsSync(resolvedCoveragePath)) {
39
+ console.error(`Missing coverage JSON: ${resolvedCoveragePath}`);
40
+ console.error(
41
+ "Run coverage first, pass --coverage-file, or use a valid --coverage-command.",
42
+ );
43
+ return 1;
44
+ }
45
+
46
+ const coverageJson = JSON.parse(readFileSync(resolvedCoveragePath, "utf8"));
47
+ const coverageByFile = extractCoverageFunctions(coverageJson);
48
+ const risks = [];
49
+
50
+ for (const [
51
+ coverageFilePath,
52
+ coverageFunctions,
53
+ ] of coverageByFile.entries()) {
54
+ if (!shouldIncludePath(coverageFilePath, includes)) {
55
+ continue;
56
+ }
57
+
58
+ const sourceFilePath = isAbsolute(coverageFilePath)
59
+ ? coverageFilePath
60
+ : resolve(cwd, coverageFilePath);
61
+
62
+ if (!existsSync(sourceFilePath)) {
63
+ continue;
64
+ }
65
+
66
+ const sourceText = readFileSync(sourceFilePath, "utf8");
67
+ const relativeFilePath = relative(cwd, sourceFilePath);
68
+
69
+ risks.push(
70
+ ...(await analyzeFileRisk({
71
+ coverageFunctions,
72
+ filePath: relativeFilePath,
73
+ minLines,
74
+ sourceFilePath,
75
+ sourceText,
76
+ })),
77
+ );
78
+ }
79
+
80
+ const sortedRisks = risks.sort(
81
+ (left, right) => right.crapScore - left.crapScore,
82
+ );
83
+ const failingRisks = sortedRisks.filter((risk) => risk.crapScore > maxScore);
84
+
85
+ console.log();
86
+ console.log(
87
+ `CRAP report: ${sortedRisks.length} functions checked, ${failingRisks.length} above ${maxScore}.`,
88
+ );
89
+
90
+ const printedRisks = all ? sortedRisks : sortedRisks.slice(0, limit);
91
+
92
+ for (const risk of printedRisks) {
93
+ console.log(formatRiskLine(risk));
94
+ }
95
+
96
+ if (failingRisks.length > 0 && !reportOnly) {
97
+ console.error("");
98
+ console.error(
99
+ "CRAP check failed. Use --report-only while calibrating, or lower complexity / add coverage for the listed functions.",
100
+ );
101
+ return 1;
102
+ }
103
+
104
+ return 0;
93
105
  }
94
106
 
95
107
  function shouldIncludePath(filePath, includes) {
96
- if (includes.length === 0) {
97
- return true;
98
- }
108
+ if (includes.length === 0) {
109
+ return true;
110
+ }
99
111
 
100
- const normalizedPath = normalizePath(filePath);
112
+ const normalizedPath = normalizePath(filePath);
101
113
 
102
- return includes.some((include) => normalizedPath.includes(normalizePath(include)));
114
+ return includes.some((include) =>
115
+ normalizedPath.includes(normalizePath(include)),
116
+ );
103
117
  }