name: 'Run in Docker with environment'
description: 'Run a command in a Docker container, while passing explicitly set environment variables into the container.'
inputs:
  dockerfile:
    description: 'A Dockerfile that defines an image'
    required: true
  scope:
    description: 'A cached image scope'
    required: false
    default: ${{ runner.arch }}
  command:
    description: 'A command to run in a container'
    required: true
runs:
  using: "composite"
  steps:
    - uses: docker/setup-buildx-action@v3

    - uses: docker/build-push-action@v6
      id: main_builder
      continue-on-error: true
      with:
        context: .
        file: ${{ inputs.dockerfile }}
        load: true
        cache-from: type=gha,scope=${{ inputs.scope }}

    - uses: docker/build-push-action@v6
      id: retry_builder
      if: steps.main_builder.outcome == 'failure'
      with:
        context: .
        file: ${{ inputs.dockerfile }}
        load: true
        cache-from: type=gha,scope=${{ inputs.scope }}

    - # Workaround for https://github.com/google/sanitizers/issues/1614 .
      # The underlying issue has been fixed in clang 18.1.3.
      run: sudo sysctl -w vm.mmap_rnd_bits=28
      shell: bash

    - # Tell Docker to pass environment variables in `env` into the container.
      run: >
        docker run \
          $(echo '${{ toJSON(env) }}' | jq -r 'keys[] | "--env \(.) "') \
          --volume ${{ github.workspace }}:${{ github.workspace }} \
          --workdir ${{ github.workspace }} \
          $(docker images -q | head -n1) \
          bash -c "
            git config --global --add safe.directory ${{ github.workspace }}
            ${{ inputs.command }}
          "
      shell: bash
