aboutsummaryrefslogtreecommitdiff
path: root/gn3
diff options
context:
space:
mode:
authorMunyoki Kilyungi2024-04-17 14:18:11 +0300
committerBonfaceKilz2024-04-30 12:18:58 +0300
commit8d9cc98a261feda984eeb3d02e64c7a06d4413ec (patch)
tree066de956f78a07313e9d49d8d2b0896da8945802 /gn3
parent515f80661d44427fe32914c5071905794a20b67b (diff)
downloadgenenetwork3-8d9cc98a261feda984eeb3d02e64c7a06d4413ec.tar.gz
Add command function that returns an Either monad.
* gn3/commands.py: Import Either, Left, Right. (monadic_run_cmd): New function. Signed-off-by: Munyoki Kilyungi <me@bonfacemunyoki.com>
Diffstat (limited to 'gn3')
-rw-r--r--gn3/commands.py23
1 files changed, 23 insertions, 0 deletions
diff --git a/gn3/commands.py b/gn3/commands.py
index b873d4d..79e1e7e 100644
--- a/gn3/commands.py
+++ b/gn3/commands.py
@@ -18,6 +18,8 @@ from uuid import uuid4
from flask import current_app
from redis.client import Redis # Used only in type hinting
+from pymonad.either import Either, Left, Right
+
from gn3.chancy import random_string
from gn3.exceptions import RedisConnectionError
@@ -168,3 +170,24 @@ def run_async_cmd(
cmd_id = queue_cmd(conn, job_queue, cmd, email, env)
subprocess.Popen([f"{sys.executable}", "-m", "sheepdog.worker"]) # pylint: disable=[consider-using-with]
return cmd_id
+
+
+def monadic_run_cmd(cmd) -> Either:
+ """Run a given command and return it's results as an Either monad"""
+ result = ""
+ try:
+ result = subprocess.run(cmd,
+ capture_output=True,
+ check=True).stdout.decode()
+ # This command does not exist
+ except FileNotFoundError as excpt:
+ return Left({
+ "command": cmd,
+ "error": str(excpt),
+ })
+ except subprocess.CalledProcessError as excpt:
+ return Left({
+ "command": cmd,
+ "error": str(excpt),
+ })
+ return Right(result)