-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmodules.js
More file actions
134 lines (110 loc) · 3.66 KB
/
modules.js
File metadata and controls
134 lines (110 loc) · 3.66 KB
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
const fs = require('fs');
const { spawnSync } = require('child_process');
const path = require('path');
const { sanitizePath } = require('@contentstack/cli-utilities');
const os = require('os');
const { builtinModules } = require('module');
const internalModules = new Set(builtinModules);
function checkWritePermissionToDirectory(directory) {
try {
fs.accessSync(directory, fs.constants.W_OK);
return true;
} catch (err) {
console.log(`Permission Denied! You do not have the necessary write access for this directory.`);
return false;
}
}
function doesPackageJsonExist(directory) {
return fs.existsSync(path.join(sanitizePath(directory), 'package.json'));
}
function scanDirectory(directory) {
return fs.readdirSync(directory);
}
function scanFileForDependencies(directory, files) {
const dependencies = new Set();
files.forEach((file) => {
const filePath = path.join(sanitizePath(directory), sanitizePath(file));
if (path.extname(filePath) === '.js') {
const fileContent = fs.readFileSync(filePath, 'utf-8');
findModulesSync(fileContent).forEach((dep) => dependencies.add(dep));
}
});
return [...dependencies];
}
function createPackageJson(directory) {
const templateString = `{
"name": "MigrationPackage",
"version": "1.0.0",
"main": "",
"scripts": {},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}`;
fs.writeFileSync(path.join(sanitizePath(directory), 'package.json'), templateString);
}
function installDependencies(dependencies, directory) {
const installedDependencies = new Set();
dependencies.forEach((dep) => {
if (!internalModules.has(dep)) {
const pkg = dep.startsWith('@') ? dep : dep.split('/')[0];
if (!installedDependencies.has(pkg)) {
executeShellCommand(pkg, directory);
installedDependencies.add(pkg);
}
}
});
}
function executeShellCommand(pkg, directory = '') {
try {
const result = spawnSync(`npm`, ['i', pkg], { stdio: 'inherit', cwd: directory, shell: false });
if (result?.error) throw result.error;
console.log(`Command executed successfully`);
} catch (error) {
console.error(`Command execution failed. Error: ${error?.message}`);
}
}
async function installModules(filePath, multiple) {
const files = multiple ? [] : [path.basename(filePath)];
const dirPath = multiple ? filePath : path.dirname(filePath);
if (checkWritePermissionToDirectory(dirPath)) {
if (multiple) {
files.push(...scanDirectory(dirPath));
}
if (files.length === 0) {
console.log(`Error: Could not locate files needed to create package.json. Exiting the process.`);
return true;
}
const dependencies = scanFileForDependencies(dirPath, files);
if (!doesPackageJsonExist(dirPath)) {
console.log(`package.json not found. Creating a new package.json...`);
createPackageJson(dirPath);
}
installDependencies(dependencies, dirPath);
} else {
console.log(`You don't have write permission to the directory`);
return false;
}
console.log(`All dependencies installed successfully.`);
return true;
}
function findModulesSync(data) {
try {
const requireRegex = /require\(['"`](.*?)['"`]\)/g;
const importRegex = /import\s+(?:(?:[\w*\s{},]*)\s+from\s+)?['"`](.*?)['"`]/g;
const modules = new Set();
let match;
while ((match = requireRegex.exec(data)) !== null) {
modules.add(match[1]);
}
while ((match = importRegex.exec(data)) !== null) {
modules.add(match[1]);
}
return [...modules];
} catch (error) {
console.error(`Error reading file: ${error.message}`);
return [];
}
}
module.exports = installModules;