fix-owner.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict'
  2. const BB = require('bluebird')
  3. const chownr = BB.promisify(require('chownr'))
  4. const mkdirp = BB.promisify(require('mkdirp'))
  5. const inflight = require('promise-inflight')
  6. module.exports.chownr = fixOwner
  7. function fixOwner (filepath, uid, gid) {
  8. if (!process.getuid) {
  9. // This platform doesn't need ownership fixing
  10. return BB.resolve()
  11. }
  12. if (typeof uid !== 'number' && typeof gid !== 'number') {
  13. // There's no permissions override. Nothing to do here.
  14. return BB.resolve()
  15. }
  16. if ((typeof uid === 'number' && process.getuid() === uid) &&
  17. (typeof gid === 'number' && process.getgid() === gid)) {
  18. // No need to override if it's already what we used.
  19. return BB.resolve()
  20. }
  21. return inflight(
  22. 'fixOwner: fixing ownership on ' + filepath,
  23. () => chownr(
  24. filepath,
  25. typeof uid === 'number' ? uid : process.getuid(),
  26. typeof gid === 'number' ? gid : process.getgid()
  27. ).catch({code: 'ENOENT'}, () => null)
  28. )
  29. }
  30. module.exports.chownr.sync = fixOwnerSync
  31. function fixOwnerSync (filepath, uid, gid) {
  32. if (!process.getuid) {
  33. // This platform doesn't need ownership fixing
  34. return
  35. }
  36. if (typeof uid !== 'number' && typeof gid !== 'number') {
  37. // There's no permissions override. Nothing to do here.
  38. return
  39. }
  40. if ((typeof uid === 'number' && process.getuid() === uid) &&
  41. (typeof gid === 'number' && process.getgid() === gid)) {
  42. // No need to override if it's already what we used.
  43. return
  44. }
  45. try {
  46. chownr.sync(
  47. filepath,
  48. typeof uid === 'number' ? uid : process.getuid(),
  49. typeof gid === 'number' ? gid : process.getgid()
  50. )
  51. } catch (err) {
  52. if (err.code === 'ENOENT') {
  53. return null
  54. }
  55. }
  56. }
  57. module.exports.mkdirfix = mkdirfix
  58. function mkdirfix (p, uid, gid, cb) {
  59. return mkdirp(p).then(made => {
  60. if (made) {
  61. return fixOwner(made, uid, gid).then(() => made)
  62. }
  63. }).catch({code: 'EEXIST'}, () => {
  64. // There's a race in mkdirp!
  65. return fixOwner(p, uid, gid).then(() => null)
  66. })
  67. }
  68. module.exports.mkdirfix.sync = mkdirfixSync
  69. function mkdirfixSync (p, uid, gid) {
  70. try {
  71. const made = mkdirp.sync(p)
  72. if (made) {
  73. fixOwnerSync(made, uid, gid)
  74. return made
  75. }
  76. } catch (err) {
  77. if (err.code === 'EEXIST') {
  78. fixOwnerSync(p, uid, gid)
  79. return null
  80. } else {
  81. throw err
  82. }
  83. }
  84. }