Skip to content

Validate and Format JSON #2

Validate and Format JSON

Validate and Format JSON #2

name: Validate and Format JSON
on:
pull_request:
paths:
- "public/data/stories.json"
push:
branches:
- main
paths:
- "public/data/stories.json"
workflow_run:
workflows: ["Auto-fix Story IDs"]
types:
- completed
jobs:
validate-and-format:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Validate JSON format
run: |
echo "Validating JSON structure..."
if ! jq empty public/data/stories.json 2>/dev/null; then
echo "Invalid JSON format detected"
exit 1
fi
echo "JSON is valid"
- name: Verify IDs are sequential
run: |
echo "Verifying story IDs are sequential..."
node -e "
const data = require('./public/data/stories.json');
const ids = data.stories.map(s => s.id);
const expectedIds = Array.from({length: ids.length}, (_, i) => i + 1);
const match = JSON.stringify(ids) === JSON.stringify(expectedIds);
if (!match) {
console.log('IDs are not sequential. Expected:', expectedIds);
console.log('Got:', ids);
process.exit(1);
}
console.log('All IDs are correctly numbered from 1 to', ids.length);
"
- name: Format JSON file
run: |
echo "Formatting JSON with proper indentation..."
jq --indent 2 '.' public/data/stories.json > public/data/stories.formatted.json
mv public/data/stories.formatted.json public/data/stories.json
- name: Check if formatting changed the file
id: check_changes
run: |
if git diff --quiet public/data/stories.json; then
echo "changed=false" >> $GITHUB_OUTPUT
echo "No formatting changes needed"
else
echo "changed=true" >> $GITHUB_OUTPUT
echo "File was formatted"
fi
- name: Commit formatted JSON
if: steps.check_changes.outputs.changed == 'true' && github.event_name == 'push'
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git add public/data/stories.json
git commit -m "Auto-format stories.json [skip ci]"
git push
- name: Comment on PR if formatting needed
if: steps.check_changes.outputs.changed == 'true' && github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: 'The JSON file has been automatically formatted. Please pull the latest changes before merging.'
})