Writing a GitHub Action that pushes commits

Goal

So, you are hoping:

  • automatically reformat code pushed to PR?

  • automatically merge one branch into another at a certain cadence?

  • something else involving automatically creating and pushing git commits?

All of these can be solved using a GitHub Action workflow!

There are different ways to set up your workflow, with varying levels of control over the result. This article describes the most dead-simple way I could come up with.

My solution

First, make sure GitHub Actions are enabled for your repository. Make sure that GitHub Actions has write access to your repository – this can be done in repo settings.

Now, add a workflow named <your-workflow-name>.yml to ./.github/workflows/, following this template:

name: Name of your workflow on: push: branches: [ ... ] # Replace ... with the branches you want to trigger upon. jobs: job-name: # set your job name to something nice. runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: fetch-depth: 0 # all branches and tags - name: Set git identity run: | git config user.name 'github-actions[bot]' git config user.email 'github-actions[bot]@users.noreply.github.com' # ... # ADD YOUR GIT OPERATION STEPS HERE # ... - name: Push run: | git remote set-url origin https://x-access-token:${{ github.token }}@github.com/${{ github.repository }} git push

 

Example: https://github.com/openedx/tutor-contrib-coursegraph/blob/master/.github/workflows/merge-to-nightly.yml

Discussion

Pros

  • This approach is very simple to set up.

  • Using github-actions[bot] gives you the GitHub logo as the profile picture on the commit.

  • github-actions[bot] isn’t a real GitHub user account, which will hopefully make it clear that a user account isn’t responsible for commits that the action makes.

Cons:

  • For the branches being pushed to, you cannot have protections that require a PR or any status checks. This is probably a showstopper if you’re hoping to push to master or any other critical branch.

Improvements

If you want to push to a branch without making the branch unprotected, you may want to ditch the github.token strategy for in favor of authenticating as a GitHub App. This would allow you to protect the target branch, while marking the GitHub App as an explicit exception to the branch protection.