# Build and publish a Docker image.
#
# Assumed to run as a subworkflow of .github/workflows/release.yml; specifically, as a local
# artifacts job within `cargo-dist`.
#
# TODO(charlie): Ideally, the publish step would happen as a publish job within `cargo-dist`, but
# sharing the built image as an artifact between jobs is challenging.
name: "Build Docker image"

on:
  workflow_call:
    inputs:
      plan:
        required: true
        type: string
  pull_request:
    paths:
      - .github/workflows/build-docker.yml

jobs:
  docker-publish:
    name: Build Docker image (ghcr.io/astral-sh/uv)
    runs-on: ubuntu-latest
    environment:
      name: release
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: recursive

      - uses: docker/setup-buildx-action@v3

      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/astral-sh/uv

      - name: Check tag consistency
        if: ${{ inputs.plan != '' && !fromJson(inputs.plan).announcement_tag_is_implicit }}
        run: |
          version=$(grep "version = " pyproject.toml | sed -e 's/version = "\(.*\)"/\1/g')
          if [ "${{ fromJson(inputs.plan).announcement_tag }}" != "${version}" ]; then
            echo "The input tag does not match the version from pyproject.toml:" >&2
            echo "${{ fromJson(inputs.plan).announcement_tag }}" >&2
            echo "${version}" >&2
            exit 1
          else
            echo "Releasing ${version}"
          fi

      - name: "Build and push Docker image"
        uses: docker/build-push-action@v5
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          # Reuse the builder
          cache-from: type=gha
          cache-to: type=gha,mode=max
          push: ${{ inputs.plan != '' && !fromJson(inputs.plan).announcement_tag_is_implicit }}
          tags: ghcr.io/astral-sh/uv:latest,ghcr.io/astral-sh/uv:${{ (inputs.plan != '' && fromJson(inputs.plan).announcement_tag) || 'dry-run' }}
          labels: ${{ steps.meta.outputs.labels }}
