name: Check mergeability of ghstack PR

on:
  pull_request:
    types: [opened, synchronize, reopened]
    branches: [gh/**/base]

jobs:
  ghstack-mergeability-check:
    if: github.repository_owner == 'pytorch'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup git
        shell: bash
        run: |
          git config --global user.email "pytorchmergebot@users.noreply.github.com"
          git config --global user.name "PyTorch MergeBot"
          git fetch origin main:main

      - name: Wait for orig branch
        shell: bash
        run: |
          BRANCH="${{ github.base_ref }}"
          echo "$BRANCH"
          BRANCH="${BRANCH%/base}/orig"
          echo "$BRANCH"

          WAIT_SECONDS=300
          END_WAIT=$((SECONDS+WAIT_SECONDS))
          BRANCH_EXISTS=0

          while [ $SECONDS -lt $END_WAIT ]; do
            git fetch --prune origin "${BRANCH}" || true
            if git rev-parse --verify "origin/${BRANCH}"; then
              BRANCH_EXISTS=1
              break
            fi
            echo "Waiting for branch ${BRANCH} to exist..."
            sleep 30  # Wait for 30 seconds before retrying
          done

          if [ $BRANCH_EXISTS -eq 0 ]; then
            echo "Branch ${BRANCH} not found after ${WAIT_SECONDS} seconds."
            echo "Mergeability check failed for infrastructure reasons."
            exit 1
          fi

      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.9'
          cache: pip
          architecture: x64

      - run: pip install pyyaml==6.0
        shell: bash

      - name: Verify mergeability
        shell: bash
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_NUM: ${{ github.event.pull_request.number }}
        run: |
          set -ex
          python3 .github/scripts/trymerge.py --check-mergeability "${PR_NUM}"

      - name: Print debug info
        if: failure()
        shell: bash
        env:
          PR_NUM: ${{ github.event.pull_request.number }}
        run: |
          {
            echo "# PR $PR_NUM is not mergeable into main"
            echo "To debug, run the diagnostic workflow:"
            echo "https://github.com/pytorch/test-infra/actions/workflows/pr-dependencies-check.yml"
          } >> "$GITHUB_STEP_SUMMARY"


concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}-${{ github.event_name == 'workflow_dispatch' }}
  cancel-in-progress: true
