|
| 1 | +const npm = require('../npm.js') |
| 2 | +const path = require('path') |
| 3 | +const chownr = require('chownr') |
| 4 | +const writeFileAtomic = require('write-file-atomic') |
| 5 | +const mkdirp = require('mkdirp') |
| 6 | +const fs = require('graceful-fs') |
| 7 | + |
| 8 | +let cache = null |
| 9 | +let cacheUid = null |
| 10 | +let cacheGid = null |
| 11 | +let needChown = typeof process.getuid === 'function' |
| 12 | + |
| 13 | +const getCacheOwner = () => { |
| 14 | + let st |
| 15 | + try { |
| 16 | + st = fs.lstatSync(cache) |
| 17 | + } catch (er) { |
| 18 | + if (er.code !== 'ENOENT') { |
| 19 | + throw er |
| 20 | + } |
| 21 | + st = fs.lstatSync(path.dirname(cache)) |
| 22 | + } |
| 23 | + |
| 24 | + cacheUid = st.uid |
| 25 | + cacheGid = st.gid |
| 26 | + |
| 27 | + needChown = st.uid !== process.getuid() || |
| 28 | + st.gid !== process.getgid() |
| 29 | +} |
| 30 | + |
| 31 | +const writeOrAppend = (method, file, data) => { |
| 32 | + if (!cache) { |
| 33 | + cache = npm.config.get('cache') |
| 34 | + } |
| 35 | + |
| 36 | + // redundant if already absolute, but prevents non-absolute files |
| 37 | + // from being written as if they're part of the cache. |
| 38 | + file = path.resolve(cache, file) |
| 39 | + |
| 40 | + if (cacheUid === null && needChown) { |
| 41 | + getCacheOwner() |
| 42 | + } |
| 43 | + |
| 44 | + const dir = path.dirname(file) |
| 45 | + const firstMade = mkdirp.sync(dir) |
| 46 | + |
| 47 | + if (!needChown) { |
| 48 | + return method(file, data) |
| 49 | + } |
| 50 | + |
| 51 | + let methodThrew = true |
| 52 | + try { |
| 53 | + method(file, data) |
| 54 | + methodThrew = false |
| 55 | + } finally { |
| 56 | + // always try to leave it in the right ownership state, even on failure |
| 57 | + // let the method error fail it instead of the chownr error, though |
| 58 | + if (!methodThrew) { |
| 59 | + chownr.sync(firstMade || file, cacheUid, cacheGid) |
| 60 | + } else { |
| 61 | + try { |
| 62 | + chownr.sync(firstMade || file, cacheUid, cacheGid) |
| 63 | + } catch (_) {} |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +exports.append = (file, data) => writeOrAppend(fs.appendFileSync, file, data) |
| 69 | +exports.write = (file, data) => writeOrAppend(writeFileAtomic.sync, file, data) |
0 commit comments