# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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

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

permissions: {}

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
        with:
          persist-credentials: false

      - name: Get changed files
        id: changed-files
        uses: tj-actions/changed-files@3f54ebb830831fc121d3263c1857cfbdc310cdb9 #v42
        with:
          files: docker/**
          json: "true"

      - name: Run step if only the files listed above change  # zizmor: ignore[template-injection]
        if: steps.changed-files.outputs.any_changed == 'true'
        id: set-matrix
        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
        with:
          cache-binary: false

      - name: Check out code
        uses: actions/checkout@v4
        with:
          persist-credentials: false

      - 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 }}
