Projects Blog

Commit and push changes to the current branch from a GitHub Action

In specific scenarios, such as when a GitHub Action modifies local files (e.g., a JSON database), you may want to commit and push these changes to the repository.

In my case, I run a scraper weekly in Octagon API project, where I update several local JSON’s files from a GitHub action workflow.

If you only need to run this workflow from a specific branch, you can simply use your branch name as a string, as shown in this example:

name: Push local changes
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-22.04
name: Push changes
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- uses: actions/setup-node@v4
with:
node-version: 20
- uses: pnpm/action-setup@v4
with:
version: 8
run_install: true
- run: |
pnpm run your-package-script
git config user.name my-bot-name
git add -A
git commit -am "[BOT] Your message"
git push origin main

However, if you need to run this workflow from different branches, you can use the context data github.ref_name to get the current branch name.

name: Push local changes
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-22.04
name: Push changes
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- uses: actions/setup-node@v4
with:
node-version: 20
- uses: pnpm/action-setup@v4
with:
version: 8
run_install: true
- run: |
pnpm run your-package-script
git config user.name my-bot-name
git add -A
git commit -am "[BOT] Your message"
git push origin ${{ github.ref_name }}

I hope you found this article useful.

Happy coding! 🚀

Related posts