Created
December 2, 2021 02:25
-
-
Save rody/743ab916d5b4e35aed99f9d96b9986cb to your computer and use it in GitHub Desktop.
Github workflow to format files with Prettier on pull request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.