Compare commits
64 Commits
Author | SHA1 | Date | |
---|---|---|---|
5a32817349 | |||
35d22175db | |||
cd3675280a | |||
7c14102324 | |||
cb41dbaf1c | |||
149eb800e7 | |||
91e84c8422 | |||
ff26cd0678 | |||
acdd729e06 | |||
522fbfc42c | |||
b854715940 | |||
35f59054f8 | |||
c9a3de2207 | |||
6904097960 | |||
1474fd541f | |||
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 |
20
.gitignore
vendored
20
.gitignore
vendored
@@ -1,4 +1,20 @@
|
|||||||
|
.nogit/
|
||||||
|
|
||||||
|
# artifacts
|
||||||
coverage/
|
coverage/
|
||||||
node_modules/
|
|
||||||
pages/
|
|
||||||
public/
|
public/
|
||||||
|
pages/
|
||||||
|
|
||||||
|
# installs
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# caches
|
||||||
|
.yarn/
|
||||||
|
.cache/
|
||||||
|
.rpt2_cache
|
||||||
|
|
||||||
|
# builds
|
||||||
|
dist/
|
||||||
|
dist_*/
|
||||||
|
|
||||||
|
# custom
|
125
.gitlab-ci.yml
125
.gitlab-ci.yml
@@ -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 typedoc typescript
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci npm install
|
|
||||||
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
artifacts:
|
|
||||||
expire_in: 1 week
|
|
||||||
paths:
|
|
||||||
- public
|
|
||||||
allow_failure: true
|
|
BIN
.serena/cache/typescript/document_symbols_cache_v23-06-25.pkl
vendored
Normal file
BIN
.serena/cache/typescript/document_symbols_cache_v23-06-25.pkl
vendored
Normal file
Binary file not shown.
68
.serena/project.yml
Normal file
68
.serena/project.yml
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
||||||
|
# * For C, use cpp
|
||||||
|
# * For JavaScript, use typescript
|
||||||
|
# Special requirements:
|
||||||
|
# * csharp: Requires the presence of a .sln file in the project folder.
|
||||||
|
language: typescript
|
||||||
|
|
||||||
|
# whether to use the project's gitignore file to ignore files
|
||||||
|
# Added on 2025-04-07
|
||||||
|
ignore_all_files_in_gitignore: true
|
||||||
|
# list of additional paths to ignore
|
||||||
|
# same syntax as gitignore, so you can use * and **
|
||||||
|
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
||||||
|
# Added (renamed) on 2025-04-07
|
||||||
|
ignored_paths: []
|
||||||
|
|
||||||
|
# whether the project is in read-only mode
|
||||||
|
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||||
|
# Added on 2025-04-18
|
||||||
|
read_only: false
|
||||||
|
|
||||||
|
|
||||||
|
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
||||||
|
# Below is the complete list of tools for convenience.
|
||||||
|
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||||
|
# execute `uv run scripts/print_tool_overview.py`.
|
||||||
|
#
|
||||||
|
# * `activate_project`: Activates a project by name.
|
||||||
|
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||||
|
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||||
|
# * `delete_lines`: Deletes a range of lines within a file.
|
||||||
|
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
||||||
|
# * `execute_shell_command`: Executes a shell command.
|
||||||
|
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
||||||
|
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
||||||
|
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
||||||
|
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||||
|
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||||
|
# * `initial_instructions`: Gets the initial instructions for the current project.
|
||||||
|
# Should only be used in settings where the system prompt cannot be set,
|
||||||
|
# e.g. in clients you have no control over, like Claude Desktop.
|
||||||
|
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||||
|
# * `insert_at_line`: Inserts content at a given line in a file.
|
||||||
|
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||||
|
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||||
|
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
||||||
|
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||||
|
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
||||||
|
# * `read_file`: Reads a file within the project directory.
|
||||||
|
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
||||||
|
# * `remove_project`: Removes a project from the Serena configuration.
|
||||||
|
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
||||||
|
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
||||||
|
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
||||||
|
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||||
|
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
||||||
|
# * `switch_modes`: Activates modes by providing a list of their names
|
||||||
|
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
||||||
|
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
||||||
|
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
||||||
|
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
||||||
|
excluded_tools: []
|
||||||
|
|
||||||
|
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||||
|
# (contrary to the memories, which are loaded on demand).
|
||||||
|
initial_prompt: ""
|
||||||
|
|
||||||
|
project_name: "smartshell"
|
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)
|
|
98
changelog.md
Normal file
98
changelog.md
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 2025-08-16 - 3.2.4 - fix(tests)
|
||||||
|
Update tests & CI config, bump deps, add docs and project configs
|
||||||
|
|
||||||
|
- Add comprehensive README overhaul with detailed usage, examples, API reference and best practices.
|
||||||
|
- Add extensive silent-mode tests (test/test.silent.ts) to validate execSilent, execStrictSilent, execStreamingSilent and execAndWaitForLineSilent behaviors.
|
||||||
|
- Update test runner and script: test script now runs tstest with --verbose, --logfile and --timeout; tests now import tapbundle from @git.zone/tstest.
|
||||||
|
- Fix import in test/test.ts to use @git.zone/tstest/tapbundle.
|
||||||
|
- Bump devDependencies: @git.zone/tsbuild -> ^2.6.4, @git.zone/tstest -> ^2.3.2; bump @push.rocks/smartpromise -> ^4.2.3.
|
||||||
|
- Add typings entry and packageManager field to package.json.
|
||||||
|
- Add project configuration files (.serena/project.yml) and local settings (.claude/settings.local.json).
|
||||||
|
|
||||||
|
## 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
|
@@ -3,5 +3,30 @@
|
|||||||
"npmGlobalTools": [],
|
"npmGlobalTools": [],
|
||||||
"npmAccessLevel": "public",
|
"npmAccessLevel": "public",
|
||||||
"npmRegistryUrl": "registry.npmjs.org"
|
"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
69
package.json
69
package.json
@@ -1,40 +1,65 @@
|
|||||||
{
|
{
|
||||||
"name": "@pushrocks/smartshell",
|
"name": "@push.rocks/smartshell",
|
||||||
"private": false,
|
"private": false,
|
||||||
"version": "2.0.13",
|
"version": "3.2.4",
|
||||||
"description": "shell actions designed as promises",
|
"description": "A library for executing shell commands using promises.",
|
||||||
"main": "dist/index.js",
|
"main": "dist_ts/index.js",
|
||||||
"typings": "dist/index.d.ts",
|
"typings": "dist_ts/index.d.ts",
|
||||||
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "(tstest test/)",
|
"test": "(tstest test/ --verbose --logfile --timeout 20)",
|
||||||
"build": "(tsbuild)"
|
"build": "(tsbuild tsfolders --web)",
|
||||||
|
"buildDocs": "tsdoc"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+ssh://git@gitlab.com/pushrocks/smartshell.git"
|
"url": "https://code.foss.global/push.rocks/smartshell.git"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"shell",
|
"shell commands",
|
||||||
"promise"
|
"promises",
|
||||||
|
"asynchronous execution",
|
||||||
|
"child processes",
|
||||||
|
"environment management",
|
||||||
|
"command streaming",
|
||||||
|
"interactive commands",
|
||||||
|
"process management",
|
||||||
|
"typescript"
|
||||||
],
|
],
|
||||||
"author": "Lossless GmbH",
|
"author": "Lossless GmbH",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://gitlab.com/pushrocks/smartshell/issues"
|
"url": "https://gitlab.com/pushrocks/smartshell/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://gitlab.com/pushrocks/smartshell#README",
|
"homepage": "https://code.foss.global/push.rocks/smartshell",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@gitzone/tsbuild": "^2.0.22",
|
"@git.zone/tsbuild": "^2.6.4",
|
||||||
"@gitzone/tsrun": "^1.1.13",
|
"@git.zone/tsrun": "^1.3.3",
|
||||||
"@gitzone/tstest": "^1.0.15",
|
"@git.zone/tstest": "^2.3.2",
|
||||||
"@pushrocks/tapbundle": "^3.0.7",
|
"@types/node": "^22.10.2"
|
||||||
"@types/node": "^10.12.10",
|
|
||||||
"tslint": "^5.11.0",
|
|
||||||
"tslint-config-prettier": "^1.16.0"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@pushrocks/smartpromise": "^2.0.5",
|
"@push.rocks/smartdelay": "^3.0.1",
|
||||||
"@types/which": "^1.3.1",
|
"@push.rocks/smartexit": "^1.0.23",
|
||||||
"which": "^1.3.1"
|
"@push.rocks/smartpromise": "^4.2.3",
|
||||||
}
|
"@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"
|
||||||
|
],
|
||||||
|
"packageManager": "pnpm@10.14.0+sha512.ad27a79641b49c3e481a16a805baa71817a04bbe06a38d17e60e2eaee83f6a146c6a688125f5792e48dd5ba30e7da52a5cda4c3992b9ccf333f9ce223af84748"
|
||||||
}
|
}
|
||||||
|
9817
pnpm-lock.yaml
generated
Normal file
9817
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 @@
|
|||||||
|
|
815
readme.md
Normal file
815
readme.md
Normal file
@@ -0,0 +1,815 @@
|
|||||||
|
# @push.rocks/smartshell 🐚
|
||||||
|
**Execute shell commands with superpowers in Node.js**
|
||||||
|
|
||||||
|
[](https://www.npmjs.com/package/@push.rocks/smartshell)
|
||||||
|
[](https://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
## Why smartshell? 🚀
|
||||||
|
|
||||||
|
Tired of wrestling with Node.js child processes? Meet `@push.rocks/smartshell` - your promise-based shell command companion that makes executing system commands feel like a breeze. Whether you're building automation scripts, CI/CD pipelines, or need fine-grained control over shell execution, smartshell has got you covered.
|
||||||
|
|
||||||
|
### ✨ Key Features
|
||||||
|
|
||||||
|
- 🎯 **Promise-based API** - Async/await ready for modern codebases
|
||||||
|
- 🔇 **Silent execution modes** - Control output verbosity
|
||||||
|
- 📡 **Streaming support** - Real-time output for long-running processes
|
||||||
|
- 🎮 **Interactive commands** - Handle user input when needed
|
||||||
|
- ⚡ **Smart execution modes** - Strict, silent, or streaming
|
||||||
|
- 🔍 **Pattern matching** - Wait for specific output patterns
|
||||||
|
- 🌍 **Environment management** - Custom env vars and PATH handling
|
||||||
|
- 🛡️ **TypeScript first** - Full type safety and IntelliSense
|
||||||
|
|
||||||
|
## Installation 📦
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Using npm
|
||||||
|
npm install @push.rocks/smartshell --save
|
||||||
|
|
||||||
|
# Using yarn
|
||||||
|
yarn add @push.rocks/smartshell
|
||||||
|
|
||||||
|
# Using pnpm (recommended)
|
||||||
|
pnpm add @push.rocks/smartshell
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start 🏃♂️
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Smartshell } from '@push.rocks/smartshell';
|
||||||
|
|
||||||
|
// Create your shell instance
|
||||||
|
const shell = new Smartshell({
|
||||||
|
executor: 'bash' // or 'sh' for lighter shells
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run a simple command
|
||||||
|
const result = await shell.exec('echo "Hello, World!"');
|
||||||
|
console.log(result.stdout); // "Hello, World!"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Core Concepts 💡
|
||||||
|
|
||||||
|
### The Smartshell Instance
|
||||||
|
|
||||||
|
The heart of smartshell is the `Smartshell` class. Each instance maintains its own environment and configuration:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({
|
||||||
|
executor: 'bash', // Choose your shell: 'bash' or 'sh'
|
||||||
|
sourceFilePaths: ['/path/to/env.sh'], // Optional: source files on init
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Execution Modes 🎛️
|
||||||
|
|
||||||
|
### Standard Execution
|
||||||
|
|
||||||
|
Perfect for general commands where you want to see the output:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const result = await shell.exec('ls -la');
|
||||||
|
console.log(result.stdout); // Directory listing
|
||||||
|
console.log(result.exitCode); // 0 for success
|
||||||
|
```
|
||||||
|
|
||||||
|
### Silent Execution
|
||||||
|
|
||||||
|
Run commands without printing to console - ideal for capturing output:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const result = await shell.execSilent('cat /etc/hostname');
|
||||||
|
// Output is NOT printed to console but IS captured in result
|
||||||
|
console.log(result.stdout); // Access the captured output here
|
||||||
|
console.log(result.exitCode); // Check exit code (0 = success)
|
||||||
|
|
||||||
|
// Example: Process output programmatically
|
||||||
|
const files = await shell.execSilent('ls -la');
|
||||||
|
const fileList = files.stdout.split('
|
||||||
|
');
|
||||||
|
fileList.forEach(file => {
|
||||||
|
// Process each file entry
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Point:** Silent methods (`execSilent`, `execStrictSilent`, `execStreamingSilent`) suppress console output but still capture everything in the result object for programmatic access.
|
||||||
|
|
||||||
|
### Strict Execution
|
||||||
|
|
||||||
|
Throws an error if the command fails - great for critical operations:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
try {
|
||||||
|
await shell.execStrict('critical-command');
|
||||||
|
console.log('✅ Command succeeded!');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Command failed:', error);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Streaming Execution
|
||||||
|
|
||||||
|
For long-running processes or when you need real-time output:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const streaming = await shell.execStreaming('npm install');
|
||||||
|
|
||||||
|
// Access the child process directly
|
||||||
|
streaming.childProcess.stdout.on('data', (chunk) => {
|
||||||
|
console.log('📦 Installing:', chunk.toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait for completion
|
||||||
|
await streaming.finalPromise;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Interactive Execution
|
||||||
|
|
||||||
|
When commands need user input:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// This will connect to your terminal for input
|
||||||
|
await shell.execInteractive('npm init');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Features 🔥
|
||||||
|
|
||||||
|
### Wait for Specific Output
|
||||||
|
|
||||||
|
Perfect for waiting on services to start:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Wait for a specific line before continuing
|
||||||
|
await shell.execAndWaitForLine(
|
||||||
|
'npm run dev',
|
||||||
|
/Server started on port 3000/
|
||||||
|
);
|
||||||
|
console.log('🚀 Server is ready!');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Silent Pattern Waiting
|
||||||
|
|
||||||
|
Same as above, but without console output:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
await shell.execAndWaitForLineSilent(
|
||||||
|
'docker-compose up',
|
||||||
|
/database system is ready to accept connections/
|
||||||
|
);
|
||||||
|
// The command output is suppressed from console but the pattern matching still works
|
||||||
|
```
|
||||||
|
|
||||||
|
### Environment Customization
|
||||||
|
|
||||||
|
Smartshell provides powerful environment management:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Add custom source files
|
||||||
|
shell.shellEnv.addSourceFiles([
|
||||||
|
'/home/user/.custom_env',
|
||||||
|
'./project.env.sh'
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Modify PATH
|
||||||
|
shell.shellEnv.pathDirArray.push('/custom/bin');
|
||||||
|
shell.shellEnv.pathDirArray.push('/usr/local/special');
|
||||||
|
|
||||||
|
// Your custom environment is ready
|
||||||
|
const result = await shell.exec('my-custom-command');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Smart Execution Utility
|
||||||
|
|
||||||
|
The `SmartExecution` class enables restartable streaming processes:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { SmartExecution } from '@push.rocks/smartshell';
|
||||||
|
|
||||||
|
const execution = new SmartExecution(shell, 'npm run watch');
|
||||||
|
|
||||||
|
// Restart the process whenever needed
|
||||||
|
await execution.restart();
|
||||||
|
|
||||||
|
// Access the current streaming execution
|
||||||
|
if (execution.currentStreamingExecution) {
|
||||||
|
execution.currentStreamingExecution.childProcess.stdout.on('data', (data) => {
|
||||||
|
console.log(data.toString());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Shell Detection
|
||||||
|
|
||||||
|
Need to check if a command exists? We export the `which` utility:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { which } from '@push.rocks/smartshell';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const gitPath = await which('git');
|
||||||
|
console.log(`Git found at: ${gitPath}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Git is not installed');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Real-World Examples 🌍
|
||||||
|
|
||||||
|
### Build Pipeline
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({ executor: 'bash' });
|
||||||
|
|
||||||
|
// Clean build directory
|
||||||
|
await shell.execSilent('rm -rf dist');
|
||||||
|
|
||||||
|
// Run TypeScript compiler
|
||||||
|
const buildResult = await shell.execStrict('tsc');
|
||||||
|
|
||||||
|
// Run tests
|
||||||
|
await shell.execStrict('npm test');
|
||||||
|
|
||||||
|
// Build succeeded!
|
||||||
|
console.log('✅ Build pipeline completed successfully');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Development Server with Auto-Restart
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({ executor: 'bash' });
|
||||||
|
const devServer = new SmartExecution(shell, 'npm run dev');
|
||||||
|
|
||||||
|
// Watch for file changes and restart
|
||||||
|
fs.watch('./src', async () => {
|
||||||
|
console.log('🔄 Changes detected, restarting...');
|
||||||
|
await devServer.restart();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker Compose Helper
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({ executor: 'bash' });
|
||||||
|
|
||||||
|
// Start services and wait for readiness
|
||||||
|
console.log('🐳 Starting Docker services...');
|
||||||
|
await shell.execAndWaitForLine(
|
||||||
|
'docker-compose up',
|
||||||
|
/All services are ready/,
|
||||||
|
{ timeout: 60000 }
|
||||||
|
);
|
||||||
|
|
||||||
|
// Run migrations
|
||||||
|
await shell.execStrict('docker-compose exec app npm run migrate');
|
||||||
|
console.log('✅ Environment ready!');
|
||||||
|
```
|
||||||
|
|
||||||
|
### CI/CD Integration
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({ executor: 'bash' });
|
||||||
|
|
||||||
|
async function runCIPipeline() {
|
||||||
|
// Install dependencies
|
||||||
|
await shell.execStrict('pnpm install --frozen-lockfile');
|
||||||
|
|
||||||
|
// Run linting
|
||||||
|
const lintResult = await shell.execSilent('npm run lint');
|
||||||
|
if (lintResult.exitCode !== 0) {
|
||||||
|
throw new Error(`Linting failed:
|
||||||
|
${lintResult.stdout}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run tests with coverage
|
||||||
|
const testResult = await shell.exec('npm run test:coverage');
|
||||||
|
|
||||||
|
// Build project
|
||||||
|
await shell.execStrict('npm run build');
|
||||||
|
|
||||||
|
// Deploy if on main branch
|
||||||
|
if (process.env.BRANCH === 'main') {
|
||||||
|
await shell.execStrict('npm run deploy');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Reference 📚
|
||||||
|
|
||||||
|
### Smartshell Class
|
||||||
|
|
||||||
|
| Method | Description | Returns |
|
||||||
|
|--------|-------------|---------|
|
||||||
|
| `exec(command)` | Execute command with output | `Promise<IExecResult>` |
|
||||||
|
| `execSilent(command)` | Execute without console output | `Promise<IExecResult>` |
|
||||||
|
| `execStrict(command)` | Execute, throw on failure | `Promise<IExecResult>` |
|
||||||
|
| `execStrictSilent(command)` | Strict + silent execution | `Promise<IExecResult>` |
|
||||||
|
| `execStreaming(command)` | Stream output in real-time | `Promise<IExecResultStreaming>` |
|
||||||
|
| `execStreamingSilent(command)` | Stream without console output | `Promise<IExecResultStreaming>` |
|
||||||
|
| `execInteractive(command)` | Interactive terminal mode | `Promise<void>` |
|
||||||
|
| `execAndWaitForLine(command, regex)` | Wait for pattern match | `Promise<void>` |
|
||||||
|
| `execAndWaitForLineSilent(command, regex)` | Silent pattern waiting | `Promise<void>` |
|
||||||
|
|
||||||
|
### Result Interfaces
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface IExecResult {
|
||||||
|
exitCode: number; // Process exit code
|
||||||
|
stdout: string; // Standard output
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IExecResultStreaming {
|
||||||
|
childProcess: ChildProcess; // Node.js ChildProcess instance
|
||||||
|
finalPromise: Promise<void>; // Resolves when process exits
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Understanding Silent Modes 🤫
|
||||||
|
|
||||||
|
Silent execution modes are perfect when you need to capture command output for processing without cluttering the console. Here's what you need to know:
|
||||||
|
|
||||||
|
### How Silent Modes Work
|
||||||
|
|
||||||
|
1. **Output is captured, not lost**: All stdout content is stored in the result object
|
||||||
|
2. **Console stays clean**: Nothing is printed during execution
|
||||||
|
3. **Full programmatic access**: Process the output however you need
|
||||||
|
|
||||||
|
### Available Silent Methods
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Basic silent execution
|
||||||
|
const result = await shell.execSilent('ls -la');
|
||||||
|
console.log(result.stdout); // Access captured output
|
||||||
|
console.log(result.exitCode); // Check success/failure
|
||||||
|
|
||||||
|
// Strict + Silent (throws on error)
|
||||||
|
try {
|
||||||
|
const result = await shell.execStrictSilent('important-command');
|
||||||
|
const output = result.stdout; // Process the output
|
||||||
|
} catch (error) {
|
||||||
|
// Handle failure
|
||||||
|
}
|
||||||
|
|
||||||
|
// Streaming + Silent
|
||||||
|
const streaming = await shell.execStreamingSilent('long-running-process');
|
||||||
|
streaming.childProcess.stdout.on('data', (chunk) => {
|
||||||
|
// Process chunks as they arrive
|
||||||
|
const data = chunk.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pattern matching + Silent
|
||||||
|
await shell.execAndWaitForLineSilent('server-start', /Ready on port/);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Common Use Cases for Silent Execution
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Parse JSON output
|
||||||
|
const jsonResult = await shell.execSilent('aws s3 ls --output json');
|
||||||
|
const buckets = JSON.parse(jsonResult.stdout);
|
||||||
|
|
||||||
|
// Count lines
|
||||||
|
const wcResult = await shell.execSilent('wc -l huge-file.txt');
|
||||||
|
const lineCount = parseInt(wcResult.stdout.split(' ')[0]);
|
||||||
|
|
||||||
|
// Check if command exists
|
||||||
|
const whichResult = await shell.execSilent('which docker');
|
||||||
|
const dockerPath = whichResult.exitCode === 0 ? whichResult.stdout.trim() : null;
|
||||||
|
|
||||||
|
// Collect system info
|
||||||
|
const unameResult = await shell.execSilent('uname -a');
|
||||||
|
const systemInfo = unameResult.stdout.trim();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tips & Best Practices 💎
|
||||||
|
|
||||||
|
1. **Choose the right executor**: Use `bash` for full features, `sh` for minimal overhead
|
||||||
|
2. **Use strict mode for critical operations**: Ensures failures don't go unnoticed
|
||||||
|
3. **Stream long-running processes**: Better UX and memory efficiency
|
||||||
|
4. **Leverage silent modes**: When you only need to capture output
|
||||||
|
5. **Handle errors gracefully**: Always wrap strict executions in try-catch
|
||||||
|
6. **Clean up resources**: Streaming processes should be properly terminated
|
||||||
|
|
||||||
|
## 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.# @push.rocks/smartshell 🐚
|
||||||
|
**Execute shell commands with superpowers in Node.js**
|
||||||
|
|
||||||
|
[](https://www.npmjs.com/package/@push.rocks/smartshell)
|
||||||
|
[](https://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
## Why smartshell? 🚀
|
||||||
|
|
||||||
|
Tired of wrestling with Node.js child processes? Meet `@push.rocks/smartshell` - your promise-based shell command companion that makes executing system commands feel like a breeze. Whether you're building automation scripts, CI/CD pipelines, or need fine-grained control over shell execution, smartshell has got you covered.
|
||||||
|
|
||||||
|
### ✨ Key Features
|
||||||
|
|
||||||
|
- 🎯 **Promise-based API** - Async/await ready for modern codebases
|
||||||
|
- 🔇 **Silent execution modes** - Control output verbosity
|
||||||
|
- 📡 **Streaming support** - Real-time output for long-running processes
|
||||||
|
- 🎮 **Interactive commands** - Handle user input when needed
|
||||||
|
- ⚡ **Smart execution modes** - Strict, silent, or streaming
|
||||||
|
- 🔍 **Pattern matching** - Wait for specific output patterns
|
||||||
|
- 🌍 **Environment management** - Custom env vars and PATH handling
|
||||||
|
- 🛡️ **TypeScript first** - Full type safety and IntelliSense
|
||||||
|
|
||||||
|
## Installation 📦
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Using npm
|
||||||
|
npm install @push.rocks/smartshell --save
|
||||||
|
|
||||||
|
# Using yarn
|
||||||
|
yarn add @push.rocks/smartshell
|
||||||
|
|
||||||
|
# Using pnpm (recommended)
|
||||||
|
pnpm add @push.rocks/smartshell
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start 🏃♂️
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Smartshell } from '@push.rocks/smartshell';
|
||||||
|
|
||||||
|
// Create your shell instance
|
||||||
|
const shell = new Smartshell({
|
||||||
|
executor: 'bash' // or 'sh' for lighter shells
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run a simple command
|
||||||
|
const result = await shell.exec('echo "Hello, World!"');
|
||||||
|
console.log(result.stdout); // "Hello, World!"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Core Concepts 💡
|
||||||
|
|
||||||
|
### The Smartshell Instance
|
||||||
|
|
||||||
|
The heart of smartshell is the `Smartshell` class. Each instance maintains its own environment and configuration:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({
|
||||||
|
executor: 'bash', // Choose your shell: 'bash' or 'sh'
|
||||||
|
sourceFilePaths: ['/path/to/env.sh'], // Optional: source files on init
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Execution Modes 🎛️
|
||||||
|
|
||||||
|
### Standard Execution
|
||||||
|
|
||||||
|
Perfect for general commands where you want to see the output:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const result = await shell.exec('ls -la');
|
||||||
|
console.log(result.stdout); // Directory listing
|
||||||
|
console.log(result.exitCode); // 0 for success
|
||||||
|
```
|
||||||
|
|
||||||
|
### Silent Execution
|
||||||
|
|
||||||
|
Run commands without printing to console - ideal for capturing output:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const result = await shell.execSilent('cat /etc/hostname');
|
||||||
|
// Output is NOT printed to console but IS captured in result
|
||||||
|
console.log(result.stdout); // Access the captured output here
|
||||||
|
console.log(result.exitCode); // Check exit code (0 = success)
|
||||||
|
|
||||||
|
// Example: Process output programmatically
|
||||||
|
const files = await shell.execSilent('ls -la');
|
||||||
|
const fileList = files.stdout.split('
|
||||||
|
');
|
||||||
|
fileList.forEach(file => {
|
||||||
|
// Process each file entry
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Point:** Silent methods (`execSilent`, `execStrictSilent`, `execStreamingSilent`) suppress console output but still capture everything in the result object for programmatic access.
|
||||||
|
|
||||||
|
### Strict Execution
|
||||||
|
|
||||||
|
Throws an error if the command fails - great for critical operations:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
try {
|
||||||
|
await shell.execStrict('critical-command');
|
||||||
|
console.log('✅ Command succeeded!');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Command failed:', error);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Streaming Execution
|
||||||
|
|
||||||
|
For long-running processes or when you need real-time output:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const streaming = await shell.execStreaming('npm install');
|
||||||
|
|
||||||
|
// Access the child process directly
|
||||||
|
streaming.childProcess.stdout.on('data', (chunk) => {
|
||||||
|
console.log('📦 Installing:', chunk.toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait for completion
|
||||||
|
await streaming.finalPromise;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Interactive Execution
|
||||||
|
|
||||||
|
When commands need user input:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// This will connect to your terminal for input
|
||||||
|
await shell.execInteractive('npm init');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Features 🔥
|
||||||
|
|
||||||
|
### Wait for Specific Output
|
||||||
|
|
||||||
|
Perfect for waiting on services to start:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Wait for a specific line before continuing
|
||||||
|
await shell.execAndWaitForLine(
|
||||||
|
'npm run dev',
|
||||||
|
/Server started on port 3000/
|
||||||
|
);
|
||||||
|
console.log('🚀 Server is ready!');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Silent Pattern Waiting
|
||||||
|
|
||||||
|
Same as above, but without console output:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
await shell.execAndWaitForLineSilent(
|
||||||
|
'docker-compose up',
|
||||||
|
/database system is ready to accept connections/
|
||||||
|
);
|
||||||
|
// The command output is suppressed from console but the pattern matching still works
|
||||||
|
```
|
||||||
|
|
||||||
|
### Environment Customization
|
||||||
|
|
||||||
|
Smartshell provides powerful environment management:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Add custom source files
|
||||||
|
shell.shellEnv.addSourceFiles([
|
||||||
|
'/home/user/.custom_env',
|
||||||
|
'./project.env.sh'
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Modify PATH
|
||||||
|
shell.shellEnv.pathDirArray.push('/custom/bin');
|
||||||
|
shell.shellEnv.pathDirArray.push('/usr/local/special');
|
||||||
|
|
||||||
|
// Your custom environment is ready
|
||||||
|
const result = await shell.exec('my-custom-command');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Smart Execution Utility
|
||||||
|
|
||||||
|
The `SmartExecution` class enables restartable streaming processes:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { SmartExecution } from '@push.rocks/smartshell';
|
||||||
|
|
||||||
|
const execution = new SmartExecution(shell, 'npm run watch');
|
||||||
|
|
||||||
|
// Restart the process whenever needed
|
||||||
|
await execution.restart();
|
||||||
|
|
||||||
|
// Access the current streaming execution
|
||||||
|
if (execution.currentStreamingExecution) {
|
||||||
|
execution.currentStreamingExecution.childProcess.stdout.on('data', (data) => {
|
||||||
|
console.log(data.toString());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Shell Detection
|
||||||
|
|
||||||
|
Need to check if a command exists? We export the `which` utility:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { which } from '@push.rocks/smartshell';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const gitPath = await which('git');
|
||||||
|
console.log(`Git found at: ${gitPath}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Git is not installed');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Real-World Examples 🌍
|
||||||
|
|
||||||
|
### Build Pipeline
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({ executor: 'bash' });
|
||||||
|
|
||||||
|
// Clean build directory
|
||||||
|
await shell.execSilent('rm -rf dist');
|
||||||
|
|
||||||
|
// Run TypeScript compiler
|
||||||
|
const buildResult = await shell.execStrict('tsc');
|
||||||
|
|
||||||
|
// Run tests
|
||||||
|
await shell.execStrict('npm test');
|
||||||
|
|
||||||
|
// Build succeeded!
|
||||||
|
console.log('✅ Build pipeline completed successfully');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Development Server with Auto-Restart
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({ executor: 'bash' });
|
||||||
|
const devServer = new SmartExecution(shell, 'npm run dev');
|
||||||
|
|
||||||
|
// Watch for file changes and restart
|
||||||
|
fs.watch('./src', async () => {
|
||||||
|
console.log('🔄 Changes detected, restarting...');
|
||||||
|
await devServer.restart();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker Compose Helper
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({ executor: 'bash' });
|
||||||
|
|
||||||
|
// Start services and wait for readiness
|
||||||
|
console.log('🐳 Starting Docker services...');
|
||||||
|
await shell.execAndWaitForLine(
|
||||||
|
'docker-compose up',
|
||||||
|
/All services are ready/,
|
||||||
|
{ timeout: 60000 }
|
||||||
|
);
|
||||||
|
|
||||||
|
// Run migrations
|
||||||
|
await shell.execStrict('docker-compose exec app npm run migrate');
|
||||||
|
console.log('✅ Environment ready!');
|
||||||
|
```
|
||||||
|
|
||||||
|
### CI/CD Integration
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const shell = new Smartshell({ executor: 'bash' });
|
||||||
|
|
||||||
|
async function runCIPipeline() {
|
||||||
|
// Install dependencies
|
||||||
|
await shell.execStrict('pnpm install --frozen-lockfile');
|
||||||
|
|
||||||
|
// Run linting
|
||||||
|
const lintResult = await shell.execSilent('npm run lint');
|
||||||
|
if (lintResult.exitCode !== 0) {
|
||||||
|
throw new Error(`Linting failed:
|
||||||
|
${lintResult.stdout}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run tests with coverage
|
||||||
|
const testResult = await shell.exec('npm run test:coverage');
|
||||||
|
|
||||||
|
// Build project
|
||||||
|
await shell.execStrict('npm run build');
|
||||||
|
|
||||||
|
// Deploy if on main branch
|
||||||
|
if (process.env.BRANCH === 'main') {
|
||||||
|
await shell.execStrict('npm run deploy');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Reference 📚
|
||||||
|
|
||||||
|
### Smartshell Class
|
||||||
|
|
||||||
|
| Method | Description | Returns |
|
||||||
|
|--------|-------------|---------|
|
||||||
|
| `exec(command)` | Execute command with output | `Promise<IExecResult>` |
|
||||||
|
| `execSilent(command)` | Execute without console output | `Promise<IExecResult>` |
|
||||||
|
| `execStrict(command)` | Execute, throw on failure | `Promise<IExecResult>` |
|
||||||
|
| `execStrictSilent(command)` | Strict + silent execution | `Promise<IExecResult>` |
|
||||||
|
| `execStreaming(command)` | Stream output in real-time | `Promise<IExecResultStreaming>` |
|
||||||
|
| `execStreamingSilent(command)` | Stream without console output | `Promise<IExecResultStreaming>` |
|
||||||
|
| `execInteractive(command)` | Interactive terminal mode | `Promise<void>` |
|
||||||
|
| `execAndWaitForLine(command, regex)` | Wait for pattern match | `Promise<void>` |
|
||||||
|
| `execAndWaitForLineSilent(command, regex)` | Silent pattern waiting | `Promise<void>` |
|
||||||
|
|
||||||
|
### Result Interfaces
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface IExecResult {
|
||||||
|
exitCode: number; // Process exit code
|
||||||
|
stdout: string; // Standard output
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IExecResultStreaming {
|
||||||
|
childProcess: ChildProcess; // Node.js ChildProcess instance
|
||||||
|
finalPromise: Promise<void>; // Resolves when process exits
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Understanding Silent Modes 🤫
|
||||||
|
|
||||||
|
Silent execution modes are perfect when you need to capture command output for processing without cluttering the console. Here's what you need to know:
|
||||||
|
|
||||||
|
### How Silent Modes Work
|
||||||
|
|
||||||
|
1. **Output is captured, not lost**: All stdout content is stored in the result object
|
||||||
|
2. **Console stays clean**: Nothing is printed during execution
|
||||||
|
3. **Full programmatic access**: Process the output however you need
|
||||||
|
|
||||||
|
### Available Silent Methods
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Basic silent execution
|
||||||
|
const result = await shell.execSilent('ls -la');
|
||||||
|
console.log(result.stdout); // Access captured output
|
||||||
|
console.log(result.exitCode); // Check success/failure
|
||||||
|
|
||||||
|
// Strict + Silent (throws on error)
|
||||||
|
try {
|
||||||
|
const result = await shell.execStrictSilent('important-command');
|
||||||
|
const output = result.stdout; // Process the output
|
||||||
|
} catch (error) {
|
||||||
|
// Handle failure
|
||||||
|
}
|
||||||
|
|
||||||
|
// Streaming + Silent
|
||||||
|
const streaming = await shell.execStreamingSilent('long-running-process');
|
||||||
|
streaming.childProcess.stdout.on('data', (chunk) => {
|
||||||
|
// Process chunks as they arrive
|
||||||
|
const data = chunk.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pattern matching + Silent
|
||||||
|
await shell.execAndWaitForLineSilent('server-start', /Ready on port/);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Common Use Cases for Silent Execution
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Parse JSON output
|
||||||
|
const jsonResult = await shell.execSilent('aws s3 ls --output json');
|
||||||
|
const buckets = JSON.parse(jsonResult.stdout);
|
||||||
|
|
||||||
|
// Count lines
|
||||||
|
const wcResult = await shell.execSilent('wc -l huge-file.txt');
|
||||||
|
const lineCount = parseInt(wcResult.stdout.split(' ')[0]);
|
||||||
|
|
||||||
|
// Check if command exists
|
||||||
|
const whichResult = await shell.execSilent('which docker');
|
||||||
|
const dockerPath = whichResult.exitCode === 0 ? whichResult.stdout.trim() : null;
|
||||||
|
|
||||||
|
// Collect system info
|
||||||
|
const unameResult = await shell.execSilent('uname -a');
|
||||||
|
const systemInfo = unameResult.stdout.trim();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tips & Best Practices 💎
|
||||||
|
|
||||||
|
1. **Choose the right executor**: Use `bash` for full features, `sh` for minimal overhead
|
||||||
|
2. **Use strict mode for critical operations**: Ensures failures don't go unnoticed
|
||||||
|
3. **Stream long-running processes**: Better UX and memory efficiency
|
||||||
|
4. **Leverage silent modes**: When you only need to capture output
|
||||||
|
5. **Handle errors gracefully**: Always wrap strict executions in try-catch
|
||||||
|
6. **Clean up resources**: Streaming processes should be properly terminated
|
||||||
|
|
||||||
|
## 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.
|
104
test/test.silent.ts
Normal file
104
test/test.silent.ts
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||||
|
import * as smartshell from '../ts/index.js';
|
||||||
|
|
||||||
|
let testSmartshell: smartshell.Smartshell;
|
||||||
|
|
||||||
|
tap.test('setup for silent execution tests', async () => {
|
||||||
|
testSmartshell = new smartshell.Smartshell({
|
||||||
|
executor: 'bash',
|
||||||
|
sourceFilePaths: [],
|
||||||
|
});
|
||||||
|
expect(testSmartshell).toBeInstanceOf(smartshell.Smartshell);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execSilent should capture output without printing to console', async () => {
|
||||||
|
const result = await testSmartshell.execSilent('echo "Hidden from console"');
|
||||||
|
expect(result.stdout).toContain('Hidden from console');
|
||||||
|
expect(result.exitCode).toEqual(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execSilent should capture multi-line output', async () => {
|
||||||
|
const result = await testSmartshell.execSilent('echo "Line 1" && echo "Line 2" && echo "Line 3"');
|
||||||
|
const lines = result.stdout.trim().split('\n');
|
||||||
|
expect(lines).toHaveLength(3);
|
||||||
|
expect(lines[0]).toEqual('Line 1');
|
||||||
|
expect(lines[1]).toEqual('Line 2');
|
||||||
|
expect(lines[2]).toEqual('Line 3');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execSilent should capture error output', async () => {
|
||||||
|
const result = await testSmartshell.execSilent('echo "This works" && exit 1');
|
||||||
|
expect(result.stdout).toContain('This works');
|
||||||
|
expect(result.exitCode).toEqual(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execSilent should parse command output programmatically', async () => {
|
||||||
|
// Test that we can programmatically process the captured output
|
||||||
|
const result = await testSmartshell.execSilent('echo "apple,banana,cherry"');
|
||||||
|
const items = result.stdout.trim().split(',');
|
||||||
|
expect(items).toHaveLength(3);
|
||||||
|
expect(items[0]).toEqual('apple');
|
||||||
|
expect(items[1]).toEqual('banana');
|
||||||
|
expect(items[2]).toEqual('cherry');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execStrictSilent should capture output and throw on error', async () => {
|
||||||
|
// Test successful command
|
||||||
|
const successResult = await testSmartshell.execStrictSilent('echo "Success"');
|
||||||
|
expect(successResult.stdout).toContain('Success');
|
||||||
|
expect(successResult.exitCode).toEqual(0);
|
||||||
|
|
||||||
|
// Test that it throws on error
|
||||||
|
let errorThrown = false;
|
||||||
|
try {
|
||||||
|
await testSmartshell.execStrictSilent('echo "Error output" && exit 1');
|
||||||
|
} catch (error) {
|
||||||
|
errorThrown = true;
|
||||||
|
}
|
||||||
|
expect(errorThrown).toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execStreamingSilent should capture streaming output without console display', async () => {
|
||||||
|
const streamingResult = await testSmartshell.execStreamingSilent('echo "Line 1" && sleep 0.1 && echo "Line 2"');
|
||||||
|
|
||||||
|
let capturedData = '';
|
||||||
|
streamingResult.childProcess.stdout.on('data', (data) => {
|
||||||
|
capturedData += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
await streamingResult.finalPromise;
|
||||||
|
expect(capturedData).toContain('Line 1');
|
||||||
|
expect(capturedData).toContain('Line 2');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execAndWaitForLineSilent should wait for pattern without console output', async () => {
|
||||||
|
// This should complete without printing to console
|
||||||
|
await testSmartshell.execAndWaitForLineSilent('echo "Starting..." && echo "Ready to go"', /Ready to go/);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execSilent should handle commands with quotes', async () => {
|
||||||
|
const result = await testSmartshell.execSilent('echo "Hello World"');
|
||||||
|
expect(result.stdout.trim()).toEqual('Hello World');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execSilent should capture large output', async () => {
|
||||||
|
// Generate 100 lines of output
|
||||||
|
const result = await testSmartshell.execSilent('for i in {1..100}; do echo "Line $i"; done');
|
||||||
|
const lines = result.stdout.trim().split('\n');
|
||||||
|
expect(lines).toHaveLength(100);
|
||||||
|
expect(lines[0]).toEqual('Line 1');
|
||||||
|
expect(lines[99]).toEqual('Line 100');
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('execSilent vs exec output comparison', async () => {
|
||||||
|
// Both should capture the same output, but exec prints to console
|
||||||
|
const silentResult = await testSmartshell.execSilent('echo "Test output"');
|
||||||
|
const normalResult = await testSmartshell.exec('echo "Test output"');
|
||||||
|
|
||||||
|
expect(silentResult.stdout).toEqual(normalResult.stdout);
|
||||||
|
expect(silentResult.exitCode).toEqual(normalResult.exitCode);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default tap.start({
|
||||||
|
throwOnError: true,
|
||||||
|
});
|
28
test/test.ts
28
test/test.ts
@@ -1,36 +1,36 @@
|
|||||||
import { expect, tap } from '@pushrocks/tapbundle';
|
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||||
|
|
||||||
import * as smartshell from '../ts';
|
import * as smartshell from '../ts/index.js';
|
||||||
import * as smartpromise from '@pushrocks/smartpromise';
|
import * as smartpromise from '@push.rocks/smartpromise';
|
||||||
|
|
||||||
let testSmartshell: smartshell.Smartshell;
|
let testSmartshell: smartshell.Smartshell;
|
||||||
|
|
||||||
tap.test('smartshell should create a Smartshell instance', async () => {
|
tap.test('smartshell should create a Smartshell instance', async () => {
|
||||||
testSmartshell = new smartshell.Smartshell({
|
testSmartshell = new smartshell.Smartshell({
|
||||||
executor: 'bash',
|
executor: 'bash',
|
||||||
sourceFilePaths: []
|
sourceFilePaths: [],
|
||||||
});
|
});
|
||||||
expect(testSmartshell).to.be.instanceof(smartshell.Smartshell);
|
expect(testSmartshell).toBeInstanceOf(smartshell.Smartshell);
|
||||||
});
|
});
|
||||||
|
|
||||||
tap.test('smartshell should run async', async () => {
|
tap.test('smartshell should run async', async () => {
|
||||||
let execResult = await testSmartshell.exec('npm -v');
|
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 () => {
|
tap.test('smartshell should run async and silent', async () => {
|
||||||
let execResult = await testSmartshell.execSilent('npm -v');
|
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 () => {
|
tap.test('smartshell should stream a shell execution', async () => {
|
||||||
let done = smartpromise.defer();
|
let done = smartpromise.defer();
|
||||||
let execStreamingResponse = await testSmartshell.execStreaming('npm -v');
|
let execStreamingResponse = await testSmartshell.execStreaming('npm -v');
|
||||||
execStreamingResponse.childProcess.stdout.on('data', data => {
|
execStreamingResponse.childProcess.stdout.on('data', (data) => {
|
||||||
done.resolve(data);
|
done.resolve(data);
|
||||||
});
|
});
|
||||||
let data = await done.promise;
|
let data = await done.promise;
|
||||||
expect(data).to.match(/[0-9\.]*/);
|
expect(data).toMatch(/[0-9\.]*/);
|
||||||
await execStreamingResponse.finalPromise;
|
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 () => {
|
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);
|
console.log(execResult.stdout);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
tap.test('should be able to find git', async () => {
|
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({
|
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 @push.rocks/commitinfo
|
||||||
|
*/
|
||||||
|
export const commitinfo = {
|
||||||
|
name: '@push.rocks/smartshell',
|
||||||
|
version: '3.2.4',
|
||||||
|
description: 'A library for executing shell commands using promises.'
|
||||||
|
}
|
@@ -31,7 +31,7 @@ export class ShellEnv {
|
|||||||
/**
|
/**
|
||||||
* imports path into the shell from env if available and returns it with
|
* 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 commandResult = commandStringArg;
|
||||||
let commandPaths: string[] = [];
|
let commandPaths: string[] = [];
|
||||||
commandPaths = commandPaths.concat(process.env.PATH.split(':'));
|
commandPaths = commandPaths.concat(process.env.PATH.split(':'));
|
||||||
@@ -41,7 +41,7 @@ export class ShellEnv {
|
|||||||
|
|
||||||
// lets filter for unwanted paths
|
// lets filter for unwanted paths
|
||||||
// Windows WSL
|
// Windows WSL
|
||||||
commandPaths = commandPaths.filter(commandPathArg => {
|
commandPaths = commandPaths.filter((commandPathArg) => {
|
||||||
const filterResult =
|
const filterResult =
|
||||||
!commandPathArg.startsWith('/mnt/c/') &&
|
!commandPathArg.startsWith('/mnt/c/') &&
|
||||||
!commandPathArg.startsWith('Files/1E') &&
|
!commandPathArg.startsWith('Files/1E') &&
|
||||||
@@ -73,22 +73,28 @@ export class ShellEnv {
|
|||||||
this.sourceFileArray = [];
|
this.sourceFileArray = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
createEnvExecString(commandArg): string {
|
public createEnvExecString(commandArg: string): string {
|
||||||
let commandResult = '';
|
let commandResult = '';
|
||||||
let sourceString = '';
|
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) {
|
switch (this.executor) {
|
||||||
case 'bash':
|
case 'bash':
|
||||||
for (let sourceFilePath of this.sourceFileArray) {
|
commandResult = `bash -c '${pathString}${sourceString}${commandArg}'`;
|
||||||
sourceString = sourceString + `source ${sourceFilePath} && `;
|
|
||||||
}
|
|
||||||
commandResult = `bash -c '${sourceString}${commandArg}'`;
|
|
||||||
break;
|
break;
|
||||||
case 'sh':
|
case 'sh':
|
||||||
for (let sourceFilePath of this.sourceFileArray) {
|
commandResult = `${pathString}${sourceString}${commandArg}`;
|
||||||
sourceString = sourceString + `source ${sourceFilePath} && `;
|
|
||||||
}
|
|
||||||
commandResult = `${sourceString}${commandArg}`;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
commandResult = this._setPath(commandResult);
|
commandResult = this._setPath(commandResult);
|
@@ -1,17 +1,17 @@
|
|||||||
import * as plugins from './smartshell.plugins';
|
import * as plugins from './plugins.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* a log handler for spawned logs
|
* a log handler for spawned logs
|
||||||
* making sure the process doesn't run out of memory
|
* making sure the process doesn't run out of memory
|
||||||
*/
|
*/
|
||||||
export class ShellLog {
|
export class ShellLog {
|
||||||
logStore = Buffer.from('');
|
public logStore = Buffer.from('');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* log data to console
|
* log data to console
|
||||||
* @param dataArg
|
* @param dataArg
|
||||||
*/
|
*/
|
||||||
logToConsole(dataArg: string | Buffer): void {
|
public writeToConsole(dataArg: string | Buffer): void {
|
||||||
// make sure we have the data as string
|
// make sure we have the data as string
|
||||||
process.stdout.write(dataArg);
|
process.stdout.write(dataArg);
|
||||||
}
|
}
|
||||||
@@ -20,7 +20,7 @@ export class ShellLog {
|
|||||||
* add data to Buffer for later consumption
|
* add data to Buffer for later consumption
|
||||||
* @param dataArg
|
* @param dataArg
|
||||||
*/
|
*/
|
||||||
addToBuffer(dataArg: string | Buffer): void {
|
public addToBuffer(dataArg: string | Buffer): void {
|
||||||
// make sure we have the data as Buffer
|
// make sure we have the data as Buffer
|
||||||
const dataBuffer: Buffer = (() => {
|
const dataBuffer: Buffer = (() => {
|
||||||
if (!Buffer.isBuffer(dataArg)) {
|
if (!Buffer.isBuffer(dataArg)) {
|
||||||
@@ -31,8 +31,8 @@ export class ShellLog {
|
|||||||
this.logStore = Buffer.concat([this.logStore, dataBuffer]);
|
this.logStore = Buffer.concat([this.logStore, dataBuffer]);
|
||||||
}
|
}
|
||||||
|
|
||||||
logAndAdd(dataArg: string | Buffer): void {
|
public logAndAdd(dataArg: string | Buffer): void {
|
||||||
this.logToConsole(dataArg);
|
this.writeToConsole(dataArg);
|
||||||
this.addToBuffer(dataArg);
|
this.addToBuffer(dataArg);
|
||||||
}
|
}
|
||||||
}
|
}
|
55
ts/classes.smartexecution.ts
Normal file
55
ts/classes.smartexecution.ts
Normal 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
203
ts/classes.smartshell.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
@@ -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
6
ts/plugins.ts
Normal 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 };
|
@@ -1,154 +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 {
|
|
||||||
shellEnv: ShellEnv;
|
|
||||||
|
|
||||||
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
|
|
||||||
});
|
|
||||||
|
|
||||||
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) => {
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,4 +0,0 @@
|
|||||||
import * as smartpromise from '@pushrocks/smartpromise';
|
|
||||||
import * as which from 'which';
|
|
||||||
|
|
||||||
export { 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