Skip to content

Instantly share code, notes, and snippets.

@samdoran
Created November 21, 2024 05:45
Show Gist options
  • Select an option

  • Save samdoran/a4d41fe8a6784eeec31af70036ca7320 to your computer and use it in GitHub Desktop.

Select an option

Save samdoran/a4d41fe8a6784eeec31af70036ca7320 to your computer and use it in GitHub Desktop.

Revisions

  1. samdoran created this gist Nov 21, 2024.
    57 changes: 57 additions & 0 deletions bake.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    #!/usr/bin/env python

    from __future__ import annotations

    import argparse
    import subprocess
    import sys
    import time


    def run(command: str | list[str], capture_output: bool = False, container_id: None | str = None) -> subprocess.CompletedProcess[str]:
    try:
    return subprocess.run(command, check=True, text=True, capture_output=capture_output)
    except subprocess.CalledProcessError as err:
    if container_id:
    if capture_output:
    print(f"ERROR: {err.stderr}, {err.stdout}")

    print(f"Stopping container {container_id}")
    subprocess.run(["docker", "stop", container_id])

    sys.exit(err.returncode)


    def main() -> None:
    """Main entry point."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--container-runtime", default="docker")
    parser.add_argument("container", nargs="?", default="release_notes_db_image")
    parser.add_argument("--no-cache", action="store_true")

    args = parser.parse_args()
    container_runtime = args.container_runtime
    container = args.container
    no_cache = args.no_cache

    build_command = [container_runtime, "build", "--tag", container, "--file", "Containerfile", "."]
    if no_cache:
    build_command.insert(2, "--no-cache")

    print("Building container.")
    run(build_command)

    print("Running container to initialize database")
    container_id = run([container_runtime, "run", "--rm", "--tty", "--detach", container], capture_output=True).stdout.rstrip()

    print("Saving container with populated database.")
    run([container_runtime, "commit", container_id, f"{container}:final"])

    print("Stopping container")
    run([container_runtime, "stop", container_id])

    print("Build complete.")


    if __name__ == "__main__":
    main()