check-permissions.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict'
  2. var path = require('path')
  3. var log = require('npmlog')
  4. var validate = require('aproba')
  5. var uniq = require('lodash.uniq')
  6. var asyncMap = require('slide').asyncMap
  7. var npm = require('../npm.js')
  8. var exists = require('./exists.js')
  9. var writable = require('./writable.js')
  10. module.exports = function (actions, next) {
  11. validate('AF', arguments)
  12. var errors = []
  13. asyncMap(actions, function (action, done) {
  14. var cmd = action[0]
  15. var pkg = action[1]
  16. switch (cmd) {
  17. case 'add':
  18. hasAnyWriteAccess(path.resolve(pkg.path, '..'), errors, done)
  19. break
  20. case 'update':
  21. case 'remove':
  22. hasWriteAccess(pkg.path, errors, andHasWriteAccess(path.resolve(pkg.path, '..'), errors, done))
  23. break
  24. case 'move':
  25. hasAnyWriteAccess(pkg.path, errors, andHasWriteAccess(path.resolve(pkg.fromPath, '..'), errors, done))
  26. break
  27. default:
  28. done()
  29. }
  30. }, function () {
  31. if (!errors.length) return next()
  32. uniq(errors.map(function (er) { return 'Missing write access to ' + er.path })).forEach(function (er) {
  33. log.warn('checkPermissions', er)
  34. })
  35. npm.config.get('force') ? next() : next(errors[0])
  36. })
  37. }
  38. function andHasWriteAccess (dir, errors, done) {
  39. validate('SAF', arguments)
  40. return function () {
  41. hasWriteAccess(dir, errors, done)
  42. }
  43. }
  44. function hasAnyWriteAccess (dir, errors, done) {
  45. validate('SAF', arguments)
  46. findNearestDir()
  47. function findNearestDir () {
  48. var nextDir = path.resolve(dir, '..')
  49. exists(dir, function (dirDoesntExist) {
  50. if (!dirDoesntExist || nextDir === dir) {
  51. return hasWriteAccess(dir, errors, done)
  52. } else {
  53. dir = nextDir
  54. findNearestDir()
  55. }
  56. })
  57. }
  58. }
  59. function hasWriteAccess (dir, errors, done) {
  60. validate('SAF', arguments)
  61. writable(dir, function (er) {
  62. if (er) errors.push(er)
  63. done()
  64. })
  65. }