runner-images/build_image.py
Marc Cataford 3cf574de84
Some checks failed
/ post-run (push) Has been skipped
/ pre-run (push) Successful in 22s
/ build-images (ubuntu-2204) (push) Failing after 53s
ci: replace shell scripts with python util
2024-07-28 23:20:04 -04:00

94 lines
2.2 KiB
Python

"""
Builds a container image with the provided image name and tag.
Usage:
python build_image.py <image-name> <tag> [<image-path>]
"""
import subprocess
import pathlib
import logging
import typing
import sys
import os
import re
logger = logging.getLogger("build-image")
def get_tag(is_ci: bool) -> str:
"""
Gets an image tag composed of the short sha of the current commit
and, depending on the is_ci flag, a "-dev" suffix.
"""
result = subprocess.run(
"git rev-parse --short HEAD", shell=True, capture_output=True, check=True
)
sha = re.sub(r"\n", "", str(result.stdout.decode('utf-8')))
if not is_ci:
return f"{sha}-dev"
return sha
def build_image(image_name: str, tag: str, image_path: typing.Optional[pathlib.Path]):
"""
Calls Podman to build the container image defined at image_path, which defaults to
the current directory.
The built image is named and tagged using image_name and tag.
"""
if image_path is None:
image_path = pathlib.Path("./Dockerfile")
cwd = image_path.parent
image_path = image_path.relative_to(cwd)
subprocess.run(
f"podman build -t {image_name}:{tag} -f {str(image_path)}",
shell=True,
check=True,
cwd=cwd,
)
def run(args: list[str]):
"""
CLI entrypoint.
"""
if len(args) < 1:
raise ValueError(
"There should be at least one argument. "
"Correct usage: python build_image.py <image-name:tag> [image-path]"
)
if len(args) > 2:
raise ValueError(
"Unrecognized arguments. "
"Correct usage: python build_image.py <image-name:tag> [image-path]"
)
tagged_image_name = args[0]
image_name_parts = tagged_image_name.split(":")
name = image_name_parts[0]
tag = (
image_name_parts[1]
if len(image_name_parts) == 2
else get_tag(bool(os.environ.get("CI", False)))
)
image_path = args[1] if len(args) == 2 else None
build_image(name, tag, pathlib.Path(image_path))
if __name__ == "__main__":
try:
run(sys.argv[1:])
except Exception as e: # pylint: disable=broad-exception-caught
logger.error(e)