Created
March 31, 2021 01:21
-
-
Save revanth0212/7978da74a26a98622d6ca28790c2a7bf to your computer and use it in GitHub Desktop.
Get a list of all the packages that have pre and post install scripts to access the extent of damage we can cause by using --ignore-scripts flag while running npm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lets check which packages have pre and post install scripts | |
const fs = require('fs'); | |
const path = require('path'); | |
const verifyNodeModulesExists = folderPath => { | |
return fs.existsSync(folderPath); | |
}; | |
const getPackageJsonPath = (folderPath, packageName) => { | |
return path.join(folderPath, packageName, './package.json'); | |
}; | |
const isScopeFolder = packageName => { | |
return packageName.startsWith('@'); | |
}; | |
const isValidPackage = (folderPath, packageName) => { | |
const packageJsonPath = getPackageJsonPath(folderPath, packageName); | |
return fs.existsSync(packageJsonPath); | |
}; | |
const getPackageScripts = packageJsonPath => { | |
const packageJson = require(path.resolve(packageJsonPath)); | |
return packageJson.scripts; | |
}; | |
const hasPreAndPostInstallScripts = scripts => { | |
return scripts.preinstall || scripts.postinstall; | |
}; | |
const filterPackagesWithInstallScripts = (packages, folderPath) => { | |
const effectedPackages = []; | |
packages.forEach(packageName => { | |
if (isScopeFolder(packageName)) { | |
const packages = fs.readdirSync(path.join(folderPath, packageName)); | |
effectedPackages.push( | |
...filterPackagesWithInstallScripts( | |
packages, | |
path.join(folderPath, packageName) | |
) | |
); | |
} else if (isValidPackage(folderPath, packageName)) { | |
const packageJsonPath = getPackageJsonPath(folderPath, packageName); | |
const scripts = getPackageScripts(packageJsonPath); | |
if (scripts && hasPreAndPostInstallScripts(scripts)) { | |
effectedPackages.push(packageName); | |
} | |
} | |
}); | |
return effectedPackages; | |
}; | |
const getPackagesWithInstallScripts = (projectPath = './') => { | |
const nodeModulesPath = path.resolve(projectPath, './node_modules'); | |
if (verifyNodeModulesExists(nodeModulesPath)) { | |
const packages = fs.readdirSync(nodeModulesPath); | |
return filterPackagesWithInstallScripts(packages, nodeModulesPath); | |
} | |
}; | |
console.log(getPackagesWithInstallScripts()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment