prune.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict'
  2. const common = require('./common')
  3. const galactus = require('galactus')
  4. const fs = require('fs-extra')
  5. const path = require('path')
  6. const ELECTRON_MODULES = [
  7. 'electron',
  8. 'electron-prebuilt',
  9. 'electron-prebuilt-compile'
  10. ]
  11. class Pruner {
  12. constructor (dir) {
  13. this.baseDir = common.normalizePath(dir)
  14. this.galactus = new galactus.DestroyerOfModules({
  15. rootDirectory: dir,
  16. shouldKeepModuleTest: (module, isDevDep) => this.shouldKeepModule(module, isDevDep)
  17. })
  18. this.walkedTree = false
  19. }
  20. setModules (moduleMap) {
  21. const modulePaths = Array.from(moduleMap.keys()).map(modulePath => `/${common.normalizePath(modulePath)}`)
  22. this.modules = new Set(modulePaths)
  23. this.walkedTree = true
  24. }
  25. pruneModule (name) {
  26. if (this.walkedTree) {
  27. return this.isProductionModule(name)
  28. } else {
  29. return this.galactus.collectKeptModules({ relativePaths: true })
  30. .then(moduleMap => this.setModules(moduleMap))
  31. .then(() => this.isProductionModule(name))
  32. }
  33. }
  34. shouldKeepModule (module, isDevDep) {
  35. if (isDevDep || module.depType === galactus.DepType.ROOT) {
  36. return false
  37. }
  38. // Node 6 has Array.prototype.includes
  39. if (ELECTRON_MODULES.indexOf(module.name) !== -1) {
  40. common.warning(`Found '${module.name}' but not as a devDependency, pruning anyway`)
  41. return false
  42. }
  43. return true
  44. }
  45. isProductionModule (name) {
  46. return this.modules.has(name)
  47. }
  48. }
  49. module.exports = {
  50. isModule: function isModule (pathToCheck) {
  51. return fs.pathExists(path.join(pathToCheck, 'package.json'))
  52. },
  53. Pruner: Pruner
  54. }