pooliot-client
Version:
96 lines (79 loc) • 2.9 kB
JavaScript
import { spawn, spawnSync } from 'child_process';
import Logger from 'nightingale';
import { user } from '../argv';
const logger = new Logger('app:commands:exec');
const scriptDirname = `${__dirname}/../../scripts/`;
type StdioOptionValueType = 'ignore' | 'pipe' | 'inherit';
type StdioOptionType = StdioOptionValueType | Array<StdioOptionValueType | any>;
type RunOptionsType = {|
cwd: ?string,
env: ?Object,
stdio: ?StdioOptionType,
|};
type ArgsType = Array<string | number>;
const escapeArgs = args =>
args.map(arg => (typeof arg !== 'string' ? arg : `"${arg.replace('"', '\\"')}"`)).join(' ');
export const runSync = (script: string, args: ArgsType = [], { cwd, env }: RunOptionsType = {}) => {
logger.debug('run', { script, args, cwd, env });
const result = spawnSync(script, args, {
cwd: cwd || scriptDirname,
env: env && { ...process.env, ...env },
});
if (result.error) {
logger.error(result.error.message);
}
if (result.stderr) {
const stderr = result.stderr.toString();
if (stderr) {
logger.error(stderr, { script, args, env });
}
}
if (result.stdout) {
const stdout = result.stdout.toString().trim();
logger.debug(stdout, { script, args });
return stdout;
}
};
export const runSyncOk = (
script: string,
args: ArgsType = [],
{ cwd, env }: RunOptionsType = {},
) => {
const result = spawnSync(script, args, { cwd: cwd || scriptDirname, env });
return !result.status;
};
export const runSyncAsUser = (
script: string,
args: ArgsType,
{ cwd, env }: RunOptionsType = {},
) => {
if (env) throw new Error('env not supported in runSyncAsUser');
return runSync('su', ['-c', `${script} ${escapeArgs(args)}`, user], { cwd });
};
export const runAsync = (script: string, args: ArgsType, { cwd, env }: RunOptionsType = {}) => {
logger.info('exec', { script, args });
const childProcess = spawn(script, args, { cwd: cwd || scriptDirname, env, stdio: 'pipe' });
childProcess.stdout.on('data', data => logger.debug(data.toString()));
childProcess.stderr.on('data', data => logger.error(data.toString()));
return childProcess;
};
export const runAsyncAsUser = (script: string, args: ArgsType) =>
runAsync('su', ['-c', `${script} ${escapeArgs(args)}`, user]);
export const runPipe = (script: string, args: ArgsType, { cwd, env }: RunOptionsType = {}) => {
logger.debug('pipe', { script, args, cwd, env });
const result = spawnSync(script, args, { cwd: cwd || scriptDirname, env });
if (result.error) {
logger.error(result.error.message);
return null;
}
if (result.stderr) {
const stderr = result.stderr.toString();
if (stderr) {
logger.error(stderr, { script, args });
return null;
}
}
return result.stdout;
};
export const runPipeAsUser = (script: string, args: ArgsType) =>
runPipe('su', ['-c', `${script} ${escapeArgs(args)}`, user]);