summaryrefslogtreecommitdiff
path: root/deps/npm/lib/install/check-permissions.js
blob: 7806fcff993e19046ef0db05e32b71eeb73d94e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict'
var path = require('path')
var log = require('npmlog')
var validate = require('aproba')
var uniq = require('lodash.uniq')
var asyncMap = require('slide').asyncMap
var npm = require('../npm.js')
var exists = require('./exists.js')
var writable = require('./writable.js')

module.exports = function (actions, next) {
  validate('AF', arguments)
  var errors = []
  asyncMap(actions, function (action, done) {
    var cmd = action[0]
    var pkg = action[1]
    switch (cmd) {
      case 'add':
        hasAnyWriteAccess(path.resolve(pkg.path, '..'), errors, done)
        break
      case 'update':
      case 'remove':
        hasWriteAccess(pkg.path, errors, andHasWriteAccess(path.resolve(pkg.path, '..'), errors, done))
        break
      case 'move':
        hasAnyWriteAccess(pkg.path, errors, andHasWriteAccess(path.resolve(pkg.fromPath, '..'), errors, done))
        break
      default:
        done()
    }
  }, function () {
    if (!errors.length) return next()
    uniq(errors.map(function (er) { return 'Missing write access to ' + er.path })).forEach(function (er) {
      log.warn('checkPermissions', er)
    })
    npm.config.get('force') ? next() : next(errors[0])
  })
}

function andHasWriteAccess (dir, errors, done) {
  validate('SAF', arguments)
  return function () {
    hasWriteAccess(dir, errors, done)
  }
}

function hasAnyWriteAccess (dir, errors, done) {
  validate('SAF', arguments)
  findNearestDir()
  function findNearestDir () {
    var nextDir = path.resolve(dir, '..')
    exists(dir, function (dirDoesntExist) {
      if (!dirDoesntExist || nextDir === dir) {
        return hasWriteAccess(dir, errors, done)
      } else {
        dir = nextDir
        findNearestDir()
      }
    })
  }
}

function hasWriteAccess (dir, errors, done) {
  validate('SAF', arguments)
  writable(dir, function (er) {
    if (er) errors.push(er)
    done()
  })
}