diff --git a/server/src/util/__tests__/sh.test.ts b/server/src/util/__tests__/sh.test.ts index b87235d94..84663c06b 100644 --- a/server/src/util/__tests__/sh.test.ts +++ b/server/src/util/__tests__/sh.test.ts @@ -1,6 +1,19 @@ /* eslint-disable no-useless-escape */ import * as sh from '../sh' +describe('execShellScript', () => { + it('resolves if childprocess sends close signal', async () => { + return expect(sh.execShellScript('echo')).resolves + }) + + it('rejects if childprocess sends error signal', async () => { + // an error is sent if child_process cant spawn 'some-nonexistant-command' + return expect( + sh.execShellScript('something', 'some-nonexistant-command'), + ).rejects.toBe('Failed to execute something') + }) +}) + describe('getDocumentation', () => { it('returns null for an unknown builtin', async () => { const result = await sh.getShellDocumentation({ word: 'foobar' }) diff --git a/server/src/util/sh.ts b/server/src/util/sh.ts index 4194e3aca..42b50457d 100644 --- a/server/src/util/sh.ts +++ b/server/src/util/sh.ts @@ -3,24 +3,27 @@ import * as ChildProcess from 'child_process' /** * Execute the following sh program. */ -export function execShellScript(body: string): Promise { +export function execShellScript(body: string, cmd = 'bash'): Promise { const args = ['-c', body] - const process = ChildProcess.spawn('bash', args) + const process = ChildProcess.spawn(cmd, args) return new Promise((resolve, reject) => { let output = '' - process.stdout.on('data', buffer => { - output += buffer - }) - - process.on('close', returnCode => { + const handleClose = (returnCode: number | Error) => { if (returnCode === 0) { resolve(output) } else { reject(`Failed to execute ${body}`) } + } + + process.stdout.on('data', buffer => { + output += buffer }) + + process.on('close', handleClose) + process.on('error', handleClose) }) }