Search code examples
githubgithub-pagesgithub-actions

GitHub action runs twice on merge


I have a build and deploy GitHub action that runs when I update my GitHub pages repository. In addition I have one that updates the recipes using I store.

Most of the time it runs fine but occasionally I update from my phone (with Working Copy) and do a merge, then each action runs twice, all of them triggered by the same push. The recipe update action succeeds both times.

Yet when that happens one of the build and deploy actions fails with something like “! [remote rejected] master -> gh-pages (cannot lock ref 'refs/heads/gh-pages': is at 37c581108d857f9d9c8fe584103d78e4473d280b but expected ceaf2249cc2f7864f0269e64d372fc40ce0b06e0)”

It doesn’t break anything but I’m not sure why it happens and I’d like to fix it.

Build and deploy


on:
  push:
    branches:
      - main
  schedule:
    - cron:  '0 */2 * * *'
  workflow_dispatch:


jobs:

  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Code
        uses: actions/checkout@v2
        with:
          persist-credentials: false

      - name: Setup Python Environment
        uses: actions/setup-python@v2
        with:
          python-version: 3.8
        
      - name: Install Requirements
        run: pip install -r requirements.txt

      - name: Execute Python script
        run: |
          python3 -m papexp
        env:
          EMAIL: ${{ secrets.EMAIL }}
          PASSWORD: ${{ secrets.PASSWORD }}

      - name: setup git config
        run: |
          git config --local user.name ${{ secrets.USERNAME_GITHUB }}
          git config --local user.email ${{ secrets.EMAIL }}
          git pull --ff-only origin main
          git add images/recipes/*
          git add .
          git commit -am "Update recipes" || echo "Nothing to update"
      - name: Push changes
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: ${{ github.ref }}

Solution

  • I don't think the action is running twice because of a single push, and I don't think it's related to whether you update from your mobile or not.

    Your action runs when you push to main, but it also runs every 2 hours. So sometimes you're going to get conflicts, when the action triggered by a push runs at the same time as a scheduled action.

    If you need the action to run in both situations (triggered and scheduled), and if the occasional collisions aren't causing you problems, I'd just put up with it TBH. Trying to implement some kind of locking mechanism to avoid collisions is probably more effort than it's worth.