Skip to content
Open
72 changes: 72 additions & 0 deletions .github/workflows/prettier.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
name: Prettier

on:
pull_request:
permissions:
contents: write
jobs:
prettier:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 1

- name: Set up Node.js
uses: actions/setup-node@v7
with:
node-version: 24
cache: npm

- name: Install dependencies
run: npm ci

- name: Get changed files and run Prettier
id: run_prettier
run: |
# Fetch only the base branch tip and compare it with the checked-out PR merge commit
git fetch --no-tags --depth=1 origin \
"+refs/heads/${{ github.base_ref }}:refs/remotes/origin/${{ github.base_ref }}"
changed_files=$(git diff --name-only --diff-filter=ACMRT origin/${{ github.base_ref }}..HEAD | grep -E '\.(js|mjs|cjs|json|css|html|md|yml)$' || true)

if [[ -n "$changed_files" ]]; then
echo "Found changed files to format:"
echo "$changed_files"

# Run prettier on the changed files
echo "$changed_files" | xargs npx --no-install prettier --write

# Check if prettier actually made any changes
if git diff --quiet && git diff --cached --quiet; then
echo "No formatting changes were made by Prettier"
echo "prettier_changes=false" >> "$GITHUB_OUTPUT"
else
echo "Prettier made formatting changes"
echo "prettier_changes=true" >> "$GITHUB_OUTPUT"
fi

echo "prose_changes=true" >> "$GITHUB_OUTPUT"
else
echo "No relevant files were changed in this pull request branch."
echo "prose_changes=false" >> "$GITHUB_OUTPUT"
exit 0
fi

- name: Warn when PR is from fork
if: steps.run_prettier.outputs.prettier_changes == 'true' && github.event.pull_request.head.repo.fork == true
run: |
echo "::warning title=Fork PR detected::Prettier made changes, but this workflow cannot push commits to fork branches. Please run Prettier locally and push the formatting commit or allow edits from maintainers."
echo "### Fork PR notice" >> "$GITHUB_STEP_SUMMARY"
echo "Prettier found formatting changes, but auto-commit is skipped for forks. Run prettier locally or allow edits from maintainers." >> "$GITHUB_STEP_SUMMARY"

- name: Commit and push changes
if: steps.run_prettier.outputs.prettier_changes == 'true'
run: |
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
git add .
git commit -m "Chore: Format files with Prettier"
git push origin HEAD:${{ github.head_ref }}
echo "Changes committed and pushed successfully"
Loading