gitgithub-actions

Workflow to commit file to remote branch in a PR


I have a repo with a main branch and a testing branch. I make modifications in the testing branch, push, open a PR. This triggers the following workflow (borrowed from https://stackoverflow.com/a/73687159/659117) which creates a file (e.g. a PDF from latex files) and commits it:

name: Example workflow
on:

  pull_request:
    branches: [ main ]

jobs:
  example_job:
    runs-on: ubuntu-latest

    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.head_ref }}
      - shell: bash
        run: |
          date > 1.txt
          git config user.name github-actions
          git config user.email github-actions@github.com
          git add 1.txt
          git commit -m "updated"
          git push origin HEAD:${{ github.head_ref }}

So far, so good: the file 1.txt is created and added to the branch testing, and I can see the commit in the PR.

However, if I now make another change to the code (locally) and push it, the commit is rejected with the error:

hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.

I know I can override it by doing push -f, but it is not something I want to do on a regular basis. So I would I set up a workflow that does this, without running into this problem? Am I missing something here?


Solution

  • So the answer is that the workflow is correct, but after it is triggered and executed, and before any other commit is pushed to the repo, the user has to either manually pull from the remote branch or set up a pre-commit hook (or do push -f which is not advisable). There is no other way to do it. Is this correct?

    Thanks to @grim and @jonrsharpe