Add `.node()` method (#200)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Guillaume Martigny · committed by Sindre Sorhus · parent be1d70f · Browse files · 53 files·+1161 added−965 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
53 files+1161 added−965 removed
- tests:+1041 added−34 removed
- other:+120 added−931 removed
Provenance
- Commit
c2f5edf- Tree
962fe54- Author
Guillaume Martigny <guillaume.martigny@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
be1d70f
53 files changed+1161 added−965 removed
deleted:fixtures/command with space-3 removed
1-#!/usr/bin/env node2-'use strict';3-console.log(process.argv.slice(2).join('\n'));deleted:fixtures/delay-4 removed
1-#!/usr/bin/env node2-'use strict';3-4-setTimeout(() => {}, Number(process.argv[2]));deleted:fixtures/detach-8 removed
1-#!/usr/bin/env node2-'use strict';3-4-const execa = require('..');5-6-const subprocess = execa('node', ['./fixtures/forever'], {detached: true});7-console.log(subprocess.pid);8-process.exit();deleted:fixtures/echo-3 removed
1-#!/usr/bin/env node2-'use strict';3-console.log(process.argv.slice(2).join('\n'))deleted:fixtures/environment-4 removed
1-#!/usr/bin/env node2-'use strict';3-console.log(process.env.FOO);4-console.log(process.env.BAR);deleted:fixtures/exit-3 removed
1-#!/usr/bin/env node2-'use strict';3-process.exit(Number(process.argv[2]));deleted:fixtures/fail-4 removed
1-#!/usr/bin/env node2-'use strict';3-4-process.exit(2);deleted:fixtures/fast-exit-darwinbinary
A binary file, deleted.
deleted:fixtures/fast-exit-linuxbinary
A binary file, deleted.
deleted:fixtures/forever-4 removed
1-#!/usr/bin/env node2-'use strict';3-4-setTimeout(() => {}, 1e8);deleted:fixtures/hello.cmd-1 removed
1-ECHO Hello Worlddeleted:fixtures/max-buffer-6 removed
1-#!/usr/bin/env node2-'use strict';3-const output = process.argv[2];4-const bytes = Number(process.argv[3]);5-6-process[output].write('.'.repeat(bytes - 1) + '\n');deleted:fixtures/no-killable-12 removed
1-#!/usr/bin/env node2-'use strict';3-4-process.on('SIGTERM', () => {5- console.log('Received SIGTERM, but we ignore it');6-});7-8-process.send('');9-10-setInterval(() => {11- // Run forever12-}, 20000);deleted:fixtures/non-executable-2 removed
1-#!/usr/bin/env node2-'use strict';deleted:fixtures/noop-3 removed
1-#!/usr/bin/env node2-'use strict';3-console.log(process.argv[2]);deleted:fixtures/noop-132-9 removed
1-#!/usr/bin/env node2-'use strict';3-4-process.stdout.write('1');5-process.stderr.write('3');6-7-setTimeout(() => {8- process.stdout.write('2');9-}, 1000);deleted:fixtures/noop-err-3 removed
1-#!/usr/bin/env node2-'use strict';3-console.error(process.argv[2]);deleted:fixtures/noop-throw-4 removed
1-#!/usr/bin/env node2-'use strict';3-console.error(process.argv[2]);4-process.exit(2);deleted:fixtures/stdin-3 removed
1-#!/usr/bin/env node2-'use strict';3-process.stdin.pipe(process.stdout);deleted:fixtures/sub-process-8 removed
1-#!/usr/bin/env node2-'use strict';3-const execa = require('..');4-5-const cleanup = process.argv[2] === 'true';6-const detached = process.argv[3] === 'true';7-const subprocess = execa('node', ['./fixtures/forever'], {cleanup, detached});8-process.send(subprocess.pid);deleted:fixtures/sub-process-exit-7 removed
1-#!/usr/bin/env node2-'use strict';3-const execa = require('..');4-5-const cleanup = process.argv[2] === 'true';6-const detached = process.argv[3] === 'true';7-execa('node', ['./fixtures/noop'], {cleanup, detached});modified:lib/stdio.js+21 added-1 removed
1 unmodified line2 const alias = ['stdin', 'stdout', 'stderr'];3 4 const hasAlias = opts => alias.some(x => Boolean(opts[x]));5 6-module.exports = opts => {6+const stdio = opts => {7 if (!opts) {8 return;9 }10 27 unmodified lines38 }39 40 return result;41 };42+43+module.exports = stdio;44+45+module.exports.node = opts => {46+ const defaultOption = 'pipe';47+48+ let stdioOption = stdio(opts || {stdio: defaultOption});49+50+ if (typeof stdioOption === 'string') {51+ stdioOption = [...new Array(3)].fill(stdioOption);52+ } else if (Array.isArray(stdioOption)) {53+ stdioOption = stdioOption.map((channel = defaultOption) => channel);54+ }55+56+ if (!stdioOption.includes('ipc')) {57+ stdioOption.push('ipc');58+ }59+60+ return stdioOption;61+};added:test/fixtures/command with space+3 added
1+#!/usr/bin/env node2+'use strict';3+console.log(process.argv.slice(2).join('\n'));added:test/fixtures/delay+4 added
1+#!/usr/bin/env node2+'use strict';3+4+setTimeout(() => {}, Number(process.argv[2]));added:test/fixtures/detach+8 added
1+#!/usr/bin/env node2+'use strict';3+4+const execa = require('../..');5+6+const subprocess = execa('node', ['./test/fixtures/forever'], {detached: true});7+console.log(subprocess.pid);8+process.exit();added:test/fixtures/echo+3 added
1+#!/usr/bin/env node2+'use strict';3+console.log(process.argv.slice(2).join('\n'));added:test/fixtures/environment+4 added
1+#!/usr/bin/env node2+'use strict';3+console.log(process.env.FOO);4+console.log(process.env.BAR);added:test/fixtures/exit+3 added
1+#!/usr/bin/env node2+'use strict';3+process.exit(Number(process.argv[2]));added:test/fixtures/fail+4 added
1+#!/usr/bin/env node2+'use strict';3+4+process.exit(2);added:test/fixtures/fast-exit-darwinbinary
A binary file, added.
added:test/fixtures/fast-exit-linuxbinary
A binary file, added.
added:test/fixtures/forever+4 added
1+#!/usr/bin/env node2+'use strict';3+4+setTimeout(() => {}, 1e8);added:test/fixtures/hello.cmd+1 added
1+ECHO Hello Worldadded:test/fixtures/hello.sh+1 added
1+echo Hello Worldadded:test/fixtures/max-buffer+6 added
1+#!/usr/bin/env node2+'use strict';3+const output = process.argv[2];4+const bytes = Number(process.argv[3]);5+6+process[output].write('.'.repeat(bytes - 1) + '\n');added:test/fixtures/no-killable+12 added
1+#!/usr/bin/env node2+'use strict';3+4+process.on('SIGTERM', () => {5+ console.log('Received SIGTERM, but we ignore it');6+});7+8+process.send('');9+10+setInterval(() => {11+ // Run forever12+}, 20000);added:test/fixtures/non-executable+2 added
1+#!/usr/bin/env node2+'use strict';added:test/fixtures/noop+3 added
1+#!/usr/bin/env node2+'use strict';3+console.log(process.argv[2]);added:test/fixtures/noop-132+9 added
1+#!/usr/bin/env node2+'use strict';3+4+process.stdout.write('1');5+process.stderr.write('3');6+7+setTimeout(() => {8+ process.stdout.write('2');9+}, 1000);added:test/fixtures/noop-err+3 added
1+#!/usr/bin/env node2+'use strict';3+console.error(process.argv[2]);added:test/fixtures/noop-throw+4 added
1+#!/usr/bin/env node2+'use strict';3+console.error(process.argv[2]);4+process.exit(2);added:test/fixtures/send+9 added
1+#!/usr/bin/env node2+'use strict';3+process.on('message', message => {4+ if (message === 'ping') {5+ process.send('pong');6+ } else {7+ throw new Error('Receive wrong message');8+ }9+});added:test/fixtures/stdin+3 added
1+#!/usr/bin/env node2+'use strict';3+process.stdin.pipe(process.stdout);added:test/fixtures/sub-process+8 added
1+#!/usr/bin/env node2+'use strict';3+const execa = require('../..');4+5+const cleanup = process.argv[2] === 'true';6+const detached = process.argv[3] === 'true';7+const subprocess = execa('node', ['./test/fixtures/forever'], {cleanup, detached});8+process.send(subprocess.pid);added:test/fixtures/sub-process-exit+7 added
1+#!/usr/bin/env node2+'use strict';3+const execa = require('../..');4+5+const cleanup = process.argv[2] === 'true';6+const detached = process.argv[3] === 'true';7+execa('node', ['./test/fixtures/noop'], {cleanup, detached});added:test/node.js+46 added
1+import test from 'ava';2+import pEvent from 'p-event';3+import path from 'path';4+import execa from '..';5+6+process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;7+8+test('node()', async t => {9+ const {exitCode} = await execa.node('test/fixtures/noop');10+ t.is(exitCode, 0);11+});12+13+test('node pipe stdout', async t => {14+ const {stdout} = await execa.node('test/fixtures/noop', ['foo'], {15+ stdout: 'pipe'16+ });17+18+ t.is(stdout, 'foo');19+});20+21+test('node correctly use nodePath', async t => {22+ const {stdout} = await execa.node(process.platform === 'win32' ? 'hello.cmd' : 'hello.sh', {23+ stdout: 'pipe',24+ nodePath: process.platform === 'win32' ? 'cmd.exe' : 'bash',25+ nodeArguments: process.platform === 'win32' ? ['/c'] : []26+ });27+28+ t.is(stdout, 'Hello World');29+});30+31+test('node pass on nodeArguments', async t => {32+ const {stdout} = await execa.node('console.log("foo")', {33+ stdout: 'pipe',34+ nodeArguments: ['-e']35+ });36+37+ t.is(stdout, 'foo');38+});39+40+test('node\'s forked script has a communication channel', async t => {41+ const subprocess = execa.node('test/fixtures/send');42+ subprocess.send('ping');43+44+ const message = await pEvent(subprocess, 'message');45+ t.is(message, 'pong');46+});modified:test/stdio.js+57 added-34 removed
2 unmodified lines3 import stdio from '../lib/stdio';4 5 util.inspect.styles.name = 'magenta';6 7-function macro(t, input, expected) {8- if (expected instanceof Error) {9- t.throws(() => stdio(input), expected.message);10- return;11- }7+function createMacro(func) {8+ const macro = (t, input, expected) => {9+ if (expected instanceof Error) {10+ t.throws(() => {11+ stdio(input);12+ }, expected.message);13+ return;14+ }15 13- const result = stdio(input);16+ const result = func(input);17 15- if (typeof expected === 'object' && expected !== null) {16- t.deepEqual(result, expected);17- } else {18- t.is(result, expected);19- }18+ if (typeof expected === 'object' && expected !== null) {19+ t.deepEqual(result, expected);20+ } else {21+ t.is(result, expected);22+ }23+ };24+25+ macro.title = (providedTitle, input) => `${func.name} ${(providedTitle || util.inspect(input, {colors: true}))}`;26+27+ return macro;28 }29 22-macro.title = (providedTitle, input) => providedTitle || util.inspect(input, {colors: true});30+const stdioMacro = createMacro(stdio);31 24-test(macro, undefined, undefined);32+test(stdioMacro, undefined, undefined);33+test(stdioMacro, null, undefined);34 26-test(macro, {stdio: 'inherit'}, 'inherit');27-test(macro, {stdio: 'pipe'}, 'pipe');28-test(macro, {stdio: 'ignore'}, 'ignore');29-test(macro, {stdio: [0, 1, 2]}, [0, 1, 2]);35+test(stdioMacro, {stdio: 'inherit'}, 'inherit');36+test(stdioMacro, {stdio: 'pipe'}, 'pipe');37+test(stdioMacro, {stdio: 'ignore'}, 'ignore');38+test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);39 31-test(macro, {}, [undefined, undefined, undefined]);32-test(macro, {stdio: []}, [undefined, undefined, undefined]);33-test(macro, {stdin: 'pipe'}, ['pipe', undefined, undefined]);34-test(macro, {stdout: 'ignore'}, [undefined, 'ignore', undefined]);35-test(macro, {stderr: 'inherit'}, [undefined, undefined, 'inherit']);36-test(macro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);37-test(macro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', undefined]);38-test(macro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', undefined, 'inherit']);39-test(macro, {stdout: 'ignore', stderr: 'inherit'}, [undefined, 'ignore', 'inherit']);40-test(macro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);41-test(macro, {stdin: 0, stdout: 1}, [0, 1, undefined]);42-test(macro, {stdin: 0, stderr: 2}, [0, undefined, 2]);43-test(macro, {stdout: 1, stderr: 2}, [undefined, 1, 2]);40+test(stdioMacro, {}, [undefined, undefined, undefined]);41+test(stdioMacro, {stdio: []}, [undefined, undefined, undefined]);42+test(stdioMacro, {stdin: 'pipe'}, ['pipe', undefined, undefined]);43+test(stdioMacro, {stdout: 'ignore'}, [undefined, 'ignore', undefined]);44+test(stdioMacro, {stderr: 'inherit'}, [undefined, undefined, 'inherit']);45+test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);46+test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', undefined]);47+test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', undefined, 'inherit']);48+test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, [undefined, 'ignore', 'inherit']);49+test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);50+test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, undefined]);51+test(stdioMacro, {stdin: 0, stderr: 2}, [0, undefined, 2]);52+test(stdioMacro, {stdout: 1, stderr: 2}, [undefined, 1, 2]);53 45-test(macro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));54+test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));55 47-test(macro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));48-test(macro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));49-test(macro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));56+test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));57+test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));58+test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));59+60+const forkMacro = createMacro(stdio.node);61+62+test(forkMacro, undefined, ['pipe', 'pipe', 'pipe', 'ipc']);63+test(forkMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore', 'ipc']);64+test(forkMacro, {stdio: [0, 1, 2]}, [0, 1, 2, 'ipc']);65+test(forkMacro, {stdio: [0, 1, 2, 3]}, [0, 1, 2, 3, 'ipc']);66+test(forkMacro, {stdio: [0, 1, 2, 'ipc']}, [0, 1, 2, 'ipc']);67+68+test(forkMacro, {stdout: 'ignore'}, ['pipe', 'ignore', 'pipe', 'ipc']);69+test(forkMacro, {stdout: 'ignore', stderr: 'ignore'}, ['pipe', 'ignore', 'ignore', 'ipc']);70+71+test(forkMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));72+test(forkMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));added:test/test.js+837 added
1+import path from 'path';2+import fs from 'fs';3+import stream from 'stream';4+import childProcess from 'child_process';5+import test from 'ava';6+import getStream from 'get-stream';7+import isRunning from 'is-running';8+import tempfile from 'tempfile';9+import pEvent from 'p-event';10+import execa from '..';11+12+process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;13+process.env.FOO = 'foo';14+15+const TIMEOUT_REGEXP = /timed out after/;16+17+const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);18+19+test('execa()', async t => {20+ const {stdout} = await execa('noop', ['foo']);21+ t.is(stdout, 'foo');22+});23+24+if (process.platform === 'win32') {25+ test('execa() - cmd file', async t => {26+ const {stdout} = await execa('hello.cmd');27+ t.is(stdout, 'Hello World');28+ });29+30+ test('execa() - run cmd command', async t => {31+ const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);32+ t.is(stdout, 'Hello World');33+ });34+}35+36+test('buffer', async t => {37+ const {stdout} = await execa('noop', ['foo'], {encoding: null});38+ t.true(Buffer.isBuffer(stdout));39+ t.is(stdout.toString(), 'foo');40+});41+42+test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {43+ const {all} = await execa('noop-132');44+ t.is(all, '132');45+});46+47+test('stdout/stderr/all available on errors', async t => {48+ const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});49+ t.is(typeof stdout, 'string');50+ t.is(typeof stderr, 'string');51+ t.is(typeof all, 'string');52+});53+54+test('stdout/stderr/all are undefined if ignored', async t => {55+ const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore'});56+ t.is(stdout, undefined);57+ t.is(stderr, undefined);58+ t.is(all, undefined);59+});60+61+test('stdout/stderr/all are undefined if ignored in sync mode', t => {62+ const {stdout, stderr, all} = execa.sync('noop', {stdio: 'ignore'});63+ t.is(stdout, undefined);64+ t.is(stderr, undefined);65+ t.is(all, undefined);66+});67+68+const WRONG_COMMAND = process.platform === 'win32' ?69+ '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :70+ '';71+72+test('stdout/stderr/all on process errors', async t => {73+ const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command'));74+ t.is(stdout, '');75+ t.is(stderr, WRONG_COMMAND);76+ t.is(all, WRONG_COMMAND);77+});78+79+test('stdout/stderr/all on process errors, in sync mode', t => {80+ const {stdout, stderr, all} = t.throws(() => {81+ execa.sync('wrong command');82+ });83+ t.is(stdout, '');84+ t.is(stderr, WRONG_COMMAND);85+ t.is(all, undefined);86+});87+88+test('pass `stdout` to a file descriptor', async t => {89+ const file = tempfile('.txt');90+ await execa('test/fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});91+ t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');92+});93+94+test('pass `stderr` to a file descriptor', async t => {95+ const file = tempfile('.txt');96+ await execa('test/fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});97+ t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');98+});99+100+test('execa.sync()', t => {101+ const {stdout} = execa.sync('noop', ['foo']);102+ t.is(stdout, 'foo');103+});104+105+test('execa.sync() throws error if written to stderr', t => {106+ t.throws(() => {107+ execa.sync('foo');108+ }, process.platform === 'win32' ? /failed with exit code 1/ : /spawnSync foo ENOENT/);109+});110+111+test('skip throwing when using reject option', async t => {112+ const {exitCode} = await execa('fail', {reject: false});113+ t.is(exitCode, 2);114+});115+116+test('skip throwing when using reject option in sync mode', t => {117+ const {exitCode} = execa.sync('fail', {reject: false});118+ t.is(exitCode, 2);119+});120+121+test('kill("SIGKILL") should terminate cleanly', async t => {122+ const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});123+ await pEvent(subprocess, 'message');124+125+ subprocess.kill('SIGKILL');126+127+ const {signal} = await t.throwsAsync(subprocess);128+ t.is(signal, 'SIGKILL');129+});130+131+// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).132+// Therefore, this feature and those tests do not make sense on Windows.133+if (process.platform !== 'win32') {134+ test('`forceKillAfterTimeout: false` should not kill after a timeout', async t => {135+ const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});136+ await pEvent(subprocess, 'message');137+138+ subprocess.kill('SIGTERM', {forceKillAfterTimeout: false});139+140+ t.true(isRunning(subprocess.pid));141+ subprocess.kill('SIGKILL');142+ });143+144+ test('`forceKillAfterTimeout: number` should kill after a timeout', async t => {145+ const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});146+ await pEvent(subprocess, 'message');147+148+ subprocess.kill('SIGTERM', {forceKillAfterTimeout: 50});149+150+ const {signal} = await t.throwsAsync(subprocess);151+ t.is(signal, 'SIGKILL');152+ });153+154+ test('`forceKillAfterTimeout: true` should kill after a timeout', async t => {155+ const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});156+ await pEvent(subprocess, 'message');157+158+ subprocess.kill('SIGTERM', {forceKillAfterTimeout: true});159+160+ const {signal} = await t.throwsAsync(subprocess);161+ t.is(signal, 'SIGKILL');162+ });163+164+ test('kill() with no arguments should kill after a timeout', async t => {165+ const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});166+ await pEvent(subprocess, 'message');167+168+ subprocess.kill();169+170+ const {signal} = await t.throwsAsync(subprocess);171+ t.is(signal, 'SIGKILL');172+ });173+174+ test('`forceKillAfterTimeout` should not be a float', t => {175+ t.throws(() => {176+ execa('noop').kill('SIGTERM', {forceKillAfterTimeout: 0.5});177+ }, {instanceOf: TypeError, message: /non-negative integer/});178+ });179+180+ test('`forceKillAfterTimeout` should not be negative', t => {181+ t.throws(() => {182+ execa('noop').kill('SIGTERM', {forceKillAfterTimeout: -1});183+ }, {instanceOf: TypeError, message: /non-negative integer/});184+ });185+}186+187+test('stripFinalNewline: true', async t => {188+ const {stdout} = await execa('noop', ['foo']);189+ t.is(stdout, 'foo');190+});191+192+test('stripFinalNewline: false', async t => {193+ const {stdout} = await execa('noop', ['foo'], {stripFinalNewline: false});194+ t.is(stdout, 'foo\n');195+});196+197+test('stripFinalNewline on failure', async t => {198+ const {stderr} = await t.throwsAsync(execa('noop-throw', ['foo'], {stripFinalNewline: true}));199+ t.is(stderr, 'foo');200+});201+202+test('stripFinalNewline in sync mode', t => {203+ const {stdout} = execa.sync('noop', ['foo'], {stripFinalNewline: true});204+ t.is(stdout, 'foo');205+});206+207+test('stripFinalNewline in sync mode on failure', t => {208+ const {stderr} = t.throws(() => {209+ execa.sync('noop-throw', ['foo'], {stripFinalNewline: true});210+ });211+ t.is(stderr, 'foo');212+});213+214+test('preferLocal option', async t => {215+ await execa('ava', ['--version'], {env: {PATH: ''}});216+ const errorRegExp = process.platform === 'win32' ? /failed with exit code 1/ : /spawn ava ENOENT/;217+ await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: {PATH: ''}}), errorRegExp);218+});219+220+test('localDir option', async t => {221+ const command = process.platform === 'win32' ? 'echo %PATH%' : 'echo $PATH';222+ const {stdout} = await execa(command, {shell: true, localDir: '/test'});223+ const envPaths = stdout.split(path.delimiter).map(envPath =>224+ envPath.replace(/\\/g, '/').replace(/^[^/]+/, '')225+ );226+ t.true(envPaths.some(envPath => envPath === '/test/node_modules/.bin'));227+});228+229+test('input option can be a String', async t => {230+ const {stdout} = await execa('stdin', {input: 'foobar'});231+ t.is(stdout, 'foobar');232+});233+234+test('input option can be a Buffer', async t => {235+ const {stdout} = await execa('stdin', {input: 'testing12'});236+ t.is(stdout, 'testing12');237+});238+239+test('input can be a Stream', async t => {240+ const s = new stream.PassThrough();241+ s.write('howdy');242+ s.end();243+ const {stdout} = await execa('stdin', {input: s});244+ t.is(stdout, 'howdy');245+});246+247+test('you can write to child.stdin', async t => {248+ const child = execa('stdin');249+ child.stdin.end('unicorns');250+ t.is((await child).stdout, 'unicorns');251+});252+253+test('input option can be a String - sync', t => {254+ const {stdout} = execa.sync('stdin', {input: 'foobar'});255+ t.is(stdout, 'foobar');256+});257+258+test('input option can be a Buffer - sync', t => {259+ const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});260+ t.is(stdout, 'testing12');261+});262+263+test('stdin errors are handled', async t => {264+ const child = execa('noop');265+ child.stdin.emit('error', new Error('test'));266+ await t.throwsAsync(child, /test/);267+});268+269+test('child process errors are handled', async t => {270+ const child = execa('noop');271+ child.emit('error', new Error('test'));272+ await t.throwsAsync(child, /test/);273+});274+275+test('opts.stdout:ignore - stdout will not collect data', async t => {276+ const {stdout} = await execa('stdin', {277+ input: 'hello',278+ stdio: [undefined, 'ignore', undefined]279+ });280+ t.is(stdout, undefined);281+});282+283+test('helpful error trying to provide an input stream in sync mode', t => {284+ t.throws(285+ () => {286+ execa.sync('stdin', {input: new stream.PassThrough()});287+ },288+ /The `input` option cannot be a stream in sync mode/289+ );290+});291+292+test('child process errors rejects promise right away', async t => {293+ const child = execa('forever');294+ child.emit('error', new Error('test'));295+ await t.throwsAsync(child, /test/);296+});297+298+test('execa() returns a promise with kill() and pid', t => {299+ const {kill, pid} = execa('noop', ['foo']);300+ t.is(typeof kill, 'function');301+ t.is(typeof pid, 'number');302+});303+304+test('child_process.spawn() propagated errors have correct shape', t => {305+ const cp = execa('noop', {uid: -1});306+ t.notThrows(() => {307+ cp.catch(() => {});308+ cp.unref();309+ cp.on('error', () => {});310+ });311+});312+313+test('child_process.spawn() errors are propagated', async t => {314+ const {failed} = await t.throwsAsync(execa('noop', {uid: -1}));315+ t.true(failed);316+});317+318+test('child_process.spawnSync() errors are propagated with a correct shape', t => {319+ const {failed} = t.throws(() => {320+ execa.sync('noop', {timeout: -1});321+ });322+ t.true(failed);323+});324+325+test('maxBuffer affects stdout', async t => {326+ await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));327+ const {stdout, all} = await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /max-buffer stdout/);328+ t.is(stdout, '.'.repeat(10));329+ t.is(all, '.'.repeat(10));330+});331+332+test('maxBuffer affects stderr', async t => {333+ await t.notThrowsAsync(execa('max-buffer', ['stderr', '10'], {maxBuffer: 10}));334+ const {stderr, all} = await t.throwsAsync(execa('max-buffer', ['stderr', '11'], {maxBuffer: 10}), /max-buffer stderr/);335+ t.is(stderr, '.'.repeat(10));336+ t.is(all, '.'.repeat(10));337+});338+339+test('do not buffer stdout when `buffer` set to `false`', async t => {340+ const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});341+ const [result, stdout] = await Promise.all([342+ promise,343+ getStream(promise.stdout),344+ getStream(promise.all)345+ ]);346+347+ t.is(result.stdout, undefined);348+ t.is(stdout, '.........\n');349+});350+351+test('do not buffer stderr when `buffer` set to `false`', async t => {352+ const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});353+ const [result, stderr] = await Promise.all([354+ promise,355+ getStream(promise.stderr),356+ getStream(promise.all)357+ ]);358+359+ t.is(result.stderr, undefined);360+ t.is(stderr, '.........\n');361+});362+363+test('allow unknown exit code', async t => {364+ const {exitCode, exitCodeName} = await t.throwsAsync(execa('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});365+ t.is(exitCode, 255);366+ t.is(exitCodeName, 'Unknown system error -255');367+});368+369+test('execa() does not return code and failed properties on success', async t => {370+ const {exitCode, exitCodeName, failed} = await execa('noop', ['foo']);371+ t.is(exitCode, 0);372+ t.is(exitCodeName, 'SUCCESS');373+ t.false(failed);374+});375+376+test('execa() returns code and failed properties', async t => {377+ const {exitCode, exitCodeName, failed} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});378+ t.is(exitCode, 2);379+ const expectedName = process.platform === 'win32' ? 'Unknown system error -2' : 'ENOENT';380+ t.is(exitCodeName, expectedName);381+ t.true(failed);382+});383+384+test('use relative path with \'..\' chars', async t => {385+ const pathViaParentDir = path.join('..', path.basename(path.dirname(__dirname)), 'test', 'fixtures', 'noop');386+ const {stdout} = await execa(pathViaParentDir, ['foo']);387+ t.is(stdout, 'foo');388+});389+390+if (process.platform !== 'win32') {391+ test('execa() rejects if running non-executable', async t => {392+ const cp = execa('non-executable');393+ await t.throwsAsync(cp);394+ });395+396+ test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {397+ await t.throwsAsync(execa('non-executable', {input: 'Hey!'}), /EACCES/);398+ });399+}400+401+test('error.killed is true if process was killed directly', async t => {402+ const cp = execa('forever');403+404+ cp.kill();405+406+ const {killed} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});407+ t.true(killed);408+});409+410+test('error.killed is false if process was killed indirectly', async t => {411+ const cp = execa('forever');412+413+ process.kill(cp.pid, 'SIGINT');414+415+ // `process.kill()` is emulated by Node.js on Windows416+ const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;417+ const {killed} = await t.throwsAsync(cp, {message});418+ t.false(killed);419+});420+421+test('result.killed is false if not killed', async t => {422+ const {killed} = await execa('noop');423+ t.false(killed);424+});425+426+test('result.killed is false if not killed, in sync mode', t => {427+ const {killed} = execa.sync('noop');428+ t.false(killed);429+});430+431+test('result.killed is false on process error', async t => {432+ const {killed} = await t.throwsAsync(execa('wrong command'));433+ t.false(killed);434+});435+436+test('result.killed is false on process error, in sync mode', t => {437+ const {killed} = t.throws(() => {438+ execa.sync('wrong command');439+ });440+ t.false(killed);441+});442+443+if (process.platform === 'darwin') {444+ test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {445+ const {pid} = childProcess.exec('forever', error => {446+ t.truthy(error);447+ t.false(error.killed);448+ t.end();449+ });450+451+ process.kill(pid, 'SIGINT');452+ });453+}454+455+if (process.platform !== 'win32') {456+ test('error.signal is SIGINT', async t => {457+ const cp = execa('forever');458+459+ process.kill(cp.pid, 'SIGINT');460+461+ const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGINT/});462+ t.is(signal, 'SIGINT');463+ });464+465+ test('error.signal is SIGTERM', async t => {466+ const cp = execa('forever');467+468+ process.kill(cp.pid, 'SIGTERM');469+470+ const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});471+ t.is(signal, 'SIGTERM');472+ });473+474+ test('custom error.signal', async t => {475+ const {signal} = await t.throwsAsync(execa('forever', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));476+ t.is(signal, 'SIGHUP');477+ });478+}479+480+test('result.signal is undefined for successful execution', async t => {481+ const {signal} = await execa('noop');482+ t.is(signal, undefined);483+});484+485+test('result.signal is undefined if process failed, but was not killed', async t => {486+ const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});487+ t.is(signal, undefined);488+});489+490+async function testExitCode(t, num) {491+ const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});492+ t.is(exitCode, num);493+}494+495+test('error.exitCode is 2', testExitCode, 2);496+test('error.exitCode is 3', testExitCode, 3);497+test('error.exitCode is 4', testExitCode, 4);498+499+test('timeout kills the process if it times out', async t => {500+ const {killed, timedOut} = await t.throwsAsync(execa('forever', {timeout: 1, message: TIMEOUT_REGEXP}));501+ t.false(killed);502+ t.true(timedOut);503+});504+505+test('timeout kills the process if it times out, in sync mode', async t => {506+ const {killed, timedOut} = await t.throws(() => {507+ execa.sync('forever', {timeout: 1, message: TIMEOUT_REGEXP});508+ });509+ t.false(killed);510+ t.true(timedOut);511+});512+513+test('timeout does not kill the process if it does not time out', async t => {514+ const {timedOut} = await execa('delay', ['500'], {timeout: 1e8});515+ t.false(timedOut);516+});517+518+test('timedOut is false if no timeout was set', async t => {519+ const {timedOut} = await execa('noop');520+ t.false(timedOut);521+});522+523+test('timedOut will be false if no timeout was set and zero exit code in sync mode', t => {524+ const {timedOut} = execa.sync('noop');525+ t.false(timedOut);526+});527+528+async function errorMessage(t, expected, ...args) {529+ await t.throwsAsync(execa('exit', args), {message: expected});530+}531+532+errorMessage.title = (message, expected) => `error.message matches: ${expected}`;533+534+test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');535+test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');536+537+async function command(t, expected, ...args) {538+ const {command: failCommand} = await t.throwsAsync(execa('fail', args));539+ t.is(failCommand, `fail${expected}`);540+541+ const {command} = await execa('noop', args);542+ t.is(command, `noop${expected}`);543+}544+545+command.title = (message, expected) => `command is: ${JSON.stringify(expected)}`;546+547+test(command, ' foo bar', 'foo', 'bar');548+test(command, ' baz quz', 'baz', 'quz');549+test(command, '');550+551+// When child process exits before parent process552+async function spawnAndExit(t, cleanup, detached) {553+ await t.notThrowsAsync(execa('sub-process-exit', [cleanup, detached]));554+}555+556+test('spawnAndExit', spawnAndExit, false, false);557+test('spawnAndExit cleanup', spawnAndExit, true, false);558+test('spawnAndExit detached', spawnAndExit, false, true);559+test('spawnAndExit cleanup detached', spawnAndExit, true, true);560+561+// When parent process exits before child process562+async function spawnAndKill(t, signal, cleanup, detached, isKilled) {563+ const subprocess = execa('sub-process', [cleanup, detached], {stdio: ['ignore', 'ignore', 'ignore', 'ipc']});564+565+ const pid = await pEvent(subprocess, 'message');566+ t.true(Number.isInteger(pid));567+ t.true(isRunning(pid));568+569+ process.kill(subprocess.pid, signal);570+571+ await t.throwsAsync(subprocess);572+573+ t.false(isRunning(subprocess.pid));574+ t.is(isRunning(pid), !isKilled);575+576+ if (!isKilled) {577+ process.kill(pid, 'SIGKILL');578+ }579+}580+581+// Without `options.cleanup`:582+// - on Windows subprocesses are killed if `options.detached: false`, but not583+// if `options.detached: true`584+// - on Linux subprocesses are never killed regardless of `options.detached`585+// With `options.cleanup`, subprocesses are always killed586+// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled587+const exitIfWindows = process.platform === 'win32';588+test('spawnAndKill SIGTERM', spawnAndKill, 'SIGTERM', false, false, exitIfWindows);589+test('spawnAndKill SIGKILL', spawnAndKill, 'SIGKILL', false, false, exitIfWindows);590+test('spawnAndKill cleanup SIGTERM', spawnAndKill, 'SIGTERM', true, false, true);591+test('spawnAndKill cleanup SIGKILL', spawnAndKill, 'SIGKILL', true, false, exitIfWindows);592+test('spawnAndKill detached SIGTERM', spawnAndKill, 'SIGTERM', false, true, false);593+test('spawnAndKill detached SIGKILL', spawnAndKill, 'SIGKILL', false, true, false);594+test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, 'SIGTERM', true, true, false);595+test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, 'SIGKILL', true, true, false);596+597+if (process.platform !== 'win32') {598+ test('write to fast-exit process', async t => {599+ // Try-catch here is necessary, because this test is not 100% accurate600+ // Sometimes process can manage to accept input before exiting601+ try {602+ await execa(`fast-exit-${process.platform}`, [], {input: 'data'});603+ t.pass();604+ } catch (error) {605+ t.is(error.exitCode, 32);606+ }607+ });608+}609+610+test('use environment variables by default', async t => {611+ const {stdout} = await execa('environment');612+ t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);613+});614+615+test('extend environment variables by default', async t => {616+ const {stdout} = await execa('environment', [], {env: {BAR: 'bar'}});617+ t.deepEqual(stdout.split('\n'), ['foo', 'bar']);618+});619+620+test('do not extend environment with `extendEnv: false`', async t => {621+ const {stdout} = await execa('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});622+ t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);623+});624+625+test('can use `options.shell: true`', async t => {626+ const {stdout} = await execa('node test/fixtures/noop foo', {shell: true});627+ t.is(stdout, 'foo');628+});629+630+test('can use `options.shell: string`', async t => {631+ const shell = process.platform === 'win32' ? 'cmd.exe' : '/bin/bash';632+ const {stdout} = await execa('node test/fixtures/noop foo', {shell});633+ t.is(stdout, 'foo');634+});635+636+test('use extend environment with `extendEnv: true` and `shell: true`', async t => {637+ process.env.TEST = 'test';638+ const command = process.platform === 'win32' ? 'echo %TEST%' : 'echo $TEST';639+ const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});640+ t.is(stdout, 'test');641+ delete process.env.TEST;642+});643+644+test('do not buffer when streaming', async t => {645+ const {stdout} = execa('max-buffer', ['stdout', '21'], {maxBuffer: 10});646+ const result = await getStream(stdout);647+ t.is(result, '....................\n');648+});649+650+test('detach child process', async t => {651+ const {stdout} = await execa('detach');652+ const pid = Number(stdout);653+ t.true(Number.isInteger(pid));654+ t.true(isRunning(pid));655+656+ process.kill(pid, 'SIGKILL');657+});658+659+// See #128660+test('removes exit handler on exit', async t => {661+ // FIXME: This relies on `signal-exit` internals662+ const ee = process.__signal_exit_emitter__;663+664+ const child = execa('noop');665+ const listener = ee.listeners('exit').pop();666+667+ await new Promise((resolve, reject) => {668+ child.on('error', reject);669+ child.on('exit', resolve);670+ });671+672+ const included = ee.listeners('exit').includes(listener);673+ t.false(included);674+});675+676+test('promise methods are not enumerable', t => {677+ const descriptors = Object.getOwnPropertyDescriptors(execa('noop'));678+ // eslint-disable-next-line promise/prefer-await-to-then679+ t.false(descriptors.then.enumerable);680+ t.false(descriptors.catch.enumerable);681+ // TOOD: Remove the `if`-guard when targeting Node.js 10682+ if (Promise.prototype.finally) {683+ t.false(descriptors.finally.enumerable);684+ }685+});686+687+// TOOD: Remove the `if`-guard when targeting Node.js 10688+if (Promise.prototype.finally) {689+ test('finally function is executed on success', async t => {690+ let isCalled = false;691+ const {stdout} = await execa('noop', ['foo']).finally(() => {692+ isCalled = true;693+ });694+ t.is(isCalled, true);695+ t.is(stdout, 'foo');696+ });697+698+ test('finally function is executed on failure', async t => {699+ let isError = false;700+ const {stdout, stderr} = await t.throwsAsync(execa('exit', ['2']).finally(() => {701+ isError = true;702+ }));703+ t.is(isError, true);704+ t.is(typeof stdout, 'string');705+ t.is(typeof stderr, 'string');706+ });707+708+ test('throw in finally function bubbles up on success', async t => {709+ const {message} = await t.throwsAsync(execa('noop', ['foo']).finally(() => {710+ throw new Error('called');711+ }));712+ t.is(message, 'called');713+ });714+715+ test('throw in finally bubbles up on error', async t => {716+ const {message} = await t.throwsAsync(execa('exit', ['2']).finally(() => {717+ throw new Error('called');718+ }));719+ t.is(message, 'called');720+ });721+}722+723+test('cancel method kills the subprocess', t => {724+ const subprocess = execa('node');725+ subprocess.cancel();726+ t.true(subprocess.killed);727+});728+729+test('result.isCanceled is false when spawned.cancel() isn\'t called (success)', async t => {730+ const {isCanceled} = await execa('noop');731+ t.false(isCanceled);732+});733+734+test('result.isCanceled is false when spawned.cancel() isn\'t called (failure)', async t => {735+ const {isCanceled} = await t.throwsAsync(execa('fail'));736+ t.false(isCanceled);737+});738+739+test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (success)', t => {740+ const {isCanceled} = execa.sync('noop');741+ t.false(isCanceled);742+});743+744+test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (failure)', t => {745+ const {isCanceled} = t.throws(() => {746+ execa.sync('fail');747+ });748+ t.false(isCanceled);749+});750+751+test('calling cancel method throws an error with message "Command was canceled"', async t => {752+ const subprocess = execa('noop');753+ subprocess.cancel();754+ await t.throwsAsync(subprocess, {message: /Command was canceled/});755+});756+757+test('error.isCanceled is true when cancel method is used', async t => {758+ const subprocess = execa('noop');759+ subprocess.cancel();760+ const {isCanceled} = await t.throwsAsync(subprocess);761+ t.true(isCanceled);762+});763+764+test('error.isCanceled is false when kill method is used', async t => {765+ const subprocess = execa('noop');766+ subprocess.kill();767+ const {isCanceled} = await t.throwsAsync(subprocess);768+ t.false(isCanceled);769+});770+771+test('calling cancel method twice should show the same behaviour as calling it once', async t => {772+ const subprocess = execa('noop');773+ subprocess.cancel();774+ subprocess.cancel();775+ const {isCanceled} = await t.throwsAsync(subprocess);776+ t.true(isCanceled);777+ t.true(subprocess.killed);778+});779+780+test('calling cancel method on a successfully completed process does not make result.isCanceled true', async t => {781+ const subprocess = execa('noop');782+ const {isCanceled} = await subprocess;783+ subprocess.cancel();784+ t.false(isCanceled);785+});786+787+test('calling cancel method on a process which has been killed does not make error.isCanceled true', async t => {788+ const subprocess = execa('noop');789+ subprocess.kill();790+ const {isCanceled} = await t.throwsAsync(subprocess);791+ t.false(isCanceled);792+});793+794+test('allow commands with spaces and no array arguments', async t => {795+ const {stdout} = await execa('command with space');796+ t.is(stdout, '');797+});798+799+test('allow commands with spaces and array arguments', async t => {800+ const {stdout} = await execa('command with space', ['foo', 'bar']);801+ t.is(stdout, 'foo\nbar');802+});803+804+test('execa.command()', async t => {805+ const {stdout} = await execa.command('node test/fixtures/echo foo bar');806+ t.is(stdout, 'foo\nbar');807+});808+809+test('execa.command() ignores consecutive spaces', async t => {810+ const {stdout} = await execa.command('node test/fixtures/echo foo bar');811+ t.is(stdout, 'foo\nbar');812+});813+814+test('execa.command() allows escaping spaces in commands', async t => {815+ const {stdout} = await execa.command('command\\ with\\ space foo bar');816+ t.is(stdout, 'foo\nbar');817+});818+819+test('execa.command() allows escaping spaces in arguments', async t => {820+ const {stdout} = await execa.command('node test/fixtures/echo foo\\ bar');821+ t.is(stdout, 'foo bar');822+});823+824+test('execa.command() escapes other whitespaces', async t => {825+ const {stdout} = await execa.command('node test/fixtures/echo foo\tbar');826+ t.is(stdout, 'foo\tbar');827+});828+829+test('execa.command() trims', async t => {830+ const {stdout} = await execa.command(' node test/fixtures/echo foo bar ');831+ t.is(stdout, 'foo\nbar');832+});833+834+test('execa.command.sync()', t => {835+ const {stdout} = execa.commandSync('node test/fixtures/echo foo bar');836+ t.is(stdout, 'foo\nbar');837+});modified:index.d.ts+37 added-2 removed
185 unmodified lines186 */187 readonly input?: string | Buffer | ReadableStream;188 }189 190- interface SyncOptions<EncodingType = string>191- extends CommonOptions<EncodingType> {190+ interface SyncOptions<EncodingType = string> extends CommonOptions<EncodingType> {191 /**192 Write some input to the `stdin` of your binary.193 */194 readonly input?: string | Buffer;195 }196 197+ interface NodeOptions<EncodingType = string> extends Options<EncodingType> {198+ /**199+ The Node.js executable to use.200+201+ @default process.execPath202+ */203+ readonly nodePath?: string;204+205+ /**206+ List of string arguments passed to the Node.js executable.207+208+ @default process.execArgv209+ */210+ readonly nodeArguments?: string[];211+ }212+213 interface ExecaReturnBase<StdoutStderrType> {214 /**215 The file and arguments that were run.216 */214 unmodified lines431 @returns A result `Object` with `stdout` and `stderr` properties.432 */433 commandSync(command: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;434 commandSync(command: string, options?: execa.SyncOptions<null>): execa.ExecaSyncReturnValue<Buffer>;435+436+ /**437+ Execute a Node.js script as a child process.438+439+ @param scriptPath - Node.js script to execute.440+ @param arguments - Arguments to pass to `scriptPath` on execution.441+ @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.442+ */443+ node(444+ scriptPath: string,445+ arguments?: readonly string[],446+ options?: execa.NodeOptions447+ ): execa.ExecaChildProcess;448+ node(449+ file: string,450+ arguments?: readonly string[],451+ options?: execa.Options<null>452+ ): execa.ExecaChildProcess<Buffer>;453+ node(file: string, options?: execa.Options): execa.ExecaChildProcess;454+ node(file: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;455 };456 457 export = execa;modified:index.js+27 added
518 unmodified lines519 module.exports.commandSync = (command, options) => {520 const [file, ...args] = parseCommand(command);521 return execa.sync(file, args, options);522 };523+524+module.exports.node = (scriptPath, args, options) => {525+ if (args && !Array.isArray(args) && typeof args === 'object') {526+ options = args;527+ args = [];528+ }529+530+ const stdioOption = stdio.node(options);531+ options = options || {};532+533+ return execa(534+ options.nodePath || process.execPath,535+ [536+ ...(options.nodeArguments || process.execArgv),537+ scriptPath,538+ ...(Array.isArray(args) ? args : [])539+ ],540+ {541+ ...options,542+ stdin: undefined,543+ stdout: undefined,544+ stderr: undefined,545+ stdio: stdioOption,546+ shell: false547+ }548+ );549+};modified:index.test-d.ts+13 added
164 unmodified lines165 expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns', {encoding: 'utf8'}));166 expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns', {encoding: null}));167 expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns foo', {encoding: 'utf8'}));168 expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns foo', {encoding: null}));169+170+expectType<ExecaChildProcess<string>>(execa.node('unicorns'));171+expectType<ExecaReturnValue<string>>(await execa.node('unicorns'));172+expectType<ExecaReturnValue<string>>(173+ await execa.node('unicorns', {encoding: 'utf8'})174+);175+expectType<ExecaReturnValue<Buffer>>(await execa.node('unicorns', {encoding: null}));176+expectType<ExecaReturnValue<string>>(177+ await execa.node('unicorns', ['foo'], {encoding: 'utf8'})178+);179+expectType<ExecaReturnValue<Buffer>>(180+ await execa.node('unicorns', ['foo'], {encoding: null})181+);modified:readme.md+22 added
182 unmodified lines183 Same as [`execa.command()`](#execacommand-command-options) but synchronous.184 185 Returns or throws a [`childProcessResult`](#childProcessResult).186 187+### execa.node(scriptPath, [arguments], [options])188+189+Execute a Node.js script as a child process.190+191+Same as `execa('node', [file, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):192+ - the [`nodePath`](#nodepath-for-node-only) and [`nodeArguments`](#nodearguments-for-node-only) options can be used193+ - the [`shell`](#shell) option cannot be used 194+ - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)195+196 ### childProcessResult197 198 Type: `object`199 246 unmodified lines446 Default: `false`447 448 If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.449 450+#### nodePath *(for `.node()` only)*451 452+Type: `string`<br>453+Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath)454+455+Node.js executable used to create the child process.456+457+#### nodeArguments *(for `.node()` only)*458+459+Type: `string[]`<br>460+Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv)461+462+List of string arguments passed to the Node.js executable.463+464 ## Tips465 466 ### Save and pipe output from a child process467 55 unmodified linesdeleted:test.js-837 removed
1-import path from 'path';2-import fs from 'fs';3-import stream from 'stream';4-import childProcess from 'child_process';5-import test from 'ava';6-import getStream from 'get-stream';7-import isRunning from 'is-running';8-import tempfile from 'tempfile';9-import pEvent from 'p-event';10-import execa from '.';11-12-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;13-process.env.FOO = 'foo';14-15-const TIMEOUT_REGEXP = /timed out after/;16-17-const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);18-19-test('execa()', async t => {20- const {stdout} = await execa('noop', ['foo']);21- t.is(stdout, 'foo');22-});23-24-if (process.platform === 'win32') {25- test('execa() - cmd file', async t => {26- const {stdout} = await execa('hello.cmd');27- t.is(stdout, 'Hello World');28- });29-30- test('execa() - run cmd command', async t => {31- const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);32- t.is(stdout, 'Hello World');33- });34-}35-36-test('buffer', async t => {37- const {stdout} = await execa('noop', ['foo'], {encoding: null});38- t.true(Buffer.isBuffer(stdout));39- t.is(stdout.toString(), 'foo');40-});41-42-test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {43- const {all} = await execa('noop-132');44- t.is(all, '132');45-});46-47-test('stdout/stderr/all available on errors', async t => {48- const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});49- t.is(typeof stdout, 'string');50- t.is(typeof stderr, 'string');51- t.is(typeof all, 'string');52-});53-54-test('stdout/stderr/all are undefined if ignored', async t => {55- const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore'});56- t.is(stdout, undefined);57- t.is(stderr, undefined);58- t.is(all, undefined);59-});60-61-test('stdout/stderr/all are undefined if ignored in sync mode', t => {62- const {stdout, stderr, all} = execa.sync('noop', {stdio: 'ignore'});63- t.is(stdout, undefined);64- t.is(stderr, undefined);65- t.is(all, undefined);66-});67-68-const WRONG_COMMAND = process.platform === 'win32' ?69- '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :70- '';71-72-test('stdout/stderr/all on process errors', async t => {73- const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command'));74- t.is(stdout, '');75- t.is(stderr, WRONG_COMMAND);76- t.is(all, WRONG_COMMAND);77-});78-79-test('stdout/stderr/all on process errors, in sync mode', t => {80- const {stdout, stderr, all} = t.throws(() => {81- execa.sync('wrong command');82- });83- t.is(stdout, '');84- t.is(stderr, WRONG_COMMAND);85- t.is(all, undefined);86-});87-88-test('pass `stdout` to a file descriptor', async t => {89- const file = tempfile('.txt');90- await execa('fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});91- t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');92-});93-94-test('pass `stderr` to a file descriptor', async t => {95- const file = tempfile('.txt');96- await execa('fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});97- t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');98-});99-100-test('execa.sync()', t => {101- const {stdout} = execa.sync('noop', ['foo']);102- t.is(stdout, 'foo');103-});104-105-test('execa.sync() throws error if written to stderr', t => {106- t.throws(() => {107- execa.sync('foo');108- }, process.platform === 'win32' ? /failed with exit code 1/ : /spawnSync foo ENOENT/);109-});110-111-test('skip throwing when using reject option', async t => {112- const {exitCode} = await execa('fail', {reject: false});113- t.is(exitCode, 2);114-});115-116-test('skip throwing when using reject option in sync mode', t => {117- const {exitCode} = execa.sync('fail', {reject: false});118- t.is(exitCode, 2);119-});120-121-test('kill("SIGKILL") should terminate cleanly', async t => {122- const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});123- await pEvent(subprocess, 'message');124-125- subprocess.kill('SIGKILL');126-127- const {signal} = await t.throwsAsync(subprocess);128- t.is(signal, 'SIGKILL');129-});130-131-// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).132-// Therefore, this feature and those tests do not make sense on Windows.133-if (process.platform !== 'win32') {134- test('`forceKillAfterTimeout: false` should not kill after a timeout', async t => {135- const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});136- await pEvent(subprocess, 'message');137-138- subprocess.kill('SIGTERM', {forceKillAfterTimeout: false});139-140- t.true(isRunning(subprocess.pid));141- subprocess.kill('SIGKILL');142- });143-144- test('`forceKillAfterTimeout: number` should kill after a timeout', async t => {145- const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});146- await pEvent(subprocess, 'message');147-148- subprocess.kill('SIGTERM', {forceKillAfterTimeout: 50});149-150- const {signal} = await t.throwsAsync(subprocess);151- t.is(signal, 'SIGKILL');152- });153-154- test('`forceKillAfterTimeout: true` should kill after a timeout', async t => {155- const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});156- await pEvent(subprocess, 'message');157-158- subprocess.kill('SIGTERM', {forceKillAfterTimeout: true});159-160- const {signal} = await t.throwsAsync(subprocess);161- t.is(signal, 'SIGKILL');162- });163-164- test('kill() with no arguments should kill after a timeout', async t => {165- const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});166- await pEvent(subprocess, 'message');167-168- subprocess.kill();169-170- const {signal} = await t.throwsAsync(subprocess);171- t.is(signal, 'SIGKILL');172- });173-174- test('`forceKillAfterTimeout` should not be a float', t => {175- t.throws(() => {176- execa('noop').kill('SIGTERM', {forceKillAfterTimeout: 0.5});177- }, {instanceOf: TypeError, message: /non-negative integer/});178- });179-180- test('`forceKillAfterTimeout` should not be negative', t => {181- t.throws(() => {182- execa('noop').kill('SIGTERM', {forceKillAfterTimeout: -1});183- }, {instanceOf: TypeError, message: /non-negative integer/});184- });185-}186-187-test('stripFinalNewline: true', async t => {188- const {stdout} = await execa('noop', ['foo']);189- t.is(stdout, 'foo');190-});191-192-test('stripFinalNewline: false', async t => {193- const {stdout} = await execa('noop', ['foo'], {stripFinalNewline: false});194- t.is(stdout, 'foo\n');195-});196-197-test('stripFinalNewline on failure', async t => {198- const {stderr} = await t.throwsAsync(execa('noop-throw', ['foo'], {stripFinalNewline: true}));199- t.is(stderr, 'foo');200-});201-202-test('stripFinalNewline in sync mode', t => {203- const {stdout} = execa.sync('noop', ['foo'], {stripFinalNewline: true});204- t.is(stdout, 'foo');205-});206-207-test('stripFinalNewline in sync mode on failure', t => {208- const {stderr} = t.throws(() => {209- execa.sync('noop-throw', ['foo'], {stripFinalNewline: true});210- });211- t.is(stderr, 'foo');212-});213-214-test('preferLocal option', async t => {215- await execa('ava', ['--version'], {env: {PATH: ''}});216- const errorRegExp = process.platform === 'win32' ? /failed with exit code 1/ : /spawn ava ENOENT/;217- await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: {PATH: ''}}), errorRegExp);218-});219-220-test('localDir option', async t => {221- const command = process.platform === 'win32' ? 'echo %PATH%' : 'echo $PATH';222- const {stdout} = await execa(command, {shell: true, localDir: '/test'});223- const envPaths = stdout.split(path.delimiter).map(envPath =>224- envPath.replace(/\\/g, '/').replace(/^[^/]+/, '')225- );226- t.true(envPaths.some(envPath => envPath === '/test/node_modules/.bin'));227-});228-229-test('input option can be a String', async t => {230- const {stdout} = await execa('stdin', {input: 'foobar'});231- t.is(stdout, 'foobar');232-});233-234-test('input option can be a Buffer', async t => {235- const {stdout} = await execa('stdin', {input: 'testing12'});236- t.is(stdout, 'testing12');237-});238-239-test('input can be a Stream', async t => {240- const s = new stream.PassThrough();241- s.write('howdy');242- s.end();243- const {stdout} = await execa('stdin', {input: s});244- t.is(stdout, 'howdy');245-});246-247-test('you can write to child.stdin', async t => {248- const child = execa('stdin');249- child.stdin.end('unicorns');250- t.is((await child).stdout, 'unicorns');251-});252-253-test('input option can be a String - sync', t => {254- const {stdout} = execa.sync('stdin', {input: 'foobar'});255- t.is(stdout, 'foobar');256-});257-258-test('input option can be a Buffer - sync', t => {259- const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});260- t.is(stdout, 'testing12');261-});262-263-test('stdin errors are handled', async t => {264- const child = execa('noop');265- child.stdin.emit('error', new Error('test'));266- await t.throwsAsync(child, /test/);267-});268-269-test('child process errors are handled', async t => {270- const child = execa('noop');271- child.emit('error', new Error('test'));272- await t.throwsAsync(child, /test/);273-});274-275-test('opts.stdout:ignore - stdout will not collect data', async t => {276- const {stdout} = await execa('stdin', {277- input: 'hello',278- stdio: [undefined, 'ignore', undefined]279- });280- t.is(stdout, undefined);281-});282-283-test('helpful error trying to provide an input stream in sync mode', t => {284- t.throws(285- () => {286- execa.sync('stdin', {input: new stream.PassThrough()});287- },288- /The `input` option cannot be a stream in sync mode/289- );290-});291-292-test('child process errors rejects promise right away', async t => {293- const child = execa('forever');294- child.emit('error', new Error('test'));295- await t.throwsAsync(child, /test/);296-});297-298-test('execa() returns a promise with kill() and pid', t => {299- const {kill, pid} = execa('noop', ['foo']);300- t.is(typeof kill, 'function');301- t.is(typeof pid, 'number');302-});303-304-test('child_process.spawn() propagated errors have correct shape', t => {305- const cp = execa('noop', {uid: -1});306- t.notThrows(() => {307- cp.catch(() => {});308- cp.unref();309- cp.on('error', () => {});310- });311-});312-313-test('child_process.spawn() errors are propagated', async t => {314- const {failed} = await t.throwsAsync(execa('noop', {uid: -1}));315- t.true(failed);316-});317-318-test('child_process.spawnSync() errors are propagated with a correct shape', t => {319- const {failed} = t.throws(() => {320- execa.sync('noop', {timeout: -1});321- });322- t.true(failed);323-});324-325-test('maxBuffer affects stdout', async t => {326- await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));327- const {stdout, all} = await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /max-buffer stdout/);328- t.is(stdout, '.'.repeat(10));329- t.is(all, '.'.repeat(10));330-});331-332-test('maxBuffer affects stderr', async t => {333- await t.notThrowsAsync(execa('max-buffer', ['stderr', '10'], {maxBuffer: 10}));334- const {stderr, all} = await t.throwsAsync(execa('max-buffer', ['stderr', '11'], {maxBuffer: 10}), /max-buffer stderr/);335- t.is(stderr, '.'.repeat(10));336- t.is(all, '.'.repeat(10));337-});338-339-test('do not buffer stdout when `buffer` set to `false`', async t => {340- const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});341- const [result, stdout] = await Promise.all([342- promise,343- getStream(promise.stdout),344- getStream(promise.all)345- ]);346-347- t.is(result.stdout, undefined);348- t.is(stdout, '.........\n');349-});350-351-test('do not buffer stderr when `buffer` set to `false`', async t => {352- const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});353- const [result, stderr] = await Promise.all([354- promise,355- getStream(promise.stderr),356- getStream(promise.all)357- ]);358-359- t.is(result.stderr, undefined);360- t.is(stderr, '.........\n');361-});362-363-test('allow unknown exit code', async t => {364- const {exitCode, exitCodeName} = await t.throwsAsync(execa('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});365- t.is(exitCode, 255);366- t.is(exitCodeName, 'Unknown system error -255');367-});368-369-test('execa() does not return code and failed properties on success', async t => {370- const {exitCode, exitCodeName, failed} = await execa('noop', ['foo']);371- t.is(exitCode, 0);372- t.is(exitCodeName, 'SUCCESS');373- t.false(failed);374-});375-376-test('execa() returns code and failed properties', async t => {377- const {exitCode, exitCodeName, failed} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});378- t.is(exitCode, 2);379- const expectedName = process.platform === 'win32' ? 'Unknown system error -2' : 'ENOENT';380- t.is(exitCodeName, expectedName);381- t.true(failed);382-});383-384-test('use relative path with \'..\' chars', async t => {385- const pathViaParentDir = path.join('..', path.basename(__dirname), 'fixtures', 'noop');386- const {stdout} = await execa(pathViaParentDir, ['foo']);387- t.is(stdout, 'foo');388-});389-390-if (process.platform !== 'win32') {391- test('execa() rejects if running non-executable', async t => {392- const cp = execa('non-executable');393- await t.throwsAsync(cp);394- });395-396- test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {397- await t.throwsAsync(execa('non-executable', {input: 'Hey!'}), /EACCES/);398- });399-}400-401-test('error.killed is true if process was killed directly', async t => {402- const cp = execa('forever');403-404- cp.kill();405-406- const {killed} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});407- t.true(killed);408-});409-410-test('error.killed is false if process was killed indirectly', async t => {411- const cp = execa('forever');412-413- process.kill(cp.pid, 'SIGINT');414-415- // `process.kill()` is emulated by Node.js on Windows416- const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;417- const {killed} = await t.throwsAsync(cp, {message});418- t.false(killed);419-});420-421-test('result.killed is false if not killed', async t => {422- const {killed} = await execa('noop');423- t.false(killed);424-});425-426-test('result.killed is false if not killed, in sync mode', t => {427- const {killed} = execa.sync('noop');428- t.false(killed);429-});430-431-test('result.killed is false on process error', async t => {432- const {killed} = await t.throwsAsync(execa('wrong command'));433- t.false(killed);434-});435-436-test('result.killed is false on process error, in sync mode', t => {437- const {killed} = t.throws(() => {438- execa.sync('wrong command');439- });440- t.false(killed);441-});442-443-if (process.platform === 'darwin') {444- test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {445- const {pid} = childProcess.exec('forever', error => {446- t.truthy(error);447- t.false(error.killed);448- t.end();449- });450-451- process.kill(pid, 'SIGINT');452- });453-}454-455-if (process.platform !== 'win32') {456- test('error.signal is SIGINT', async t => {457- const cp = execa('forever');458-459- process.kill(cp.pid, 'SIGINT');460-461- const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGINT/});462- t.is(signal, 'SIGINT');463- });464-465- test('error.signal is SIGTERM', async t => {466- const cp = execa('forever');467-468- process.kill(cp.pid, 'SIGTERM');469-470- const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});471- t.is(signal, 'SIGTERM');472- });473-474- test('custom error.signal', async t => {475- const {signal} = await t.throwsAsync(execa('forever', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));476- t.is(signal, 'SIGHUP');477- });478-}479-480-test('result.signal is undefined for successful execution', async t => {481- const {signal} = await execa('noop');482- t.is(signal, undefined);483-});484-485-test('result.signal is undefined if process failed, but was not killed', async t => {486- const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});487- t.is(signal, undefined);488-});489-490-async function testExitCode(t, num) {491- const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});492- t.is(exitCode, num);493-}494-495-test('error.exitCode is 2', testExitCode, 2);496-test('error.exitCode is 3', testExitCode, 3);497-test('error.exitCode is 4', testExitCode, 4);498-499-test('timeout kills the process if it times out', async t => {500- const {killed, timedOut} = await t.throwsAsync(execa('forever', {timeout: 1, message: TIMEOUT_REGEXP}));501- t.false(killed);502- t.true(timedOut);503-});504-505-test('timeout kills the process if it times out, in sync mode', async t => {506- const {killed, timedOut} = await t.throws(() => {507- execa.sync('forever', {timeout: 1, message: TIMEOUT_REGEXP});508- });509- t.false(killed);510- t.true(timedOut);511-});512-513-test('timeout does not kill the process if it does not time out', async t => {514- const {timedOut} = await execa('delay', ['500'], {timeout: 1e8});515- t.false(timedOut);516-});517-518-test('timedOut is false if no timeout was set', async t => {519- const {timedOut} = await execa('noop');520- t.false(timedOut);521-});522-523-test('timedOut will be false if no timeout was set and zero exit code in sync mode', t => {524- const {timedOut} = execa.sync('noop');525- t.false(timedOut);526-});527-528-async function errorMessage(t, expected, ...args) {529- await t.throwsAsync(execa('exit', args), {message: expected});530-}531-532-errorMessage.title = (message, expected) => `error.message matches: ${expected}`;533-534-test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');535-test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');536-537-async function command(t, expected, ...args) {538- const {command: failCommand} = await t.throwsAsync(execa('fail', args));539- t.is(failCommand, `fail${expected}`);540-541- const {command} = await execa('noop', args);542- t.is(command, `noop${expected}`);543-}544-545-command.title = (message, expected) => `command is: ${JSON.stringify(expected)}`;546-547-test(command, ' foo bar', 'foo', 'bar');548-test(command, ' baz quz', 'baz', 'quz');549-test(command, '');550-551-// When child process exits before parent process552-async function spawnAndExit(t, cleanup, detached) {553- await t.notThrowsAsync(execa('sub-process-exit', [cleanup, detached]));554-}555-556-test('spawnAndExit', spawnAndExit, false, false);557-test('spawnAndExit cleanup', spawnAndExit, true, false);558-test('spawnAndExit detached', spawnAndExit, false, true);559-test('spawnAndExit cleanup detached', spawnAndExit, true, true);560-561-// When parent process exits before child process562-async function spawnAndKill(t, signal, cleanup, detached, isKilled) {563- const subprocess = execa('sub-process', [cleanup, detached], {stdio: ['ignore', 'ignore', 'ignore', 'ipc']});564-565- const pid = await pEvent(subprocess, 'message');566- t.true(Number.isInteger(pid));567- t.true(isRunning(pid));568-569- process.kill(subprocess.pid, signal);570-571- await t.throwsAsync(subprocess);572-573- t.false(isRunning(subprocess.pid));574- t.is(isRunning(pid), !isKilled);575-576- if (!isKilled) {577- process.kill(pid, 'SIGKILL');578- }579-}580-581-// Without `options.cleanup`:582-// - on Windows subprocesses are killed if `options.detached: false`, but not583-// if `options.detached: true`584-// - on Linux subprocesses are never killed regardless of `options.detached`585-// With `options.cleanup`, subprocesses are always killed586-// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled587-const exitIfWindows = process.platform === 'win32';588-test('spawnAndKill SIGTERM', spawnAndKill, 'SIGTERM', false, false, exitIfWindows);589-test('spawnAndKill SIGKILL', spawnAndKill, 'SIGKILL', false, false, exitIfWindows);590-test('spawnAndKill cleanup SIGTERM', spawnAndKill, 'SIGTERM', true, false, true);591-test('spawnAndKill cleanup SIGKILL', spawnAndKill, 'SIGKILL', true, false, exitIfWindows);592-test('spawnAndKill detached SIGTERM', spawnAndKill, 'SIGTERM', false, true, false);593-test('spawnAndKill detached SIGKILL', spawnAndKill, 'SIGKILL', false, true, false);594-test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, 'SIGTERM', true, true, false);595-test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, 'SIGKILL', true, true, false);596-597-if (process.platform !== 'win32') {598- test('write to fast-exit process', async t => {599- // Try-catch here is necessary, because this test is not 100% accurate600- // Sometimes process can manage to accept input before exiting601- try {602- await execa(`fast-exit-${process.platform}`, [], {input: 'data'});603- t.pass();604- } catch (error) {605- t.is(error.exitCode, 32);606- }607- });608-}609-610-test('use environment variables by default', async t => {611- const {stdout} = await execa('environment');612- t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);613-});614-615-test('extend environment variables by default', async t => {616- const {stdout} = await execa('environment', [], {env: {BAR: 'bar'}});617- t.deepEqual(stdout.split('\n'), ['foo', 'bar']);618-});619-620-test('do not extend environment with `extendEnv: false`', async t => {621- const {stdout} = await execa('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});622- t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);623-});624-625-test('can use `options.shell: true`', async t => {626- const {stdout} = await execa('node fixtures/noop foo', {shell: true});627- t.is(stdout, 'foo');628-});629-630-test('can use `options.shell: string`', async t => {631- const shell = process.platform === 'win32' ? 'cmd.exe' : '/bin/bash';632- const {stdout} = await execa('node fixtures/noop foo', {shell});633- t.is(stdout, 'foo');634-});635-636-test('use extend environment with `extendEnv: true` and `shell: true`', async t => {637- process.env.TEST = 'test';638- const command = process.platform === 'win32' ? 'echo %TEST%' : 'echo $TEST';639- const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});640- t.is(stdout, 'test');641- delete process.env.TEST;642-});643-644-test('do not buffer when streaming', async t => {645- const {stdout} = execa('max-buffer', ['stdout', '21'], {maxBuffer: 10});646- const result = await getStream(stdout);647- t.is(result, '....................\n');648-});649-650-test('detach child process', async t => {651- const {stdout} = await execa('detach');652- const pid = Number(stdout);653- t.true(Number.isInteger(pid));654- t.true(isRunning(pid));655-656- process.kill(pid, 'SIGKILL');657-});658-659-// See #128660-test('removes exit handler on exit', async t => {661- // FIXME: This relies on `signal-exit` internals662- const ee = process.__signal_exit_emitter__;663-664- const child = execa('noop');665- const listener = ee.listeners('exit').pop();666-667- await new Promise((resolve, reject) => {668- child.on('error', reject);669- child.on('exit', resolve);670- });671-672- const included = ee.listeners('exit').includes(listener);673- t.false(included);674-});675-676-test('promise methods are not enumerable', t => {677- const descriptors = Object.getOwnPropertyDescriptors(execa('noop'));678- // eslint-disable-next-line promise/prefer-await-to-then679- t.false(descriptors.then.enumerable);680- t.false(descriptors.catch.enumerable);681- // TOOD: Remove the `if`-guard when targeting Node.js 10682- if (Promise.prototype.finally) {683- t.false(descriptors.finally.enumerable);684- }685-});686-687-// TOOD: Remove the `if`-guard when targeting Node.js 10688-if (Promise.prototype.finally) {689- test('finally function is executed on success', async t => {690- let isCalled = false;691- const {stdout} = await execa('noop', ['foo']).finally(() => {692- isCalled = true;693- });694- t.is(isCalled, true);695- t.is(stdout, 'foo');696- });697-698- test('finally function is executed on failure', async t => {699- let isError = false;700- const {stdout, stderr} = await t.throwsAsync(execa('exit', ['2']).finally(() => {701- isError = true;702- }));703- t.is(isError, true);704- t.is(typeof stdout, 'string');705- t.is(typeof stderr, 'string');706- });707-708- test('throw in finally function bubbles up on success', async t => {709- const {message} = await t.throwsAsync(execa('noop', ['foo']).finally(() => {710- throw new Error('called');711- }));712- t.is(message, 'called');713- });714-715- test('throw in finally bubbles up on error', async t => {716- const {message} = await t.throwsAsync(execa('exit', ['2']).finally(() => {717- throw new Error('called');718- }));719- t.is(message, 'called');720- });721-}722-723-test('cancel method kills the subprocess', t => {724- const subprocess = execa('node');725- subprocess.cancel();726- t.true(subprocess.killed);727-});728-729-test('result.isCanceled is false when spawned.cancel() isn\'t called (success)', async t => {730- const {isCanceled} = await execa('noop');731- t.false(isCanceled);732-});733-734-test('result.isCanceled is false when spawned.cancel() isn\'t called (failure)', async t => {735- const {isCanceled} = await t.throwsAsync(execa('fail'));736- t.false(isCanceled);737-});738-739-test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (success)', t => {740- const {isCanceled} = execa.sync('noop');741- t.false(isCanceled);742-});743-744-test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (failure)', t => {745- const {isCanceled} = t.throws(() => {746- execa.sync('fail');747- });748- t.false(isCanceled);749-});750-751-test('calling cancel method throws an error with message "Command was canceled"', async t => {752- const subprocess = execa('noop');753- subprocess.cancel();754- await t.throwsAsync(subprocess, {message: /Command was canceled/});755-});756-757-test('error.isCanceled is true when cancel method is used', async t => {758- const subprocess = execa('noop');759- subprocess.cancel();760- const {isCanceled} = await t.throwsAsync(subprocess);761- t.true(isCanceled);762-});763-764-test('error.isCanceled is false when kill method is used', async t => {765- const subprocess = execa('noop');766- subprocess.kill();767- const {isCanceled} = await t.throwsAsync(subprocess);768- t.false(isCanceled);769-});770-771-test('calling cancel method twice should show the same behaviour as calling it once', async t => {772- const subprocess = execa('noop');773- subprocess.cancel();774- subprocess.cancel();775- const {isCanceled} = await t.throwsAsync(subprocess);776- t.true(isCanceled);777- t.true(subprocess.killed);778-});779-780-test('calling cancel method on a successfuly completed process does not make result.isCanceled true', async t => {781- const subprocess = execa('noop');782- const {isCanceled} = await subprocess;783- subprocess.cancel();784- t.false(isCanceled);785-});786-787-test('calling cancel method on a process which has been killed does not make error.isCanceled true', async t => {788- const subprocess = execa('noop');789- subprocess.kill();790- const {isCanceled} = await t.throwsAsync(subprocess);791- t.false(isCanceled);792-});793-794-test('allow commands with spaces and no array arguments', async t => {795- const {stdout} = await execa('./fixtures/command with space');796- t.is(stdout, '');797-});798-799-test('allow commands with spaces and array arguments', async t => {800- const {stdout} = await execa('./fixtures/command with space', ['foo', 'bar']);801- t.is(stdout, 'foo\nbar');802-});803-804-test('execa.command()', async t => {805- const {stdout} = await execa.command('node fixtures/echo foo bar');806- t.is(stdout, 'foo\nbar');807-});808-809-test('execa.command() ignores consecutive spaces', async t => {810- const {stdout} = await execa.command('node fixtures/echo foo bar');811- t.is(stdout, 'foo\nbar');812-});813-814-test('execa.command() allows escaping spaces in commands', async t => {815- const {stdout} = await execa.command('./fixtures/command\\ with\\ space foo bar');816- t.is(stdout, 'foo\nbar');817-});818-819-test('execa.command() allows escaping spaces in arguments', async t => {820- const {stdout} = await execa.command('node fixtures/echo foo\\ bar');821- t.is(stdout, 'foo bar');822-});823-824-test('execa.command() escapes other whitespaces', async t => {825- const {stdout} = await execa.command('node fixtures/echo foo\tbar');826- t.is(stdout, 'foo\tbar');827-});828-829-test('execa.command() trims', async t => {830- const {stdout} = await execa.command(' node fixtures/echo foo bar ');831- t.is(stdout, 'foo\nbar');832-});833-834-test('execa.command.sync()', t => {835- const {stdout} = execa.commandSync('node fixtures/echo foo bar');836- t.is(stdout, 'foo\nbar');837-});