Compare commits

..

No commits in common. "master" and "v3.2.1" have entirely different histories.

4 changed files with 89 additions and 99 deletions

View File

@ -1,18 +1,5 @@
# Changelog # Changelog
## 2025-02-20 - 3.2.3 - fix(core)
Refactor Smartshell class for improved code clarity and performance
- Refactored `_exec` method to improve code clarity.
- Introduced `IExecOptions` interface for better type handling.
- Replaced promise defer with native promises in command execution methods.
- Improved logging and error handling in child process execution.
- Ensured robust process management with signals handling.
## 2024-12-13 - 3.2.2 - fix(core)
Fix minor code style and formatting issues
## 2024-12-13 - 3.2.1 - fix(dependencies) ## 2024-12-13 - 3.2.1 - fix(dependencies)
Update @types/node dependency version Update @types/node dependency version

View File

@ -1,7 +1,7 @@
{ {
"name": "@push.rocks/smartshell", "name": "@push.rocks/smartshell",
"private": false, "private": false,
"version": "3.2.3", "version": "3.2.1",
"description": "A library for executing shell commands using promises.", "description": "A library for executing shell commands using promises.",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartshell', name: '@push.rocks/smartshell',
version: '3.2.3', version: '3.2.1',
description: 'A library for executing shell commands using promises.' description: 'A library for executing shell commands using promises.'
} }

View File

@ -2,6 +2,7 @@ import * as plugins from './plugins.js';
import { ShellEnv } from './classes.shellenv.js'; import { ShellEnv } from './classes.shellenv.js';
import type { IShellEnvContructorOptions, TExecutor } from './classes.shellenv.js'; import type { IShellEnvContructorOptions, TExecutor } from './classes.shellenv.js';
import { ShellLog } from './classes.shelllog.js'; import { ShellLog } from './classes.shelllog.js';
import * as cp from 'child_process'; import * as cp from 'child_process';
// -- interfaces -- // -- interfaces --
@ -16,15 +17,7 @@ export interface IExecResultStreaming {
kill: () => Promise<void>; kill: () => Promise<void>;
terminate: () => Promise<void>; terminate: () => Promise<void>;
keyboardInterrupt: () => Promise<void>; keyboardInterrupt: () => Promise<void>;
customSignal: (signal: plugins.smartexit.TProcessSignal) => Promise<void>; customSignal: (signalArg: plugins.smartexit.TProcessSignal) => Promise<void>;
}
interface IExecOptions {
commandString: string;
silent?: boolean;
strict?: boolean;
streaming?: boolean;
interactive?: boolean;
} }
export class Smartshell { export class Smartshell {
@ -36,48 +29,61 @@ export class Smartshell {
} }
/** /**
* Executes a given command asynchronously. * executes a given command async
*/ */
private async _exec(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | void> { private async _exec(options: {
commandString: string;
silent?: boolean;
strict?: boolean;
streaming?: boolean;
interactive?: boolean;
}): Promise<IExecResult | IExecResultStreaming | void> {
if (options.interactive) { if (options.interactive) {
return await this._execInteractive({ commandString: options.commandString }); return await this._execInteractive(options);
} }
return await this._execCommand(options); return await this._execCommand(options);
} }
/** private async _execInteractive(options: {
* Executes an interactive command. commandString: string;
*/ interactive?: boolean;
private async _execInteractive(options: Pick<IExecOptions, 'commandString'>): Promise<void> { }): Promise<void> {
// Skip interactive execution in CI environments.
if (process.env.CI) { if (process.env.CI) {
return; return;
} }
return new Promise<void>((resolve) => { const done = plugins.smartpromise.defer();
const shell = cp.spawn(options.commandString, {
stdio: 'inherit',
shell: true,
detached: true,
});
this.smartexit.addProcess(shell); const shell = cp.spawn(options.commandString, {
stdio: 'inherit',
shell.on('close', (code) => { shell: true,
console.log(`Interactive shell terminated with code ${code}`); detached: true
this.smartexit.removeProcess(shell);
resolve();
});
}); });
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: {
* Executes a command and returns either a non-streaming result or a streaming interface. commandString: string;
*/ silent?: boolean;
private async _execCommand(options: IExecOptions): Promise<IExecResult | IExecResultStreaming> { strict?: boolean;
const commandToExecute = this.shellEnv.createEnvExecString(options.commandString); streaming?: boolean;
const shellLogInstance = new ShellLog(); }): 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, [], { const execChildProcess = cp.spawn(commandToExecute, [], {
shell: true, shell: true,
cwd: process.cwd(), cwd: process.cwd(),
@ -87,7 +93,6 @@ export class Smartshell {
this.smartexit.addProcess(execChildProcess); this.smartexit.addProcess(execChildProcess);
// Capture stdout and stderr output.
execChildProcess.stdout.on('data', (data) => { execChildProcess.stdout.on('data', (data) => {
if (!options.silent) { if (!options.silent) {
shellLogInstance.writeToConsole(data); shellLogInstance.writeToConsole(data);
@ -102,55 +107,47 @@ export class Smartshell {
shellLogInstance.addToBuffer(data); shellLogInstance.addToBuffer(data);
}); });
// Wrap child process termination into a Promise. execChildProcess.on('exit', (code, signal) => {
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => { this.smartexit.removeProcess(execChildProcess);
execChildProcess.on('exit', (code, signal) => { if (options.strict && code === 1) {
this.smartexit.removeProcess(execChildProcess); done.reject();
}
const execResult: IExecResult = { const execResult = {
exitCode: typeof code === 'number' ? code : (signal ? 1 : 0), exitCode: code,
stdout: shellLogInstance.logStore.toString(), stdout: shellLogInstance.logStore.toString(),
}; };
if (options.strict && code !== 0) { if (!options.streaming) {
reject(new Error(`Command "${options.commandString}" exited with code ${code}`)); done.resolve(execResult);
} else { }
resolve(execResult); childProcessEnded.resolve(execResult);
}
});
execChildProcess.on('error', (error) => {
this.smartexit.removeProcess(execChildProcess);
reject(error);
});
}); });
// If streaming mode is enabled, return a streaming interface immediately.
if (options.streaming) { if (options.streaming) {
return { done.resolve({
childProcess: execChildProcess, childProcess: execChildProcess,
finalPromise: childProcessEnded, finalPromise: childProcessEnded.promise,
kill: async () => { kill: async () => {
console.log(`Running tree kill with SIGKILL on process ${execChildProcess.pid}`); console.log(`running tree kill with SIGKILL on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL'); await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
}, },
terminate: async () => { terminate: async () => {
console.log(`Running tree kill with SIGTERM on process ${execChildProcess.pid}`); console.log(`running tree kill with SIGTERM on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM'); await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
}, },
keyboardInterrupt: async () => { keyboardInterrupt: async () => {
console.log(`Running tree kill with SIGINT on process ${execChildProcess.pid}`); console.log(`running tree kill with SIGINT on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT'); await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
}, },
customSignal: async (signal: plugins.smartexit.TProcessSignal) => { customSignal: async (signalArg: plugins.smartexit.TProcessSignal) => {
console.log(`Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`); console.log(`running tree kill with custom signal ${signalArg} on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signal); await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signalArg);
}, },
} as IExecResultStreaming; });
} }
// For non-streaming mode, wait for the process to complete. return await done.promise;
return await childProcessEnded;
} }
public async exec(commandString: string): Promise<IExecResult> { public async exec(commandString: string): Promise<IExecResult> {
@ -169,35 +166,41 @@ export class Smartshell {
return (await this._exec({ commandString, silent: true, strict: true })) as IExecResult; return (await this._exec({ commandString, silent: true, strict: true })) as IExecResult;
} }
public async execStreaming(commandString: string, silent: boolean = false): Promise<IExecResultStreaming> { public async execStreaming(
commandString: string,
silent: boolean = false
): Promise<IExecResultStreaming> {
return (await this._exec({ commandString, silent, streaming: true })) as IExecResultStreaming; return (await this._exec({ commandString, silent, streaming: true })) as IExecResultStreaming;
} }
public async execStreamingSilent(commandString: string): Promise<IExecResultStreaming> { public async execStreamingSilent(commandString: string): Promise<IExecResultStreaming> {
return (await this._exec({ commandString, silent: true, streaming: true })) as IExecResultStreaming; return (await this._exec({
commandString,
silent: true,
streaming: true,
})) as IExecResultStreaming;
} }
public async execInteractive(commandString: string): Promise<void> { public async execInteractive(commandString: string) {
await this._exec({ commandString, interactive: true }); await this._exec({ commandString, interactive: true });
} }
public async execAndWaitForLine( public async execAndWaitForLine(
commandString: string, commandString: string,
regex: RegExp, regexArg: RegExp,
silent: boolean = false silentArg: boolean = false
): Promise<void> { ) {
const execStreamingResult = await this.execStreaming(commandString, silent); let done = plugins.smartpromise.defer();
return new Promise<void>((resolve) => { let execStreamingResult = await this.execStreaming(commandString, silentArg);
execStreamingResult.childProcess.stdout.on('data', (chunk: Buffer | string) => { execStreamingResult.childProcess.stdout.on('data', (stdOutChunk: string) => {
const data = typeof chunk === 'string' ? chunk : chunk.toString(); if (regexArg.test(stdOutChunk)) {
if (regex.test(data)) { done.resolve();
resolve(); }
}
});
}); });
return done.promise;
} }
public async execAndWaitForLineSilent(commandString: string, regex: RegExp): Promise<void> { public async execAndWaitForLineSilent(commandString: string, regexArg: RegExp) {
return this.execAndWaitForLine(commandString, regex, true); return this.execAndWaitForLine(commandString, regexArg, true);
} }
} }