#!/usr/bin/env python3 """Build the package in a container and write it to out/: build.py [CONTAINER BUILD OPTIONS]. The Dockerfile builds the Manager's application and the package, whose debian/changelog it writes from CHANGELOG.md; the build's files are then streamed out of the image as a tar archive into out/, so no bind mount is needed. The container runtime is CONTAINER_RUNTIME from the environment, for example docker with DOCKER_CONTEXT naming a remote engine, else Apple's container CLI on macOS and Docker on Linux. Options are passed to the runtime's build, such as --build-arg DEB_VERSION=V. A failure is a message on standard error and a non-zero exit status. """ import os import pathlib import platform import subprocess import sys import tarfile ROOT = pathlib.Path(__file__).resolve().parent OUT = ROOT / 'out' IMAGE = 'linux-manager-builder' #: The container runtime of each platform when CONTAINER_RUNTIME is not set. RUNTIMES = {'Darwin': 'container', 'Linux': 'docker'} def main(): runtime = os.environ.get('CONTAINER_RUNTIME') or RUNTIMES.get(platform.system()) if not runtime: sys.exit(f'build.py: unsupported platform {platform.system()}; set CONTAINER_RUNTIME') OUT.mkdir(exist_ok=True) build = [runtime, 'build', '--build-arg', f'HOST_UID={os.getuid()}', '--build-arg', f'HOST_GID={os.getgid()}', '-t', IMAGE, *sys.argv[1:], '.'] if subprocess.run(build, cwd=ROOT).returncode != 0: sys.exit('build.py: the image build failed') with subprocess.Popen([runtime, 'run', '--rm', IMAGE, 'tar', '-cf', '-', '-C', '/out', '.'], cwd=ROOT, stdout=subprocess.PIPE) as stream: with tarfile.open(fileobj=stream.stdout, mode='r|') as archive: archive.extractall(OUT, filter='data') if stream.returncode != 0: sys.exit('build.py: the build files could not be copied out of the image') print(f'Build artifacts written to {OUT.relative_to(ROOT)}/') return 0 if __name__ == '__main__': sys.exit(main())