locker.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var crypto = require('crypto')
  2. var resolve = require('path').resolve
  3. var lockfile = require('lockfile')
  4. var log = require('npmlog')
  5. var npm = require('../npm.js')
  6. var correctMkdir = require('../utils/correct-mkdir.js')
  7. var installLocks = {}
  8. function lockFileName (base, name) {
  9. var c = name.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '')
  10. var p = resolve(base, name)
  11. var h = crypto.createHash('sha1').update(p).digest('hex')
  12. var l = resolve(npm.cache, '_locks')
  13. return resolve(l, c.substr(0, 24) + '-' + h.substr(0, 16) + '.lock')
  14. }
  15. function lock (base, name, cb) {
  16. var lockDir = resolve(npm.cache, '_locks')
  17. correctMkdir(lockDir, function (er) {
  18. if (er) return cb(er)
  19. var opts = {
  20. stale: npm.config.get('cache-lock-stale'),
  21. retries: npm.config.get('cache-lock-retries'),
  22. wait: npm.config.get('cache-lock-wait')
  23. }
  24. var lf = lockFileName(base, name)
  25. lockfile.lock(lf, opts, function (er) {
  26. if (er) log.warn('locking', lf, 'failed', er)
  27. if (!er) {
  28. log.verbose('lock', 'using', lf, 'for', resolve(base, name))
  29. installLocks[lf] = true
  30. }
  31. cb(er)
  32. })
  33. })
  34. }
  35. function unlock (base, name, cb) {
  36. var lf = lockFileName(base, name)
  37. var locked = installLocks[lf]
  38. if (locked === false) {
  39. return process.nextTick(cb)
  40. } else if (locked === true) {
  41. lockfile.unlock(lf, function (er) {
  42. if (er) {
  43. log.warn('unlocking', lf, 'failed', er)
  44. } else {
  45. installLocks[lf] = false
  46. log.verbose('unlock', 'done using', lf, 'for', resolve(base, name))
  47. }
  48. cb(er)
  49. })
  50. } else {
  51. var notLocked = new Error(
  52. 'Attempt to unlock ' + resolve(base, name) + ", which hasn't been locked"
  53. )
  54. notLocked.code = 'ENOTLOCKED'
  55. throw notLocked
  56. }
  57. }
  58. module.exports = {
  59. lock: lock,
  60. unlock: unlock
  61. }