Skip to content
Myr

Separate error creation logic into its own file (#311)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by Sindre Sorhus · parent 8af8c96 · Browse files · 4 files+267 added−238 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+267 added−238 removed

  • tests:+165 added−158 removed
  • other:+102 added−80 removed

4 files+267 added−238 removed

added:lib/error.js+87 added
1'use strict';2const os = require('os');3const util = require('util');45const getCode = (error, code) => {6 if (error && error.code) {7 return [error.code, os.constants.errno[error.code]];8 }910 if (Number.isInteger(code)) {11 return [util.getSystemErrorName(-code), code];12 }1314 return [];15};1617const getErrorPrefix = ({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) => {18 if (timedOut) {19 return `timed out after ${timeout} milliseconds`;20 }2122 if (isCanceled) {23 return 'was canceled';24 }2526 if (signal) {27 return `was killed with ${signal}`;28 }2930 if (exitCode !== undefined) {31 return `failed with exit code ${exitCode} (${exitCodeName})`;32 }3334 return 'failed';35};3637const makeError = ({38 stdout,39 stderr,40 all,41 error,42 signal,43 code,44 command,45 timedOut,46 isCanceled,47 killed,48 parsed: {options: {timeout}}49}) => {50 const [exitCodeName, exitCode] = getCode(error, code);5152 const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled});53 const message = `Command ${prefix}: ${command}`;5455 if (error instanceof Error) {56 error.message = `${message}\n${error.message}`;57 } else {58 error = new Error(message);59 }6061 error.command = command;62 delete error.code;63 error.exitCode = exitCode;64 error.exitCodeName = exitCodeName;65 error.stdout = stdout;66 error.stderr = stderr;6768 if (all !== undefined) {69 error.all = all;70 }7172 if ('bufferedData' in error) {73 delete error.bufferedData;74 }7576 error.failed = true;77 error.timedOut = timedOut;78 error.isCanceled = isCanceled;79 error.killed = killed && !timedOut;80 // `signal` emitted on `spawned.on('exit')` event can be `null`. We normalize81 // it to `undefined`82 error.signal = signal || undefined;8384 return error;85};8687module.exports = makeError;
added:test/error.js+165 added
1import path from 'path';2import childProcess from 'child_process';3import test from 'ava';4import execa from '..';56process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;78const TIMEOUT_REGEXP = /timed out after/;910const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);1112test('stdout/stderr/all available on errors', async t => {13 const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});14 t.is(typeof stdout, 'string');15 t.is(typeof stderr, 'string');16 t.is(typeof all, 'string');17});1819const WRONG_COMMAND = process.platform === 'win32' ?20 '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :21 '';2223test('stdout/stderr/all on process errors', async t => {24 const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command'));25 t.is(stdout, '');26 t.is(stderr, WRONG_COMMAND);27 t.is(all, WRONG_COMMAND);28});2930test('stdout/stderr/all on process errors, in sync mode', t => {31 const {stdout, stderr, all} = t.throws(() => {32 execa.sync('wrong command');33 });34 t.is(stdout, '');35 t.is(stderr, WRONG_COMMAND);36 t.is(all, undefined);37});3839test('allow unknown exit code', async t => {40 const {exitCode, exitCodeName} = await t.throwsAsync(execa('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});41 t.is(exitCode, 255);42 t.is(exitCodeName, 'Unknown system error -255');43});4445test('execa() does not return code and failed properties on success', async t => {46 const {exitCode, exitCodeName, failed} = await execa('noop', ['foo']);47 t.is(exitCode, 0);48 t.is(exitCodeName, 'SUCCESS');49 t.false(failed);50});5152test('execa() returns code and failed properties', async t => {53 const {exitCode, exitCodeName, failed} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});54 t.is(exitCode, 2);55 const expectedName = process.platform === 'win32' ? 'Unknown system error -2' : 'ENOENT';56 t.is(exitCodeName, expectedName);57 t.true(failed);58});5960test('error.killed is true if process was killed directly', async t => {61 const cp = execa('forever');6263 cp.kill();6465 const {killed} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});66 t.true(killed);67});6869test('error.killed is false if process was killed indirectly', async t => {70 const cp = execa('forever');7172 process.kill(cp.pid, 'SIGINT');7374 // `process.kill()` is emulated by Node.js on Windows75 const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;76 const {killed} = await t.throwsAsync(cp, {message});77 t.false(killed);78});7980test('result.killed is false if not killed', async t => {81 const {killed} = await execa('noop');82 t.false(killed);83});8485test('result.killed is false if not killed, in sync mode', t => {86 const {killed} = execa.sync('noop');87 t.false(killed);88});8990test('result.killed is false on process error', async t => {91 const {killed} = await t.throwsAsync(execa('wrong command'));92 t.false(killed);93});9495test('result.killed is false on process error, in sync mode', t => {96 const {killed} = t.throws(() => {97 execa.sync('wrong command');98 });99 t.false(killed);100});101102if (process.platform === 'darwin') {103 test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {104 const {pid} = childProcess.exec('forever', error => {105 t.truthy(error);106 t.false(error.killed);107 t.end();108 });109110 process.kill(pid, 'SIGINT');111 });112}113114if (process.platform !== 'win32') {115 test('error.signal is SIGINT', async t => {116 const cp = execa('forever');117118 process.kill(cp.pid, 'SIGINT');119120 const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGINT/});121 t.is(signal, 'SIGINT');122 });123124 test('error.signal is SIGTERM', async t => {125 const cp = execa('forever');126127 process.kill(cp.pid, 'SIGTERM');128129 const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});130 t.is(signal, 'SIGTERM');131 });132133 test('custom error.signal', async t => {134 const {signal} = await t.throwsAsync(execa('forever', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));135 t.is(signal, 'SIGHUP');136 });137}138139test('result.signal is undefined for successful execution', async t => {140 const {signal} = await execa('noop');141 t.is(signal, undefined);142});143144test('result.signal is undefined if process failed, but was not killed', async t => {145 const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});146 t.is(signal, undefined);147});148149const testExitCode = async (t, num) => {150 const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});151 t.is(exitCode, num);152};153154test('error.exitCode is 2', testExitCode, 2);155test('error.exitCode is 3', testExitCode, 3);156test('error.exitCode is 4', testExitCode, 4);157158const errorMessage = async (t, expected, ...args) => {159 await t.throwsAsync(execa('exit', args), {message: expected});160};161162errorMessage.title = (message, expected) => `error.message matches: ${expected}`;163164test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');165test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');
modified:test/test.js-158 removed
1import path from 'path';2import fs from 'fs';3import stream from 'stream';4import childProcess from 'child_process';4import test from 'ava';5import getStream from 'get-stream';6import isRunning from 'is-running';7import tempfile from 'tempfile';
4 unmodified lines
12process.env.FOO = 'foo';1314const TIMEOUT_REGEXP = /timed out after/;1517const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);1816test('execa()', async t => {17 const {stdout} = await execa('noop', ['foo']);18 t.is(stdout, 'foo');19});
20 unmodified lines
40 const {all} = await execa('noop-132');41 t.is(all, '132');42});4347test('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});5344test('stdout/stderr/all are undefined if ignored', async t => {45 const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore'});46 t.is(stdout, undefined);47 t.is(stderr, undefined);
6 unmodified lines
54 t.is(stderr, undefined);55 t.is(all, undefined);56});5768const WRONG_COMMAND = process.platform === 'win32' ?69 '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :70 '';7172test('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});7879test('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});8758test('pass `stdout` to a file descriptor', async t => {59 const file = tempfile('.txt');60 await execa('test/fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});61 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');
267 unmodified lines
329 t.is(result.stderr, undefined);330 t.is(stderr, '.........\n');331});332363test('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});368369test('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});375376test('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});383333test('use relative path with \'..\' chars', async t => {334 const pathViaParentDir = path.join('..', path.basename(path.dirname(__dirname)), 'test', 'fixtures', 'noop');335 const {stdout} = await execa(pathViaParentDir, ['foo']);336 t.is(stdout, 'foo');
9 unmodified lines
346 await t.throwsAsync(execa('non-executable', {input: 'Hey!'}), /EACCES/);347 });348}349401test('error.killed is true if process was killed directly', async t => {402 const cp = execa('forever');403404 cp.kill();405406 const {killed} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});407 t.true(killed);408});409410test('error.killed is false if process was killed indirectly', async t => {411 const cp = execa('forever');412413 process.kill(cp.pid, 'SIGINT');414415 // `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});420421test('result.killed is false if not killed', async t => {422 const {killed} = await execa('noop');423 t.false(killed);424});425426test('result.killed is false if not killed, in sync mode', t => {427 const {killed} = execa.sync('noop');428 t.false(killed);429});430431test('result.killed is false on process error', async t => {432 const {killed} = await t.throwsAsync(execa('wrong command'));433 t.false(killed);434});435436test('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});442443if (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 });450451 process.kill(pid, 'SIGINT');452 });453}454455if (process.platform !== 'win32') {456 test('error.signal is SIGINT', async t => {457 const cp = execa('forever');458459 process.kill(cp.pid, 'SIGINT');460461 const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGINT/});462 t.is(signal, 'SIGINT');463 });464465 test('error.signal is SIGTERM', async t => {466 const cp = execa('forever');467468 process.kill(cp.pid, 'SIGTERM');469470 const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});471 t.is(signal, 'SIGTERM');472 });473474 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}479480test('result.signal is undefined for successful execution', async t => {481 const {signal} = await execa('noop');482 t.is(signal, undefined);483});484485test('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});489490const testExitCode = async (t, num) => {491 const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});492 t.is(exitCode, num);493};494495test('error.exitCode is 2', testExitCode, 2);496test('error.exitCode is 3', testExitCode, 3);497test('error.exitCode is 4', testExitCode, 4);498350test('timeout kills the process if it times out', async t => {351 const {killed, timedOut} = await t.throwsAsync(execa('forever', {timeout: 1, message: TIMEOUT_REGEXP}));352 t.false(killed);353 t.true(timedOut);
21 unmodified lines
375 const {timedOut} = execa.sync('noop');376 t.false(timedOut);377});378528const errorMessage = async (t, expected, ...args) => {529 await t.throwsAsync(execa('exit', args), {message: expected});530};531532errorMessage.title = (message, expected) => `error.message matches: ${expected}`;533534test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');535test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');536379const command = async (t, expected, ...args) => {380 const {command: failCommand} = await t.throwsAsync(execa('fail', args));381 t.is(failCommand, `fail${expected}`);382
297 unmodified lines
modified:index.js+15 added-80 removed
1'use strict';2const path = require('path');3const os = require('os');4const util = require('util');4const childProcess = require('child_process');5const crossSpawn = require('cross-spawn');6const stripFinalNewline = require('strip-final-newline');7const npmRunPath = require('npm-run-path');
1 unmodified line
9const getStream = require('get-stream');10const mergeStream = require('merge-stream');11const pFinally = require('p-finally');12const onExit = require('signal-exit');13const makeError = require('./lib/error');14const normalizeStdio = require('./lib/stdio');1516const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;17const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
139 unmodified lines
157 ]);158 }159};160161const makeError = (result, options) => {162 const {stdout, stderr, signal} = result;163 let {error} = result;164 const {code, command, timedOut, isCanceled, killed, parsed: {options: {timeout}}} = options;165166 const [exitCodeName, exitCode] = getCode(result, code);167168 const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled});169 const message = `Command ${prefix}: ${command}`;170171 if (error instanceof Error) {172 error.message = `${message}\n${error.message}`;173 } else {174 error = new Error(message);175 }176177 error.command = command;178 delete error.code;179 error.exitCode = exitCode;180 error.exitCodeName = exitCodeName;181 error.stdout = stdout;182 error.stderr = stderr;183184 if ('all' in result) {185 error.all = result.all;186 }187188 if ('bufferedData' in error) {189 delete error.bufferedData;190 }191192 error.failed = true;193 error.timedOut = timedOut;194 error.isCanceled = isCanceled;195 error.killed = killed && !timedOut;196 // `signal` emitted on `spawned.on('exit')` event can be `null`. We normalize197 // it to `undefined`198 error.signal = signal || undefined;199200 return error;201};202203const getCode = ({error = {}}, code) => {204 if (error.code) {205 return [error.code, os.constants.errno[error.code]];206 }207208 if (Number.isInteger(code)) {209 return [util.getSystemErrorName(-code), code];210 }211212 return [];213};214215const getErrorPrefix = ({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) => {216 if (timedOut) {217 return `timed out after ${timeout} milliseconds`;218 }219220 if (isCanceled) {221 return 'was canceled';222 }223224 if (signal) {225 return `was killed with ${signal}`;226 }227228 if (exitCode !== undefined) {229 return `failed with exit code ${exitCode} (${exitCodeName})`;230 }231232 return 'failed';233};234161const joinCommand = (file, args = []) => {162 if (!Array.isArray(args)) {163 return file;164 }
132 unmodified lines
297 try {298 spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);299 } catch (error) {300 return mergePromise(new childProcess.ChildProcess(), () =>375 Promise.reject(makeError({error, stdout: '', stderr: '', all: ''}, {301 Promise.reject(makeError({302 error,303 stdout: '',304 stderr: '',305 all: '',306 command,307 parsed,308 timedOut: false,309 isCanceled: false,
21 unmodified lines
331 result.stderr = handleOutput(parsed.options, stderr);332 result.all = handleOutput(parsed.options, all);333334 if (result.error || result.code !== 0 || result.signal !== null) {405 const error = makeError(result, {406 code: result.code,335 const error = makeError({336 ...result,337 command,338 parsed,339 timedOut: context.timedOut,340 isCanceled: context.isCanceled,
43 unmodified lines
384 let result;385 try {386 result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);387 } catch (error) {458 throw makeError({error, stdout: '', stderr: '', all: ''}, {388 throw makeError({389 error,390 stdout: '',391 stderr: '',392 all: '',393 command,394 parsed,395 timedOut: false,396 isCanceled: false,
4 unmodified lines
401 result.stdout = handleOutput(parsed.options, result.stdout, result.error);402 result.stderr = handleOutput(parsed.options, result.stderr, result.error);403404 if (result.error || result.status !== 0 || result.signal !== null) {471 const error = makeError(result, {405 const error = makeError({406 ...result,407 code: result.status,408 command,409 parsed,410 timedOut: result.error && result.error.errno === 'ETIMEDOUT',
83 unmodified lines