name: pre-commit

on:
  pull_request:

jobs:
  pre-commit:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
      with:
          fetch-depth: 0
          ref: ${{ github.event.pull_request.head.sha }}

    # the PR branch and the hpcaitech/colossal-ai main branch
    # must share a common commit, we need to locate that commit,
    # which is the commit checked-out or forked when the PR branch is created
    # such that we can look for files changed since that commit
    - name: Locate base commit
      id: locate-base-sha
      run: |
          curBranch=$(git rev-parse --abbrev-ref HEAD)
          commonCommit=$(git merge-base origin/main $curBranch)
          echo $commonCommit
          echo "baseSHA=$commonCommit" >> $GITHUB_OUTPUT

    - name: Find the changed files
      id: find-changed-files
      uses: tj-actions/changed-files@v35
      with:
        base_sha: ${{ steps.locate-base-sha.outputs.baseSHA }}

    - name: List all changed files
      run: |
        for file in ${{ steps.find-changed-files.outputs.all_changed_files }}; do
          echo "$file was changed"
        done

    - uses: actions/setup-python@v3

    - name: Cache pre-commit hooks
      uses: actions/cache@v3
      with:
        path: ~/.cache/pre-commit
        key: ${{ runner.os }}-pre-commit-hooks

    - name: Set up pre-commit
      run: |
        pip install pre-commit
        pre-commit install

    - name: Run pre-commit on Changed Files
      id: precommit
      run: |
        for file in ${{ steps.find-changed-files.outputs.all_changed_files }}; do
          echo "======= running pre-commit on ${file} ======="
          pre-commit run --files $file
        done

    - name: Save PR number
      if: always()
      env:
        PR_NUMBER: ${{ github.event.number }}
      run: |
        mkdir -p ./pr
        echo $PR_NUMBER > ./pr/pr_number
    - uses: actions/upload-artifact@v3
      if: always()
      with:
        name: pr_number
        path: pr/
