Skip to content

Instantly share code, notes, and snippets.

@kossnocorp
Created May 24, 2016 12:52
Show Gist options
  • Save kossnocorp/301d94d57c6b16a7b47b39e96d0fe0b5 to your computer and use it in GitHub Desktop.
Save kossnocorp/301d94d57c6b16a7b47b39e96d0fe0b5 to your computer and use it in GitHub Desktop.
// When shrinkwrap is used npm install won't update git dependencies.
// The hack removes outdated dependencies.
//
// See https://github.com/npm/npm/issues/12718 for more details about the bug.
const path = require('path')
const fs = require('fs')
const {spawn} = require('child_process')
let shrinkwrapJSON
try {
shrinkwrapJSON = require(path.join(process.cwd(), 'npm-shrinkwrap.json'))
} catch (e) {
ensureModuleNotFound(e)
console.warn('npm-shrinkwrap.json is not found')
process.exit(0)
}
const deps = shrinkwrapJSON.dependencies
Object.keys(deps).forEach((depName) => {
const dep = deps[depName]
const depDir = path.join(process.cwd(), 'node_modules', depName)
let packageJSON
try {
packageJSON = require(path.join(depDir, 'package.json'))
} catch(e) {
ensureModuleNotFound(e)
return
}
if (packageJSON._from !== dep.from) {
console.log(`Purging outdated package "${depName}"`)
remove(depDir)
}
})
function ensureModuleNotFound(e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e
}
}
function remove(dir) {
if (!fs.existsSync(dir)) return
fs.readdirSync(dir).forEach((file, index) => {
const curPath = path.join(dir, file)
if (fs.lstatSync(curPath).isDirectory()) {
remove(curPath)
} else {
fs.unlinkSync(curPath)
}
})
fs.rmdirSync(dir)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment