forked from tnobody/lerna-audit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
executable file
·78 lines (64 loc) · 2.45 KB
/
main.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
#!/usr/bin/env node
const {exec} = require('child_process');
const {promises} = require('fs');
const {join} = require('path');
async function cmd(command, cwd = process.cwd()) {
return new Promise((res, rej) => {
exec(command, {cwd}, (err, stdout, stderr) => {
if (err) {
rej(stderr || stdout);
} else {
res(stdout);
}
});
})
}
async function getPackages() {
const result = await cmd('lerna ls --all --json --loglevel=silent');
return JSON.parse(result);
}
function getPackageFilePaths(path) {
return {
backupPath: join(path, 'original-package.json'),
originalPath: join(path, 'package.json'),
}
}
(async () => {
const packages = await getPackages();
const packageNames = packages.map(p => p.name);
for (let lernaPackage of packages) {
const packagePaths = getPackageFilePaths(lernaPackage.location);
console.log(`Running ${lernaPackage.name}`)
await promises.rename(packagePaths.originalPath, packagePaths.backupPath);
try {
const packageJson = require(packagePaths.backupPath);
function filterDeps (deps) {
return Object.entries(deps || {}).filter(([name]) => {
return !packageNames.some(n => n === name)
}).reduce((deps, [name, version]) => ({...deps, [name]: version}), {})
}
const newPackageJson = ({
...packageJson,
dependencies: filterDeps(packageJson.dependencies),
devDependencies: filterDeps(packageJson.devDependencies)
});
await promises.writeFile(packagePaths.originalPath, JSON.stringify(newPackageJson, null, 2))
try {
console.log(`Run audit in ${lernaPackage.location}`)
const audit = await cmd('npm audit', lernaPackage.location);
console.log('Audit result');
console.log(audit);
} catch (e) {
console.log('Audit errors');
console.error(e)
console.log('We will fix this for you');
const auditFix = await cmd('npm audit fix', lernaPackage.location);
console.log(auditFix);
}
} catch(e) {
console.error(e);
} finally {
await promises.rename(packagePaths.backupPath, packagePaths.originalPath);
}
}
})();