From 8388362701db8e8d1afdd6763854170c76e825c9 Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Tue, 19 Dec 2023 22:49:02 +0100 Subject: [PATCH] refactor: move subprocess calls to function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - extract subprocess execution into a separate function - replace direct subprocess calls with function calls 🤖 --- dc-ops | 51 +++++++++++++++++++++++++-------------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/dc-ops b/dc-ops index 6cf6a04..34ef7c1 100755 --- a/dc-ops +++ b/dc-ops @@ -21,6 +21,25 @@ with configfile.open("r") as f: loglevel = cfg.get("loglevel", "INFO").upper() log.basicConfig(format="%(message)s", level=loglevel) + +def run_subprocess(command: str, workdir: str) -> bool: + """execute subprocess and print output + + Args: + cmd (str): command + cwd (str): working directory + + Returns: + bool: False if subprocess fails + """ + try: + subprocess.run(command, cwd=workdir, shell=True, text=True) + except subprocess.CalledProcessError: + return False + + return True + + # iterate all stacks for stack in cfg["stacks"]: # skip disabled stacks @@ -59,40 +78,20 @@ for stack in cfg["stacks"]: # run pre-command if "pre" in stack: - try: - subprocess.run( - stack["pre"], - cwd=stackdir, - shell=True, - text=True, - ) - except subprocess.CalledProcessError: + if not run_subprocess(stack["pre"], stackdir): continue # run `docker compose` for all compose-files # (or just for the directory if no compose-file defined) composefiles = stack.get("compose-files", ["docker-compose.yml"]) for composefile in composefiles: - try: - subprocess.run( - f"docker compose --file {composefile} up --build --detach --remove-orphans", # noqa - cwd=stackdir, - shell=True, - text=True, - ) - except subprocess.CalledProcessError: + if not run_subprocess( + f"docker compose --file {composefile} up --build --detach --remove-orphans", # noqa + stackdir, + ): pass # run post-command if "post" in stack: - try: - print( - subprocess.run( - stack["post"], - cwd=stackdir, - shell=True, - text=True, - ) - ) - except subprocess.CalledProcessError: + if not run_subprocess(stack["post"], stackdir): continue