|
| 1 | +const { spawn } = require('child_process') |
| 2 | +const inferOwner = require('infer-owner') |
| 3 | + |
| 4 | +const isPipe = (stdio = 'pipe', fd) => |
| 5 | + stdio === 'pipe' || stdio === null ? true |
| 6 | + : Array.isArray(stdio) ? isPipe(stdio[fd], fd) |
| 7 | + : false |
| 8 | + |
| 9 | +// 'extra' object is for decorating the error a bit more |
| 10 | +const promiseSpawn = (cmd, args, opts = {}, extra = {}) => { |
| 11 | + const cwd = opts.cwd || process.cwd() |
| 12 | + const isRoot = process.getuid && process.getuid() === 0 |
| 13 | + const { uid, gid } = isRoot ? inferOwner.sync(cwd) : {} |
| 14 | + return promiseSpawnUid(cmd, args, { |
| 15 | + ...opts, |
| 16 | + cwd, |
| 17 | + uid, |
| 18 | + gid, |
| 19 | + }, extra) |
| 20 | +} |
| 21 | + |
| 22 | +const stdioResult = (stdout, stderr, { stdioString, stdio }) => |
| 23 | + stdioString ? { |
| 24 | + stdout: isPipe(stdio, 1) ? Buffer.concat(stdout).toString() : null, |
| 25 | + stderr: isPipe(stdio, 2) ? Buffer.concat(stderr).toString() : null, |
| 26 | + } |
| 27 | + : { |
| 28 | + stdout: isPipe(stdio, 1) ? Buffer.concat(stdout) : null, |
| 29 | + stderr: isPipe(stdio, 2) ? Buffer.concat(stderr) : null, |
| 30 | + } |
| 31 | + |
| 32 | +const promiseSpawnUid = (cmd, args, opts, extra) => { |
| 33 | + let proc |
| 34 | + const p = new Promise((res, rej) => { |
| 35 | + proc = spawn(cmd, args, opts) |
| 36 | + const stdout = [] |
| 37 | + const stderr = [] |
| 38 | + const reject = er => rej(Object.assign(er, { |
| 39 | + cmd, |
| 40 | + args, |
| 41 | + ...stdioResult(stdout, stderr, opts), |
| 42 | + ...extra, |
| 43 | + })) |
| 44 | + proc.on('error', reject) |
| 45 | + if (proc.stdout) { |
| 46 | + proc.stdout.on('data', c => stdout.push(c)).on('error', reject) |
| 47 | + proc.stdout.on('error', er => reject(er)) |
| 48 | + } |
| 49 | + if (proc.stderr) { |
| 50 | + proc.stderr.on('data', c => stderr.push(c)).on('error', reject) |
| 51 | + proc.stderr.on('error', er => reject(er)) |
| 52 | + } |
| 53 | + proc.on('close', (code, signal) => { |
| 54 | + const result = { |
| 55 | + cmd, |
| 56 | + args, |
| 57 | + code, |
| 58 | + signal, |
| 59 | + ...stdioResult(stdout, stderr, opts), |
| 60 | + ...extra, |
| 61 | + } |
| 62 | + if (code || signal) { |
| 63 | + rej(Object.assign(new Error('command failed'), result)) |
| 64 | + } else { |
| 65 | + res(result) |
| 66 | + } |
| 67 | + }) |
| 68 | + }) |
| 69 | + |
| 70 | + p.stdin = proc.stdin |
| 71 | + p.process = proc |
| 72 | + return p |
| 73 | +} |
| 74 | + |
| 75 | +module.exports = promiseSpawn |
0 commit comments