Handle exceptions and print stderr

This commit is contained in:
erik 2023-07-12 13:36:23 +02:00
parent 07cf60ba59
commit c182505b76

View file

@ -1,4 +1,4 @@
from subprocess import Popen, PIPE, run from subprocess import Popen, PIPE, run, CalledProcessError
from pathlib import Path from pathlib import Path
from sys import stdout from sys import stdout
from os import chmod, environ from os import chmod, environ
@ -49,55 +49,42 @@ class FileApi:
class ImageApi: class ImageApi:
def __init__(self):
self.execution_api = ExecutionApi()
def image(self, name: str, path: Path): def image(self, name: str, path: Path):
run( self.execution_api.run_handled(
f"docker build -t {name} --file {path}/image/Dockerfile {path}/image", f"docker build -t {name} --file {path}/image/Dockerfile {path}/image"
shell=True,
check=True,
) )
def drun(self, name: str): def drun(self, name: str):
run( self.execution_api.run_handled(
f'docker run -it --entrypoint="" {name} /bin/bash', f'docker run -it --entrypoint="" {name} /bin/bash'
shell=True,
check=True,
) )
def dockerhub_login(self, username: str, password: str): def dockerhub_login(self, username: str, password: str):
run( self.execution_api.run_handled(
f"docker login --username {username} --password {password}", f"docker login --username {username} --password {password}"
shell=True,
check=True,
) )
def dockerhub_publish(self, name: str, username: str, tag=None): def dockerhub_publish(self, name: str, username: str, tag=None):
if tag is not None: if tag is not None:
run( self.execution_api.run_handled(
f"docker tag {name} {username}/{name}:{tag}", f"docker tag {name} {username}/{name}:{tag}"
shell=True,
check=True,
) )
run( self.execution_api.run_handled(
f"docker push {username}/{name}:{tag}", f"docker push {username}/{name}:{tag}"
shell=True,
check=True,
) )
run( self.execution_api.run_handled(
f"docker tag {name} {username}/{name}:latest", f"docker tag {name} {username}/{name}:latest"
shell=True,
check=True,
) )
run( self.execution_api.run_handled(
f"docker push {username}/{name}:latest", f"docker push {username}/{name}:latest"
shell=True,
check=True,
) )
def test(self, name: str, path: Path): def test(self, name: str, path: Path):
run( self.execution_api.run_handled(
f"docker build -t {name} -test --file {path}/test/Dockerfile {path}/test", f"docker build -t {name} -test --file {path}/test/Dockerfile {path}/test"
shell=True,
check=True,
) )
@ -123,6 +110,18 @@ class ExecutionApi:
print(line.decode("utf-8"), end="") print(line.decode("utf-8"), end="")
process.stdout.close() process.stdout.close()
process.wait() process.wait()
def run_handled(self, command: str, shell=True, check=True):
try:
run(
command,
shell=shell,
check=check,
capture_output=True,
text=True)
except CalledProcessError as exc:
print("Command failed with code: ", exc.returncode, " and message:", exc.stderr)
class EnvironmentApi: class EnvironmentApi: