Skip to content

Instantly share code, notes, and snippets.

@rody
Created December 2, 2021 02:25
Show Gist options
  • Save rody/743ab916d5b4e35aed99f9d96b9986cb to your computer and use it in GitHub Desktop.
Save rody/743ab916d5b4e35aed99f9d96b9986cb to your computer and use it in GitHub Desktop.
Github workflow to format files with Prettier on pull request
name: format-code-pull-request
on:
- pull_request
jobs:
format-source-code:
# Check if the PR is not from a fork
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
# only run if there are changed files
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.event.pull_request.head.sha }}
- name: Install NodeJS
uses: actions/setup-node@v2
with:
node-version: "14"
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Get changed files
id: changes
run: |
git diff -z --name-only --diff-filter=ACMRT origin/${{ github.event.pull_request.base.ref}}...origin/${{ github.event.pull_request.head.ref }} | xargs -0 -I {} npx prettier --write "{}"
- name: Commit formatted files
run: |
git config --local user.email "$(git log --format='%ae' HEAD^!)"
git config --local user.name "$(git log --format='%an' HEAD^!)"
git add .
if [ -z "$(git status --porcelain)" ]; then
exit 0
fi
git commit -m "chore: format source code with Prettier"
git push origin HEAD:${{ github.event.pull_request.head.ref }}
@rody
Copy link
Author

rody commented Dec 2, 2021

Note: it formats only the files changed in the pull-request, so it is safe to use on bigger projects where none of the files have been formatted previously.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment