From b2bcd88004f6ca31313a17132190e6e8243f7a4e Mon Sep 17 00:00:00 2001 From: Kamaal Farah Date: Wed, 24 Apr 2024 14:25:21 +0200 Subject: [PATCH] Adding async exec --- package.json | 3 +++ src/index.ts | 1 + src/shell/async-exec.ts | 42 +++++++++++++++++++++++++++++++++++++++++ src/shell/index.ts | 1 + yarn.lock | 5 +++++ 5 files changed, 52 insertions(+) create mode 100644 src/shell/async-exec.ts create mode 100644 src/shell/index.ts diff --git a/package.json b/package.json index e6216f0..ed08514 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,9 @@ "peerDependencies": {}, "name": "@kamaalio/kamaal", "author": "Kamaal Farah", + "dependencies": { + "@thames/monads": "^0.6.2" + }, "devDependencies": { "@babel/core": "^7.24.4", "@babel/preset-env": "^7.24.4", diff --git a/src/index.ts b/src/index.ts index 29f414d..d000e93 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,3 +2,4 @@ export * as objects from './objects'; export * as maths from './maths'; export * as strings from './strings'; export * as arrays from './arrays'; +export * as shell from './shell'; diff --git a/src/shell/async-exec.ts b/src/shell/async-exec.ts new file mode 100644 index 0000000..724cff2 --- /dev/null +++ b/src/shell/async-exec.ts @@ -0,0 +1,42 @@ +import { exec } from 'node:child_process'; +import type { ExecException, ExecOptions } from 'node:child_process'; + +import { Err, Ok } from '@thames/monads'; +import type { Result } from '@thames/monads'; + +async function internalAsyncExec( + command: string, + options?: ExecOptions +): Promise { + return await new Promise((resolve, reject) => { + exec(command, options ?? {}, (error, stdout, stderr) => { + if (error != null) { + reject(error); + return; + } + + if (stderr !== '') { + reject(stderr); + return; + } + + resolve(stdout); + }); + }); +} + +export async function asyncExec( + command: string, + commandWorkingDirectory?: string +): Promise> { + let result: Awaited>; + try { + result = await internalAsyncExec(command, { cwd: commandWorkingDirectory }); + } catch (error) { + return Err(error as ExecException | string); + } + + return Ok(result); +} + +export default asyncExec; diff --git a/src/shell/index.ts b/src/shell/index.ts new file mode 100644 index 0000000..578978a --- /dev/null +++ b/src/shell/index.ts @@ -0,0 +1 @@ +export * from './async-exec'; diff --git a/yarn.lock b/yarn.lock index d271de0..4193b97 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1360,6 +1360,11 @@ eslint-visitor-keys "^3.4.3" espree "^9.6.1" +"@thames/monads@^0.6.2": + version "0.6.2" + resolved "https://registry.yarnpkg.com/@thames/monads/-/monads-0.6.2.tgz#471fcbbc21f4beb578156f18c2e27c82af51a273" + integrity sha512-LxsJ5g4kYK/VS+s+b5fEz6GG1v5eyysURaDE3hOjQB1vmWaCsRoqAKOwpl8YF9FZ86on1BwxIHev3ZF8u41X7g== + "@tsconfig/node10@^1.0.7": version "1.0.11" resolved "https://registry.yarnpkg.com/@tsconfig/node10/-/node10-1.0.11.tgz#6ee46400685f130e278128c7b38b7e031ff5b2f2"