Skip to content

Commit

Permalink
feat(utils/exec, core/exec): uses child_process spawn and fork in ord…
Browse files Browse the repository at this point in the history
…er to manage child processes in
  • Loading branch information
rafamel committed May 6, 2019
1 parent c90f121 commit 19467fa
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
7 changes: 5 additions & 2 deletions src/core/exec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import manage from 'manage-path';
import { IOfType } from '~/types';
import _exec from '~/utils/exec';
import manage from 'manage-path';
import manager from '~/utils/ps-manager';

export default async function exec(
command: string,
Expand All @@ -17,5 +18,7 @@ export default async function exec(
const alter = manage(opts.env);
alter.unshift(bin);

return _exec(command, args, fork, opts);
const { ps, promise } = _exec(command, args, fork, opts);
manager.add(ps.pid, promise);
return promise;
}
38 changes: 24 additions & 14 deletions src/utils/exec.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,41 @@
import { SpawnOptions } from 'child_process';
import { DEFAULT_STDIO, NODE_PATH } from '~/constants';
import {
spawn,
fork as _fork,
SpawnOptions,
ChildProcess,
ForkOptions
} from 'child_process';
import { DEFAULT_STDIO } from '~/constants';
import logger from '~/utils/logger';
import join from 'command-join';
import { IExecOptions } from '~/types';
import { spawn } from 'exits';
import errors from './errors';
import { rejects } from 'errorish';

export default async function exec(
export default function exec(
cmd: string,
args: string[],
fork: boolean,
options: IExecOptions = {}
): Promise<void> {
const opts: SpawnOptions = {
shell: !fork,
): { ps: ChildProcess; promise: Promise<void> } {
const opts: SpawnOptions | ForkOptions = {
shell: fork ? undefined : true,
cwd: options.cwd,
env: options.env || process.env,
stdio: options.stdio || DEFAULT_STDIO
};

logger.debug('Executing: ' + join([cmd].concat(args)));

const { promise } = fork
? spawn(NODE_PATH, [cmd].concat(args), opts)
: spawn(cmd, args, opts);
const ps = fork ? _fork(cmd, args, opts) : spawn(cmd, args, opts);

await promise.catch(async (err) => {
throw new errors.CustomError(`Process failed: ${join([cmd])}`, null, err);
});
const promise = new Promise((resolve: (arg: void) => void, reject) => {
ps.on('error', (err: any) => reject(err));
ps.on('close', (code: number) => {
return code
? reject(Error(`Process failed with code ${code}: ${join([cmd])}`))
: resolve();
});
}).catch(rejects);

return { ps, promise };
}

0 comments on commit 19467fa

Please sign in to comment.