-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComponentGraphAnalyzer.ts
81 lines (61 loc) · 2.02 KB
/
ComponentGraphAnalyzer.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { parse } from "@typescript-eslint/typescript-estree";
import * as fs from "node:fs";
import { generateGraphDiagram } from "./src/utils/generateDiagram";
import { analyzeAstBodyDeclaration } from "./src/declarations/AstBodyDeclaration";
import { analyzeAstChildren } from "./src/declarations/AstChildren";
import { GlobalConfig, RawConfig } from "./src/types/Config";
import { FileNode } from "./src/types/FileNode";
import { getFilesList } from "./src/utils/getFilesList";
import * as nodePath from "node:path";
const getAbstractSyntaxTree = (filePath: string) => {
try {
const code = fs.readFileSync(filePath).toString();
return parse(code, { jsx: true, loc: true, loggerFn: false });
} catch (err) {
return null;
}
};
const analyze = (fileNode: FileNode) => {
const config = GlobalConfig.getInstance();
const { path: relativePath } = fileNode;
const path = nodePath.normalize(relativePath);
if (config.isFileAnalyzed(path)) {
return;
}
config.setFileAsAnalyzed(path);
const abstractSyntaxTree = getAbstractSyntaxTree(path);
if (!abstractSyntaxTree) {
return;
}
analyzeAstBodyDeclaration(fileNode, abstractSyntaxTree.body);
analyzeAstChildren(fileNode);
for (const dependency of fileNode.dependencies) {
if (dependency.isUsed) {
analyze(dependency);
}
}
};
export const fileBasedAnalyze = (filePath: string, config: RawConfig = {}) => {
GlobalConfig.clear();
GlobalConfig.getInstance(config);
const rootNode = new FileNode(filePath);
rootNode.setAsUsed();
analyze(rootNode);
return generateGraphDiagram(rootNode);
};
export const directoryBasedAnalyze = (
catalogPath: string,
config: RawConfig = {}
) => {
GlobalConfig.clear();
GlobalConfig.getInstance(config);
const results: string[] = [];
const files = getFilesList(catalogPath);
for (let filePath of files) {
const rootNode = new FileNode(filePath);
rootNode.setAsUsed();
analyze(rootNode);
results.push(...generateGraphDiagram(rootNode));
}
return [...new Set(results)];
};