2022-08-13 18:52:32 +02:00
|
|
|
import os
|
|
|
|
import subprocess
|
2023-02-18 16:21:03 +01:00
|
|
|
from typing import Any
|
2022-08-13 18:52:32 +02:00
|
|
|
|
2022-12-29 18:13:19 +01:00
|
|
|
from loguru import logger as log
|
2022-08-13 18:52:32 +02:00
|
|
|
|
|
|
|
|
2023-02-18 16:21:03 +01:00
|
|
|
def run_hook(command: str, hook_type: str, **kwargs: Any) -> int:
|
2023-02-18 12:29:25 +01:00
|
|
|
"""Run a command.
|
|
|
|
|
|
|
|
Run a command with subprocess.run and add kwargs to the environment.
|
|
|
|
|
2022-08-13 18:52:32 +02:00
|
|
|
Args:
|
2022-12-29 18:13:19 +01:00
|
|
|
command (str): command to run
|
|
|
|
hook_type (str): type of the hook
|
|
|
|
kwargs: key value pairs of env vars to set
|
2022-08-13 18:52:32 +02:00
|
|
|
|
2022-12-29 18:13:19 +01:00
|
|
|
Returns:
|
|
|
|
exit_code (int): exit code of command
|
2022-08-13 18:52:32 +02:00
|
|
|
"""
|
2022-12-29 18:13:19 +01:00
|
|
|
# check if hook commands are empty
|
|
|
|
if not command or command == "None":
|
|
|
|
log.debug(f"Hook '{hook_type}' empty. Not running")
|
|
|
|
return 2
|
2022-08-13 18:52:32 +02:00
|
|
|
|
2022-12-29 18:13:19 +01:00
|
|
|
command_list = command.split(" ")
|
2022-08-13 18:52:32 +02:00
|
|
|
|
2022-12-29 18:13:19 +01:00
|
|
|
# setting env vars
|
|
|
|
for key, value in kwargs.items():
|
|
|
|
os.environ[f"MDLP_{key.upper()}"] = str(value)
|
2022-08-13 18:52:32 +02:00
|
|
|
|
2022-12-29 18:13:19 +01:00
|
|
|
# running command
|
|
|
|
log.info(f"Hook '{hook_type}' - running command: '{command}'")
|
|
|
|
proc = subprocess.run(command_list, check=False, timeout=15, encoding="utf8")
|
|
|
|
exit_code = proc.returncode
|
2022-08-13 18:52:32 +02:00
|
|
|
|
2022-12-29 18:13:19 +01:00
|
|
|
if exit_code == 0:
|
|
|
|
log.debug("Hook returned status code 0. All good")
|
|
|
|
else:
|
|
|
|
log.warning(f"Hook returned status code {exit_code}. Possible error")
|
2022-08-13 18:52:32 +02:00
|
|
|
|
2022-12-29 18:13:19 +01:00
|
|
|
# return exit code of command
|
|
|
|
return exit_code
|