name: prettier

on:
  pull_request_target:
    types: [opened, edited, reopened, synchronize]

concurrency: 
  group: ${{github.workflow}} - ${{github.ref}}
  cancel-in-progress: true

jobs:
  format:
    # ---------------------------------------------------------
    # SAFETY CHECK:
    # Only run for PRs from the SAME repository.
    # Fork PRs are skipped entirely to prevent RCE via pnpm install.
    # ---------------------------------------------------------
    if: ${{ github.event.pull_request.head.repo.fork == false }}
    permissions:
      contents: write
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          repository: ${{ github.event.pull_request.head.repo.full_name }}
          ref: ${{ github.head_ref }}
          fetch-depth: 0
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 18
      - name: Install pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 10.25.0
      - name: Install Dependencies
        run: pnpm install
      - name: Run prettier
        run: |
          git config --global core.quotepath off
          changed_files=$(git diff --name-only "${{ github.event.pull_request.base.sha }}" | grep -E '\.js$|\.ts$|\.php$|\.sql$|\.md$' || true)
          if [ -n "$changed_files" ]; then
            echo "Running prettier on the changed files"
            echo "$changed_files" | xargs -d '\n' pnpm exec prettier --write
          else
            echo "No matching files to run prettier on."
          fi
      - name: Commit changes
        uses: stefanzweifel/git-auto-commit-action@v5
        with:
          commit_message: "style: format code and docs with prettier"
          commit_user_name: idoocs
          commit_user_email: doocs-bot@outlook.com