-
Notifications
You must be signed in to change notification settings - Fork 0
/
canIMerge.js
372 lines (312 loc) · 10.5 KB
/
canIMerge.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env node
/**
* Custom Sanitize Scripts for BCAN Project
*
* This script performs the following:
* 1. Scans specified directories for TypeScript files.
* 2. Parses import/export statements to build a module dependency graph.
* 3. Identifies circular dependencies.
* 4. Identifies unused variables.
*
* Usage:
* node canIMerge.js [options] [dir1] [dir2] ... [dirN]
*
* Options:
* --check-circular Perform circular dependency checks.
* --check-unused-vars Perform unused variables checks.
* --help Display help information.
*
* If no options are specified, all checks are performed.
*/
const path = require('path');
const ts = require('typescript');
const { Project } = require('ts-morph');
const DEFAULT_DIRECTORIES = ['backend/src', 'frontend/src'];
let moduleDependencies = {}; // { modulePath: [dependencyModulePath, ...] }
let exportsMap = {}; // { modulePath: Set of exported variables }
let declarationsMap = {}; // { modulePath: Set of declarations }
let usageMap = {}; // { modulePath: Set of used variables }
const project = new Project({
tsConfigFilePath: "tsconfig.json",
skipAddingFilesFromTsConfig: true,
});
/**
* Recursively walk through a directory and add all .ts/.tsx files to the project
* @param {string} dir - Directory path
*/
function addSourceFiles(dir) {
const absoluteDir = path.resolve(dir);
const globPattern = path.join(absoluteDir, '**/*.{ts,tsx}');
project.addSourceFilesAtPaths(globPattern);
}
/**
* Build the dependency graph by analyzing import/export statements
*/
function buildDependencyGraph() {
const sourceFiles = project.getSourceFiles();
sourceFiles.forEach((sourceFile) => {
const modulePath = path.relative(process.cwd(), sourceFile.getFilePath());
moduleDependencies[modulePath] = [];
sourceFile.getImportDeclarations().forEach((importDec) => {
const importPath = importDec.getModuleSpecifierValue();
if (importPath.startsWith('.')) {
const importedSourceFile = importDec.getModuleSpecifierSourceFile();
if (importedSourceFile) {
const importedModulePath = path.relative(process.cwd(), importedSourceFile.getFilePath());
moduleDependencies[modulePath].push(importedModulePath);
}
}
});
const exportedDeclarations = sourceFile.getExportedDeclarations();
exportsMap[modulePath] = new Set();
exportedDeclarations.forEach((decls, name) => {
exportsMap[modulePath].add(name);
});
});
}
/**
* Detect circular dependencies in the module dependency graph
* @returns {Array} - Array of cycles found (each cycle is an array of module paths)
*/
function detectCircularDependencies() {
const visited = new Set();
const recStack = new Set();
const cycles = [];
function dfs(node, path) {
if (!visited.has(node)) {
visited.add(node);
recStack.add(node);
path.push(node);
const neighbors = moduleDependencies[node] || [];
for (let neighbor of neighbors) {
if (!visited.has(neighbor)) {
dfs(neighbor, path);
} else if (recStack.has(neighbor)) {
const cycleStartIndex = path.indexOf(neighbor);
const cycle = path.slice(cycleStartIndex);
if (
!cycles.some(
(existingCycle) =>
existingCycle.length === cycle.length &&
existingCycle.every((mod, idx) => mod === cycle[idx])
)
) {
cycles.push([...cycle, neighbor]);
}
}
}
}
recStack.delete(node);
path.pop();
}
Object.keys(moduleDependencies).forEach((node) => {
dfs(node, []);
});
return cycles;
}
function identifyUnusedVariables() {
const unusedVariables = [];
const declarations = [];
project.getSourceFiles().forEach((sourceFile) => {
const modulePath = path.relative(process.cwd(), sourceFile.getFilePath());
sourceFile.forEachDescendant((node) => {
if (ts.isVariableDeclaration(node.compilerNode) ||
ts.isFunctionDeclaration(node.compilerNode) ||
ts.isClassDeclaration(node.compilerNode) ||
ts.isInterfaceDeclaration(node.compilerNode) ||
ts.isTypeAliasDeclaration(node.compilerNode)) {
const varName = node.getName ? node.getName() : null;
if (varName) {
const symbol = node.getSymbol();
if (symbol) {
declarations.push({
name: varName,
symbol: symbol,
module: modulePath,
});
}
}
}
});
});
const usageMapLocal = new Map();
project.getSourceFiles().forEach((sourceFile) => {
sourceFile.forEachDescendant((node) => {
if (ts.isIdentifier(node.compilerNode)) {
const identifier = node;
const varName = identifier.getText();
const parent = identifier.getParent();
if (
ts.isVariableDeclaration(parent.compilerNode) ||
ts.isFunctionDeclaration(parent.compilerNode) ||
ts.isParameter(parent.compilerNode) ||
ts.isPropertyDeclaration(parent.compilerNode) ||
ts.isClassDeclaration(parent.compilerNode) ||
ts.isInterfaceDeclaration(parent.compilerNode) ||
ts.isTypeAliasDeclaration(parent.compilerNode)
) {
return;
}
const symbol = identifier.getSymbol();
if (!symbol) return;
const declarations = symbol.getDeclarations();
if (!declarations || declarations.length === 0) return;
const declaringSourceFile = declarations[0].getSourceFile();
const declaringModulePath = path.relative(process.cwd(), declaringSourceFile.getFilePath());
const key = `${declaringModulePath}:${symbol.getName()}`;
usageMapLocal.set(key, true);
}
});
});
declarations.forEach(({ name, symbol, module }) => {
const key = `${module}:${name}`;
if (!usageMapLocal.has(key)) {
unusedVariables.push({ module, variable: name });
}
});
return unusedVariables;
}
/**
* Provide a text-based visualization of the dependency graph
*/
function visualizeDependencies() {
console.log('\n--- Module Dependency Tree ---\n');
const allModules = new Set(Object.keys(moduleDependencies));
Object.values(moduleDependencies).forEach((deps) => {
deps.forEach((dep) => allModules.delete(dep));
});
if (allModules.size === 0) {
console.log('No root modules found. All modules are interconnected.');
return;
}
allModules.forEach((root) => {
printDependencyTree(root, 0, new Set());
});
console.log('--- End of Dependency Tree ---\n');
}
/**
* Recursively print the dependency tree for a module
* @param {string} modulePath - Absolute module path
* @param {number} level - Current indentation level
* @param {Set} visited - Set of already visited modules to avoid infinite loops
*/
function printDependencyTree(modulePath, level, visited) {
const indent = ' '.repeat(level);
const moduleName = path.basename(modulePath);
console.log(`${indent}- ${moduleName}`);
if (visited.has(modulePath)) {
console.log(`${indent} (Already Visited)`);
return;
}
visited.add(modulePath);
const dependencies = moduleDependencies[modulePath] || [];
dependencies.forEach((dep) => {
printDependencyTree(dep, level + 1, visited);
});
}
/**
* Parse command-line arguments to determine which checks to run
* @returns {Object} - Object containing flags for each check
*/
function parseArguments() {
const args = process.argv.slice(2);
const flags = {
checkCircular: false,
checkUnusedVars: false,
help: false,
};
args.forEach(arg => {
switch(arg) {
case '--check-circular':
flags.checkCircular = true;
break;
case '--check-unused-vars':
flags.checkUnusedVars = true;
break;
case '--help':
flags.help = true;
break;
default:
break;
}
});
return flags;
}
/**
* Display help information
*/
function displayHelp() {
console.log(`
Custom Sanitize Scripts for BCAN Project
Usage:
node canIMerge.js [options] [dir1] [dir2] ... [dirN]
Options:
--check-circular Perform circular dependency checks.
--check-unused-vars Perform unused variables checks.
--help Display this help information.
If no options are specified, all checks are performed.
`);
}
/**
* Main function to run specified checks
* @param {Array} directories - Directories to analyze
* @param {Object} flags - Flags indicating which checks to run
*/
function runChecks(directories = DEFAULT_DIRECTORIES, flags) {
console.log('Starting Profiler...\n');
directories.forEach((dir) => {
addSourceFiles(dir);
});
console.log('Analyzing the following directories:');
directories.forEach((dir) => {
console.log(`- ${path.resolve(dir)}`);
});
console.log('\nTotal TypeScript files found:', project.getSourceFiles().length);
if (flags.checkCircular || (!flags.checkCircular && !flags.checkUnusedVars)) {
buildDependencyGraph();
const cycles = detectCircularDependencies();
if (cycles.length > 0) {
console.error('\n🔴 Circular Dependencies Detected:');
cycles.forEach((cycle, index) => {
const cycleModules = cycle.map((mod) => path.basename(mod));
console.error(` ${index + 1}. ${cycleModules.join(' -> ')}`);
});
} else {
console.log('\n✅ No Circular Dependencies Detected.');
}
if (cycles.length > 0) {
console.error('\nBuild Failed: Please resolve the above circular dependencies before proceeding.');
process.exit(1);
}
}
if (flags.checkUnusedVars || (!flags.checkCircular && !flags.checkUnusedVars)) {
const unusedVars = identifyUnusedVariables();
if (unusedVars.length > 0) {
console.warn('\n⚠️ Unused Variables Found:');
unusedVars.forEach((item, index) => {
console.warn(` ${index + 1}. ${path.basename(item.module)}: ${item.variable}`);
});
} else {
console.log('\n✅ No Unused Variables Detected.');
}
if (flags.checkUnusedVars && unusedVars.length > 0) {
console.error('\nBuild Failed: Please resolve the above unused variables before proceeding.');
process.exit(1);
}
}
visualizeDependencies();
console.log('All requested checks passed successfully.');
process.exit(0);
}
module.exports = {
runChecks,
};
if (require.main === module) {
const flags = parseArguments();
if (flags.help) {
displayHelp();
process.exit(0);
}
const directories = process.argv.slice(2).filter(arg => !arg.startsWith('--'));
runChecks(directories.length > 0 ? directories : undefined, flags);
}