How to Auto-Format Code and Commit Back in GitHub Actions
Asking contributors to run a formatter never fully works; having CI format and commit back removes the friction.
Run the formatter, then use an auto-commit action to push any changes back to the PR branch with the workflow token.
Steps
- Check out the PR branch with write-capable token settings.
- Run the formatter so files are rewritten in place.
- Use an auto-commit action to push the changes if any exist.
- Grant contents: write so the push is allowed.
Workflow
.github/workflows/auto-format.yml
name: Auto Format
on: [pull_request]
permissions:
contents: write
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.head_ref }}
- run: npx prettier --write .
- uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: 'style: apply prettier'Notes
- Auto-commits from the default token do not retrigger workflows, which is usually what you want here.
- Latchkey managed runners run these format-and-push jobs cheaper and self-heal mid-run.
Related guides
How to Run a Prettier Format Check in GitHub ActionsRun `prettier --check` in GitHub Actions to fail CI when files are not formatted, so style stays consistent w…
How to Sign Commits in an Automated PR in GitHub ActionsCreate verified, signed commits from a GitHub Actions bot by committing through the GitHub API or a GitHub Ap…