# Inspired by
# https://github.com/huggingface/peft/blob/main/.github/workflows/test-docker-build.yml
name: Test Dockerfiles

on:
  pull_request:
    branches:
      - main
    paths:
      # Run only when DockerFile files are modified
      - "docker/**"

env:
  PYTHON_VERSION: "3.10"

jobs:
  get_changed_files:
    name: Detect modified Dockerfiles
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
    steps:
      - name: Check out code
        uses: actions/checkout@v4

      - name: Get changed files
        id: changed-files
        uses: tj-actions/changed-files@v44
        with:
          files: docker/**
          json: "true"

      - name: Run step if only the files listed above change
        if: steps.changed-files.outputs.any_changed == 'true'
        id: set-matrix
        env:
          ALL_CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }}
        run: |
          echo "matrix=${{ steps.changed-files.outputs.all_changed_files}}" >> $GITHUB_OUTPUT


  build_modified_dockerfiles:
    name: Build modified Docker images
    needs: get_changed_files
    runs-on:
      group: aws-general-8-plus
    if: ${{ needs.get_changed_files.outputs.matrix }} != ''
    strategy:
      fail-fast: false
      matrix:
        docker-file: ${{ fromJson(needs.get_changed_files.outputs.matrix) }}
    steps:
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Check out code
        uses: actions/checkout@v4

      - name: Build Docker image
        uses: docker/build-push-action@v5
        with:
          file: ${{ matrix.docker-file }}
          context: .
          push: False
          build-args: PYTHON_VERSION=${{ env.PYTHON_VERSION }}
