Compare commits
54 Commits
Author | SHA1 | Date | |
---|---|---|---|
9befccefd6 | |||
415c9de553 | |||
980a2c9781 | |||
c13a0f5d48 | |||
71e239c5b1 | |||
0d7c87051b | |||
067f1a9c17 | |||
e7cf3bcb5e | |||
18cfa3e16a | |||
ea921766dc | |||
7e6d632afb | |||
25c61d7d7d | |||
d84c7a16a4 | |||
c5937da870 | |||
ec29db26ef | |||
e4e08910c7 | |||
730a4a05a4 | |||
20a2804924 | |||
d7247add7e | |||
b304b01ab6 | |||
9ba5447e72 | |||
6cb7ab8f19 | |||
efdb80ddba | |||
db712b2223 | |||
0199160013 | |||
199fa19899 | |||
23a3230f07 | |||
ad0b7ac21c | |||
c8c0cbd47a | |||
213dac474e | |||
a4c188051a | |||
62195b63d6 | |||
16ba3803a4 | |||
613241cdcb | |||
f5df21e144 | |||
ba8c2d06d8 | |||
9bb0999f0e | |||
1beb3a0bbe | |||
c1133e9131 | |||
48dd3c3cca | |||
f0a5be41ea | |||
970d28a4ad | |||
76f2126eb3 | |||
a6f164602c | |||
f8457ad58d | |||
8ceac74a1f | |||
f63c4456bf | |||
32c33cad5b | |||
0758e58fa4 | |||
e981ca6bdd | |||
2853a48708 | |||
389f8f4a52 | |||
c1a537f052 | |||
4701341c0c |
20
.gitignore
vendored
20
.gitignore
vendored
@ -1,4 +1,20 @@
|
||||
.nogit/
|
||||
|
||||
# artifacts
|
||||
coverage/
|
||||
node_modules/
|
||||
pages/
|
||||
public/
|
||||
pages/
|
||||
|
||||
# installs
|
||||
node_modules/
|
||||
|
||||
# caches
|
||||
.yarn/
|
||||
.cache/
|
||||
.rpt2_cache
|
||||
|
||||
# builds
|
||||
dist/
|
||||
dist_*/
|
||||
|
||||
# custom
|
125
.gitlab-ci.yml
125
.gitlab-ci.yml
@ -1,119 +1,122 @@
|
||||
# gitzone standard
|
||||
image: hosttoday/ht-docker-node:npmci
|
||||
# gitzone ci_default
|
||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
|
||||
cache:
|
||||
paths:
|
||||
- .npmci_cache/
|
||||
key: "$CI_BUILD_STAGE"
|
||||
- .npmci_cache/
|
||||
key: '$CI_BUILD_STAGE'
|
||||
|
||||
stages:
|
||||
- security
|
||||
- test
|
||||
- release
|
||||
- metadata
|
||||
- security
|
||||
- test
|
||||
- release
|
||||
- metadata
|
||||
|
||||
before_script:
|
||||
- pnpm install -g pnpm
|
||||
- pnpm install -g @shipzone/npmci
|
||||
- npmci npm prepare
|
||||
|
||||
# ====================
|
||||
# security stage
|
||||
# ====================
|
||||
mirror:
|
||||
# ====================
|
||||
# security stage
|
||||
# ====================
|
||||
auditProductionDependencies:
|
||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
stage: security
|
||||
script:
|
||||
- npmci git mirror
|
||||
- npmci command npm config set registry https://registry.npmjs.org
|
||||
- npmci command pnpm audit --audit-level=high --prod
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
- lossless
|
||||
- docker
|
||||
allow_failure: true
|
||||
|
||||
snyk:
|
||||
auditDevDependencies:
|
||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
stage: security
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci command npm install -g snyk
|
||||
- npmci command npm install --ignore-scripts
|
||||
- npmci command snyk test
|
||||
- npmci command npm config set registry https://registry.npmjs.org
|
||||
- npmci command pnpm audit --audit-level=high --dev
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
- lossless
|
||||
- docker
|
||||
allow_failure: true
|
||||
|
||||
# ====================
|
||||
# test stage
|
||||
# ====================
|
||||
|
||||
testLTS:
|
||||
testStable:
|
||||
stage: test
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci node install lts
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
testSTABLE:
|
||||
- docker
|
||||
|
||||
testBuild:
|
||||
stage: test
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci npm build
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
- docker
|
||||
|
||||
release:
|
||||
stage: release
|
||||
script:
|
||||
- npmci node install stable
|
||||
- npmci npm publish
|
||||
- npmci node install stable
|
||||
- npmci npm publish
|
||||
only:
|
||||
- tags
|
||||
- tags
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
# ====================
|
||||
# metadata stage
|
||||
# ====================
|
||||
codequality:
|
||||
stage: metadata
|
||||
image: docker:stable
|
||||
allow_failure: true
|
||||
services:
|
||||
- docker:stable-dind
|
||||
only:
|
||||
- tags
|
||||
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]
|
||||
- npmci command npm install -g typescript
|
||||
- npmci npm prepare
|
||||
- npmci npm install
|
||||
tags:
|
||||
- docker
|
||||
- priv
|
||||
- lossless
|
||||
- docker
|
||||
- priv
|
||||
|
||||
trigger:
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci trigger
|
||||
- npmci trigger
|
||||
only:
|
||||
- tags
|
||||
- tags
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
pages:
|
||||
image: hosttoday/ht-docker-node:npmci
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci command npm install -g typedoc typescript
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
|
||||
- npmci command npm run buildDocs
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
only:
|
||||
@ -121,5 +124,5 @@ pages:
|
||||
artifacts:
|
||||
expire_in: 1 week
|
||||
paths:
|
||||
- public
|
||||
- public
|
||||
allow_failure: true
|
||||
|
11
.vscode/launch.json
vendored
Normal file
11
.vscode/launch.json
vendored
Normal 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
26
.vscode/settings.json
vendored
Normal 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"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
32
README.md
32
README.md
@ -1,32 +0,0 @@
|
||||
# smartshell
|
||||
|
||||
shell actions designed as promises
|
||||
|
||||
## Availabililty
|
||||
|
||||
[](https://www.npmjs.com/package/smartshell)
|
||||
[](https://GitLab.com/pushrocks/smartshell)
|
||||
[](https://github.com/pushrocks/smartshell)
|
||||
[](https://pushrocks.gitlab.io/smartshell/)
|
||||
|
||||
## Status for master
|
||||
|
||||
[](https://GitLab.com/pushrocks/smartshell/commits/master)
|
||||
[](https://GitLab.com/pushrocks/smartshell/commits/master)
|
||||
[](https://www.npmjs.com/package/smartshell)
|
||||
[](https://david-dm.org/pushrocks/smartshell)
|
||||
[](https://www.bithound.io/github/pushrocks/smartshell/master/dependencies/npm)
|
||||
[](https://www.bithound.io/github/pushrocks/smartshell)
|
||||
[](https://nodejs.org/dist/latest-v6.x/docs/api/)
|
||||
[](https://nodejs.org/dist/latest-v6.x/docs/api/)
|
||||
[](http://standardjs.com/)
|
||||
|
||||
## 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)
|
||||
|
||||
[](https://push.rocks)
|
@ -1,6 +1,32 @@
|
||||
{
|
||||
"npmci": {
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
"npmAccessLevel": "public",
|
||||
"npmRegistryUrl": "registry.npmjs.org"
|
||||
},
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "push.rocks",
|
||||
"gitrepo": "smartshell",
|
||||
"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"
|
||||
}
|
||||
}
|
1052
package-lock.json
generated
1052
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
63
package.json
63
package.json
@ -1,21 +1,30 @@
|
||||
{
|
||||
"name": "@pushrocks/smartshell",
|
||||
"name": "@push.rocks/smartshell",
|
||||
"private": false,
|
||||
"version": "2.0.11",
|
||||
"description": "shell actions designed as promises",
|
||||
"main": "dist/index.js",
|
||||
"typings": "dist/index.d.ts",
|
||||
"version": "3.0.5",
|
||||
"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 --web)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@gitlab.com/pushrocks/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",
|
||||
@ -24,17 +33,33 @@
|
||||
},
|
||||
"homepage": "https://gitlab.com/pushrocks/smartshell#README",
|
||||
"devDependencies": {
|
||||
"@gitzone/tsbuild": "^2.0.22",
|
||||
"@gitzone/tsrun": "^1.1.13",
|
||||
"@gitzone/tstest": "^1.0.15",
|
||||
"@pushrocks/tapbundle": "^3.0.7",
|
||||
"@types/node": "^10.12.10",
|
||||
"tslint": "^5.11.0",
|
||||
"tslint-config-prettier": "^1.16.0"
|
||||
"@git.zone/tsbuild": "^2.1.66",
|
||||
"@git.zone/tsrun": "^1.2.44",
|
||||
"@git.zone/tstest": "^1.0.77",
|
||||
"@push.rocks/tapbundle": "^5.0.23",
|
||||
"@types/node": "^20.12.7"
|
||||
},
|
||||
"dependencies": {
|
||||
"@pushrocks/smartpromise": "^2.0.5",
|
||||
"@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.2",
|
||||
"@types/which": "^3.0.3",
|
||||
"tree-kill": "^1.2.2",
|
||||
"which": "^4.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"
|
||||
]
|
||||
}
|
||||
|
4833
pnpm-lock.yaml
generated
Normal file
4833
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
1
readme.hints.md
Normal file
1
readme.hints.md
Normal file
@ -0,0 +1 @@
|
||||
|
152
readme.md
Normal file
152
readme.md
Normal 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 shell’s 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.
|
28
test/test.ts
28
test/test.ts
@ -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
8
ts/00_commitinfo_data.ts
Normal file
@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartshell',
|
||||
version: '3.0.5',
|
||||
description: 'A library for executing shell commands using promises.'
|
||||
}
|
@ -1 +1,2 @@
|
||||
export * from './smartshell.classes.smartshell';
|
||||
export * from './smartshell.classes.smartshell.js';
|
||||
export { which } from './smartshell.plugins.js';
|
||||
|
@ -31,13 +31,28 @@ 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 commandPath = process.env.PATH;
|
||||
let commandPaths: string[] = [];
|
||||
commandPaths = commandPaths.concat(process.env.PATH.split(':'));
|
||||
if (process.env.SMARTSHELL_PATH) {
|
||||
commandPath = `${commandPath}:${process.env.SMARTSHELL_PATH}`;
|
||||
commandPaths = commandPaths.concat(process.env.SMARTSHELL_PATH.split(':'));
|
||||
}
|
||||
commandResult = `PATH=${commandPath} && ${commandStringArg}`;
|
||||
|
||||
// lets filter for unwanted paths
|
||||
// Windows WSL
|
||||
commandPaths = commandPaths.filter((commandPathArg) => {
|
||||
const filterResult =
|
||||
!commandPathArg.startsWith('/mnt/c/') &&
|
||||
!commandPathArg.startsWith('Files/1E') &&
|
||||
!commandPathArg.includes(' ');
|
||||
if (!filterResult) {
|
||||
// console.log(`${commandPathArg} will be filtered!`);
|
||||
}
|
||||
return filterResult;
|
||||
});
|
||||
|
||||
commandResult = `PATH=${commandPaths.join(':')} && ${commandStringArg}`;
|
||||
return commandResult;
|
||||
}
|
||||
|
||||
@ -58,14 +73,29 @@ export class ShellEnv {
|
||||
this.sourceFileArray = [];
|
||||
}
|
||||
|
||||
createEnvExecString(commandArg): string {
|
||||
public createEnvExecString(commandArg: string): string {
|
||||
let commandResult = '';
|
||||
if (this.executor === 'bash') {
|
||||
let sourceString = '';
|
||||
for (let sourceFilePath of this.sourceFileArray) {
|
||||
sourceString = sourceString + `source ${sourceFilePath} && `;
|
||||
}
|
||||
commandResult = `bash -c '${sourceString} ${commandArg}'`;
|
||||
let sourceString = '';
|
||||
|
||||
// deal with sourcestring
|
||||
for (const sourceFilePath of this.sourceFileArray) {
|
||||
sourceString = sourceString + `source ${sourceFilePath} && `;
|
||||
}
|
||||
|
||||
// deal with available path
|
||||
let pathString = 'PATH=$PATH';
|
||||
for (const pathDir of this.pathDirArray) {
|
||||
pathString += `:${pathDir}`;
|
||||
}
|
||||
pathString += ` && `;
|
||||
|
||||
switch (this.executor) {
|
||||
case 'bash':
|
||||
commandResult = `bash -c '${pathString}${sourceString}${commandArg}'`;
|
||||
break;
|
||||
case 'sh':
|
||||
commandResult = `${pathString}${sourceString}${commandArg}`;
|
||||
break;
|
||||
}
|
||||
commandResult = this._setPath(commandResult);
|
||||
return commandResult;
|
||||
|
@ -1,32 +1,26 @@
|
||||
import * as plugins from './smartshell.plugins';
|
||||
import * as plugins from './smartshell.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
|
||||
const dataString: string = (() => {
|
||||
if (Buffer.isBuffer(dataArg)) {
|
||||
return dataArg.toString();
|
||||
}
|
||||
return dataArg;
|
||||
})();
|
||||
process.stdout.write(dataString);
|
||||
process.stdout.write(dataArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)) {
|
||||
@ -37,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);
|
||||
}
|
||||
}
|
||||
|
@ -1,32 +1,28 @@
|
||||
// -- imports --
|
||||
import * as plugins from './smartshell.plugins';
|
||||
import { ShellEnv, IShellEnvContructorOptions, TExecutor } from './smartshell.classes.shellenv';
|
||||
import { ShellLog } from './smartshell.classes.shelllog';
|
||||
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';
|
||||
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;
|
||||
kill: () => Promise<void>;
|
||||
terminate: () => Promise<void>;
|
||||
keyboardInterrupt: () => Promise<void>;
|
||||
customSignal: (signalArg: plugins.smartexit.TProcessSignal) => Promise<void>;
|
||||
}
|
||||
|
||||
// -- SmartShell --
|
||||
export class Smartshell {
|
||||
shellEnv: ShellEnv;
|
||||
public shellEnv: ShellEnv;
|
||||
public smartexit = new plugins.smartexit.SmartExit();
|
||||
|
||||
constructor(optionsArg: IShellEnvContructorOptions) {
|
||||
this.shellEnv = new ShellEnv(optionsArg);
|
||||
@ -34,112 +30,156 @@ export class Smartshell {
|
||||
|
||||
/**
|
||||
* 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
|
||||
private async _exec(options: {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
}): Promise<IExecResult | IExecResultStreaming | void> {
|
||||
if (options.interactive) {
|
||||
if (process.env.CI) {
|
||||
return;
|
||||
}
|
||||
|
||||
const done = plugins.smartpromise.defer();
|
||||
|
||||
// Notice that stdio is set to 'inherit'
|
||||
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;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const done = plugins.smartpromise.defer<IExecResult | IExecResultStreaming>();
|
||||
const childProcessEnded = plugins.smartpromise.defer<IExecResult>();
|
||||
// build commandToExecute
|
||||
let commandToExecute = commandStringArg;
|
||||
commandToExecute = this.shellEnv.createEnvExecString(commandStringArg);
|
||||
|
||||
let commandToExecute = options.commandString;
|
||||
commandToExecute = this.shellEnv.createEnvExecString(options.commandString);
|
||||
|
||||
const spawnlogInstance = new ShellLog();
|
||||
const execChildProcess = cp.spawn(commandToExecute, [], {
|
||||
shell: true,
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
detached: true
|
||||
detached: false,
|
||||
});
|
||||
|
||||
execChildProcess.stdout.on('data', data => {
|
||||
if (!silentArg) {
|
||||
spawnlogInstance.logToConsole(data);
|
||||
}
|
||||
spawnlogInstance.addToBuffer(data);
|
||||
});
|
||||
execChildProcess.stderr.on('data', data => {
|
||||
if (!silentArg) {
|
||||
spawnlogInstance.logToConsole(data);
|
||||
this.smartexit.addProcess(execChildProcess);
|
||||
|
||||
execChildProcess.stdout.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
spawnlogInstance.writeToConsole(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.stderr.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
spawnlogInstance.writeToConsole(data);
|
||||
}
|
||||
spawnlogInstance.addToBuffer(data);
|
||||
});
|
||||
|
||||
execChildProcess.on('exit', (code, signal) => {
|
||||
if (strictArg && code === 1) {
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
if (options.strict && code === 1) {
|
||||
done.reject();
|
||||
}
|
||||
|
||||
const execResult = {
|
||||
exitCode: code,
|
||||
stdout: spawnlogInstance.logStore.toString()
|
||||
stdout: spawnlogInstance.logStore.toString(),
|
||||
};
|
||||
|
||||
if (!streamingArg) {
|
||||
if (!options.streaming) {
|
||||
done.resolve(execResult);
|
||||
}
|
||||
childProcessEnded.resolve(execResult);
|
||||
});
|
||||
|
||||
const result = await done.promise;
|
||||
return result;
|
||||
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;
|
||||
}
|
||||
|
||||
async exec(commandStringArg: string): Promise<IExecResult> {
|
||||
return (await this._exec(commandStringArg, false)) as IExecResult;
|
||||
public async exec(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString })) 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;
|
||||
public async execSilent(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, silent: 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;
|
||||
public async execStrict(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* executes a command and allows you to stream output
|
||||
*/
|
||||
async execStreaming(
|
||||
commandStringArg: string,
|
||||
silentArg: boolean = false
|
||||
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(commandStringArg, silentArg, false, true)) as IExecResultStreaming;
|
||||
return (await this._exec({ commandString, silent, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
async execStreamingSilent(commandStringArg: string) {
|
||||
return (await this.execStreaming(commandStringArg, true)) as IExecResultStreaming;
|
||||
public async execStreamingSilent(commandString: string): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({
|
||||
commandString,
|
||||
silent: true,
|
||||
streaming: 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) {
|
||||
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(commandStringArg, silentArg);
|
||||
let execStreamingResult = await this.execStreaming(commandString, silentArg);
|
||||
execStreamingResult.childProcess.stdout.on('data', (stdOutChunk: string) => {
|
||||
if (regexArg.test(stdOutChunk)) {
|
||||
done.resolve();
|
||||
@ -148,7 +188,7 @@ export class Smartshell {
|
||||
return done.promise;
|
||||
}
|
||||
|
||||
async execAndWaitForLineSilent(commandStringArg: string, regexArg: RegExp) {
|
||||
this.execAndWaitForLine(commandStringArg, regexArg, true);
|
||||
public async execAndWaitForLineSilent(commandString: string, regexArg: RegExp) {
|
||||
return this.execAndWaitForLine(commandString, regexArg, true);
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,6 @@
|
||||
import * as smartpromise from '@pushrocks/smartpromise';
|
||||
import * as which from 'which';
|
||||
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 { smartpromise, which };
|
||||
export { smartdelay, smartexit, smartpromise, which };
|
||||
|
14
tsconfig.json
Normal file
14
tsconfig.json
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
]
|
||||
}
|
17
tslint.json
17
tslint.json
@ -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"
|
||||
}
|
Reference in New Issue
Block a user