smartshell/ts/smartshell.classes.smartshell.ts

206 lines
6.2 KiB
TypeScript

import * as plugins from './smartshell.plugins.js';
import { ShellEnv } from './smartshell.classes.shellenv.js';
import type { IShellEnvContructorOptions, TExecutor } from './smartshell.classes.shellenv.js';
import { ShellLog } from './smartshell.classes.shelllog.js';
import * as cp from 'child_process';
// -- interfaces --
export interface IExecResult {
exitCode: number;
stdout: string;
}
export interface IExecResultStreaming {
childProcess: cp.ChildProcess;
finalPromise: Promise<IExecResult>;
kill: () => Promise<void>;
terminate: () => Promise<void>;
keyboardInterrupt: () => Promise<void>;
customSignal: (signalArg: plugins.smartexit.TProcessSignal) => Promise<void>;
}
export class Smartshell {
public shellEnv: ShellEnv;
public smartexit = new plugins.smartexit.SmartExit();
constructor(optionsArg: IShellEnvContructorOptions) {
this.shellEnv = new ShellEnv(optionsArg);
}
/**
* executes a given command async
*/
private async _exec(options: {
commandString: string;
silent?: boolean;
strict?: boolean;
streaming?: boolean;
interactive?: boolean;
}): Promise<IExecResult | IExecResultStreaming | void> {
if (options.interactive) {
return await this._execInteractive(options);
}
return await this._execCommand(options);
}
private async _execInteractive(options: {
commandString: string;
interactive?: boolean;
}): Promise<void> {
if (process.env.CI) {
return;
}
const done = plugins.smartpromise.defer();
const shell = cp.spawn(options.commandString, {
stdio: 'inherit',
shell: true,
detached: true
});
this.smartexit.addProcess(shell);
shell.on('close', (code) => {
console.log(`interactive shell terminated with code ${code}`);
this.smartexit.removeProcess(shell);
done.resolve();
});
await done.promise;
}
private async _execCommand(options: {
commandString: string;
silent?: boolean;
strict?: boolean;
streaming?: boolean;
}): Promise<IExecResult | IExecResultStreaming> {
const done = plugins.smartpromise.defer<IExecResult | IExecResultStreaming>();
const childProcessEnded = plugins.smartpromise.defer<IExecResult>();
const commandToExecute = this.shellEnv.createEnvExecString(options.commandString);
const shellLogInstance = new ShellLog();
const execChildProcess = cp.spawn(commandToExecute, [], {
shell: true,
cwd: process.cwd(),
env: process.env,
detached: false,
});
this.smartexit.addProcess(execChildProcess);
execChildProcess.stdout.on('data', (data) => {
if (!options.silent) {
shellLogInstance.writeToConsole(data);
}
shellLogInstance.addToBuffer(data);
});
execChildProcess.stderr.on('data', (data) => {
if (!options.silent) {
shellLogInstance.writeToConsole(data);
}
shellLogInstance.addToBuffer(data);
});
execChildProcess.on('exit', (code, signal) => {
this.smartexit.removeProcess(execChildProcess);
if (options.strict && code === 1) {
done.reject();
}
const execResult = {
exitCode: code,
stdout: shellLogInstance.logStore.toString(),
};
if (!options.streaming) {
done.resolve(execResult);
}
childProcessEnded.resolve(execResult);
});
if (options.streaming) {
done.resolve({
childProcess: execChildProcess,
finalPromise: childProcessEnded.promise,
kill: async () => {
console.log(`running tree kill with SIGKILL on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
},
terminate: async () => {
console.log(`running tree kill with SIGTERM on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
},
keyboardInterrupt: async () => {
console.log(`running tree kill with SIGINT on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
},
customSignal: async (signalArg: plugins.smartexit.TProcessSignal) => {
console.log(`running tree kill with custom signal ${signalArg} on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signalArg);
},
});
}
return await done.promise;
}
public async exec(commandString: string): Promise<IExecResult> {
return (await this._exec({ commandString })) as IExecResult;
}
public async execSilent(commandString: string): Promise<IExecResult> {
return (await this._exec({ commandString, silent: true })) as IExecResult;
}
public async execStrict(commandString: string): Promise<IExecResult> {
return (await this._exec({ commandString, strict: true })) as IExecResult;
}
public async execStrictSilent(commandString: string): Promise<IExecResult> {
return (await this._exec({ commandString, silent: true, strict: true })) as IExecResult;
}
public async execStreaming(
commandString: string,
silent: boolean = false
): Promise<IExecResultStreaming> {
return (await this._exec({ commandString, silent, streaming: true })) as IExecResultStreaming;
}
public async execStreamingSilent(commandString: string): Promise<IExecResultStreaming> {
return (await this._exec({
commandString,
silent: true,
streaming: true,
})) as IExecResultStreaming;
}
public async execInteractive(commandString: string) {
await this._exec({ commandString, interactive: true });
}
public async execAndWaitForLine(
commandString: string,
regexArg: RegExp,
silentArg: boolean = false
) {
let done = plugins.smartpromise.defer();
let execStreamingResult = await this.execStreaming(commandString, silentArg);
execStreamingResult.childProcess.stdout.on('data', (stdOutChunk: string) => {
if (regexArg.test(stdOutChunk)) {
done.resolve();
}
});
return done.promise;
}
public async execAndWaitForLineSilent(commandString: string, regexArg: RegExp) {
return this.execAndWaitForLine(commandString, regexArg, true);
}
}