-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (63 loc) · 2.31 KB
/
index.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
const fs = require('fs');
const path = require('path');
const yargs = require('yargs');
const argv = yargs
.command('analyze', '分析依赖', {
depth: {
alias: 'd',
describe: '递归深度',
type: 'number',
default: Infinity,
},
json: {
describe: 'JSON输出路径',
type: 'string',
},
})
.help().argv;
const command = argv._[0];
if (command === 'analyze') {
const depth = argv.depth;
const jsonFilePath = argv.json;
const packageJsonPath = path.join(process.cwd(), 'package.json');
try {
const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf8');
const packageJson = JSON.parse(packageJsonContent);
const dependencies = packageJson.dependencies || {};
const dependencyGraph = {};
function analyzeDependencies(dependencies, currentDepth, maxDepth, parentDependency = null) {
if (currentDepth <= maxDepth) {
for (const dependencyName in dependencies) {
const dependencyVersion = dependencies[dependencyName];
if (!dependencyGraph[parentDependency]) {
dependencyGraph[parentDependency] = [];
}
dependencyGraph[parentDependency].push({ name: dependencyName, version: dependencyVersion });
const dependentPackageJsonPath = path.resolve(
__dirname,
'node_modules',
dependencyName,
'package.json'
);
try {
const dependentPackageJsonContent = fs.readFileSync(dependentPackageJsonPath, 'utf8');
const dependentPackageJson = JSON.parse(dependentPackageJsonContent);
const dependentDependencies = dependentPackageJson.dependencies || {};
analyzeDependencies(dependentDependencies, currentDepth + 1, maxDepth, dependencyName);
} catch (error) {
console.error(`Error reading ${dependencyName}'s package.json:`, error.message);
}
}
}
}
analyzeDependencies(dependencies, 0, depth);
if (jsonFilePath) {
fs.writeFileSync(jsonFilePath, JSON.stringify(dependencyGraph, null, 2));
console.log(`Dependency graph saved to ${jsonFilePath}`);
} else {
console.log(JSON.stringify(dependencyGraph, null, 2));
}
} catch (error) {
console.error('Error reading package.json:', error.message);
}
}