# .github/workflows/precheck.yml
name: PR Precheck
on: [pull_request]

permissions:
  contents: read
  issues: write

jobs:
  conflict-check:
    runs-on: ubuntu-24.04
    outputs:
      conflict: ${{ steps.check-conflicts.outputs.conflict }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ github.event.pull_request.head.sha }}
      - name: Check Conflicts
        id: check-conflicts
        env:
          BASE_REF: ${{ github.event.pull_request.base.ref }}
        run: |
          set -euo pipefail

          git fetch origin "$BASE_REF":"refs/remotes/origin/$BASE_REF" --depth=1
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git config user.name "github-actions[bot]"

          if git merge --no-commit --no-ff "origin/$BASE_REF" > /tmp/precheck-merge.log 2>&1; then
            echo "conflict=false" >> "$GITHUB_OUTPUT"
            echo "No conflicts detected against origin/$BASE_REF"
            git merge --abort > /dev/null 2>&1 || true
            exit 0
          fi

          if git diff --name-only --diff-filter=U | grep -q .; then
            echo "conflict=true" >> "$GITHUB_OUTPUT"
            echo "Conflicts detected against origin/$BASE_REF:"
            git diff --name-only --diff-filter=U
          else
            echo "conflict=false" >> "$GITHUB_OUTPUT"
            echo "Merge check returned non-zero without unmerged files against origin/$BASE_REF"
            cat /tmp/precheck-merge.log
          fi

          git merge --abort > /dev/null 2>&1 || true
        shell: bash
  labeler:
    runs-on: ubuntu-24.04
    needs: conflict-check
    if: needs.conflict-check.outputs.conflict == 'true'
    steps:
      - uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.addLabels({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              labels: ['🚫冲突需处理']
            })
