Compare commits

...

52 Commits

Author SHA1 Message Date
cd3675280a 3.2.3 2025-02-20 12:37:11 +01:00
7c14102324 fix(core): Refactor Smartshell class for improved code clarity and performance 2025-02-20 12:37:10 +01:00
cb41dbaf1c 3.2.2 2024-12-13 19:03:51 +01:00
149eb800e7 fix(core): Fix minor code style and formatting issues 2024-12-13 19:03:50 +01:00
91e84c8422 3.2.1 2024-12-13 18:55:34 +01:00
ff26cd0678 fix(dependencies): Update @types/node dependency version 2024-12-13 18:55:34 +01:00
acdd729e06 3.2.0 2024-12-09 02:52:14 +01:00
522fbfc42c feat(SmartExecution): Add support for scheduling restarts to SmartExecution 2024-12-09 02:52:14 +01:00
b854715940 3.1.0 2024-12-09 02:39:31 +01:00
35f59054f8 feat(core): Refactor codebase and update dependencies. 2024-12-09 02:39:31 +01:00
c9a3de2207 3.0.6 2024-09-17 17:02:43 +02:00
6904097960 fix(core): Fix interactive shell execution and update dependencies 2024-09-17 17:02:42 +02:00
1474fd541f update description 2024-05-29 14:16:08 +02:00
9befccefd6 3.0.5 2024-04-18 13:42:51 +02:00
415c9de553 fix(core): update 2024-04-18 13:42:51 +02:00
980a2c9781 update tsconfig 2024-04-14 18:17:36 +02:00
c13a0f5d48 update tsconfig 2024-04-01 21:40:56 +02:00
71e239c5b1 update npmextra.json: githost 2024-04-01 19:59:36 +02:00
0d7c87051b update npmextra.json: githost 2024-03-30 21:48:37 +01:00
067f1a9c17 3.0.4 2024-03-16 11:18:53 +01:00
e7cf3bcb5e fix(core): update 2024-03-16 11:18:53 +01:00
18cfa3e16a 3.0.3 2023-06-22 14:17:50 +02:00
ea921766dc fix(core): update 2023-06-22 14:17:49 +02:00
7e6d632afb 3.0.2 2023-06-22 14:16:16 +02:00
25c61d7d7d fix(core): update 2023-06-22 14:16:16 +02:00
d84c7a16a4 3.0.1 2023-06-22 13:54:40 +02:00
c5937da870 fix(core): update 2023-06-22 13:54:39 +02:00
ec29db26ef 3.0.0 2023-06-22 11:51:45 +02:00
e4e08910c7 BREAKING CHANGE(core): switched to ES syntax and added support for interactivity 2023-06-22 11:51:44 +02:00
730a4a05a4 2.0.30 2021-11-26 15:17:52 +01:00
20a2804924 fix(core): cosmetics 2021-11-26 15:17:52 +01:00
d7247add7e 2.0.29 2021-11-07 19:18:01 +01:00
b304b01ab6 fix(core): update 2021-11-07 19:18:01 +01:00
9ba5447e72 2.0.28 2021-08-17 18:19:53 +02:00
6cb7ab8f19 fix(core): update 2021-08-17 18:19:52 +02:00
efdb80ddba 2.0.27 2021-07-26 21:24:13 +02:00
db712b2223 fix(core): update 2021-07-26 21:24:13 +02:00
0199160013 2.0.26 2020-05-22 01:23:27 +00:00
199fa19899 fix(core): update 2020-05-22 01:23:27 +00:00
23a3230f07 2.0.25 2019-08-27 20:15:23 +02:00
ad0b7ac21c fix(core): update 2019-08-27 20:15:22 +02:00
c8c0cbd47a 2.0.24 2019-08-27 19:41:25 +02:00
213dac474e fix(core): update 2019-08-27 19:41:25 +02:00
a4c188051a 2.0.23 2019-05-29 10:56:46 +02:00
62195b63d6 fix(core): update 2019-05-29 10:56:45 +02:00
16ba3803a4 2.0.22 2019-05-28 11:14:33 +02:00
613241cdcb fix(core): update 2019-05-28 11:14:32 +02:00
f5df21e144 2.0.21 2019-05-28 10:43:55 +02:00
ba8c2d06d8 fix(core): update 2019-05-28 10:43:54 +02:00
9bb0999f0e 2.0.20 2019-05-27 15:31:15 +02:00
1beb3a0bbe 2.0.19 2019-05-27 15:30:52 +02:00
c1133e9131 fix(core): update 2019-05-27 15:30:52 +02:00
24 changed files with 10497 additions and 2001 deletions

4
.gitignore vendored
View File

@ -15,8 +15,6 @@ node_modules/
# builds
dist/
dist_web/
dist_serve/
dist_ts_web/
dist_*/
# custom

View File

@ -1,125 +0,0 @@
# gitzone standard
image: hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- docker
- notpriv
snyk:
stage: security
script:
- npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
tags:
- docker
- notpriv
# ====================
# test stage
# ====================
testLTS:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testSTABLE:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
image: docker:stable
allow_failure: true
services:
- docker:stable-dind
script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SOURCE_CODE="$PWD"
--volume "$PWD":/code
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
tags:
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
script:
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

11
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

View File

@ -1,28 +0,0 @@
# @pushrocks/smartshell
shell actions designed as promises
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartshell)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartshell)
* [github.com (source mirror)](https://github.com/pushrocks/smartshell)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartshell/)
## Status for master
[![build status](https://gitlab.com/pushrocks/smartshell/badges/master/build.svg)](https://gitlab.com/pushrocks/smartshell/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartshell/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartshell/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartshell.svg)](https://www.npmjs.com/package/@pushrocks/smartshell)
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartshell/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartshell)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
## Usage
Use TypeScript for best in class instellisense.
For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
[![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://maintainedby.lossless.com)

87
changelog.md Normal file
View File

@ -0,0 +1,87 @@
# 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)
Update @types/node dependency version
- Updated @types/node dependency from version ^22.10.1 to ^22.10.2.
## 2024-12-09 - 3.2.0 - feat(SmartExecution)
Add support for scheduling restarts to SmartExecution
- Introduced the ability to handle consecutive restarts efficiently in SmartExecution.
- Ensures that multiple restart requests merge into a single additional restart request if one is already in progress.
## 2024-12-09 - 3.1.0 - feat(core)
Refactor codebase and update dependencies.
- Refactored core classes with improved structure and modularization.
- Updated tsbuild, tsrun, tapbundle, and @types/node dependencies to newer versions.
- Improved build script in package.json to use tsbuild with tsfolders.
## 2024-09-17 - 3.0.6 - fix(core)
Fix interactive shell execution and update dependencies
- Corrected the interactive shell execution logic by separating it into a dedicated method.
- Updated development dependencies for `@git.zone/tsbuild`, `@git.zone/tsrun`, `@git.zone/tstest`, `@push.rocks/tapbundle`, and `@types/node`.
- Updated runtime dependencies for `@push.rocks/smartpromise`, and `@types/which`.
- Removed legacy .gitlab-ci.yml file.
## 2024-05-29 - 3.0.5 - Documentation
update description
## 2024-04-18 - 3.0.4 to 3.0.5 - Maintenance
Bug fixes and configuration updates
- fix(core): update
- update tsconfig
- update npmextra.json: githost
## 2024-03-16 - 3.0.3 to 3.0.4 - Maintenance
Bug fixes
- fix(core): update
## 2023-06-22 - 2.0.30 to 3.0.3 - Major Update
Major changes including breaking changes, bug fixes, and improvements.
- BREAKING CHANGE(core): switched to ES syntax and added support for interactivity
- fix(core): update
## 2021-11-07 - 2.0.27 to 2.0.30 - Maintenance
Bug fixes
- fix(core): cosmetics
- fix(core): update
## 2021-08-17 - 2.0.26 to 2.0.27 - Maintenance
Bug fixes
- fix(core): update
## 2020-05-22 - 2.0.25 to 2.0.26 - Maintenance
Bug fixes
- fix(core): update
## 2019-08-27 - 2.0.22 to 2.0.25 - Maintenance
Bug fixes
- fix(core): update
## 2019-05-28 - 2.0.16 to 2.0.22 - Maintenance
Bug fixes
- fix(core): update

View File

@ -5,13 +5,28 @@
"npmRegistryUrl": "registry.npmjs.org"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartshell",
"shortDescription": "shell actions designed as promises",
"npmPackagename": "@pushrocks/smartshell",
"license": "MIT"
"description": "A library for executing shell commands using promises.",
"npmPackagename": "@push.rocks/smartshell",
"license": "MIT",
"keywords": [
"shell commands",
"promises",
"asynchronous execution",
"child processes",
"environment management",
"command streaming",
"interactive commands",
"process management",
"typescript"
]
}
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}

1616
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,41 +1,65 @@
{
"name": "@pushrocks/smartshell",
"name": "@push.rocks/smartshell",
"private": false,
"version": "2.0.18",
"description": "shell actions designed as promises",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"version": "3.2.3",
"description": "A library for executing shell commands using promises.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild)"
"build": "(tsbuild tsfolders --web)",
"buildDocs": "tsdoc"
},
"repository": {
"type": "git",
"url": "git+ssh://git@gitlab.com/pushrocks/smartshell.git"
"url": "https://code.foss.global/push.rocks/smartshell.git"
},
"keywords": [
"shell",
"promise"
"shell commands",
"promises",
"asynchronous execution",
"child processes",
"environment management",
"command streaming",
"interactive commands",
"process management",
"typescript"
],
"author": "Lossless GmbH",
"license": "MIT",
"bugs": {
"url": "https://gitlab.com/pushrocks/smartshell/issues"
},
"homepage": "https://gitlab.com/pushrocks/smartshell#README",
"homepage": "https://code.foss.global/push.rocks/smartshell",
"devDependencies": {
"@gitzone/tsbuild": "^2.1.11",
"@gitzone/tsrun": "^1.2.6",
"@gitzone/tstest": "^1.0.22",
"@pushrocks/tapbundle": "^3.0.9",
"@types/node": "^12.0.2",
"tslint": "^5.16.0",
"tslint-config-prettier": "^1.18.0"
"@git.zone/tsbuild": "^2.2.0",
"@git.zone/tsrun": "^1.3.3",
"@git.zone/tstest": "^1.0.90",
"@push.rocks/tapbundle": "^5.5.3",
"@types/node": "^22.10.2"
},
"dependencies": {
"@pushrocks/smartexit": "^1.0.11",
"@pushrocks/smartpromise": "^3.0.2",
"@types/which": "^1.3.1",
"which": "^1.3.1"
}
"@push.rocks/smartdelay": "^3.0.1",
"@push.rocks/smartexit": "^1.0.23",
"@push.rocks/smartpromise": "^4.0.4",
"@types/which": "^3.0.4",
"tree-kill": "^1.2.2",
"which": "^5.0.0"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
]
}

9839
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

152
readme.md Normal file
View File

@ -0,0 +1,152 @@
# @push.rocks/smartshell
shell actions designed as promises
## Install
To install `@push.rocks/smartshell`, use npm:
```sh
npm install @push.rocks/smartshell --save
```
Or if you prefer using Yarn:
```sh
yarn add @push.rocks/smartshell
```
Ensure that you have TypeScript and the related dependencies installed as well since `@push.rocks/smartshell` is designed to work with TypeScript.
## Usage
The `@push.rocks/smartshell` package simplifies running shell commands within Node.js applications by wrapping these commands within promises. This approach enhances the readability and maintainability of code that relies on shell execution, making it particularly useful in automation scripts, build processes, and any scenario where interaction with the system shell is required.
### Getting Started with `@push.rocks/smartshell`
First, ensure that you import `Smartshell` from `@push.rocks/smartshell` using ESM syntax in your TypeScript file:
```typescript
import { Smartshell } from '@push.rocks/smartshell';
```
### Creating a Smartshell Instance
Before executing any shell command, you need to create an instance of `Smartshell`. The constructor accepts configuration options such as the shell executor (`bash` or `sh`), and optionally, paths to source files and directories to include in the shells environment.
```typescript
const smartShellInstance = new Smartshell({
executor: 'bash', // or 'sh'
});
```
### Executing Commands
#### Basic Execution
To execute a shell command, use the `exec` method. This method returns a promise that resolves with an execution result object containing `exitCode` and `stdout`.
```typescript
(async () => {
const result = await smartShellInstance.exec('echo "Hello, SmartShell"');
console.log(result.stdout); // Outputs: Hello, SmartShell
})();
```
#### Silent Execution
If you prefer not to display the output in the console, use `execSilent`:
```typescript
(async () => {
const result = await smartShellInstance.execSilent('ls');
console.log(result.stdout); // Outputs the list of files and directories
})();
```
#### Strict Execution
For scenarios where an execution error should immediately throw an exception, use `execStrict`:
```typescript
(async () => {
try {
const result = await smartShellInstance.execStrict('exit 1');
} catch (error) {
console.error('Command execution failed');
}
})();
```
#### Streaming Output
Some commands benefit from streaming output as they execute, especially long-running tasks. For these cases, use `execStreaming`:
```typescript
(async () => {
const execStreamingResult = await smartShellInstance.execStreaming('tail -f /var/log/system.log');
execStreamingResult.childProcess.stdout.on('data', (data) => {
console.log(data.toString());
});
// Remember to handle the process termination as necessary.
})();
```
### Advanced Usage
#### Executing With Custom Environment Variables
`smartshell` allows for the execution of commands within a modified environment, facilitating the use of custom variables or altered PATH values:
```typescript
(async () => {
smartShellInstance.shellEnv.addSourceFiles(['/path/to/envFile']);
smartShellInstance.shellEnv.pathDirArray.push('/custom/bin');
const result = await smartShellInstance.exec('echo $CUSTOM_VAR');
console.log(result.stdout); // Outputs the value of CUSTOM_VAR
})();
```
### Interactive Mode
For commands that require interactive terminal input (not typically recommended for automated scripts), you can use `execInteractive`:
```typescript
(async () => {
await smartShellInstance.execInteractive('npm init');
})();
```
### Waiting for Specific Output
To wait for a specific line before proceeding, you might use `execAndWaitForLine`. This is useful for waiting on a process to log a certain message:
```typescript
(async () => {
await smartShellInstance.execAndWaitForLine('npm run watch', /Compilation complete./);
console.log('The watch process has finished compiling.');
})();
```
Given the vast array of features offered by `@push.rocks/smartshell`, integrating shell operations into your TypeScript applications becomes both straightforward and powerful. By harnessing promises and async/await syntax, `smartshell` effectively streamlines shell interactions, making your code cleaner and more intuitive.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -1,36 +1,36 @@
import { expect, tap } from '@pushrocks/tapbundle';
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartshell from '../ts';
import * as smartpromise from '@pushrocks/smartpromise';
import * as smartshell from '../ts/index.js';
import * as smartpromise from '@push.rocks/smartpromise';
let testSmartshell: smartshell.Smartshell;
tap.test('smartshell should create a Smartshell instance', async () => {
testSmartshell = new smartshell.Smartshell({
executor: 'bash',
sourceFilePaths: []
sourceFilePaths: [],
});
expect(testSmartshell).to.be.instanceof(smartshell.Smartshell);
expect(testSmartshell).toBeInstanceOf(smartshell.Smartshell);
});
tap.test('smartshell should run async', async () => {
let execResult = await testSmartshell.exec('npm -v');
expect(execResult.stdout).to.match(/[0-9\.]*/);
expect(execResult.stdout).toMatch(/[0-9\.]*/);
});
tap.test('smartshell should run async and silent', async () => {
let execResult = await testSmartshell.execSilent('npm -v');
expect(execResult.stdout).to.match(/[0-9\.]*/);
expect(execResult.stdout).toMatch(/[0-9\.]*/);
});
tap.test('smartshell should stream a shell execution', async () => {
let done = smartpromise.defer();
let execStreamingResponse = await testSmartshell.execStreaming('npm -v');
execStreamingResponse.childProcess.stdout.on('data', data => {
execStreamingResponse.childProcess.stdout.on('data', (data) => {
done.resolve(data);
});
let data = await done.promise;
expect(data).to.match(/[0-9\.]*/);
expect(data).toMatch(/[0-9\.]*/);
await execStreamingResponse.finalPromise;
});
@ -39,15 +39,19 @@ tap.test('it should execute and wait for a line in the output', async () => {
});
tap.test('smartshell should run async', async () => {
return testSmartshell.execSilent('sleep 1 && npm -v').then(async execResult => {
return testSmartshell.execSilent('sleep 1 && npm -v').then(async (execResult) => {
console.log(execResult.stdout);
});
});
tap.test('should be able to find git', async () => {
testSmartshell.exec('git --version');
await testSmartshell.exec('git --version');
});
tap.test('should spawn an interactive cli', async () => {
await testSmartshell.execInteractive('echo "hi"');
});
tap.start({
throwOnError: true
throwOnError: true,
});

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartshell',
version: '3.2.3',
description: 'A library for executing shell commands using promises.'
}

View File

@ -31,7 +31,7 @@ export class ShellEnv {
/**
* imports path into the shell from env if available and returns it with
*/
private _setPath(commandStringArg): string {
private _setPath(commandStringArg: string): string {
let commandResult = commandStringArg;
let commandPaths: string[] = [];
commandPaths = commandPaths.concat(process.env.PATH.split(':'));
@ -41,7 +41,7 @@ export class ShellEnv {
// lets filter for unwanted paths
// Windows WSL
commandPaths = commandPaths.filter(commandPathArg => {
commandPaths = commandPaths.filter((commandPathArg) => {
const filterResult =
!commandPathArg.startsWith('/mnt/c/') &&
!commandPathArg.startsWith('Files/1E') &&
@ -82,7 +82,7 @@ export class ShellEnv {
sourceString = sourceString + `source ${sourceFilePath} && `;
}
// deal with avaiable path
// deal with available path
let pathString = 'PATH=$PATH';
for (const pathDir of this.pathDirArray) {
pathString += `:${pathDir}`;

View File

@ -1,17 +1,17 @@
import * as plugins from './smartshell.plugins';
import * as plugins from './plugins.js';
/**
* a log handler for spawned logs
* making sure the process doesn't run out of memory
*/
export class ShellLog {
logStore = Buffer.from('');
public logStore = Buffer.from('');
/**
* log data to console
* @param dataArg
*/
logToConsole(dataArg: string | Buffer): void {
public writeToConsole(dataArg: string | Buffer): void {
// make sure we have the data as string
process.stdout.write(dataArg);
}
@ -20,7 +20,7 @@ export class ShellLog {
* add data to Buffer for later consumption
* @param dataArg
*/
addToBuffer(dataArg: string | Buffer): void {
public addToBuffer(dataArg: string | Buffer): void {
// make sure we have the data as Buffer
const dataBuffer: Buffer = (() => {
if (!Buffer.isBuffer(dataArg)) {
@ -31,8 +31,8 @@ export class ShellLog {
this.logStore = Buffer.concat([this.logStore, dataBuffer]);
}
logAndAdd(dataArg: string | Buffer): void {
this.logToConsole(dataArg);
public logAndAdd(dataArg: string | Buffer): void {
this.writeToConsole(dataArg);
this.addToBuffer(dataArg);
}
}

View File

@ -0,0 +1,55 @@
import * as plugins from './plugins.js';
import { Smartshell, type IExecResultStreaming } from './classes.smartshell.js';
export interface IDeferred<T> {
resolve: (value?: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
promise: Promise<T>;
}
export class SmartExecution {
public smartshell: Smartshell;
public currentStreamingExecution: IExecResultStreaming;
public commandString: string;
private isRestartInProgress = false;
private isAnotherRestartRequested = false;
constructor(commandStringArg: string) {
this.commandString = commandStringArg;
}
/**
* Schedules a restart. If a restart is currently in progress, any additional calls
* to restart will merge into a single additional restart request, which will only execute
* once the current restart completes.
*/
public async restart(): Promise<void> {
if (this.isRestartInProgress) {
// If there's already a restart in progress, just mark that another restart was requested
this.isAnotherRestartRequested = true;
return;
}
this.isRestartInProgress = true;
try {
if (!this.smartshell) {
this.smartshell = new Smartshell({
executor: 'bash',
});
}
if (this.currentStreamingExecution) {
await this.currentStreamingExecution.kill();
}
this.currentStreamingExecution = await this.smartshell.execStreaming(this.commandString);
} finally {
this.isRestartInProgress = false;
}
// If another restart was requested while we were busy, we handle it now
if (this.isAnotherRestartRequested) {
this.isAnotherRestartRequested = false;
await this.restart();
}
}
}

203
ts/classes.smartshell.ts Normal file
View File

@ -0,0 +1,203 @@
import * as plugins from './plugins.js';
import { ShellEnv } from './classes.shellenv.js';
import type { IShellEnvContructorOptions, TExecutor } from './classes.shellenv.js';
import { ShellLog } from './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: (signal: plugins.smartexit.TProcessSignal) => Promise<void>;
}
interface IExecOptions {
commandString: string;
silent?: boolean;
strict?: boolean;
streaming?: boolean;
interactive?: boolean;
}
export class Smartshell {
public shellEnv: ShellEnv;
public smartexit = new plugins.smartexit.SmartExit();
constructor(optionsArg: IShellEnvContructorOptions) {
this.shellEnv = new ShellEnv(optionsArg);
}
/**
* Executes a given command asynchronously.
*/
private async _exec(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | void> {
if (options.interactive) {
return await this._execInteractive({ commandString: options.commandString });
}
return await this._execCommand(options);
}
/**
* Executes an interactive command.
*/
private async _execInteractive(options: Pick<IExecOptions, 'commandString'>): Promise<void> {
// Skip interactive execution in CI environments.
if (process.env.CI) {
return;
}
return new Promise<void>((resolve) => {
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);
resolve();
});
});
}
/**
* Executes a command and returns either a non-streaming result or a streaming interface.
*/
private async _execCommand(options: IExecOptions): Promise<IExecResult | IExecResultStreaming> {
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);
// Capture stdout and stderr output.
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);
});
// Wrap child process termination into a Promise.
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
execChildProcess.on('exit', (code, signal) => {
this.smartexit.removeProcess(execChildProcess);
const execResult: IExecResult = {
exitCode: typeof code === 'number' ? code : (signal ? 1 : 0),
stdout: shellLogInstance.logStore.toString(),
};
if (options.strict && code !== 0) {
reject(new Error(`Command "${options.commandString}" exited with code ${code}`));
} else {
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) {
return {
childProcess: execChildProcess,
finalPromise: childProcessEnded,
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 (signal: plugins.smartexit.TProcessSignal) => {
console.log(`Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signal);
},
} as IExecResultStreaming;
}
// For non-streaming mode, wait for the process to complete.
return await childProcessEnded;
}
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): Promise<void> {
await this._exec({ commandString, interactive: true });
}
public async execAndWaitForLine(
commandString: string,
regex: RegExp,
silent: boolean = false
): Promise<void> {
const execStreamingResult = await this.execStreaming(commandString, silent);
return new Promise<void>((resolve) => {
execStreamingResult.childProcess.stdout.on('data', (chunk: Buffer | string) => {
const data = typeof chunk === 'string' ? chunk : chunk.toString();
if (regex.test(data)) {
resolve();
}
});
});
}
public async execAndWaitForLineSilent(commandString: string, regex: RegExp): Promise<void> {
return this.execAndWaitForLine(commandString, regex, true);
}
}

View File

@ -1 +1,3 @@
export * from './smartshell.classes.smartshell';
export * from './classes.smartshell.js';
export * from './classes.smartexecution.js';
export { which } from './plugins.js';

6
ts/plugins.ts Normal file
View File

@ -0,0 +1,6 @@
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartexit from '@push.rocks/smartexit';
import * as smartpromise from '@push.rocks/smartpromise';
import which from 'which';
export { smartdelay, smartexit, smartpromise, which };

View File

@ -1,158 +0,0 @@
// -- imports --
import * as plugins from './smartshell.plugins';
import { ShellEnv, IShellEnvContructorOptions, TExecutor } from './smartshell.classes.shellenv';
import { ShellLog } from './smartshell.classes.shelllog';
import * as cp from 'child_process';
import { Deferred } from '@pushrocks/smartpromise';
// -- interfaces --
/**
* interface for ExecResult
*/
export interface IExecResult {
exitCode: number;
stdout: string;
}
/**
* interface for streaming ExecResult
*/
export interface IExecResultStreaming {
childProcess: cp.ChildProcess;
finalPromise: Promise<IExecResult>;
kill: () => void;
}
// -- SmartShell --
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
* @param commandStringArg
*/
private async _exec(
commandStringArg: string,
silentArg: boolean = false,
strictArg = false,
streamingArg = false
): Promise<IExecResult | IExecResultStreaming> {
// flow control promises
const done = plugins.smartpromise.defer<IExecResult | IExecResultStreaming>();
const childProcessEnded = plugins.smartpromise.defer<IExecResult>();
// build commandToExecute
let commandToExecute = commandStringArg;
commandToExecute = this.shellEnv.createEnvExecString(commandStringArg);
const spawnlogInstance = new ShellLog();
const execChildProcess = cp.spawn(commandToExecute, [], {
shell: true,
env: process.env,
detached: true
});
this.smartexit.addProcess(execChildProcess);
execChildProcess.stdout.on('data', data => {
if (!silentArg) {
spawnlogInstance.logToConsole(data);
}
spawnlogInstance.addToBuffer(data);
});
execChildProcess.stderr.on('data', data => {
if (!silentArg) {
spawnlogInstance.logToConsole(data);
}
spawnlogInstance.addToBuffer(data);
});
if (streamingArg) {
done.resolve({
childProcess: execChildProcess,
finalPromise: childProcessEnded.promise,
kill: () => {
// this notation with the - kills the whole process group
process.kill(-execChildProcess.pid);
}
});
}
execChildProcess.on('exit', (code, signal) => {
this.smartexit.removeProcess(execChildProcess);
if (strictArg && code === 1) {
done.reject();
}
const execResult = {
exitCode: code,
stdout: spawnlogInstance.logStore.toString()
};
if (!streamingArg) {
done.resolve(execResult);
}
childProcessEnded.resolve(execResult);
});
const result = await done.promise;
return result;
}
async exec(commandStringArg: string): Promise<IExecResult> {
return (await this._exec(commandStringArg, false)) as IExecResult;
}
/**
* executes a given command async and silent
* @param commandStringArg
*/
async execSilent(commandStringArg: string): Promise<IExecResult> {
return (await this._exec(commandStringArg, true)) as IExecResult;
}
/**
* executes a command async and strict, meaning it rejects the promise if something happens
*/
async execStrict(commandStringArg: string): Promise<IExecResult> {
return (await this._exec(commandStringArg, true, true)) as IExecResult;
}
/**
* executes a command and allows you to stream output
*/
async execStreaming(
commandStringArg: string,
silentArg: boolean = false
): Promise<IExecResultStreaming> {
return (await this._exec(commandStringArg, silentArg, false, true)) as IExecResultStreaming;
}
async execStreamingSilent(commandStringArg: string) {
return (await this.execStreaming(commandStringArg, true)) as IExecResultStreaming;
}
/**
* executes a command and returns promise that will be fullfilled once an putput line matches RegexArg
* @param commandStringArg
* @param regexArg
*/
async execAndWaitForLine(commandStringArg: string, regexArg: RegExp, silentArg: boolean = false) {
let done = plugins.smartpromise.defer();
let execStreamingResult = await this.execStreaming(commandStringArg, silentArg);
execStreamingResult.childProcess.stdout.on('data', (stdOutChunk: string) => {
if (regexArg.test(stdOutChunk)) {
done.resolve();
}
});
return done.promise;
}
async execAndWaitForLineSilent(commandStringArg: string, regexArg: RegExp) {
this.execAndWaitForLine(commandStringArg, regexArg, true);
}
}

View File

@ -1,5 +0,0 @@
import * as smartexit from '@pushrocks/smartexit';
import * as smartpromise from '@pushrocks/smartpromise';
import * as which from 'which';
export { smartexit, smartpromise, which };

14
tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}