Skip to content

Instantly share code, notes, and snippets.

@naholyr
Created October 16, 2017 00:57
Show Gist options
  • Save naholyr/1ffaf41a7c384ff801653b38695aa68e to your computer and use it in GitHub Desktop.
Save naholyr/1ffaf41a7c384ff801653b38695aa68e to your computer and use it in GitHub Desktop.

scan-dependencies

Usage : node scan-dependencies.js <path>

  • will find every root project inside <path> (a project is a folder with package.json file, himself not inside a node_modules directory)
  • will npm install then npm outdated from project
  • will list all *.js files and check for missing require(…) for every dependency
#!/usr/bin/env node
const path = require('path')
const { readdirSync, statSync, accessSync, readFileSync } = require('fs')
const { execSync } = require('child_process')
const baseDir = path.resolve(process.argv[2] || '.')
const exists = f => { try { return accessSync(f), true } catch (e) { return false } }
const isDir = d => exists(d) && statSync(d).isDirectory()
const isFile = f => exists(f) && statSync(f).isFile()
const readDirAbs = d => readdirSync(d).map(f => path.join(d, f))
const findFiles = d => readDirAbs(d).reduce((fs, f) => fs.concat(isFile(f) ? [f] : findFiles(f)), [])
const testFiles = (files, test) => files.filter(f => test(readFileSync(f, 'utf8')))
const isNotInSubModule = f => f.indexOf(path.sep + 'node_modules' + path.sep) === -1
const findScripts = d => findFiles(d).filter(isNotInSubModule).filter(f => f.match(/\.js$/))
const findRoots = d =>
readDirAbs(d)
.filter(isNotInSubModule)
.filter(isDir)
.reduce((ds, d) => ds
.concat(exists(path.join(d, 'package.json')) ? [d] : [])
.concat(findRoots(d))
, [])
const checkDeps = (files, deps, dev = false) => {
if (deps.length === 0) {
return
}
console.log(`\tChecking ${dev?'dev ':''} dependencies…`)
deps.forEach(m => {
const req = new RegExp(`require\\(['"]${m}['"]\\)`)
const reqFiles = testFiles(files, req.test.bind(req))
if (reqFiles.length === 0) {
console.log(`\t\t${m}: UNUSED?`)
} else {
console.log(`\t\t${m}: Used in ${reqFiles.length} file(s)`)
}
})
}
findRoots(baseDir)
.forEach(d => {
console.log(`Testing ${d}…`)
const pkg = require(path.join(d, 'package.json'))
execSync('npm install --registry="http://npm.medissimo.fr:4873" --silent', { cwd: d, stdio: 'inherit' })
try {
execSync('npm outdated --registry="http://npm.medissimo.fr:4873"', { cwd: d, stdio: 'inherit' })
console.log('\tDependencies look up to date')
} catch (e) {
console.log('\tYou may have out of date dependencies, check your semver')
}
const files = findScripts(d)
checkDeps(files, Object.keys(pkg.dependencies || {}), false)
//checkDeps(files, Object.keys(pkg.devDependencies || {}), true)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment