name: Pre-Commit Check

on:
  workflow_call:

jobs:
  pre-commit:
    name: pre-commit (code formatting)
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
          cache: 'pip'
      - name: Compute hash of pre-commit config
        id: cache-key
        run: |
          echo "pre_commit_hash=$(sha256sum .pre-commit-config.yaml | cut -d ' ' -f 1)" >> $GITHUB_OUTPUT
        shell: bash
      - name: Cache pre-commit's cache dir
        uses: actions/cache@v4
        with:
          # Note that we cannot use environment variables here given there is
          # no shell to interpret them in the paths.
          path: |
            ~/.cache/pre-commit
          key: ${{ runner.os }}-${{ steps.cache-key.outputs.pre_commit_hash }}
      - name: Check pre-commit
        run: |
          python3 -m pip install --upgrade pre-commit
          python3 -m pre_commit run --all-files --verbose
      - name: Print diff of changes if pre-commit failed
        if: failure()
        run: |
          git diff
