From 265cef1a22c3df08284f8f2470f8bf0634bef430 Mon Sep 17 00:00:00 2001 From: Chris Reynolds Date: Tue, 29 Oct 2024 15:07:32 -0600 Subject: [PATCH] Add Prettier pre-push hook (#9283) * test pre-push hook * test pre-push hook * add prettier pre-push hook to .github/hooks * add git hooks section to readme * actually add the changed files to git --------- Co-authored-by: Rachel --- .github/hooks/pre-push | 17 +++++++++++++++++ README.md | 13 +++++++++++++ 2 files changed, 30 insertions(+) create mode 100755 .github/hooks/pre-push diff --git a/.github/hooks/pre-push b/.github/hooks/pre-push new file mode 100755 index 0000000000..59225bf26f --- /dev/null +++ b/.github/hooks/pre-push @@ -0,0 +1,17 @@ +#!/bin/sh +git fetch origin main +# Check for changed JavaScript files. +CHANGED_FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.js$|\.jsx$|\.ts$|\.tsx$' || echo "") +# If JavaScript files have changed, run Prettier. +if [ -n "$CHANGED_FILES" ]; then + echo "Fixing the following files:" + echo "$CHANGED_FILES" + + # Run Prettier on the changed files. + echo "$CHANGED_FILES" | xargs npx prettier --write + echo "Adding Prettier changes to commit" + git add . + git commit -m "Apply Prettier formatting" +else + echo "No files to format" +fi \ No newline at end of file diff --git a/README.md b/README.md index 7eb2f92cc5..54e3ada0c6 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,19 @@ nvm install 18 npm install -g gatsby-cli ``` +### Using Git Hooks +Git hooks have been added to `[.github/hooks](.github/hooks)` to help automate some of the tasks that make it easier to work locally with the repository. The following hooks are available: + +- `pre-commit`: Runs Prettier to check for code styling issues on updated/changed javascript files. If Prettier made any changes, those changes are automatically committed back to the PR. This mirrors the functionality of the [Prettier GitHub Action](.github/workflows/prettier.yml). + +To use the git hooks, you must configure your local environment to use `.github/hooks` as the hooks path (normally `.git/hooks`, but this folder is ignored by Git). This can be done by running the following command from the root of the repository: + +```bash +git config core.hooksPath .github/hooks +``` + +It's recommended (but not required) to use the provided git hooks if you are working with any javascript files in the repository. This will help ensure that your changes are formatted correctly before being committed and ensure that your local environment and the remote branch are the same. + ### Get the Code Fork and clone this repository: