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