feat: prettier workflow #2458
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
# This workflow ensures consistent code formatting across the project using Prettier. | |
# It runs on pull requests and pushes to main, staging, and develop branches. | |
# What it does: | |
# 1. Checks out the code and sets up the Node.js environment. | |
# 2. Installs pnpm and project dependencies. | |
# 3. Runs Prettier to check code formatting. | |
# 4. If formatting issues are found, it generates a diff and comments on the PR. | |
# 5. The workflow fails if formatting issues are detected, preventing merge until fixed. | |
name: Code Formatting | |
on: | |
pull_request: | |
push: | |
branches: | |
- main | |
- staging | |
- develop | |
jobs: | |
prettier: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout | |
uses: actions/checkout@v3 | |
with: | |
# Use GITHUB_TOKEN for authentication | |
token: ${{ secrets.GITHUB_TOKEN }} | |
ref: ${{ github.head_ref }} | |
- name: Use Node.js | |
uses: actions/setup-node@v2 | |
with: | |
node-version: '21.1.0' | |
- name: Install pnpm | |
uses: pnpm/action-setup@v2 | |
with: | |
version: 8 | |
- name: Install Dependencies | |
run: pnpm install --frozen-lockfile | |
- name: Check Formatting | |
run: pnpm exec prettier --config prettier.config.js --check . | |
- name: Suggest Formatting Changes | |
if: failure() | |
uses: actions/github-script@v6 | |
with: | |
github-token: ${{secrets.GITHUB_TOKEN}} | |
script: | | |
const fs = require('fs'); | |
const { execSync } = require('child_process'); | |
// Run Prettier and capture the diff | |
let diff; | |
try { | |
execSync('pnpm exec prettier --config prettier.config.js --write .'); | |
diff = execSync('git diff').toString(); | |
} catch (error) { | |
console.error('Error running Prettier:', error); | |
return; | |
} | |
if (diff) { | |
const pullRequest = context.payload.pull_request; | |
if (pullRequest) { | |
github.rest.issues.createComment({ | |
issue_number: pullRequest.number, | |
owner: context.repo.owner, | |
repo: context.repo.repo, | |
body: 'Formatting issues detected. Please run Prettier locally and commit the changes.\n\n```diff\n' + diff + '\n```' | |
}); | |
} | |
} |