lib/mix/tasks/pot.build.ex

defmodule Mix.Tasks.Pot.Build do
  use Mix.Task
  require Logger

  @shortdoc "Builds the image from the Dockerfile created by pot"
  @impl Mix.Task
  def run([]) do
    Mix.Task.rerun("pot.build", [:no_name])
  end

  @shortdoc "Builds the image from the Dockerfile created by pot"
  @impl Mix.Task
  def run([pot_name]) do
    runtime = PotUtils.get_runtime()
    Logger.info("Using container runtime: #{runtime}")
    build_image(pot_name)
  end

  @doc """
  Takes in the runtime ["docker" | "podman" | "nerdctl"], the pot name
  passed in as arguments or `:no_name`. It will check to see
  if there is an exisiting Dockerfile generated by pot
  and if not run the tast `pot.new` with default arguments.
  Then it will run the container runtime command in the following
  format to generate the image.
  `<container-runtime> build -f <docker-file> --build-arg MIX_ENV=dev -t <app-name> --label pot_<app-name>=pot`
  """
  def build_image(pot_name) do
    docker_file = PotUtils.get_docker_file_for_pot(pot_name)
    Logger.info("Building dockerfile: #{docker_file}")

    if !File.exists?(docker_file) do
      Logger.info("Docker file not found, create file: #{docker_file}")
      Mix.Task.run("pot.new", [])
    end

    Logger.info("Creating dockerfile: #{docker_file}")
    app_name = PotUtils.app_name()

    PotUtils.runtime_cmd(
      "build -f #{docker_file} --build-arg MIX_ENV=dev -t #{app_name} --label pot_#{app_name}=pot"
    )
  end
end