-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcyclomatic.ts
48 lines (42 loc) · 1.53 KB
/
cyclomatic.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
import { extname } from "node:path";
import { readFileSync } from "node:fs";
import { buildDebugger, UnsupportedExtension } from "../../../utils";
import { transformSync } from "@babel/core";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const escomplex = require("escomplex");
const internal = { debug: buildDebugger("cyclomatic") };
export function calculate(path: string): number | UnsupportedExtension {
switch (extname(path)) {
case ".ts":
return fromTypeScript(path);
case ".mjs":
case ".js":
return fromJavaScript(path);
default:
internal.debug(
"Unsupported file extension. Falling back on default complexity (1)"
);
return new UnsupportedExtension();
}
}
function fromJavaScript(path: string): number {
const content = readFileSync(path, { encoding: "utf8" });
const babelResult = transformSync(content, {
filename: path,
presets: ["@babel/preset-env"],
});
if (!babelResult) throw new Error(`Error while parsing file ${path}`);
const result = escomplex.analyse(babelResult.code, {});
return result.aggregate.cyclomatic;
}
function fromTypeScript(path: string): number {
const content = readFileSync(path, { encoding: "utf8" });
const babelResult = transformSync(content, {
filename: path,
plugins: ["@babel/plugin-transform-typescript"],
presets: ["@babel/preset-env"],
});
if (!babelResult) throw new Error(`Error while parsing file ${path}`);
const result = escomplex.analyse(babelResult.code);
return result.aggregate.cyclomatic;
}