name: Autodeps

on:
  workflow_dispatch:
  schedule:
    - cron:  '0 0 1 * *'

jobs:
  Autodeps:
    if: github.repository_owner == 'python-trio'
    name: Autodeps
    timeout-minutes: 10
    runs-on: 'ubuntu-latest'
    # https://docs.github.com/en/code-security/dependabot/working-with-dependabot/automating-dependabot-with-github-actions#changing-github_token-permissions
    permissions:
      pull-requests: write
      issues: write
      repository-projects: write
      contents: write

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          persist-credentials: true  # credentials are needed to push commits
      - name: Setup python
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"

      - name: Bump dependencies
        run: |
          python -m pip install -U pip pre-commit
          python -m pip install -r test-requirements.txt
          uv pip compile --universal --python-version=3.10 --upgrade test-requirements.in -o test-requirements.txt
          uv pip compile --universal --python-version=3.11 --upgrade docs-requirements.in -o docs-requirements.txt
          pre-commit autoupdate --jobs 0

      - name: Install new requirements
        run: python -m pip install -r test-requirements.txt

      - name: Pre-commit fixes
        run: pre-commit run -a || true

      - name: Commit changes and create automerge PR
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          # setup git repo
          git switch --force-create autodeps/bump_from_${GITHUB_SHA:0:6}
          git config user.name 'github-actions[bot]'
          git config user.email '41898282+github-actions[bot]@users.noreply.github.com'

          if ! git commit -am "Dependency updates"; then
            echo "No changes to commit!"
            exit 0
          fi

          git push --force --set-upstream origin autodeps/bump_from_${GITHUB_SHA:0:6}

          # git push returns before github is ready for a pr, so we poll until success
          for BACKOFF in 1 2 4 8 0; do
            sleep $BACKOFF
            if gh pr create \
              --label dependencies --body "" \
              --title "Bump dependencies from commit ${GITHUB_SHA:0:6}" \
              ; then
              break
            fi
          done

          if [ $BACKOFF -eq 0 ]; then
            echo "Could not create the PR"
            exit 1
          fi

          # gh pr create returns before the pr is ready, so we again poll until success
          # https://github.com/cli/cli/issues/2619#issuecomment-1240543096
          for BACKOFF in 1 2 4 8 0; do
            sleep $BACKOFF
            if gh pr merge --auto --squash; then
              break
            fi
          done

          if [ $BACKOFF -eq 0 ]; then
            echo "Could not set automerge"
            exit 1
          fi
