name: Update Sorbet files
on:
  push:
    paths:
      - .github/workflows/sorbet.yml
    branches-ignore:
      - master
  schedule:
    - cron: '0 0 * * *'
jobs:
  tapioca:
    if: github.repository == 'Homebrew/brew'
    runs-on: ubuntu-latest
    steps:
      - name: Set up Homebrew
        id: set-up-homebrew
        uses: Homebrew/actions/setup-homebrew@master

      - name: Configure Git user
        uses: Homebrew/actions/git-user-config@master
        with:
          username: BrewTestBot

      - name: Update Tapioca definitions
        id: update
        run: |
          git fetch origin

          BRANCH="sorbet-files-update"
          echo "::set-output name=branch::${BRANCH}"

          if git ls-remote --exit-code --heads origin "$BRANCH"; then
            git checkout "$BRANCH"
            git reset origin/master
          else
            git checkout -B "$BRANCH" origin/master
            BRANCH_EXISTS="1"
          fi

          if brew typecheck --update --fail-if-not-changed; then
            git add "$GITHUB_WORKSPACE/Library/Homebrew/sorbet"
            git commit -m "sorbet: Update RBI files." \
                       -m "Autogenerated by the [sorbet](https://github.com/Homebrew/brew/blob/master/.github/workflows/sorbet.yml) workflow."
            echo "::set-output name=committed::true"
            if [ -n "$BRANCH_EXISTS" ]; then
              echo "::set-output name=pull_request::true"
            fi
          fi

      - name: Push commits
        if: steps.update.outputs.committed == 'true'
        uses: Homebrew/actions/git-try-push@master
        with:
          token: ${{ secrets.HOMEBREW_GITHUB_API_TOKEN }}
          branch: ${{ steps.update.outputs.branch }}
          force: true

      - name: Open a pull request
        if: steps.update.outputs.pull_request == 'true'
        run: hub pull-request --no-edit
        env:
          GITHUB_TOKEN: ${{ secrets.HOMEBREW_GITHUB_API_TOKEN }}
